text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { PdfDocument, PdfPage ,PdfColor, PdfFont, PdfStandardFont} from './../../../src/index'; import { PointF, PdfFontFamily, PdfSolidBrush, PdfPageOrientation } from './../../../src/index'; import { PdfPageRotateAngle, PdfPageSize, SizeF } from './../../../src/index'; import { Utils } from './../utils.spec'; describe('UTC-01: adding multiple pages', () => { it('-adding multiple pages', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // create black brush let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); // add a new page to the document let page1 : PdfPage = document.pages.add(); // draw the text in the first page page1.graphics.drawString('Hello World!!!', font, null, blackBrush, 0, 0, null); // add a new page to the document let page2 : PdfPage = document.pages.add(); // draw the text in the second page page2.graphics.drawString('Hello World!!!', font, null, blackBrush, 0, 0, null); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_pages_01.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-02: page margins', () => { it('-page margins', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // set the page margins document.pageSettings.margins.right = 50; // set the custom page margins document.pageSettings.margins.left = 10; // add a page to the document let page1 : PdfPage = document.pages.add(); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 10); // create black brush let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); // draw the text page1.graphics.drawString('Hello world', font, null, blackBrush, 0, 0, null); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_pages_02.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-03: page orientation', () => { it('-page orientation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // change the page orientation to landscape document.pageSettings.orientation = PdfPageOrientation.Landscape; // add pages to the document let page1 : PdfPage = document.pages.add(); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // create black brush let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); // draw the text page1.graphics.drawString('Hello World!!!', font, null, blackBrush, 0, 0, null); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_pages_03.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-04: page rotation', () => { it('-page rotation', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // apply 90 degree rotation on the page document.pageSettings.rotate = PdfPageRotateAngle.RotateAngle90; // create a new page let page1 : PdfPage = document.pages.add(); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // create black brush let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); // draw the text page1.graphics.drawString('Hello World!!!', font, null, blackBrush, 0, 0, null); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_pages_04.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-05: page size', () => { it('-page size', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // set the page size document.pageSettings.size = PdfPageSize.a3; // add pages to the document let page1 : PdfPage = document.pages.add(); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // create black brush let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); // draw the text page1.graphics.drawString('Hello World!!!', font, null, blackBrush, 0, 0, null); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_pages_05.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-06: custom page size', () => { it('-custom page size', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // set the page size document.pageSettings.size = new SizeF(200, 300); // add pages to the document let page1 : PdfPage = document.pages.add(); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // create black brush let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); // draw the text page1.graphics.drawString('Hello World!!!', font, null, blackBrush, 0, 0, null); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_pages_06.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-07: Adding empty pages', () => { it('-Adding empty pages', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // set the page size document.pageSettings.size = new SizeF(200, 300); // add pages to the document let page1 : PdfPage = document.pages.add(); // set the font let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // create black brush let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); // draw the text page1.graphics.drawString('Hello World!!!', font, null, blackBrush, 0, 0, null); // add pages to the document let page2 : PdfPage = document.pages.add(); // draw the text page1.graphics.getNextPage().graphics.drawString('Hello World!!!', font, null, blackBrush, 0, 0, null); // draw the text page2.graphics.getNextPage().graphics.drawString('Hello World!!!', font, null, blackBrush, 0, 0, null); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_pages_07.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) }); describe('UTC-08: getNextPage method overloads', () => { it('-getNextPage method overloads', (done) => { // create a new PDF document let document : PdfDocument = new PdfDocument(); // set the page size document.pageSettings.size = new SizeF(200, 300); // add pages to the document let page1 : PdfPage = document.pages.add(); // add pages to the document let page2 : PdfPage = document.pages.add(); //Save the document. document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'utc_working_with_pages_08.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }) });
the_stack
import DataFrame from "../core/frame" import { ArrayType1D, ArrayType2D } from "../shared/types" import Utils from "../shared/utils"; const utils = new Utils(); type mergeParam = { left: DataFrame, right: DataFrame, on: Array<string>, how: "outer" | "inner" | "left" | "right" } type keyComb = { [key: string] : { filters: ArrayType2D, combValues: ArrayType1D } } class Merge { left: DataFrame right: DataFrame on: Array<string> how: "outer" | "inner" | "left" | "right" leftColIndex: ArrayType1D = [] rightColIndex: ArrayType1D = [] leftCol?: ArrayType1D rightCol?: ArrayType1D columns?: ArrayType1D constructor({left, right, on, how}: mergeParam) { this.left = left this.right = right this.on = on this.how = how //Obtain the column index of the column will //want to merge on for both left and right dataframe for(let i =0; i < this.on.length; i++) { let key = this.on[i] if (this.left.columns.includes(key) && this.right.columns.includes(key)) { let leftIndex = this.left.columns.indexOf(key) let rightIndex = this.right.columns.indexOf(key) this.leftColIndex.push(leftIndex) this.rightColIndex.push(rightIndex) } } } /** * Generate key combination base on the columns we want to merge on * e.g df = { * key1: ["KO", "K0", "K3", "K4"], * Key2: ["K1", "K1", "K3", "K5"], * A: [1,2,3,4] * B: [3,4,5,6] * } * keycomb = generateKeyCombination(df.values, [0,1]) * This should output * { * 'k0_k1': { * filters: [[1,3], [2,4]], # the value of other columns in thesame row with the combination keys * combValues: ["KO", "k1"] # the combination key from column Key1 (index 2) and key2 (index 1) * }, * 'K3_K3 : { * filters: [[3,5]], * combValues: ['K3', 'k3'] * }, * 'k4_k5' : { * filters: [[4,6]] * combValues: ['K4', 'K5'] * } * } * This key combination will be generated for both left and right dataframe * @param values * @param colIndex */ private generateKeyCombination(values: ArrayType2D, colIndex: ArrayType1D): keyComb { let colKeyComb: keyComb = {} for (let i=0; i < values.length; i++) { let rowValues = values[i] let rowKeyCombValues = []; for (let j =0; j < colIndex.length; j++) { let index = colIndex[j] as number rowKeyCombValues.push(rowValues[index]) } let rowKeyComb = rowKeyCombValues.join('_') let otherValues = rowValues.filter((val, index) => { return !colIndex.includes(index) }) if (utils.keyInObject(colKeyComb, rowKeyComb)) { colKeyComb[rowKeyComb].filters.push(otherValues) } else { colKeyComb[rowKeyComb] = { filters: [otherValues], combValues: rowKeyCombValues } } } return colKeyComb } /** * Generate columns for the newly generated merged DataFrame * e.g df = { * key1: ["KO", "K0", "K3", "K4"], * Key2: ["K1", "K1", "K3", "K5"], * A: [1,2,3,4] * B: [3,4,5,6] * } * df2 = { * key1: ["KO", "K0", "K3", "K4"], * Key2: ["K1", "K1", "K3", "K5"], * A: [1,2,3,4] * c: [3,4,5,6] * } * And both dataframe are to be merged on `key1` and `key2` * the newly generated column will be of the form * columns = ['key1', 'Key2', 'A', 'A_1', 'B', 'C'] * Notice 'A_1' , this because both DataFrame as column A and 1 is the * number of duplicate of that column */ private createColumns() { const self = this this.leftCol = self.left.columns.filter((_, index)=>{ return !self.leftColIndex.includes(index) }) this.rightCol = self.right.columns.filter((_, index) => { return !self.rightColIndex.includes(index) }) this.columns = [...this.on] const duplicateColumn: { [key: string] : number } = {} const tempColumn = [...this.leftCol] tempColumn.push(...this.rightCol) for (let i=0; i< tempColumn.length; i++) { const col = tempColumn[i] as string if (utils.keyInObject(duplicateColumn, col)) { let columnName = `${col}_${duplicateColumn[col]}` this.columns.push(columnName) duplicateColumn[col] +=1 } else { this.columns.push(col) duplicateColumn[col] = 1 } } } /** * The basic methos perform the underneath operation of generating * the merge dataframe; using the combination keys generated from * bothe left and right DataFrame * e.g df = { * key1: ["KO", "K0", "K3", "K4"], * Key2: ["K1", "K1", "K3", "K5"], * A: [1,2,3,4] * B: [3,4,5,6] * } * df2 = { * key1: ["KO", "K0", "K3", "K4"], * Key2: ["K1", "K2", "K4", "K5"], * A: [3,6,8,9] * c: [2,4,6,8] * } * Running generatekeyCombination on both left and right data frame * we should have * leftKeyDict = { * 'k0_k1': { * filters: [[1,3], [2,4]], * combValues: ["KO", "k1"] * }, * 'K3_K3' : { * filters: [[3,5]], * combValues: ['K3', 'k3'] * }, * 'k4_k5' : { * filters: [[4,6]] * combValues: ['K4', 'K5'] * } * } * rightKeyDict = { * 'k0_k1': { * filters: [[3,2]], * combValues: ["KO", "k1"] * }, * 'K0_K2': { * filters: [[6,4]], * combValues: ['K0', 'K2'] * }, * 'K3_K4' : { * filters: [[8,9]], * combValues: ['K3', 'k4'] * }, * 'k4_k5' : { * filters: [[9,8]] * combValues: ['K4', 'K5'] * } * } * The `keys` is generated base on the type of merge operation we want to * perform. If we assume we are performing `outer` merge (which is a set of the * key combination from both leftKeyDict and rightKeyDict) then Keys should be * this * keys = ['K0_K1', 'K3_K3', 'k4_k5', 'K0_K2', 'k3_k4'] * The Keys, leftKeyDict and rightKeyDict are used to generated DataFrame data, * by looping through the Keys and checking if leftKeyDict and rightKeyDict as the * key if one of them does not the column in that row will be NaN * e.g Data for each row base on keys * COLUMNS = ['key1', 'Key2', 'A', 'B', 'A_1', 'C'] * 'K0_K1': ['K0', 'K1', 1, 3 , 3, 2 ] * 'K0_K1': ['K0', 'K1', 2, 4, NaN, NaN] * 'K3_K3': ['k3', 'K3', 3, 5, NaN, NaN] * 'K4_K5': ['K4', 'K5', 4, 6, 9, 8] * 'k0_K2': ['k0', 'K2' NaN, NaN, 6, 4] * 'k3_k4': ['K3', 'K4', NaN, NaN, 8, 6] * * @param keys * @param leftKeyDict * @param rightKeyDict */ private basic(keys: ArrayType1D, leftKeyDict: keyComb, rightKeyDict: keyComb): ArrayType2D { const data = [] for (let i=0; i < keys.length; i++) { const key = keys[i] as string if (utils.keyInObject(leftKeyDict, key)) { const leftRows = leftKeyDict[key].filters const leftCombValues = leftKeyDict[key].combValues for (let lIndex=0; lIndex < leftRows.length; lIndex++) { const leftRow = leftRows[lIndex] if (utils.keyInObject(rightKeyDict, key)) { const rightRows = rightKeyDict[key].filters for (let rIndex=0; rIndex < rightRows.length; rIndex++) { const rightRow = rightRows[rIndex] const combineData = leftCombValues.slice(0) combineData.push(...leftRow) combineData.push(...rightRow) data.push(combineData) } } else { const nanArray = Array(this.rightCol?.length).fill(NaN) const combineData = leftCombValues.slice(0) combineData.push(...leftRow) combineData.push(...nanArray) data.push(combineData) } } } else { const rightRows = rightKeyDict[key].filters const rightCombValues = rightKeyDict[key].combValues for (let i =0; i < rightRows.length; i++) { const rightRow = rightRows[i] const nanArray = Array(this.leftCol?.length).fill(NaN) const combineData = rightCombValues.slice(0) combineData.push(...nanArray) combineData.push(...rightRow) data.push(combineData) } } } return data } /** * Generate outer key from leftKeyDict and rightKeyDict * The Key pass into basic method is the union of * leftKeyDict and rightKeyDict * @param leftKeyDict * @param rightKeyDict */ private outer(leftKeyDict: keyComb, rightKeyDict: keyComb): ArrayType2D { const keys = Object.keys(leftKeyDict) keys.push(...Object.keys(rightKeyDict)) const UniqueKeys = Array.from(new Set(keys)) const data = this.basic(UniqueKeys, leftKeyDict, rightKeyDict) return data } /** * Generate Key for basic method, * the key geneerated is the intersection of * leftKeyDict and rightKeyDict * @param leftKeyDict * @param rightKeyDict */ private inner(leftKeyDict: keyComb, rightKeyDict: keyComb): ArrayType2D { const leftKey = Object.keys(leftKeyDict) const rightKey = Object.keys(rightKeyDict) const keys = leftKey.filter((val) => rightKey.includes(val)) const data = this.basic(keys, leftKeyDict, rightKeyDict) return data } /** * The key is the leftKeyDict * @param leftKeyDict * @param rightKeyDict */ private leftMerge(leftKeyDict: keyComb, rightKeyDict: keyComb): ArrayType2D { const keys = Object.keys(leftKeyDict) const data = this.basic(keys, leftKeyDict, rightKeyDict) return data } /** * The key is the rightKeyDict * @param leftKeyDict * @param rightKeyDict */ private rightMerge(leftKeyDict: keyComb, rightKeyDict: keyComb): ArrayType2D { const keys = Object.keys(rightKeyDict) const data = this.basic(keys, leftKeyDict, rightKeyDict) return data } /** * Perform the merge operation * 1) Obtain both left and right dataframe values * 2) Generate the leftkeyDict and rightKeyDict * 3) Generate new merge columns * 4) check how merge is to be done and apply the * right methods */ operation(): DataFrame { let leftValues = this.left.values as ArrayType2D let rightValues = this.right.values as ArrayType2D let leftKeyDict = this.generateKeyCombination(leftValues, this.leftColIndex) let rightKeyDict = this.generateKeyCombination(rightValues, this.rightColIndex) this.createColumns() let data: ArrayType2D= [] switch (this.how) { case "outer": data = this.outer(leftKeyDict, rightKeyDict) break; case "inner": data = this.inner(leftKeyDict, rightKeyDict) break; case "left": data = this.leftMerge(leftKeyDict, rightKeyDict) break; case "right": data = this.rightMerge(leftKeyDict, rightKeyDict) break; } const columns = this.columns as Array<string> return new DataFrame(data, {columns: [...columns]}) } } /** * Perform merge operation between two DataFrame * @param params : { * left: DataFrame * right: DataFrame * on: Array<string> * how: "outer" | "inner" | "left" | "right" * } */ export default function merge(params: mergeParam): DataFrame { const mergeClass = new Merge(params) return mergeClass.operation() }
the_stack
// clang-format off import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {ClearBrowsingDataBrowserProxyImpl, ContentSettingsTypes, CookiePrimarySetting, SafeBrowsingSetting, SiteSettingsPrefsBrowserProxyImpl} from 'chrome://settings/lazy_load.js'; import {HatsBrowserProxyImpl, MetricsBrowserProxyImpl, PrivacyPageBrowserProxyImpl, Route, Router, routes, SecureDnsMode, SettingsPrivacyPageElement, StatusAction, SyncStatus, TrustSafetyInteraction} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks, isChildVisible, isVisible} from 'chrome://webui-test/test_util.js'; import {TestClearBrowsingDataBrowserProxy} from './test_clear_browsing_data_browser_proxy.js'; import {TestHatsBrowserProxy} from './test_hats_browser_proxy.js'; import {TestMetricsBrowserProxy} from './test_metrics_browser_proxy.js'; import {TestPrivacyPageBrowserProxy} from './test_privacy_page_browser_proxy.js'; import {TestSiteSettingsPrefsBrowserProxy} from './test_site_settings_prefs_browser_proxy.js'; // clang-format on const redesignedPages: Route[] = [ routes.SITE_SETTINGS_ADS, routes.SITE_SETTINGS_AR, routes.SITE_SETTINGS_AUTOMATIC_DOWNLOADS, routes.SITE_SETTINGS_BACKGROUND_SYNC, routes.SITE_SETTINGS_CAMERA, routes.SITE_SETTINGS_CLIPBOARD, routes.SITE_SETTINGS_FONT_ACCESS, routes.SITE_SETTINGS_FILE_SYSTEM_WRITE, routes.SITE_SETTINGS_HANDLERS, routes.SITE_SETTINGS_HID_DEVICES, routes.SITE_SETTINGS_IDLE_DETECTION, routes.SITE_SETTINGS_IMAGES, routes.SITE_SETTINGS_JAVASCRIPT, routes.SITE_SETTINGS_LOCATION, routes.SITE_SETTINGS_MICROPHONE, routes.SITE_SETTINGS_MIDI_DEVICES, routes.SITE_SETTINGS_NOTIFICATIONS, routes.SITE_SETTINGS_PAYMENT_HANDLER, routes.SITE_SETTINGS_PDF_DOCUMENTS, routes.SITE_SETTINGS_POPUPS, routes.SITE_SETTINGS_PROTECTED_CONTENT, routes.SITE_SETTINGS_SENSORS, routes.SITE_SETTINGS_SERIAL_PORTS, routes.SITE_SETTINGS_SOUND, routes.SITE_SETTINGS_USB_DEVICES, routes.SITE_SETTINGS_VR, // TODO(crbug.com/1128902) After restructure add coverage for elements on // routes which depend on flags being enabled. // routes.SITE_SETTINGS_BLUETOOTH_SCANNING, // routes.SITE_SETTINGS_BLUETOOTH_DEVICES, // routes.SITE_SETTINGS_WINDOW_PLACEMENT, // Doesn't contain toggle or radio buttons // routes.SITE_SETTINGS_INSECURE_CONTENT, // routes.SITE_SETTINGS_ZOOM_LEVELS, ]; suite('PrivacyPage', function() { let page: SettingsPrivacyPageElement; let testClearBrowsingDataBrowserProxy: TestClearBrowsingDataBrowserProxy; let siteSettingsBrowserProxy: TestSiteSettingsPrefsBrowserProxy; let metricsBrowserProxy: TestMetricsBrowserProxy; const testLabels: string[] = ['test label 1', 'test label 2']; suiteSetup(function() { loadTimeData.overrideValues({ privacyReviewEnabled: false, }); }); setup(function() { testClearBrowsingDataBrowserProxy = new TestClearBrowsingDataBrowserProxy(); ClearBrowsingDataBrowserProxyImpl.setInstance( testClearBrowsingDataBrowserProxy); const testBrowserProxy = new TestPrivacyPageBrowserProxy(); PrivacyPageBrowserProxyImpl.setInstance(testBrowserProxy); siteSettingsBrowserProxy = new TestSiteSettingsPrefsBrowserProxy(); SiteSettingsPrefsBrowserProxyImpl.setInstance(siteSettingsBrowserProxy); siteSettingsBrowserProxy.setCookieSettingDescription(testLabels[0]!); metricsBrowserProxy = new TestMetricsBrowserProxy(); MetricsBrowserProxyImpl.setInstance(metricsBrowserProxy); document.body.innerHTML = ''; page = document.createElement('settings-privacy-page'); page.prefs = { profile: {password_manager_leak_detection: {value: true}}, signin: { allowed_on_next_startup: {type: chrome.settingsPrivate.PrefType.BOOLEAN, value: true} }, safebrowsing: { enabled: {value: true}, scout_reporting_enabled: {value: true}, enhanced: {value: false} }, dns_over_https: {mode: {value: SecureDnsMode.AUTOMATIC}, templates: {value: ''}}, privacy_sandbox: { apis_enabled: {value: true}, }, privacy_guide: { viewed: { type: chrome.settingsPrivate.PrefType.BOOLEAN, value: false, }, }, }; document.body.appendChild(page); return flushTasks(); }); teardown(function() { page.remove(); Router.getInstance().navigateTo(routes.BASIC); }); test('showClearBrowsingDataDialog', function() { assertFalse(!!page.shadowRoot!.querySelector( 'settings-clear-browsing-data-dialog')); page.$.clearBrowsingData.click(); flush(); const dialog = page.shadowRoot!.querySelector('settings-clear-browsing-data-dialog'); assertTrue(!!dialog); }); test('CookiesLinkRowSublabel', async function() { await siteSettingsBrowserProxy.whenCalled('getCookieSettingDescription'); flush(); assertEquals(page.$.cookiesLinkRow.subLabel, testLabels[0]); webUIListenerCallback('cookieSettingDescriptionChanged', testLabels[1]); assertEquals(page.$.cookiesLinkRow.subLabel, testLabels[1]); }); test('privacyReviewRowNotVisible', function() { assertFalse(isChildVisible(page, '#privacyReviewLinkRow')); }); test('ContentSettingsVisibility', async function() { // Ensure pages are visited so that HTML components are stamped. redesignedPages.forEach(route => Router.getInstance().navigateTo(route)); await flushTasks(); // All redesigned pages, except notifications, protocol handlers, pdf // documents and protected content (except chromeos and win), will use a // settings-category-default-radio-group. // <if expr="chromeos or is_win"> assertEquals( page.shadowRoot! .querySelectorAll('settings-category-default-radio-group') .length, redesignedPages.length - 3); // </if> // <if expr="not chromeos and not is_win"> assertEquals( page.shadowRoot! .querySelectorAll('settings-category-default-radio-group') .length, redesignedPages.length - 4); // </if> }); test('NotificationPage', async function() { Router.getInstance().navigateTo(routes.SITE_SETTINGS_NOTIFICATIONS); await flushTasks(); assertTrue(isChildVisible(page, '#notificationRadioGroup')); const categorySettingExceptions = page.shadowRoot!.querySelector('category-setting-exceptions')!; assertTrue(isVisible(categorySettingExceptions)); assertEquals( ContentSettingsTypes.NOTIFICATIONS, categorySettingExceptions.category); assertFalse(isChildVisible(page, 'category-default-setting')); }); test('privacySandboxRowSublabel', async function() { page.set('prefs.privacy_sandbox.apis_enabled.value', true); await flushTasks(); assertEquals( loadTimeData.getString('privacySandboxTrialsEnabled'), page.$.privacySandboxLinkRow.subLabel); page.set('prefs.privacy_sandbox.apis_enabled.value', false); await flushTasks(); assertEquals( loadTimeData.getString('privacySandboxTrialsDisabled'), page.$.privacySandboxLinkRow.subLabel); }); test('clickPrivacySandboxRow', async function() { page.$.privacySandboxLinkRow.click(); // Ensure UMA is logged. assertEquals( 'Settings.PrivacySandbox.OpenedFromSettingsParent', await metricsBrowserProxy.whenCalled('recordAction')); }); }); suite('PrivacyReviewEnabled', function() { let page: SettingsPrivacyPageElement; setup(function() { document.body.innerHTML = ''; page = document.createElement('settings-privacy-page'); page.prefs = { // Need privacy_sandbox pref for the page's setup. privacy_sandbox: { apis_enabled: {value: true}, }, privacy_review: { show_welcome_card: {type: chrome.settingsPrivate.PrefType.BOOLEAN, value: true}, }, privacy_guide: { viewed: { type: chrome.settingsPrivate.PrefType.BOOLEAN, value: false, }, }, generated: { cookie_primary_setting: { type: chrome.settingsPrivate.PrefType.NUMBER, value: CookiePrimarySetting.BLOCK_THIRD_PARTY, }, safe_browsing: { type: chrome.settingsPrivate.PrefType.NUMBER, value: SafeBrowsingSetting.STANDARD, }, }, }; document.body.appendChild(page); return flushTasks(); }); test('privacyReviewRowVisibleChildAccount', function() { assertTrue(isChildVisible(page, '#privacyReviewLinkRow')); // The user signs in to a child user account. This hides the privacy review // entry point. const syncStatus: SyncStatus = {childUser: true, statusAction: StatusAction.NO_ACTION}; webUIListenerCallback('sync-status-changed', syncStatus); flush(); assertFalse(isChildVisible(page, '#privacyReviewLinkRow')); // The user is no longer signed in to a child user account. This doesn't // show the entry point. syncStatus.childUser = false; webUIListenerCallback('sync-status-changed', syncStatus); flush(); assertFalse(isChildVisible(page, '#privacyReviewLinkRow')); }); test('privacyReviewRowVisibleManaged', function() { assertTrue(isChildVisible(page, '#privacyReviewLinkRow')); // The user becomes managed. This hides the privacy review entry point. webUIListenerCallback('is-managed-changed', true); flush(); assertFalse(isChildVisible(page, '#privacyReviewLinkRow')); // The user is no longer managed. This doesn't show the entry point. webUIListenerCallback('is-managed-changed', false); flush(); assertFalse(isChildVisible(page, '#privacyReviewLinkRow')); }); test('privacyReviewRowClick', function() { page.shadowRoot!.querySelector<HTMLElement>( '#privacyReviewLinkRow')!.click(); // Ensure the correct Settings page is shown. assertEquals(routes.PRIVACY_REVIEW, Router.getInstance().getCurrentRoute()); }); }); suite('PrivacyPageSound', function() { let testBrowserProxy: TestPrivacyPageBrowserProxy; let page: SettingsPrivacyPageElement; function getToggleElement() { return page.shadowRoot!.querySelector<HTMLElement>( '#block-autoplay-setting')!; } setup(() => { loadTimeData.overrideValues({enableBlockAutoplayContentSetting: true}); testBrowserProxy = new TestPrivacyPageBrowserProxy(); PrivacyPageBrowserProxyImpl.setInstance(testBrowserProxy); Router.getInstance().navigateTo(routes.SITE_SETTINGS_SOUND); document.body.innerHTML = ''; page = document.createElement('settings-privacy-page'); document.body.appendChild(page); return flushTasks(); }); teardown(() => { page.remove(); }); test('UpdateStatus', () => { assertTrue(getToggleElement().hasAttribute('disabled')); assertFalse(getToggleElement().hasAttribute('checked')); webUIListenerCallback( 'onBlockAutoplayStatusChanged', {pref: {value: true}, enabled: true}); return flushTasks().then(() => { // Check that we are on and enabled. assertFalse(getToggleElement().hasAttribute('disabled')); assertTrue(getToggleElement().hasAttribute('checked')); // Toggle the pref off. webUIListenerCallback( 'onBlockAutoplayStatusChanged', {pref: {value: false}, enabled: true}); return flushTasks().then(() => { // Check that we are off and enabled. assertFalse(getToggleElement().hasAttribute('disabled')); assertFalse(getToggleElement().hasAttribute('checked')); // Disable the autoplay status toggle. webUIListenerCallback( 'onBlockAutoplayStatusChanged', {pref: {value: false}, enabled: false}); return flushTasks().then(() => { // Check that we are off and disabled. assertTrue(getToggleElement().hasAttribute('disabled')); assertFalse(getToggleElement().hasAttribute('checked')); }); }); }); }); test('Hidden', () => { assertTrue(loadTimeData.getBoolean('enableBlockAutoplayContentSetting')); assertFalse(getToggleElement().hidden); loadTimeData.overrideValues({enableBlockAutoplayContentSetting: false}); page.remove(); page = document.createElement('settings-privacy-page'); document.body.appendChild(page); return flushTasks().then(() => { assertFalse(loadTimeData.getBoolean('enableBlockAutoplayContentSetting')); assertTrue(getToggleElement().hidden); }); }); test('Click', () => { assertTrue(getToggleElement().hasAttribute('disabled')); assertFalse(getToggleElement().hasAttribute('checked')); webUIListenerCallback( 'onBlockAutoplayStatusChanged', {pref: {value: true}, enabled: true}); return flushTasks().then(() => { // Check that we are on and enabled. assertFalse(getToggleElement().hasAttribute('disabled')); assertTrue(getToggleElement().hasAttribute('checked')); // Click on the toggle and wait for the proxy to be called. getToggleElement().click(); return testBrowserProxy.whenCalled('setBlockAutoplayEnabled') .then((enabled) => { assertFalse(enabled); }); }); }); }); suite('HappinessTrackingSurveys', function() { let testHatsBrowserProxy: TestHatsBrowserProxy; let page: SettingsPrivacyPageElement; setup(function() { testHatsBrowserProxy = new TestHatsBrowserProxy(); HatsBrowserProxyImpl.setInstance(testHatsBrowserProxy); document.body.innerHTML = ''; page = document.createElement('settings-privacy-page'); // Initialize the privacy page pref. Security page manually expands // the initially selected safe browsing option so the pref object // needs to be defined. page.prefs = { generated: { safe_browsing: { type: chrome.settingsPrivate.PrefType.NUMBER, value: SafeBrowsingSetting.STANDARD, }, cookie_session_only: {value: false}, cookie_primary_setting: {type: chrome.settingsPrivate.PrefType.NUMBER, value: 0}, password_manager_leak_detection: {value: false}, }, profile: {password_manager_leak_detection: {value: false}}, dns_over_https: {mode: {value: SecureDnsMode.AUTOMATIC}, templates: {value: ''}}, }; document.body.appendChild(page); return flushTasks(); }); teardown(function() { page.remove(); Router.getInstance().navigateTo(routes.BASIC); }); test('ClearBrowsingDataTrigger', async function() { page.$.clearBrowsingData.click(); const interaction = await testHatsBrowserProxy.whenCalled('trustSafetyInteractionOccurred'); assertEquals(TrustSafetyInteraction.USED_PRIVACY_CARD, interaction); }); test('CookiesTrigger', async function() { page.$.cookiesLinkRow.click(); const interaction = await testHatsBrowserProxy.whenCalled('trustSafetyInteractionOccurred'); assertEquals(TrustSafetyInteraction.USED_PRIVACY_CARD, interaction); }); test('SecurityTrigger', async function() { page.$.securityLinkRow.click(); const interaction = await testHatsBrowserProxy.whenCalled('trustSafetyInteractionOccurred'); assertEquals(TrustSafetyInteraction.USED_PRIVACY_CARD, interaction); }); test('PermissionsTrigger', async function() { page.$.permissionsLinkRow.click(); const interaction = await testHatsBrowserProxy.whenCalled('trustSafetyInteractionOccurred'); assertEquals(TrustSafetyInteraction.USED_PRIVACY_CARD, interaction); }); });
the_stack
import { PdfPage } from './../pages/pdf-page'; import { PdfGraphics } from './../graphics/pdf-graphics'; import { PointF, RectangleF, SizeF } from './../drawing/pdf-drawing'; import { PdfTextElement } from './../graphics/figures/text-element'; import { PdfUriAnnotation } from './uri-annotation'; import { PdfStringLayouter, PdfStringLayoutResult } from './../graphics/fonts/string-layouter'; import { PdfFontStyle } from './../graphics/fonts/enum'; import { PdfLayoutResult } from './../graphics/figures/base/element-layouter'; import { PdfTextAlignment } from './../graphics/enum'; import { PdfArray } from './../primitives/pdf-array'; import { PdfNumber } from './../primitives/pdf-number'; /** * `PdfTextWebLink` class represents the class for text web link annotation. * ```typescript * // create a new PDF document. * let document : PdfDocument = new PdfDocument(); * // add a page to the document. * let page1 : PdfPage = document.pages.add(); * // create the font * let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); * // * // create the Text Web Link * let textLink : PdfTextWebLink = new PdfTextWebLink(); * // set the hyperlink * textLink.url = 'http://www.google.com'; * // set the link text * textLink.text = 'Google'; * // set the font * textLink.font = font; * // draw the hyperlink in PDF page * textLink.draw(page1, new PointF(10, 40)); * // * // save the document. * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ export class PdfTextWebLink extends PdfTextElement { // Fields /** * Internal variable to store `Url`. * @default '' * @private */ private uniformResourceLocator : string = ''; /** * Internal variable to store `Uri Annotation` object. * @default null * @private */ private uriAnnotation : PdfUriAnnotation = null; /** * Checks whether the drawTextWebLink method with `PointF` overload is called or not. * If it set as true, then the start position of each lines excluding firest line is changed as (0, Y). * @private * @hidden */ private recalculateBounds : boolean = false; private defaultBorder : PdfArray = new PdfArray(); // Properties /** * Gets or sets the `Uri address`. * ```typescript * // create a new PDF document. * let document : PdfDocument = new PdfDocument(); * // add a page to the document. * let page1 : PdfPage = document.pages.add(); * // create the font * let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12); * // create the Text Web Link * let textLink : PdfTextWebLink = new PdfTextWebLink(); * // * // set the hyperlink * textLink.url = 'http://www.google.com'; * // * // set the link text * textLink.text = 'Google'; * // set the font * textLink.font = font; * // draw the hyperlink in PDF page * textLink.draw(page1, new PointF(10, 40)); * // save the document. * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ public get url() : string { return this.uniformResourceLocator; } public set url(value : string) { if (value.length === 0) { throw new Error('ArgumentException : Url - string can not be empty'); } this.uniformResourceLocator = value; } // Constructors /** * Initializes a new instance of the `PdfTextWebLink` class. * @private */ public constructor() { super(); for (let i : number = 0; i < 3; i++) { this.defaultBorder.add(new PdfNumber(0)); } } // Implementation /* tslint:disable */ /** * `Draws` a Text Web Link on the Page with the specified location. * @private */ public draw(page : PdfPage, location : PointF) : PdfLayoutResult /** * `Draws` a Text Web Link on the Page with the specified bounds. * @private */ public draw(page : PdfPage, bounds : RectangleF) : PdfLayoutResult /** * `Draw` a Text Web Link on the Graphics with the specified location. * @private */ public draw(graphics : PdfGraphics, location : PointF) : PdfLayoutResult /** * `Draw` a Text Web Link on the Graphics with the specified bounds. * @private */ public draw(graphics : PdfGraphics, bounds : RectangleF) : PdfLayoutResult public draw(arg1 : PdfGraphics|PdfPage, arg2 : PointF|RectangleF) : PdfLayoutResult { if (arg1 instanceof PdfPage) { let layout : PdfStringLayouter = new PdfStringLayouter(); let previousFontStyle : PdfFontStyle = this.font.style; if (arg2 instanceof PointF) { this.recalculateBounds = true; this.font.style = PdfFontStyle.Underline; let layoutResult : PdfStringLayoutResult = layout.layout(this.value, this.font, this.stringFormat, new SizeF((arg1.graphics.clientSize.width - arg2.x), 0), true, arg1.graphics.clientSize); if (layoutResult.lines.length === 1) { let textSize : SizeF = this.font.measureString(this.value); let rect : RectangleF = new RectangleF(arg2, textSize); rect = this.calculateBounds(rect, textSize.width, arg1.graphics.clientSize.width, arg2.x); this.uriAnnotation = new PdfUriAnnotation(rect, this.url); this.uriAnnotation.dictionary.items.setValue('Border', this.defaultBorder); arg1.annotations.add(this.uriAnnotation); let result : PdfLayoutResult = this.drawText(arg1, arg2); this.font.style = previousFontStyle; return result; } else { let result : PdfLayoutResult = this.drawMultipleLineWithPoint(layoutResult, arg1, arg2); this.font.style = previousFontStyle; return result; } } else { let layoutResult : PdfStringLayoutResult = layout.layout(this.value, this.font, this.stringFormat, new SizeF((arg2 as RectangleF).width, 0), false, new SizeF(0, 0)); this.font.style = PdfFontStyle.Underline; if (layoutResult.lines.length === 1) { let textSize : SizeF = this.font.measureString(this.value); let rect : RectangleF = new RectangleF(new PointF((arg2 as RectangleF).x, (arg2 as RectangleF).y), textSize); rect = this.calculateBounds(rect, textSize.width, (arg2 as RectangleF).width, (arg2 as RectangleF).x); this.uriAnnotation = new PdfUriAnnotation(rect, this.url); this.uriAnnotation.dictionary.items.setValue('Border', this.defaultBorder); arg1.annotations.add(this.uriAnnotation); let returnValue : PdfLayoutResult = this.drawText(arg1, arg2 as RectangleF); this.font.style = previousFontStyle; return returnValue; } else { let returnValue : PdfLayoutResult = this.drawMultipleLineWithBounds(layoutResult, arg1, arg2 as RectangleF); this.font.style = previousFontStyle; return returnValue; } } } else { let page : PdfPage = new PdfPage(); page = arg1.page as PdfPage; return this.draw(page, arg2); } } /* tslint:enable */ //Private methods /** * Helper method `Draw` a Multiple Line Text Web Link on the Graphics with the specified location. * @private */ private drawMultipleLineWithPoint(result : PdfStringLayoutResult, page : PdfPage, location : PointF) : PdfLayoutResult { let layoutResult : PdfLayoutResult; for (let i : number = 0; i < result.layoutLines.length; i++) { let size : SizeF = this.font.measureString(result.lines[i].text); let bounds : RectangleF = new RectangleF(location, size); if (i !== 0) { bounds.x = 0; } this.text = result.lines[i].text; if (bounds.y + size.height > page.graphics.clientSize.height) { if (i !== 0) { page = page.graphics.getNextPage(); bounds = new RectangleF(0, 0, page.graphics.clientSize.width, size.height); location.y = 0; } else { break; } } bounds = this.calculateBounds(bounds, size.width, page.graphics.clientSize.width, bounds.x); this.uriAnnotation = new PdfUriAnnotation(bounds, this.url); this.uriAnnotation.dictionary.items.setValue('Border', this.defaultBorder); page.annotations.add(this.uriAnnotation); if (i !== 0) { layoutResult = this.drawText(page, new PointF(0, bounds.y)); } else { layoutResult = this.drawText(page, bounds.x, bounds.y); } location.y += size.height; } return layoutResult; } /** * Helper method `Draw` a Multiple Line Text Web Link on the Graphics with the specified bounds. * @private */ private drawMultipleLineWithBounds(result : PdfStringLayoutResult, page : PdfPage, bounds : RectangleF) : PdfLayoutResult { let layoutResult : PdfLayoutResult; for (let i : number = 0; i < result.layoutLines.length; i++) { let size : SizeF = this.font.measureString(result.lines[i].text); let internalBounds : RectangleF = new RectangleF(new PointF(bounds.x, bounds.y), size); internalBounds = this.calculateBounds(internalBounds, size.width, bounds.width, bounds.x); this.text = result.lines[i].text; if (bounds.y + size.height > page.graphics.clientSize.height) { if (i !== 0) { page = page.graphics.getNextPage(); bounds = new RectangleF(bounds.x, 0, bounds.width, size.height); internalBounds.y = 0; } else { break; } } this.uriAnnotation = new PdfUriAnnotation(internalBounds, this.url); this.uriAnnotation.dictionary.items.setValue('Border', this.defaultBorder); page.annotations.add(this.uriAnnotation); layoutResult = this.drawText(page, bounds); bounds.y += size.height; } return layoutResult; } /* tslint:disable */ private calculateBounds(currentBounds : RectangleF, lineWidth : number, maximumWidth : number, startPosition : number) : RectangleF { let shift : number = 0; if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Center) { currentBounds.x = startPosition + (maximumWidth - lineWidth) / 2; currentBounds.width = lineWidth; } else if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Right) { currentBounds.x = startPosition + (maximumWidth - lineWidth); currentBounds.width = lineWidth; } else if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Justify) { currentBounds.x = startPosition; currentBounds.width = maximumWidth; } else { currentBounds.width = startPosition; currentBounds.width = lineWidth; } return currentBounds; } /* tslint:enable */ }
the_stack
import * as vscode from "vscode"; /** * A VS Code `Position`, `Range` or `Selection`. */ export type PRS = vscode.Position | vscode.Range | vscode.Selection; /** * A VS Code `Position` or `Selection`. */ export type PS = vscode.Position | vscode.Selection; /** * Returns whether the given value is a `vscode.Position` object. * * ### Example * * ```js * const position = new vscode.Position(0, 0), * range = new vscode.Range(position, position), * selection = new vscode.Selection(position, position); * * assert(isPosition(position)); * assert(!isPosition(range)); * assert(!isPosition(selection)); * ``` */ export function isPosition(x: unknown): x is vscode.Position { return x != null && (x as object).constructor === vscode.Position; } /** * Returns whether the given value is a `vscode.Range` object. * * ### Example * * ```js * const position = new vscode.Position(0, 0), * range = new vscode.Range(position, position), * selection = new vscode.Selection(position, position); * * assert(!isRange(position)); * assert(isRange(range)); * assert(!isRange(selection)); * ``` */ export function isRange(x: unknown): x is vscode.Range { return x != null && (x as object).constructor === vscode.Range; } /** * Returns whether the given value is a `vscode.Selection` object. * * ### Example * * ```js * const position = new vscode.Position(0, 0), * range = new vscode.Range(position, position), * selection = new vscode.Selection(position, position); * * assert(!isSelection(position)); * assert(!isSelection(range)); * assert(isSelection(selection)); * ``` */ export function isSelection(x: unknown): x is vscode.Selection { return x != null && (x as object).constructor === vscode.Selection; } /** * Returns a `PRS` whose start position is mapped using the given function. * * ### Example * * ```js * const p1 = new vscode.Position(0, 0), * p2 = new vscode.Position(0, 1); * * assert.deepStrictEqual( * mapStart(p1, (x) => x.translate(1)), * new vscode.Position(1, 0), * ); * assert.deepStrictEqual( * mapStart(new vscode.Range(p1, p2), (x) => x.translate(1)), * new vscode.Range(p2, new vscode.Position(1, 0)), * ); * assert.deepStrictEqual( * mapStart(new vscode.Selection(p1, p2), (x) => x.translate(1)), * new vscode.Selection(new vscode.Position(1, 0), p2), * ); * assert.deepStrictEqual( * mapStart(new vscode.Selection(p2, p1), (x) => x.translate(1)), * new vscode.Selection(p2, new vscode.Position(1, 0)), * ); * ``` */ export function mapStart<T extends PRS>(x: T, f: (_: vscode.Position) => vscode.Position) { if (isSelection(x)) { return x.start === x.anchor ? new vscode.Selection(f(x.start), x.end) as T : new vscode.Selection(x.end, f(x.start)) as T; } if (isRange(x)) { return new vscode.Range(f(x.start), x.end) as T; } return f(x as vscode.Position) as T; } /** * Returns a `PRS` whose end position is mapped using the given function. * * ### Example * * ```js * const p1 = new vscode.Position(0, 0), * p2 = new vscode.Position(0, 1); * * assert.deepStrictEqual( * mapEnd(p1, (x) => x.translate(1)), * new vscode.Position(1, 0), * ); * assert.deepStrictEqual( * mapEnd(new vscode.Range(p1, p2), (x) => x.translate(1)), * new vscode.Range(p1, new vscode.Position(1, 1)), * ); * assert.deepStrictEqual( * mapEnd(new vscode.Selection(p1, p2), (x) => x.translate(1)), * new vscode.Selection(p1, new vscode.Position(1, 1)), * ); * assert.deepStrictEqual( * mapEnd(new vscode.Selection(p2, p1), (x) => x.translate(1)), * new vscode.Selection(new vscode.Position(1, 1), p1), * ); * ``` */ export function mapEnd<T extends PRS>(x: T, f: (_: vscode.Position) => vscode.Position) { if (isSelection(x)) { return x.start === x.anchor ? new vscode.Selection(x.start, f(x.end)) as T : new vscode.Selection(f(x.end), x.start) as T; } if (isRange(x)) { return new vscode.Range(x.start, f(x.end)) as T; } return f(x as vscode.Position) as T; } /** * Returns a `PS` whose active position is mapped using the given function. * * ### Example * * ```js * const p1 = new vscode.Position(0, 0), * p2 = new vscode.Position(0, 1); * * assert.deepStrictEqual( * mapActive(p1, (x) => x.translate(1)), * new vscode.Position(1, 0), * ); * assert.deepStrictEqual( * mapActive(new vscode.Selection(p1, p2), (x) => x.translate(1)), * new vscode.Selection(p1, new vscode.Position(1, 1)), * ); * ``` */ export function mapActive<T extends PS>(x: T, f: (_: vscode.Position) => vscode.Position) { if (isSelection(x)) { return new vscode.Selection(x.anchor, f(x.active)) as T; } return f(x as vscode.Position) as T; } /** * Returns a `PRS` whose start and end positions are mapped using the given * function. * * ### Example * * ```js * const p1 = new vscode.Position(0, 0), * p2 = new vscode.Position(0, 1); * * assert.deepStrictEqual( * mapBoth(p1, (x) => x.translate(1)), * new vscode.Position(1, 0), * ); * assert.deepStrictEqual( * mapBoth(new vscode.Range(p1, p2), (x) => x.translate(1)), * new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 1)), * ); * assert.deepStrictEqual( * mapBoth(new vscode.Selection(p1, p2), (x) => x.translate(1)), * new vscode.Selection(new vscode.Position(1, 0), new vscode.Position(1, 1)), * ); * assert.deepStrictEqual( * mapBoth(new vscode.Selection(p2, p1), (x) => x.translate(1)), * new vscode.Selection(new vscode.Position(1, 1), new vscode.Position(1, 0)), * ); * ``` */ export function mapBoth<T extends PRS>(x: T, f: (_: vscode.Position) => vscode.Position) { if (isSelection(x)) { return new vscode.Selection(f(x.anchor), f(x.active)) as T; } if (isRange(x)) { return new vscode.Range(f(x.start), f(x.end)) as T; } return f(x as vscode.Position) as T; } /** * Given a function type with at least one parameter, returns a pair of all the * argument types except the last one, and then the last argument type. */ export type SplitParameters<F> = F extends (...args: infer AllArgs) => any ? AllArgs extends [...infer Args, infer LastArg] ? [Args, LastArg] : never : never; /** * Returns a function that takes the `n - 1` first parameters of `f`, and * returns yet another function that takes the last parameter of `f`, and * returns `f(...args, lastArg)`. * * ### Example * * ```js * const add2 = (a, b) => a + b, * add3 = (a, b, c) => a + b + c; * * expect(add2(1, 2)).to.be.equal(3); * expect(add3(1, 2, 3)).to.be.equal(6); * * expect(curry(add2)(1)(2)).to.be.equal(3); * expect(curry(add3)(1, 2)(3)).to.be.equal(6); * ``` */ export function curry<F extends (...allArgs: any) => any>(f: F, ...counts: number[]) { if (counts.length === 0) { return (...args: SplitParameters<F>[0]) => (lastArg: SplitParameters<F>[1]) => { return f(...args, lastArg); }; } // TODO: review this let curried: any = f; for (let i = counts.length - 1; i >= 0; i--) { const prev = curried, len = counts[i]; curried = (...args: any[]) => (...newArgs: any[]) => { const allArgs = args; let i = 0; for (; i < newArgs.length && i < len; i++) { allArgs.push(newArgs[i]); } for (; i < len; i++) { allArgs.push(undefined); } return prev(...allArgs); }; } return curried; } /* eslint-disable max-len */ // In case we need `pipe` for more than 10 functions: // // Array.from({ length: 10 }, (_, n) => { // const lo = n => String.fromCharCode(97 + n), // hi = n => String.fromCharCode(65 + n); // // return ` // /** // * Returns a function that maps all non-\`undefined\` values // * through the given function and returns the remaining results. // */ // export function pipe<${ // Array.from({ length: n + 2 }, (_, i) => hi(i)).join(", ") // }>(${ // Array.from({ length: n + 1 }, (_, i) => `${lo(i)}: (_: ${hi(i)}) => ${hi(i + 1)} | undefined`).join(", ") // }): (values: readonly A[]) => ${hi(n + 1)}[];`; // }).join("\n") /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. */ export function pipe<A, B>(a: (_: A) => B | undefined): (values: readonly A[]) => B[]; /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. * * ### Example * * ```js * const doubleNumbers = pipe((n) => typeof n === "number" ? n : undefined, * (n) => n * 2); * * assert.deepStrictEqual( * doubleNumbers([1, "a", 2, null, 3, {}]), * [2, 4, 6], * ); * ``` */ export function pipe<A, B, C>(a: (_: A) => B | undefined, b: (_: B) => C | undefined): (values: readonly A[]) => C[]; /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. */ export function pipe<A, B, C, D>(a: (_: A) => B | undefined, b: (_: B) => C | undefined, c: (_: C) => D | undefined): (values: readonly A[]) => D[]; /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. */ export function pipe<A, B, C, D, E>(a: (_: A) => B | undefined, b: (_: B) => C | undefined, c: (_: C) => D | undefined, d: (_: D) => E | undefined): (values: readonly A[]) => E[]; /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. */ export function pipe<A, B, C, D, E, F>(a: (_: A) => B | undefined, b: (_: B) => C | undefined, c: (_: C) => D | undefined, d: (_: D) => E | undefined, e: (_: E) => F | undefined): (values: readonly A[]) => F[]; /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. */ export function pipe<A, B, C, D, E, F, G>(a: (_: A) => B | undefined, b: (_: B) => C | undefined, c: (_: C) => D | undefined, d: (_: D) => E | undefined, e: (_: E) => F | undefined, f: (_: F) => G | undefined): (values: readonly A[]) => G[]; /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. */ export function pipe<A, B, C, D, E, F, G, H>(a: (_: A) => B | undefined, b: (_: B) => C | undefined, c: (_: C) => D | undefined, d: (_: D) => E | undefined, e: (_: E) => F | undefined, f: (_: F) => G | undefined, g: (_: G) => H | undefined): (values: readonly A[]) => H[]; /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. */ export function pipe<A, B, C, D, E, F, G, H, I>(a: (_: A) => B | undefined, b: (_: B) => C | undefined, c: (_: C) => D | undefined, d: (_: D) => E | undefined, e: (_: E) => F | undefined, f: (_: F) => G | undefined, g: (_: G) => H | undefined, h: (_: H) => I | undefined): (values: readonly A[]) => I[]; /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. */ export function pipe<A, B, C, D, E, F, G, H, I, J>(a: (_: A) => B | undefined, b: (_: B) => C | undefined, c: (_: C) => D | undefined, d: (_: D) => E | undefined, e: (_: E) => F | undefined, f: (_: F) => G | undefined, g: (_: G) => H | undefined, h: (_: H) => I | undefined, i: (_: I) => J | undefined): (values: readonly A[]) => J[]; /** * Returns a function that maps all non-`undefined` values * through the given function and returns the remaining results. */ export function pipe<A, B, C, D, E, F, G, H, I, J, K>(a: (_: A) => B | undefined, b: (_: B) => C | undefined, c: (_: C) => D | undefined, d: (_: D) => E | undefined, e: (_: E) => F | undefined, f: (_: F) => G | undefined, g: (_: G) => H | undefined, h: (_: H) => I | undefined, i: (_: I) => J | undefined, j: (_: J) => K | undefined): (values: readonly A[]) => K[]; /* eslint-enable max-len */ export function pipe(...functions: ((_: unknown) => unknown)[]) { return (values: readonly unknown[]) => { const results = [], vlen = values.length, flen = functions.length; for (let i = 0; i < vlen; i++) { let value = values[i]; for (let j = 0; value !== undefined && j < flen; j++) { value = functions[j](value); } if (value !== undefined) { results.push(value); } } return results; }; } /** * Same as `pipe`, but also works with async functions. */ export function pipeAsync(...functions: ((_: unknown) => unknown)[]) { return async (values: readonly unknown[]) => { const results = [], vlen = values.length, flen = functions.length; for (let i = 0; i < vlen; i++) { let value = values[i]; for (let j = 0; value !== undefined && j < flen; j++) { value = await functions[j](value); } if (value !== undefined) { results.push(value); } } return results; }; }
the_stack
declare namespace WXPage { /** 页面跳转参数 */ interface PageLifeTimeOptions { /** 页面跳转地址 */ url?: string; /** 跳转参数 */ query: Record<string, string>; } /** 事件监听器 */ interface Emitter { /** * 开始监听一个事件 * * @param eventName 开始监听的事件名称 * @param callback 当监听事件被触发时执行的回调 */ on(event: string, callback: (...args: any[]) => void): void; /** * 触发一个事件 * * @param eventName 触发的事件名称 * @param args 传递的参数 */ emit(event: string, ...args: any[]): void; /** 结束一个事件监听 */ off(event: string, callback: (...args: any[]) => void): void; } /** 信息监听器 */ interface Message { /** * 开始监听一个事件 * * @param eventName 开始监听的事件名称 * @param callback 当监听事件被触发时执行的回调 */ $on(event: string, callback: (...args: any[]) => void): void; /** * 触发一个事件 * * @param eventName 触发的事件名称 * @param args 传递的参数 */ $emit(event: string, ...args: any[]): void; /** 结束一个事件监听 */ $off(event: string, callback: (...args: any[]) => void): void; /** * 存放的数据,该数据只能取一次 * * @param key 存储时的键值 * @param data 存储时的数据 * * 案例: * * ```js * this.$put('play:prefetch', new Promise(function (resolve, reject) { * wx.request(url, function (err, data) { * resolve(data) * }) * })); * this.$take('play:prefetch').then(function (data) { * // get data * }); * this.$take('play:prefetch'); // => null * ``` */ $put(key: string, data: any): void; /** * 取出存放的数据 * * @param key 要取得数据的键值 * * 案例: * * ```js * this.$put('play:prefetch', new Promise(function (resolve, reject) { * wx.request(url, function (err, data) { * resolve(data) * }) * })); * this.$take('play:prefetch').then(function (data) { * // get data * }); * this.$take('play:prefetch'); // => null * ``` */ $take(key: string): any; } /** 页面跳转API */ interface Redirector { /** * 导航到指定页面 * * 本函数是`wx.navigateTo`的封装。跳转到指定页面,`pagename`可以带上`queryString` * * @param pagename 页面名称或页面的路径 * @param config 传递给`wx.navigateTo`Api的参数(url会自动由`pagename`解析的结果填充) * * 示例: * * ```js * this.$route('play?vid=xxx&cid=xxx'); * this.$route('calulator?result=98',{ * success: () => { * // do something * } * }); * ``` */ $route(pagename: string, config?: WechatMiniprogram.NavigateToOption): void; /** * 导航到指定页面,`$route`方法的别名 * * 本函数是`wx.navigateTo`的封装。跳转到指定页面,`pagename`可以带上`queryString` * * @param pagename 页面名称或页面的路径 * @param config 传递给 `wx.navigateTo` api的参数(url会自动由`pagename`解析的结果填充) * * 示例: * * ```js * this.$navigate('play?vid=xxx&cid=xxx'); * ``` */ $navigate(pagename: string): void; /** * 跳转到指定页面, **替换页面,不产生历史** * * 本函数是`wx.redirectTo`的封装。跳转到指定页面,`pagename`可以带上`queryString` * * @param pagename 页面名称或页面的路径 * @param config 传递给 `wx.redirectTo` api的参数(url会自动由`pagename`解析的结果填充) * * 示例: * * ```js * this.$redirect('calulator?result=98',{ * success: () => { * // do something * } * }); * this.$redirect('pages/about/about'); * ``` */ $redirect(pagename: string, config?: WechatMiniprogram.RedirectToOption): void; /** * 跳转到指定tabBar页面,并关闭其他所有非tabBar页面 * * 本函数是`wx.switchTab`的封装。跳转到指定页面。路径**不可包含参数** * * @param pagename 页面名称或页面的路径 * @param config 传递给 `wx.switchTab` api的参数(url会自动由`pagename`解析的结果填充) * * 示例: * * ```js * this.$switchTab('main?user=mrhope'); * this.$switchTab('pages/about/about'); * ``` */ $switchTab(pagename: string, config?: WechatMiniprogram.SwitchTabOption): void; /** * 关闭所有页面,打开到应用内的某个页面 * * 本函数是`wx.reLaunch`的封装。跳转到指定页面。`pagename`可以带上`queryString` * * @param pagename 页面名称或页面的路径 * @param config 传递给 `wx.reLaunch` api的参数(url会自动由`pagename`解析的结果填充) * * 示例: * * ```js * this.$launch('main'); * this.$launch('function/calulator?result=98'); * ``` */ $launch(pagename: string, config?: WechatMiniprogram.ReLaunchOption): void; /** * 返回上一页,`wx.navigateBack` 的封装 * * @param delta 返回的层数,默认为`1` * * 示例: * * ```js * this.$back(); * this.$back(2); * ``` */ $back(delta?: number): void; /** * 提前预加载指定页面 (会触发对应页面的 `onPreload` 声明周期) * * @param pagename 页面名称或页面的路径,可以带上`queryString` * * 示例: * * ```js * this.$preload('play?vid=xxx&cid=xxx'); * this.$preload('/page/main?userName=xxx&action=xxx'); * ``` */ $preload(pagename: string): void; /** * 点击代理方法,绑定 `$route` 逻辑,在元素上声明 `data-url` 作为跳转地址,支持切面方法: * * - `data-before` 跳转前执行 * - `data-after` 跳转后执行 * * 示例: * ```html * <button * bindtap="$bindRoute" * data-url="/pages/play" * data-before="onClickBefore" * >click redirect</button> * ``` */ $bindRoute(): void; /** * 点击代理方法,绑定 `$redirect` 逻辑,在元素上声明 `data-url` 作为跳转地址,支持切面方法: * * - `data-before` 跳转前执行 * - `data-after` 跳转后执行 * * 示例: * ```html * <button * bindtap="$bindRedirect" * data-url="/pages/play" * data-before="onClickBefore" * >click redirect</button> * ``` */ $bindRedirect(): void; /** * 点击代理方法,绑定 `$switch` 逻辑,在元素上声明 `data-url` 作为跳转地址,支持切面方法: * * - `data-before` 跳转前执行 * - `data-after` 跳转后执行 * * 示例: * ```html * <button * bindtap="$bindSwitch" * data-url="/pages/play" * data-before="onClickBefore" * >click redirect</button> * ``` */ $bindSwitch(): void; /** * 点击代理方法,绑定 `$launch` 逻辑,在元素上声明 `data-url` 作为跳转地址,支持切面方法: * * - `data-before` 跳转前执行 * - `data-after` 跳转后执行 * * 示例: * ```html * <button * bindtap="$bindReLaunch" * data-url="/pages/play" * data-before="onClickBefore" * >click redirect</button> * ``` */ $bindReLaunch(): void; } interface Cache { /** * 如果传 `callback` 参数,会使用异步模式并回调,否则直接同步返回结果。 * * @param key * @param value 缓存数据,可以为对象 * @param expire 缓存过期时间,单位为毫秒。如果为 true ,那么保持已存在的缓存时间,如果没有缓存,那么认为过期,不保存 * @param callback 可选,异步写的时候回调,接收参数:cb(err), err不为空代表失败。 */ set( key: string, value: any, expire?: number | true, callback?: (errMsg: any) => void ): void; /** * 如果传 `callback` 参数,会使用异步模式并回调 * * @param key 存储的键值 * @param callback 可选,异步读的时候回调,接收参数:`calbck(err, data)`, `err`不为空代表失败 */ get(key: string, callback?: (err: any, data: any) => void): void; /** * 如果传 `callback` 参数,会使用异步模式并回调 * * @param key 需要删除的键值 * @param callback 可选,异步删除的时候回调,接收参数:`callback(err, data)`, `err`不为空代表失败 */ remove(key: string, callback?: () => void): void; } interface Stack { /** * 获取当前页面实例。取 getCurrentPages 的最后一个项。 * * @returns 当前页面的页面名 * > 请注意: * > * > 由于实现中调用了`getCurrentPages`,在主包的`onPageLaunch`、`onAppLaunch`生命周期调用无效。 * > 因为此时 `page` 还没有生成。 */ $curPage(): PageInstance; /** * 获取当前页面实例对应的页面名。根据`AppOption.config.route`的配置解析当前页面实例的`route` * * @returns 当前页面的页面名 * > 请注意: * > * >由于基础库1.2.0以下不支持 `Page.prototype.route` ,只能取到空字符串 * > 由于实现中调用了`getCurrentPages`,在主包的`onPageLaunch`、`onAppLaunch`生命周期调用无效。 * > 因为此时 `page` 还没有生成。 * */ $curPageName(): string; } /** 页面注册选项 */ interface PageOption { /** * 在App.onLaunch触发时调用 * * @param options 启动参数: * * - `path` String 打开小程序的路径 * - `query` Object 打开小程序的query * - `scene` Number 打开小程序的场景值 */ onAppLaunch(options: WechatMiniprogram.App.LaunchShowOption): void; /** * App.onShow 第一次触发时调用。 * * 只会触发一次,需要多次调用的请使用原生的 App.onShow * * @param options 启动参数: * * - `path` String 打开小程序的路径 * - `query` Object 打开小程序的query * - `scene` Number 打开小程序的场景值 */ onAppShow(options: WechatMiniprogram.App.LaunchShowOption): void; /** * App.onShow 第一次触发时调用。 * * 只会触发一次,需要多次调用的请使用原生的 App.onShow * * @param options 启动参数: * * - `path` String 打开小程序的路径 * - `query` Object 打开小程序的query * - `scene` Number 打开小程序的场景值 */ onAwake(time: WechatMiniprogram.App.LaunchShowOption): void; /** * 页面预加载时触发,此时对应的页面并未被加载 * * 需要在调用页面中使用`this.preload(pageName或pageShortName)` */ onPreload(options: PageLifeTimeOptions): void; /** * 页面即将被导航时触发 * * 需要在调用页面中使用`this.$navigate(pageName或pageShortName)` * 才能正确触发`onNavigate` * * 另外需要特别注意第一次进入一个分包界面 * 或者是通过微信小程序二维码或微信内分享直接跳转到小程序子页面时同样不会触发 */ onNavigate(options: PageLifeTimeOptions): void; } /** 页面实例 */ interface PageInstance extends Message, Redirector, Cache, Stack { /** 当前页面名称 */ $name: string; /** 一些由wxpage生成的页面状态 */ $state: { /** 是否是打开的第一个页面 */ firstOpen: boolean; }; /** 页面与页面内组件间的事件监听 */ $emitter: Emitter; $cache: Cache; // TODO: Remove $session: Cache; /** 指定了 `ref` 的子组件实例Map */ $refs: any; } /** 页面构造器 */ interface PageConstructor { ( name: string, options: PageOption ): void; } /** 组件实例 */ interface ComponentInstance<D extends WechatMiniprogram.Component.DataOption> extends Message, Redirector, Cache, Stack { /** TODO: Remove * * 同 this.setData({...}) * * @param options 同setData的第一项 */ $set(options: Partial<D> & Record<string, any>): void; /** TODO: Remove * * 获取data对象 */ $data(): D; /** * 通过消息的方式调用父组件方法,方法不存在也不会报错 * * @param method 方法名称 * @param args 传递的参数 */ $call(method: string, ...args: any[]): void; // TODO: Remove $session: Cache; /** 页面与页面内组件间的事件监听 */ $emitter: Emitter; /** 当前组件所属的页面组件实例 只在 `attached`, `ready`生命周期后生效 */ $root: any; /** * 当前组件所属的父组件实例引用 只在 `attached`, `ready`生命周期后生效 * * 在非连续调用组件的情况下`$root`相同 */ $parent: any; /** * 指定了 ref 的子组件实例Map,在父组件获取子组件引用 * * 示例: * * ```html * <custom-component binding="$" ref="customComp"/> * ``` * * ```js * Page.P({ * onLoad: function () { * this.$refs.customComp // 根据ref属性获取子组件的实例引用 * } * }); * ``` */ $ref: any; } /** APP选项 */ interface AppOption { /** 小程序路径解析配置 */ config: { /** 小程序路径 */ route: string | string[]; /** * 解析简称 * * @param name 页面简称 * @returns 实际页面的地址 */ resolvePath?(name: string): string; /** * 自定义扩展页面,在框架执行扩展之前 * * @param name 页面名称 * @param pageoption 页面构建选项对象 * @param modules 内置模块 */ extendPageBefore?(name: string, pageoption: PageOption, modules: any): void; /** * 自定义扩展页面,在框架执行扩展之后 * * @param name 页面名称 * @param pageoption 页面构建选项对象 * @param modules 内置模块 */ extendPageAfter?(name: string, pageoption: PageOption, modules: any): void; /** * 自定义扩展组件,在框架执行扩展之前。例如为每个组件挂在一个实例方法 * * @param componentoption 组件构建选项对象 */ extendComponentBefore?(componentoption: any): void; }; /** * 小程序在切入后台后被唤醒 * * @param time 休眠时间(单位ms) */ onAwake?(time: number): void; } /** 组件实例 */ interface ComponentOption { // TODO: Remove $set?(options: Record<string, any>): void; } } declare namespace WechatMiniprogram { namespace Page { type WXInstance< D extends DataOption, C extends CustomOption> = WXPage.PageInstance & Instance<D, C> type WXOption< D extends DataOption, C extends CustomOption> = Partial<WXPage.PageOption> & ThisType<WXInstance<D, C>> & Options<D, C>; interface WXConstructor { <D extends DataOption, C extends CustomOption>( name: string, options: WXOption<D, C> ): void; } } namespace Component { type WXInstance<D extends DataOption, P extends PropertyOption, M extends MethodOption> = WXPage.ComponentInstance<D> & Instance<D, P, M>; type WXOption<D extends DataOption, P extends PropertyOption, M extends MethodOption> = ThisType<WXInstance<D, P, M>> & Options<D, P, M>; interface WXConstructor { < D extends DataOption, P extends PropertyOption, M extends MethodOption>( options: WXOption<D, P, M> ): string; } } namespace App { type WXInstance<T extends IAnyObject> = Option & T; type WXOption<T extends IAnyObject> = Partial<WXPage.AppOption> & Partial<Option> & T & ThisType<WXInstance<T>>; interface WXConstructor { <T extends IAnyObject>(options: WXOption<T>): void; } interface GetApp { (opts?: GetAppOption): WXInstance<IAnyObject>; } } } declare module 'wxpage' { interface WXPage extends WechatMiniprogram.Page.WXConstructor, WXPage.Emitter { A: WechatMiniprogram.App.WXConstructor; C: WechatMiniprogram.Component.WXConstructor; } const wxpage: WXPage; export default wxpage; }
the_stack
import { ConcreteRequest } from "relay-runtime"; export type BidderPositionInput = { artworkID: string; clientMutationId?: string | null | undefined; maxBidAmountCents: number; saleID: string; }; export type ConfirmBidCreateBidderPositionMutationVariables = { input: BidderPositionInput; }; export type ConfirmBidCreateBidderPositionMutationResponse = { readonly createBidderPosition: { readonly result: { readonly status: string; readonly message_header: string | null; readonly message_description_md: string | null; readonly position: { readonly internalID: string; readonly suggested_next_bid: { readonly cents: number | null; readonly display: string | null; } | null; readonly saleArtwork: { readonly reserveMessage: string | null; readonly currentBid: { readonly display: string | null; } | null; readonly counts: { readonly bidderPositions: number | null; } | null; readonly artwork: { readonly myLotStanding: ReadonlyArray<{ readonly activeBid: { readonly isWinning: boolean | null; } | null; readonly mostRecentBid: { readonly maxBid: { readonly display: string | null; } | null; } | null; }> | null; } | null; } | null; } | null; } | null; } | null; }; export type ConfirmBidCreateBidderPositionMutation = { readonly response: ConfirmBidCreateBidderPositionMutationResponse; readonly variables: ConfirmBidCreateBidderPositionMutationVariables; }; /* mutation ConfirmBidCreateBidderPositionMutation( $input: BidderPositionInput! ) { createBidderPosition(input: $input) { result { status message_header: messageHeader message_description_md: messageDescriptionMD position { internalID suggested_next_bid: suggestedNextBid { cents display } saleArtwork { reserveMessage currentBid { display } counts { bidderPositions } artwork { myLotStanding(live: true) { activeBid { isWinning id } mostRecentBid { maxBid { display } id } } id } id } id } } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "input" } ], v1 = [ { "kind": "Variable", "name": "input", "variableName": "input" } ], v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "status", "storageKey": null }, v3 = { "alias": "message_header", "args": null, "kind": "ScalarField", "name": "messageHeader", "storageKey": null }, v4 = { "alias": "message_description_md", "args": null, "kind": "ScalarField", "name": "messageDescriptionMD", "storageKey": null }, v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null }, v7 = { "alias": "suggested_next_bid", "args": null, "concreteType": "BidderPositionSuggestedNextBid", "kind": "LinkedField", "name": "suggestedNextBid", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "cents", "storageKey": null }, (v6/*: any*/) ], "storageKey": null }, v8 = { "alias": null, "args": null, "kind": "ScalarField", "name": "reserveMessage", "storageKey": null }, v9 = [ (v6/*: any*/) ], v10 = { "alias": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "kind": "LinkedField", "name": "currentBid", "plural": false, "selections": (v9/*: any*/), "storageKey": null }, v11 = { "alias": null, "args": null, "concreteType": "SaleArtworkCounts", "kind": "LinkedField", "name": "counts", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "bidderPositions", "storageKey": null } ], "storageKey": null }, v12 = [ { "kind": "Literal", "name": "live", "value": true } ], v13 = { "alias": null, "args": null, "kind": "ScalarField", "name": "isWinning", "storageKey": null }, v14 = { "alias": null, "args": null, "concreteType": "BidderPositionMaxBid", "kind": "LinkedField", "name": "maxBid", "plural": false, "selections": (v9/*: any*/), "storageKey": null }, v15 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "ConfirmBidCreateBidderPositionMutation", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "BidderPositionPayload", "kind": "LinkedField", "name": "createBidderPosition", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "BidderPositionResult", "kind": "LinkedField", "name": "result", "plural": false, "selections": [ (v2/*: any*/), (v3/*: any*/), (v4/*: any*/), { "alias": null, "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "position", "plural": false, "selections": [ (v5/*: any*/), (v7/*: any*/), { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtwork", "plural": false, "selections": [ (v8/*: any*/), (v10/*: any*/), (v11/*: any*/), { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": (v12/*: any*/), "concreteType": "LotStanding", "kind": "LinkedField", "name": "myLotStanding", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "activeBid", "plural": false, "selections": [ (v13/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "mostRecentBid", "plural": false, "selections": [ (v14/*: any*/) ], "storageKey": null } ], "storageKey": "myLotStanding(live:true)" } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "type": "Mutation", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "ConfirmBidCreateBidderPositionMutation", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "BidderPositionPayload", "kind": "LinkedField", "name": "createBidderPosition", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "BidderPositionResult", "kind": "LinkedField", "name": "result", "plural": false, "selections": [ (v2/*: any*/), (v3/*: any*/), (v4/*: any*/), { "alias": null, "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "position", "plural": false, "selections": [ (v5/*: any*/), (v7/*: any*/), { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtwork", "plural": false, "selections": [ (v8/*: any*/), (v10/*: any*/), (v11/*: any*/), { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": (v12/*: any*/), "concreteType": "LotStanding", "kind": "LinkedField", "name": "myLotStanding", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "activeBid", "plural": false, "selections": [ (v13/*: any*/), (v15/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "mostRecentBid", "plural": false, "selections": [ (v14/*: any*/), (v15/*: any*/) ], "storageKey": null } ], "storageKey": "myLotStanding(live:true)" }, (v15/*: any*/) ], "storageKey": null }, (v15/*: any*/) ], "storageKey": null }, (v15/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ] }, "params": { "id": "f13a1e3f9edab81a2e15f0b2e09aa384", "metadata": {}, "name": "ConfirmBidCreateBidderPositionMutation", "operationKind": "mutation", "text": null } }; })(); (node as any).hash = 'ea8fe1b16086285f4e116fe45d482dd2'; export default node;
the_stack
import { WebPartContext } from "@microsoft/sp-webpart-base"; import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions, IHttpClientOptions, } from '@microsoft/sp-http'; import { ISPList } from '../../interfaces/ISPList'; import { ISPDataSvc } from './ISPDataSvc'; import { ISPWeb } from '../../interfaces/ISPWeb'; import { ISPSite } from '../../interfaces/ISPSite'; import { IHubSitesResponse } from '../../interfaces/IHubSites'; import { ISiteGroup } from "../../interfaces/ISiteGroup"; import { ICacheService, CacheTimeout } from '../CacheService/ICacheService'; import { CacheService } from '../CacheService/CacheService'; export class SPDataSvc implements ISPDataSvc { private _context: WebPartContext; private cachService: ICacheService; constructor(Url: string, context: WebPartContext) { this._context = context; this.cachService = new CacheService(window.sessionStorage); } /************************************************************************************* * Gets Site info to determine if Site is a Hub Site * * @public * @param {string} siteUrl * @memberof SPDataSvc *************************************************************************************/ public GetSiteInfo(siteUrl): Promise<ISPSite> { let errorMsg: string; return new Promise<any>((resolve, reject) => { this._context.spHttpClient.get(`${siteUrl}/_api/site?$select=HubSiteId,Id,IsHubSite,Url,RootWeb/Title,RootWeb/Url&$expand=RootWeb`, SPHttpClient.configurations.v1, { headers: { 'Accept': 'application/json;odata=minimalmetadata', 'odata-version': '' } }) .then((response: SPHttpClientResponse) => { if (response.ok) { response.json() .then((data: ISPSite) => { console.info("Successfully retreived SP Site Info: ", data); // Check if the Url in odata.id contains the Url in the Url Property of the response. // If not, the request was from a subsite. // For display purposes, replace the URL property with the subsite URL from odata.id. // If yes, then keep original URL property. let url: string = data["odata.id"].replace(/\/_api\/site$/g, ''); data.Url = url === data.Url ? data.Url : url; resolve(data); }); } else { // Error message for UI if (response.statusText.trim().length === 0) { errorMsg = `[HTTP] ${response.status}. Failed to retrieve SP Site Info. Please enter a different Site URL or contact your SharePoint Admin.`; } else { errorMsg = `[HTTP] ${response.status} – ${response.statusText}. Failed to retrieve SP Site Info. Please enter a different Site URL or contact your SharePoint Admin.`; } // Error message for console console.error("Failed to retrieve SP Site Info: ", response); reject(errorMsg); } }); }); } /************************************************************************************* * Gets SP Lists for selected Site * * @public * @param {string} siteUrl * @param {boolean} clearCache * @param {boolean} includeDocLibraries * @param {boolean} includeEventLists * @param {boolean} includeCustomLists * @param {boolean} includeSystemLibraries * @memberof SPDataSvc *************************************************************************************/ public GetSPLists(siteUrl: string, clearCache: boolean, includeDocLibraries: boolean, includeEventLists: boolean, includeCustomLists: boolean, includeSystemLibraries: boolean): Promise<ISPList[]> { // Cache Provider const cacheKey = siteUrl.toLowerCase(); // Clear Cache when web part properties have changed if (clearCache) { console.info("Clearing session cache."); return this.cachService.ClearAll() .then((): Promise<ISPList[]> => { return this._getCachedOrLiveSPLists(cacheKey, siteUrl, includeDocLibraries, includeEventLists, includeCustomLists, includeSystemLibraries); }); } else { return this._getCachedOrLiveSPLists(cacheKey, siteUrl, includeDocLibraries, includeEventLists, includeCustomLists, includeSystemLibraries); } } /************************************************************************************* * Gets cached or live SP Lists for selected Site * * @private * @param {string} siteUrl * @param {boolean} includeDocLibraries * @param {boolean} includeEventLists * @param {boolean} includeCustomLists * @param {boolean} includeSystemLibraries * @memberof SPDataSvc *************************************************************************************/ private _getCachedOrLiveSPLists(cacheKey: string, siteUrl: string, includeDocLibraries: boolean, includeEventLists: boolean, includeCustomLists: boolean, includeSystemLibraries: boolean): Promise<ISPList[]> { let errorMsg: string; return new Promise<ISPList[]>((resolve, reject) => { this.cachService.Get(cacheKey) .then((lists: ISPList[]) => { // Get live SP Lists if (!lists) { // Set API Url to filter out lists based on web part properties // IsCatalog eq false: removes Style Library // IsApplicationList eq false: removes Site Pages. Also removes Site Assets (but in Subsites only) // ListItemEntityTypeFullName ne 'SP.Data.FormServerTemplatesItem': removes Form Templates // ListItemEntityTypeFullName ne 'SP.Data.SiteAssetsItem': removes Site Assets let apiEndpoint: string = `${siteUrl}/_api/web/lists?$select=Id,Title,ImageUrl,ItemCount,LastItemModifiedDate,BaseTemplate,ListItemEntityTypeFullName,ParentWebUrl,RootFolder/ServerRelativeUrl&$expand=RootFolder&$filter=(IsPrivate eq false) and (Hidden eq false)`; // 2 Cases: // Do not include System Libraries, include Doc Libraries // Do not include System Libraries, do not include Doc Libraries if (!includeSystemLibraries && !includeDocLibraries) { apiEndpoint = `${apiEndpoint} and (IsCatalog eq false) and (IsApplicationList eq false) and (ListItemEntityTypeFullName ne 'SP.Data.FormServerTemplatesItem') and (ListItemEntityTypeFullName ne 'SP.Data.SiteAssetsItem') and (BaseTemplate ne 101)`; } else if (!includeSystemLibraries && includeDocLibraries) { apiEndpoint = `${apiEndpoint} and (IsCatalog eq false) and (IsApplicationList eq false) and (ListItemEntityTypeFullName ne 'SP.Data.FormServerTemplatesItem') and (ListItemEntityTypeFullName ne 'SP.Data.SiteAssetsItem')`; } if (!includeEventLists) { apiEndpoint = `${apiEndpoint} and (BaseTemplate ne 106)`; } if (!includeCustomLists) { apiEndpoint = `${apiEndpoint} and (BaseTemplate ne 100)`; } this._context.spHttpClient.get( apiEndpoint, SPHttpClient.configurations.v1, { headers: { 'Accept': 'application/json;odata=nometadata', 'odata-version': '' } }) .then((response: SPHttpClientResponse) => { if (response.ok) { response.json() .then((data: { value: ISPList[] }) => { console.info("Successfully retreived SP Lists: ", data); // Set SP lists to cache this.cachService.Set(cacheKey, data.value, CacheTimeout.default) .then((didSet: boolean) => { console.log("Set lists to Cache: ", didSet); resolve(data.value); }); }); } else { console.error("Failed to retrieve lists: ", response); // Error message for UI if (response.statusText.trim().length === 0) { errorMsg = `[HTTP] ${response.status}. Failed to retrieve Lists. Please enter a different Site URL or contact your SharePoint Admin.`; } else { errorMsg = `[HTTP] ${response.status} – ${response.statusText}. Failed to retrieve Lists. Please enter a different Site URL or contact your SharePoint Admin.`; } reject(errorMsg); } }); // Get Cached SP Lists } else { console.info('Successfully retreived SP Lists from Cache: ', lists); resolve(lists); } }); }); } /************************************************************************************* * Gets SP Lists for Hub Site and all associated sites * * @public * @param {ISiteGroup[]} sites * @param {boolean} includeDocLibraries * @param {boolean} includeEventLists * @param {boolean} includeCustomLists * @param {boolean} includeSystemLibraries * @memberof SPDataSvc *************************************************************************************/ public GetSPListsBatch(sites: ISiteGroup[], includeDocLibraries: boolean, includeEventLists: boolean, includeCustomLists: boolean, includeSystemLibraries: boolean): Promise<ISPList[][]> { // Set API Url to filter out lists based on web part properties let apiUrl: string = "_api/web/lists?$select=Id,Title,ImageUrl,ItemCount,LastItemModifiedDate,BaseTemplate,ListItemEntityTypeFullName,ParentWebUrl,RootFolder/ServerRelativeUrl&$expand=RootFolder&$filter=(IsPrivate eq false) and (Hidden eq false)"; // 2 Cases: // Do not include System Libraries, Include Doc Libraries // Do not include System Libraries, Do Not Include Doc Libraries if (!includeSystemLibraries && !includeDocLibraries) { apiUrl = `${apiUrl} and (IsCatalog eq false) and (IsApplicationList eq false) and (ListItemEntityTypeFullName ne 'SP.Data.FormServerTemplatesItem') and (ListItemEntityTypeFullName ne 'SP.Data.SiteAssetsItem') and (BaseTemplate ne 101)`; } else if (!includeSystemLibraries && includeDocLibraries) { apiUrl = `${apiUrl} and (IsCatalog eq false) and (IsApplicationList eq false) and (ListItemEntityTypeFullName ne 'SP.Data.FormServerTemplatesItem') and (ListItemEntityTypeFullName ne 'SP.Data.SiteAssetsItem')`; } if (!includeEventLists) { apiUrl = `${apiUrl} and (BaseTemplate ne 106)`; } if (!includeCustomLists) { apiUrl = `${apiUrl} and (BaseTemplate ne 100)`; } return new Promise<any>((resolve, reject) => { // Array of promises to retrieve SP Lists from hub site and associated sites const PromiseArray: Promise<ISPList[]>[] = sites.map((site: ISiteGroup): Promise<ISPList[]> => { // Promise for retrieving SP Lists from site return new Promise<ISPList[]>((resolveListRequest, rejectListRequest) => { const apiEndpoint: string = `${site.key}/${apiUrl}`; let errorMsg: string; this._context.spHttpClient.get( apiEndpoint, SPHttpClient.configurations.v1, { headers: { 'Accept': 'application/json;odata=nometadata', 'odata-version': '' } }) .then((response: SPHttpClientResponse) => { if (response.ok) { response.json() .then((data: { value: ISPList[] }) => { console.info("Successfully retreived SP Lists: ", data); resolveListRequest(data.value); }); } else { console.error("Failed to retrieve lists: ", response); // Error message for UI if (response.statusText.trim().length === 0) { errorMsg = `[HTTP] ${response.status}. Failed to retrieve Lists. Please enter a different Site URL or contact your SharePoint Admin.`; } else { errorMsg = `[HTTP] ${response.status} – ${response.statusText}. Failed to retrieve Lists. Please enter a different Site URL or contact your SharePoint Admin.`; } rejectListRequest(errorMsg); } }); }); }); // Execute all promises Promise.all(PromiseArray) .then((data: ISPList[][]) => { console.info("Succesfully retrieved SP Lists in batch: ", data); resolve(data); }) .catch((error: any) => { // TODO: handle batch error reject(error); }); }); } /************************************************************************************* * Gets all Subsites for selected site * * @public * @param {string} siteUrl * @memberof SPDataSvc *************************************************************************************/ public GetSPSubSites(siteUrl: string): Promise<ISPWeb[]> { let errorMsg: string; return new Promise<any>((resolve, reject) => { this._context.spHttpClient.get(`${siteUrl}/_api/web/webinfos?$select=Id,ServerRelativeUrl,Title`, SPHttpClient.configurations.v1, { headers: { 'Accept': 'application/json;odata=nometadata', 'odata-version': '' } }) .then((response: SPHttpClientResponse) => { if (response.ok) { response.json() .then((data: { value: ISPWeb[] }) => { console.info("Succesfully retreived SP Subsites: ", data); resolve(data.value); }); } else { console.error("Failed to retrieve SP Subsites: ", response); // Error message for UI if (response.statusText.trim().length === 0) { errorMsg = `[HTTP] ${response.status}. Please try a different Site URL or contact your SharePoint Admin.`; } else { errorMsg = `[HTTP] ${response.status} – ${response.statusText}`; } reject(errorMsg); } }); }); } /************************************************************************************* * Gets Hub API Auth Token to call SharePoint Home Service API * * @private * @param {string} hubSiteUrl * @memberof SPDataSvc *************************************************************************************/ private _getHubApiToken(hubSiteUrl: string): Promise<any> { let errorMsg: string; return new Promise<any>((resolve, reject) => { const restQuery = `${hubSiteUrl}/_api/sphomeservice/context?$expand=Token,Payload`; const httpClientOptions: ISPHttpClientOptions = {}; this._context.spHttpClient.fetch(restQuery, SPHttpClient.configurations.v1, httpClientOptions) .then((response: SPHttpClientResponse) => { if (response.ok) { response.json() .then((data: any) => { console.info("Successfully retrieved Hub API Token"); // Improvement: Grab the Hub api URL from: responseJson.Urls resolve(data); }); } else { console.error("Failed to retrieve Hub API Token: ", response); // Error message for UI if (response.statusText.trim().length === 0) { errorMsg = `[HTTP] ${response.status}. Failed to retrieve Hub API Token.`; } else { errorMsg = `[HTTP] ${response.status} – ${response.statusText}. Failed to retrieve Hub API Token`; } reject(errorMsg); } }); }); } /************************************************************************************* * Gets the following (in no particular order): Hubsite, Child hubsites, and subsites of the Child hubsite * * @private * @param {string} hubUrl * @param {string} hubId * @memberof SPDataSvc *************************************************************************************/ public GetAssociatedHubSites(hubUrl: string, hubId: string): Promise<IHubSitesResponse> { let errorMsg: string; return new Promise<IHubSitesResponse>((resolve, reject) => { this._getHubApiToken(hubUrl) .then((token: any) => { // count limit set to 100, this could be a limiting factor const restQuery = `${token.Token.resource}/api/v1/sites/hub/feed?departmentId=${hubId}&acronyms=true&start=0&count=100`; const httpClientOptions: IHttpClientOptions = { headers: { 'authorization': `Bearer ${token.Token.access_token}`, 'sphome-apicontext': token.Payload } }; this._context.httpClient.fetch(restQuery, SPHttpClient.configurations.v1, httpClientOptions) .then((response: SPHttpClientResponse) => { if (response.ok) { response.json() .then((responseJson: IHubSitesResponse) => { console.info("Successfully retrieved Hubsites, child hubsites, and their subsites: ", responseJson); resolve(responseJson); }); } else { console.error("Failed to retrieve Hubsites from SharePoint Home Service API: ", response); // Error message for UI if (response.statusText.trim().length === 0) { errorMsg = `[HTTP] ${response.status}. Failed to retrieve Hubsites and Child hubsites.`; } else { errorMsg = `[HTTP] ${response.status} – ${response.statusText}. Failed to retrieve Hubsites and Child hubsites.`; } reject(errorMsg); } }); }) .catch((tokenErrorMsg: string) => { // TODO: handle Auth Token failure reject(tokenErrorMsg); }); }); } }
the_stack
import '../../../test/common-test-setup-karma'; import './gr-repo-access'; import {GrRepoAccess} from './gr-repo-access'; import {GerritNav} from '../../core/gr-navigation/gr-navigation'; import {toSortedPermissionsArray} from '../../../utils/access-util'; import { addListenerForTest, mockPromise, queryAll, queryAndAssert, stubRestApi, } from '../../../test/test-utils'; import { ChangeInfo, GitRef, RepoName, UrlEncodedRepoName, } from '../../../types/common'; import {PermissionAction} from '../../../constants/constants'; import {PageErrorEvent} from '../../../types/events'; import {GrButton} from '../../shared/gr-button/gr-button'; import { AutocompleteCommitEvent, GrAutocomplete, } from '../../shared/gr-autocomplete/gr-autocomplete'; import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions'; import {GrAccessSection} from '../gr-access-section/gr-access-section'; import {GrPermission} from '../gr-permission/gr-permission'; import {createChange} from '../../../test/test-data-generators'; const basicFixture = fixtureFromElement('gr-repo-access'); suite('gr-repo-access tests', () => { let element: GrRepoAccess; let repoStub: sinon.SinonStub; const accessRes = { local: { 'refs/*': { permissions: { owner: { rules: { 234: {action: PermissionAction.ALLOW}, 123: {action: PermissionAction.DENY}, }, }, read: { rules: { 234: {action: PermissionAction.ALLOW}, }, }, }, }, }, groups: { Administrators: { name: 'Administrators', }, Maintainers: { name: 'Maintainers', }, }, config_web_links: [ { name: 'gitiles', target: '_blank', url: 'https://my/site/+log/123/project.config', }, ], can_upload: true, }; const accessRes2 = { local: { GLOBAL_CAPABILITIES: { permissions: { accessDatabase: { rules: { group1: { action: PermissionAction.ALLOW, }, }, }, }, }, }, }; const repoRes = { id: '' as UrlEncodedRepoName, labels: { 'Code-Review': { values: { '0': 'No score', '-1': 'I would prefer this is not merged as is', '-2': 'This shall not be merged', '+1': 'Looks good to me, but someone else must approve', '+2': 'Looks good to me, approved', }, default_value: 0, }, }, }; const capabilitiesRes = { accessDatabase: { id: 'accessDatabase', name: 'Access Database', }, createAccount: { id: 'createAccount', name: 'Create Account', }, }; setup(async () => { element = basicFixture.instantiate(); stubRestApi('getAccount').returns(Promise.resolve(undefined)); repoStub = stubRestApi('getRepo').returns(Promise.resolve(repoRes)); element._loading = false; element._ownerOf = []; element._canUpload = false; await flush(); }); test('_repoChanged called when repo name changes', async () => { const repoChangedStub = sinon.stub(element, '_repoChanged'); element.repo = 'New Repo' as RepoName; await flush(); assert.isTrue(repoChangedStub.called); }); test('_repoChanged', async () => { const accessStub = stubRestApi('getRepoAccessRights'); accessStub .withArgs('New Repo' as RepoName) .returns(Promise.resolve(JSON.parse(JSON.stringify(accessRes)))); accessStub .withArgs('Another New Repo' as RepoName) .returns(Promise.resolve(JSON.parse(JSON.stringify(accessRes2)))); const capabilitiesStub = stubRestApi('getCapabilities'); capabilitiesStub.returns(Promise.resolve(capabilitiesRes)); await element._repoChanged('New Repo' as RepoName); assert.isTrue(accessStub.called); assert.isTrue(capabilitiesStub.called); assert.isTrue(repoStub.called); assert.isNotOk(element._inheritsFrom); assert.deepEqual(element._local, accessRes.local); assert.deepEqual( element._sections, toSortedPermissionsArray(accessRes.local) ); assert.deepEqual(element._labels, repoRes.labels); assert.equal( getComputedStyle(queryAndAssert<HTMLDivElement>(element, '.weblinks')) .display, 'block' ); await element._repoChanged('Another New Repo' as RepoName); assert.deepEqual( element._sections, toSortedPermissionsArray(accessRes2.local) ); assert.equal( getComputedStyle(queryAndAssert<HTMLDivElement>(element, '.weblinks')) .display, 'none' ); }); test('_repoChanged when repo changes to undefined returns', async () => { const capabilitiesRes = { accessDatabase: { id: 'accessDatabase', name: 'Access Database', }, }; const accessStub = stubRestApi('getRepoAccessRights').returns( Promise.resolve(JSON.parse(JSON.stringify(accessRes2))) ); const capabilitiesStub = stubRestApi('getCapabilities').returns( Promise.resolve(capabilitiesRes) ); await element._repoChanged(); assert.isFalse(accessStub.called); assert.isFalse(capabilitiesStub.called); assert.isFalse(repoStub.called); }); test('_computeParentHref', () => { assert.equal( element._computeParentHref('test-repo' as RepoName), '/admin/repos/test-repo,access' ); }); test('_computeMainClass', () => { let ownerOf = ['refs/*'] as GitRef[]; const editing = true; const canUpload = false; assert.equal(element._computeMainClass(ownerOf, canUpload, false), 'admin'); assert.equal( element._computeMainClass(ownerOf, canUpload, editing), 'admin editing' ); ownerOf = []; assert.equal(element._computeMainClass(ownerOf, canUpload, false), ''); assert.equal( element._computeMainClass(ownerOf, canUpload, editing), 'editing' ); }); test('inherit section', async () => { element._local = {}; element._ownerOf = []; const computeParentHrefStub = sinon.stub(element, '_computeParentHref'); await flush(); // Nothing should appear when no inherit from and not in edit mode. assert.equal(getComputedStyle(element.$.inheritsFrom).display, 'none'); // The autocomplete should be hidden, and the link should be displayed. assert.isFalse(computeParentHrefStub.called); // When in edit mode, the autocomplete should appear. element._editing = true; // When editing, the autocomplete should still not be shown. assert.equal(getComputedStyle(element.$.inheritsFrom).display, 'none'); element._editing = false; element._inheritsFrom = { id: '1234' as UrlEncodedRepoName, name: 'another-repo' as RepoName, }; await flush(); // When there is a parent project, the link should be displayed. assert.notEqual(getComputedStyle(element.$.inheritsFrom).display, 'none'); assert.notEqual( getComputedStyle(element.$.inheritFromName).display, 'none' ); assert.equal( getComputedStyle( queryAndAssert<GrAutocomplete>(element, '#editInheritFromInput') ).display, 'none' ); assert.isTrue(computeParentHrefStub.called); element._editing = true; // When editing, the autocomplete should be shown. assert.notEqual(getComputedStyle(element.$.inheritsFrom).display, 'none'); assert.equal(getComputedStyle(element.$.inheritFromName).display, 'none'); assert.notEqual( getComputedStyle( queryAndAssert<GrAutocomplete>(element, '#editInheritFromInput') ).display, 'none' ); }); test('_handleUpdateInheritFrom', async () => { element._inheritFromFilter = 'foo bar baz' as RepoName; element._handleUpdateInheritFrom({ detail: {value: 'abc+123'}, } as CustomEvent); await flush(); assert.isOk(element._inheritsFrom); assert.equal(element._inheritsFrom!.id, 'abc+123'); assert.equal(element._inheritsFrom!.name, 'foo bar baz' as RepoName); }); test('_computeLoadingClass', () => { assert.equal(element._computeLoadingClass(true), 'loading'); assert.equal(element._computeLoadingClass(false), ''); }); test('fires page-error', async () => { const response = {status: 404} as Response; stubRestApi('getRepoAccessRights').callsFake((_repoName, errFn) => { if (errFn !== undefined) { errFn(response); } return Promise.resolve(undefined); }); const promise = mockPromise(); addListenerForTest(document, 'page-error', e => { assert.deepEqual((e as PageErrorEvent).detail.response, response); promise.resolve(); }); element.repo = 'test' as RepoName; await promise; }); suite('with defined sections', () => { const testEditSaveCancelBtns = async ( shouldShowSave: boolean, shouldShowSaveReview: boolean ) => { // Edit button is visible and Save button is hidden. assert.equal( getComputedStyle(queryAndAssert<GrButton>(element, '#saveReviewBtn')) .display, 'none' ); assert.equal( getComputedStyle(queryAndAssert<GrButton>(element, '#saveBtn')).display, 'none' ); assert.notEqual( getComputedStyle(queryAndAssert<GrButton>(element, '#editBtn')).display, 'none' ); assert.equal( queryAndAssert<GrButton>(element, '#editBtn').innerText, 'EDIT' ); assert.equal( getComputedStyle( queryAndAssert<GrAutocomplete>(element, '#editInheritFromInput') ).display, 'none' ); element._inheritsFrom = { id: 'test-project' as UrlEncodedRepoName, }; await flush(); assert.equal( getComputedStyle( queryAndAssert<GrAutocomplete>(element, '#editInheritFromInput') ).display, 'none' ); MockInteractions.tap(queryAndAssert<GrButton>(element, '#editBtn')); await flush(); // Edit button changes to Cancel button, and Save button is visible but // disabled. assert.equal( queryAndAssert<GrButton>(element, '#editBtn').innerText, 'CANCEL' ); if (shouldShowSaveReview) { assert.notEqual( getComputedStyle(queryAndAssert<GrButton>(element, '#saveReviewBtn')) .display, 'none' ); assert.isTrue( queryAndAssert<GrButton>(element, '#saveReviewBtn').disabled ); } if (shouldShowSave) { assert.notEqual( getComputedStyle(queryAndAssert<GrButton>(element, '#saveBtn')) .display, 'none' ); assert.isTrue(queryAndAssert<GrButton>(element, '#saveBtn').disabled); } assert.notEqual( getComputedStyle( queryAndAssert<GrAutocomplete>(element, '#editInheritFromInput') ).display, 'none' ); // Save button should be enabled after access is modified element.dispatchEvent( new CustomEvent('access-modified', { composed: true, bubbles: true, }) ); if (shouldShowSaveReview) { assert.isFalse( queryAndAssert<GrButton>(element, '#saveReviewBtn').disabled ); } if (shouldShowSave) { assert.isFalse(queryAndAssert<GrButton>(element, '#saveBtn').disabled); } }; setup(async () => { // Create deep copies of these objects so the originals are not modified // by any tests. element._local = JSON.parse(JSON.stringify(accessRes.local)); element._ownerOf = []; element._sections = toSortedPermissionsArray(element._local); element._groups = JSON.parse(JSON.stringify(accessRes.groups)); element._capabilities = JSON.parse(JSON.stringify(capabilitiesRes)); element._labels = JSON.parse(JSON.stringify(repoRes.labels)); await flush(); }); test('removing an added section', async () => { element._editing = true; await flush(); assert.equal(element._sections!.length, 1); queryAndAssert<GrAccessSection>( element, 'gr-access-section' ).dispatchEvent( new CustomEvent('added-section-removed', { composed: true, bubbles: true, }) ); await flush(); assert.equal(element._sections!.length, 0); }); test('button visibility for non ref owner', () => { assert.equal(getComputedStyle(element.$.saveReviewBtn).display, 'none'); assert.equal(getComputedStyle(element.$.editBtn).display, 'none'); }); test('button visibility for non ref owner with upload privilege', async () => { element._canUpload = true; await flush(); testEditSaveCancelBtns(false, true); }); test('button visibility for ref owner', async () => { element._ownerOf = ['refs/for/*'] as GitRef[]; await flush(); testEditSaveCancelBtns(true, false); }); test('button visibility for ref owner and upload', async () => { element._ownerOf = ['refs/for/*'] as GitRef[]; element._canUpload = true; await flush(); testEditSaveCancelBtns(true, false); }); test('_handleAccessModified called with event fired', async () => { const handleAccessModifiedSpy = sinon.spy( element, '_handleAccessModified' ); element.dispatchEvent( new CustomEvent('access-modified', { composed: true, bubbles: true, }) ); await flush(); assert.isTrue(handleAccessModifiedSpy.called); }); test('_handleAccessModified called when parent changes', async () => { element._inheritsFrom = { id: 'test-project' as UrlEncodedRepoName, }; await flush(); queryAndAssert<GrAutocomplete>( element, '#editInheritFromInput' ).dispatchEvent( new CustomEvent('commit', { detail: {}, composed: true, bubbles: true, }) ); const handleAccessModifiedSpy = sinon.spy( element, '_handleAccessModified' ); element.dispatchEvent( new CustomEvent('access-modified', { detail: {}, composed: true, bubbles: true, }) ); await flush(); assert.isTrue(handleAccessModifiedSpy.called); }); test('_handleSaveForReview', async () => { const saveStub = stubRestApi('setRepoAccessRightsForReview'); sinon.stub(element, '_computeAddAndRemove').returns({ add: {}, remove: {}, }); element._handleSaveForReview(new Event('test')); await flush(); assert.isFalse(saveStub.called); }); test('_recursivelyRemoveDeleted', () => { const obj = { 'refs/*': { permissions: { owner: { rules: { 234: {action: 'ALLOW'}, 123: {action: 'DENY', deleted: true}, }, }, read: { deleted: true, rules: { 234: {action: 'ALLOW'}, }, }, }, }, }; const expectedResult = { 'refs/*': { permissions: { owner: { rules: { 234: {action: 'ALLOW'}, }, }, }, }, }; element._recursivelyRemoveDeleted(obj); assert.deepEqual(obj, expectedResult); }); test('_recursivelyUpdateAddRemoveObj on new added section', () => { const obj = { 'refs/for/*': { permissions: { 'label-Code-Review': { rules: { e798fed07afbc9173a587f876ef8760c78d240c1: { min: -2, max: 2, action: 'ALLOW', added: true, }, }, added: true, label: 'Code-Review', }, 'labelAs-Code-Review': { rules: { 'ldap:gerritcodereview-eng': { min: -2, max: 2, action: 'ALLOW', added: true, deleted: true, }, }, added: true, label: 'Code-Review', }, }, added: true, }, }; const expectedResult = { add: { 'refs/for/*': { permissions: { 'label-Code-Review': { rules: { e798fed07afbc9173a587f876ef8760c78d240c1: { min: -2, max: 2, action: 'ALLOW', added: true, }, }, added: true, label: 'Code-Review', }, 'labelAs-Code-Review': { rules: {}, added: true, label: 'Code-Review', }, }, added: true, }, }, remove: {}, }; const updateObj = {add: {}, remove: {}}; element._recursivelyUpdateAddRemoveObj(obj, updateObj); assert.deepEqual(updateObj, expectedResult); }); test('_handleSaveForReview with no changes', () => { assert.deepEqual(element._computeAddAndRemove(), {add: {}, remove: {}}); }); test('_handleSaveForReview parent change', async () => { element._inheritsFrom = { id: 'test-project' as UrlEncodedRepoName, }; element.originalInheritsFrom = { id: 'test-project-original' as UrlEncodedRepoName, }; await flush(); assert.deepEqual(element._computeAddAndRemove(), { parent: 'test-project', add: {}, remove: {}, }); }); test('_handleSaveForReview new parent with spaces', async () => { element._inheritsFrom = { id: 'spaces+in+project+name' as UrlEncodedRepoName, }; element.originalInheritsFrom = {id: 'old-project' as UrlEncodedRepoName}; await flush(); assert.deepEqual(element._computeAddAndRemove(), { parent: 'spaces in project name', add: {}, remove: {}, }); }); test('_handleSaveForReview rules', async () => { // Delete a rule. element._local!['refs/*'].permissions.owner.rules[123].deleted = true; await flush(); let expectedInput = { add: {}, remove: { 'refs/*': { permissions: { owner: { rules: { 123: {}, }, }, }, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Undo deleting a rule. delete element._local!['refs/*'].permissions.owner.rules[123].deleted; // Modify a rule. element._local!['refs/*'].permissions.owner.rules[123].modified = true; await flush(); expectedInput = { add: { 'refs/*': { permissions: { owner: { rules: { 123: {action: 'DENY', modified: true}, }, }, }, }, }, remove: { 'refs/*': { permissions: { owner: { rules: { 123: {}, }, }, }, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); }); test('_computeAddAndRemove permissions', async () => { // Add a new rule to a permission. let expectedInput = {}; expectedInput = { add: { 'refs/*': { permissions: { owner: { rules: { Maintainers: { action: 'ALLOW', added: true, }, }, }, }, }, }, remove: {}, }; const grAccessSection = queryAndAssert<GrAccessSection>( element, 'gr-access-section' ); queryAndAssert<GrPermission>( grAccessSection, 'gr-permission' )._handleAddRuleItem({ detail: {value: 'Maintainers'}, } as AutocompleteCommitEvent); await flush(); assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Remove the added rule. delete element._local!['refs/*'].permissions.owner.rules.Maintainers; // Delete a permission. element._local!['refs/*'].permissions.owner.deleted = true; await flush(); expectedInput = { add: {}, remove: { 'refs/*': { permissions: { owner: {rules: {}}, }, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Undo delete permission. delete element._local!['refs/*'].permissions.owner.deleted; // Modify a permission. element._local!['refs/*'].permissions.owner.modified = true; await flush(); expectedInput = { add: { 'refs/*': { permissions: { owner: { modified: true, rules: { 234: {action: 'ALLOW'}, 123: {action: 'DENY'}, }, }, }, }, }, remove: { 'refs/*': { permissions: { owner: {rules: {}}, }, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); }); test('_computeAddAndRemove sections', async () => { // Add a new permission to a section let expectedInput = {}; expectedInput = { add: { 'refs/*': { permissions: { 'label-Code-Review': { added: true, rules: {}, label: 'Code-Review', }, }, }, }, remove: {}, }; queryAndAssert<GrAccessSection>( element, 'gr-access-section' )._handleAddPermission(); await flush(); assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Add a new rule to the new permission. expectedInput = { add: { 'refs/*': { permissions: { 'label-Code-Review': { added: true, rules: { Maintainers: { min: -2, max: 2, action: 'ALLOW', added: true, }, }, label: 'Code-Review', }, }, }, }, remove: {}, }; const grAccessSection = queryAndAssert<GrAccessSection>( element, 'gr-access-section' ); const newPermission = queryAll<GrPermission>( grAccessSection, 'gr-permission' )[2]; newPermission._handleAddRuleItem({ detail: {value: 'Maintainers'}, } as AutocompleteCommitEvent); await flush(); assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Modify a section reference. element._local!['refs/*'].updatedId = 'refs/for/bar'; element._local!['refs/*'].modified = true; await flush(); expectedInput = { add: { 'refs/for/bar': { modified: true, updatedId: 'refs/for/bar', permissions: { owner: { rules: { 234: {action: 'ALLOW'}, 123: {action: 'DENY'}, }, }, read: { rules: { 234: {action: 'ALLOW'}, }, }, 'label-Code-Review': { added: true, rules: { Maintainers: { min: -2, max: 2, action: 'ALLOW', added: true, }, }, label: 'Code-Review', }, }, }, }, remove: { 'refs/*': { permissions: {}, }, }, }; await flush(); assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Delete a section. element._local!['refs/*'].deleted = true; await flush(); expectedInput = { add: {}, remove: { 'refs/*': { permissions: {}, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); }); test('_computeAddAndRemove new section', async () => { // Add a new permission to a section let expectedInput = {}; expectedInput = { add: { 'refs/for/*': { added: true, permissions: {}, }, }, remove: {}, }; MockInteractions.tap(element.$.addReferenceBtn); await flush(); assert.deepEqual(element._computeAddAndRemove(), expectedInput); expectedInput = { add: { 'refs/for/*': { added: true, permissions: { 'label-Code-Review': { added: true, rules: {}, label: 'Code-Review', }, }, }, }, remove: {}, }; const newSection = queryAll<GrAccessSection>( element, 'gr-access-section' )[1]; newSection._handleAddPermission(); await flush(); assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Add rule to the new permission. expectedInput = { add: { 'refs/for/*': { added: true, permissions: { 'label-Code-Review': { added: true, rules: { Maintainers: { action: 'ALLOW', added: true, max: 2, min: -2, }, }, label: 'Code-Review', }, }, }, }, remove: {}, }; queryAndAssert<GrPermission>( newSection, 'gr-permission' )._handleAddRuleItem({ detail: {value: 'Maintainers'}, } as AutocompleteCommitEvent); await flush(); assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Modify a the reference from the default value. element._local!['refs/for/*'].updatedId = 'refs/for/new'; await flush(); expectedInput = { add: { 'refs/for/new': { added: true, updatedId: 'refs/for/new', permissions: { 'label-Code-Review': { added: true, rules: { Maintainers: { action: 'ALLOW', added: true, max: 2, min: -2, }, }, label: 'Code-Review', }, }, }, }, remove: {}, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); }); test('_computeAddAndRemove combinations', async () => { // Modify rule and delete permission that it is inside of. element._local!['refs/*'].permissions.owner.rules[123].modified = true; element._local!['refs/*'].permissions.owner.deleted = true; await flush(); let expectedInput = {}; expectedInput = { add: {}, remove: { 'refs/*': { permissions: { owner: {rules: {}}, }, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Delete rule and delete permission that it is inside of. element._local!['refs/*'].permissions.owner.rules[123].modified = false; element._local!['refs/*'].permissions.owner.rules[123].deleted = true; await flush(); assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Also modify a different rule inside of another permission. element._local!['refs/*'].permissions.read.modified = true; await flush(); expectedInput = { add: { 'refs/*': { permissions: { read: { modified: true, rules: { 234: {action: 'ALLOW'}, }, }, }, }, }, remove: { 'refs/*': { permissions: { owner: {rules: {}}, read: {rules: {}}, }, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Modify both permissions with an exclusive bit. Owner is still // deleted. element._local!['refs/*'].permissions.owner.exclusive = true; element._local!['refs/*'].permissions.owner.modified = true; element._local!['refs/*'].permissions.read.exclusive = true; element._local!['refs/*'].permissions.read.modified = true; await flush(); expectedInput = { add: { 'refs/*': { permissions: { read: { exclusive: true, modified: true, rules: { 234: {action: 'ALLOW'}, }, }, }, }, }, remove: { 'refs/*': { permissions: { owner: {rules: {}}, read: {rules: {}}, }, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Add a rule to the existing permission; const grAccessSection = queryAndAssert<GrAccessSection>( element, 'gr-access-section' ); const readPermission = queryAll<GrPermission>( grAccessSection, 'gr-permission' )[1]; readPermission._handleAddRuleItem({ detail: {value: 'Maintainers'}, } as AutocompleteCommitEvent); await flush(); expectedInput = { add: { 'refs/*': { permissions: { read: { exclusive: true, modified: true, rules: { 234: {action: 'ALLOW'}, Maintainers: {action: 'ALLOW', added: true}, }, }, }, }, }, remove: { 'refs/*': { permissions: { owner: {rules: {}}, read: {rules: {}}, }, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Change one of the refs element._local!['refs/*'].updatedId = 'refs/for/bar'; element._local!['refs/*'].modified = true; await flush(); expectedInput = { add: { 'refs/for/bar': { modified: true, updatedId: 'refs/for/bar', permissions: { read: { exclusive: true, modified: true, rules: { 234: {action: 'ALLOW'}, Maintainers: {action: 'ALLOW', added: true}, }, }, }, }, }, remove: { 'refs/*': { permissions: {}, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); expectedInput = { add: {}, remove: { 'refs/*': { permissions: {}, }, }, }; element._local!['refs/*'].deleted = true; await flush(); assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Add a new section. MockInteractions.tap(element.$.addReferenceBtn); let newSection = queryAll<GrAccessSection>( element, 'gr-access-section' )[1]; newSection._handleAddPermission(); await flush(); queryAndAssert<GrPermission>( newSection, 'gr-permission' )._handleAddRuleItem({ detail: {value: 'Maintainers'}, } as AutocompleteCommitEvent); // Modify a the reference from the default value. element._local!['refs/for/*'].updatedId = 'refs/for/new'; await flush(); expectedInput = { add: { 'refs/for/new': { added: true, updatedId: 'refs/for/new', permissions: { 'label-Code-Review': { added: true, rules: { Maintainers: { action: 'ALLOW', added: true, max: 2, min: -2, }, }, label: 'Code-Review', }, }, }, }, remove: { 'refs/*': { permissions: {}, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Modify newly added rule inside new ref. element._local!['refs/for/*'].permissions['label-Code-Review'].rules[ 'Maintainers' ].modified = true; await flush(); expectedInput = { add: { 'refs/for/new': { added: true, updatedId: 'refs/for/new', permissions: { 'label-Code-Review': { added: true, rules: { Maintainers: { action: 'ALLOW', added: true, modified: true, max: 2, min: -2, }, }, label: 'Code-Review', }, }, }, }, remove: { 'refs/*': { permissions: {}, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); // Add a second new section. MockInteractions.tap(element.$.addReferenceBtn); await flush(); newSection = queryAll<GrAccessSection>(element, 'gr-access-section')[2]; newSection._handleAddPermission(); await flush(); queryAndAssert<GrPermission>( newSection, 'gr-permission' )._handleAddRuleItem({ detail: {value: 'Maintainers'}, } as AutocompleteCommitEvent); // Modify a the reference from the default value. element._local!['refs/for/**'].updatedId = 'refs/for/new2'; await flush(); expectedInput = { add: { 'refs/for/new': { added: true, updatedId: 'refs/for/new', permissions: { 'label-Code-Review': { added: true, rules: { Maintainers: { action: 'ALLOW', added: true, modified: true, max: 2, min: -2, }, }, label: 'Code-Review', }, }, }, 'refs/for/new2': { added: true, updatedId: 'refs/for/new2', permissions: { 'label-Code-Review': { added: true, rules: { Maintainers: { action: 'ALLOW', added: true, max: 2, min: -2, }, }, label: 'Code-Review', }, }, }, }, remove: { 'refs/*': { permissions: {}, }, }, }; assert.deepEqual(element._computeAddAndRemove(), expectedInput); }); test('Unsaved added refs are discarded when edit cancelled', async () => { // Unsaved changes are discarded when editing is cancelled. MockInteractions.tap(element.$.editBtn); await flush(); assert.equal(element._sections!.length, 1); assert.equal(Object.keys(element._local!).length, 1); MockInteractions.tap(element.$.addReferenceBtn); await flush(); assert.equal(element._sections!.length, 2); assert.equal(Object.keys(element._local!).length, 2); MockInteractions.tap(element.$.editBtn); await flush(); assert.equal(element._sections!.length, 1); assert.equal(Object.keys(element._local!).length, 1); }); test('_handleSave', async () => { const repoAccessInput = { add: { 'refs/*': { permissions: { owner: { rules: { 123: {action: 'DENY', modified: true}, }, }, }, }, }, remove: { 'refs/*': { permissions: { owner: { rules: { 123: {}, }, }, }, }, }, }; stubRestApi('getRepoAccessRights').returns( Promise.resolve(JSON.parse(JSON.stringify(accessRes))) ); const navigateToChangeStub = sinon.stub(GerritNav, 'navigateToChange'); let resolver: (value: Response | PromiseLike<Response>) => void; const saveStub = stubRestApi('setRepoAccessRights').returns( new Promise(r => (resolver = r)) ); element.repo = 'test-repo' as RepoName; sinon.stub(element, '_computeAddAndRemove').returns(repoAccessInput); element._modified = true; MockInteractions.tap(element.$.saveBtn); await flush(); assert.equal(element.$.saveBtn.hasAttribute('loading'), true); resolver!({status: 200} as Response); await flush(); assert.isTrue(saveStub.called); assert.isTrue(navigateToChangeStub.notCalled); }); test('_handleSaveForReview', async () => { const repoAccessInput = { add: { 'refs/*': { permissions: { owner: { rules: { 123: {action: 'DENY', modified: true}, }, }, }, }, }, remove: { 'refs/*': { permissions: { owner: { rules: { 123: {}, }, }, }, }, }, }; stubRestApi('getRepoAccessRights').returns( Promise.resolve(JSON.parse(JSON.stringify(accessRes))) ); const navigateToChangeStub = sinon.stub(GerritNav, 'navigateToChange'); let resolver: (value: ChangeInfo | PromiseLike<ChangeInfo>) => void; const saveForReviewStub = stubRestApi( 'setRepoAccessRightsForReview' ).returns(new Promise(r => (resolver = r))); element.repo = 'test-repo' as RepoName; sinon.stub(element, '_computeAddAndRemove').returns(repoAccessInput); element._modified = true; MockInteractions.tap(element.$.saveReviewBtn); await flush(); assert.equal(element.$.saveReviewBtn.hasAttribute('loading'), true); resolver!(createChange()); await flush(); assert.isTrue(saveForReviewStub.called); assert.isTrue( navigateToChangeStub.lastCall.calledWithExactly(createChange()) ); }); }); });
the_stack
* @module WebGL */ import { assert } from "@itwin/core-bentley"; import { WebGLDisposable } from "./Disposable"; import { GL } from "./GL"; import { RenderBuffer, RenderBufferMultiSample } from "./RenderBuffer"; import { System } from "./System"; import { TextureHandle } from "./Texture"; /** @internal */ export type DepthBuffer = RenderBuffer | RenderBufferMultiSample | TextureHandle; /* eslint-disable no-restricted-syntax */ /** @internal */ export const enum FrameBufferBindState { Unbound, Bound, BoundWithAttachments, BoundMultisampled, BoundWithAttachmentsMultisampled, Suspended, } /** @internal */ export class FrameBuffer implements WebGLDisposable { private _fbo?: WebGLFramebuffer; private _fboMs?: WebGLFramebuffer; private _bindState: FrameBufferBindState = FrameBufferBindState.Unbound; private readonly _colorTextures: TextureHandle[] = []; private readonly _colorMsBuffers: RenderBufferMultiSample[] = []; private readonly _colorAttachments: GLenum[] = []; private readonly _colorMsFilters: GL.MultiSampling.Filter[] = []; public readonly depthBuffer?: DepthBuffer; public readonly depthBufferMs?: DepthBuffer; public get isDisposed(): boolean { return this._fbo === undefined; } public get isBound(): boolean { return FrameBufferBindState.Bound <= this._bindState && FrameBufferBindState.BoundWithAttachmentsMultisampled >= this._bindState; } public get isBoundMultisampled(): boolean { return FrameBufferBindState.BoundMultisampled === this._bindState || FrameBufferBindState.BoundWithAttachmentsMultisampled === this._bindState; } public get isSuspended(): boolean { return FrameBufferBindState.Suspended === this._bindState; } public get isMultisampled(): boolean { return this._colorMsBuffers.length > 0 || undefined !== this.depthBufferMs; } public getColor(ndx: number): TextureHandle { assert(ndx < this._colorTextures.length); if (ndx < this._colorMsBuffers.length && this._colorMsBuffers[ndx].isDirty) { this.blitMsBuffersToTextures(false, ndx); } return this._colorTextures[ndx]; } private constructor(fbo: WebGLFramebuffer, colorTextures: TextureHandle[], depthBuffer?: DepthBuffer, colorMsBuffers?: RenderBufferMultiSample[], msFilters?: GL.MultiSampling.Filter[], depthBufferMs?: DepthBuffer) { this._fbo = fbo; const gl = System.instance.context; this.bind(false); let i: number = 0; for (const colTex of colorTextures) { const attachmentEnum: GLenum = gl.COLOR_ATTACHMENT0 + i; this._colorAttachments.push(attachmentEnum); this._colorTextures.push(colTex); const texHandle = colTex.getHandle(); if (undefined !== texHandle) gl.framebufferTexture2D(gl.FRAMEBUFFER, attachmentEnum, gl.TEXTURE_2D, texHandle, 0); i++; } if (depthBuffer !== undefined) { this.depthBuffer = depthBuffer; const dbHandle = depthBuffer.getHandle(); if (undefined !== dbHandle) { if (depthBuffer instanceof RenderBuffer) { gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, dbHandle); } else if (depthBuffer instanceof RenderBufferMultiSample) { gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, dbHandle); } else { // Looks like we only get a 24 bit depth buffer anyway, so use a 24-8 with a stencil. // gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, dbHandle, 0); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, dbHandle, 0); } } } this.unbind(); if (undefined !== colorMsBuffers && colorMsBuffers.length === colorTextures.length && undefined !== msFilters && msFilters.length === colorMsBuffers.length) { // Create a matching FBO with multisampling render buffers. const fbo2 = System.instance.context.createFramebuffer(); if (null !== fbo2) { this._fboMs = fbo2; this.bind(false, true); i = 0; for (const colMsBuff of colorMsBuffers) { const attachmentEnum: GLenum = gl.COLOR_ATTACHMENT0 + i; this._colorMsBuffers.push(colMsBuff); this._colorMsFilters.push(msFilters[i]); const msBuffHandle = colMsBuff.getHandle(); if (undefined !== msBuffHandle) gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachmentEnum, gl.RENDERBUFFER, msBuffHandle); i++; } if (depthBufferMs !== undefined) { this.depthBufferMs = depthBufferMs; const dbHandleMs = depthBufferMs.getHandle(); if (undefined !== dbHandleMs) { gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, dbHandleMs); } } this.unbind(); } } } public static create(colorTextures: TextureHandle[], depthBuffer?: DepthBuffer, colorMsBuffers?: RenderBufferMultiSample[], msFilters?: GL.MultiSampling.Filter[], depthBufferMs?: DepthBuffer): FrameBuffer | undefined { const fbo: WebGLFramebuffer | null = System.instance.context.createFramebuffer(); if (null === fbo) { return undefined; } return new FrameBuffer(fbo, colorTextures, depthBuffer, colorMsBuffers, msFilters, depthBufferMs); } public dispose(): void { // NB: The FrameBuffer does not *own* the textures and depth buffer. if (!this.isDisposed) { System.instance.context.deleteFramebuffer(this._fbo!); this._fbo = undefined; if (undefined !== this._fboMs) { System.instance.context.deleteFramebuffer(this._fboMs); this._fboMs = undefined; } } } public bind(bindAttachments: boolean = false, bindMS: boolean = false): boolean { assert(undefined !== this._fbo); assert(!this.isBound); if (undefined === this._fbo) return false; const gl = System.instance.context; if (bindMS && undefined !== this._fboMs) { gl.bindFramebuffer(GL.FrameBuffer.TARGET, this._fboMs); this._bindState = FrameBufferBindState.BoundMultisampled; } else { gl.bindFramebuffer(GL.FrameBuffer.TARGET, this._fbo); this._bindState = FrameBufferBindState.Bound; } if (bindAttachments) { System.instance.setDrawBuffers(this._colorAttachments); this._bindState++; } return true; } public unbind() { assert(this.isBound); System.instance.context.bindFramebuffer(GL.FrameBuffer.TARGET, null); this._bindState = FrameBufferBindState.Unbound; } public suspend() { assert(this.isBound); this._bindState = FrameBufferBindState.Suspended; } public markTargetsDirty(): void { for (const msBuff of this._colorMsBuffers) { msBuff.markBufferDirty(true); } if (undefined !== this.depthBufferMs) (this.depthBufferMs as RenderBufferMultiSample).markBufferDirty(true); } /** blitDepth is true to blit the depth/stencil buffer. ndx is index of single attachment to blit. * All color attachments are blitted if ndx is undefined, none are blitted if ndx is -1. */ public blitMsBuffersToTextures(blitDepth: boolean, ndx?: number) { if (!this._fboMs) return; System.instance.frameBufferStack.suspend(); const gl2 = System.instance.context as WebGL2RenderingContext; const attachments = []; const max = (undefined === ndx ? this._colorMsBuffers.length : ndx + 1); for (let i = 0; i < max; ++i) { if (undefined !== ndx && i < ndx) { attachments.push(gl2.NONE); // skip this one, but first add a NONE for it in the attachment list continue; } if (this._colorMsBuffers[i].isDirty) { gl2.bindFramebuffer(gl2.READ_FRAMEBUFFER, this._fboMs); gl2.readBuffer(this._colorAttachments[i]); gl2.bindFramebuffer(gl2.DRAW_FRAMEBUFFER, this._fbo!); attachments.push(this._colorAttachments[i]); gl2.drawBuffers(attachments); attachments.pop(); attachments.push(gl2.NONE); gl2.blitFramebuffer(0, 0, this._colorTextures[i].width, this._colorTextures[i].height, 0, 0, this._colorTextures[i].width, this._colorTextures[i].height, GL.BufferBit.Color, this._colorMsFilters[i]); this._colorMsBuffers[i].markBufferDirty(false); if (undefined !== ndx && i === ndx) break; } } if (blitDepth && undefined !== this.depthBuffer && undefined !== this.depthBufferMs && (this.depthBufferMs as RenderBufferMultiSample).isDirty) { const mask = GL.BufferBit.Depth; // (this.depthBuffer instanceof RenderBuffer ? GL.BufferBit.Depth : GL.BufferBit.Depth | GL.BufferBit.Stencil); gl2.bindFramebuffer(gl2.READ_FRAMEBUFFER, this._fboMs); gl2.bindFramebuffer(gl2.DRAW_FRAMEBUFFER, this._fbo!); gl2.blitFramebuffer(0, 0, this.depthBuffer.width, this.depthBuffer.height, 0, 0, this.depthBuffer.width, this.depthBuffer.height, mask, GL.MultiSampling.Filter.Nearest); (this.depthBufferMs as RenderBufferMultiSample).markBufferDirty(false); } gl2.bindFramebuffer(gl2.READ_FRAMEBUFFER, null); gl2.bindFramebuffer(gl2.DRAW_FRAMEBUFFER, null); System.instance.frameBufferStack.resume(); } /** invDepth is true to invalidate depth buffer. invStencil is true to invalidate stencil buffer. ndx is index of single color attachment to invalidate. * All color attachments are invalidated if ndx is undefined, none are invalidated if ndx is -1. * Set withMultiSampling to true to invalidate the MS buffers. */ public invalidate(invDepth: boolean, invStencil: boolean, withMultiSampling: boolean, indices?: number[]): void { const gl = System.instance.context; const attachments = invDepth ? (invStencil ? [gl.DEPTH_STENCIL_ATTACHMENT] : [System.instance.context.DEPTH_ATTACHMENT]) : (invDepth ? [gl.STENCIL_ATTACHMENT] : []); if (undefined !== indices) { if (indices.length > 0) { for (const i of indices) attachments.push(gl.COLOR_ATTACHMENT0 + i); } } else { attachments.concat(this._colorAttachments); } System.instance.frameBufferStack.execute(this, true, withMultiSampling, () => { System.instance.invalidateFrameBuffer(attachments); }); } // Chiefly for debugging currently - assumes RGBA, unsigned byte, want all pixels. public get debugPixels(): Uint8Array | undefined { if (!this.isBound || 0 === this._colorTextures.length || !(this._colorTextures[0] instanceof TextureHandle)) return undefined; const tex = this._colorTextures[0]; if (GL.Texture.Format.Rgba !== tex.format || GL.Texture.DataType.UnsignedByte !== tex.dataType) return undefined; const buffer = new Uint8Array(tex.width * tex.height * 4); for (let i = 0; i < buffer.length; i += 4) { buffer[i] = 0xba; buffer[i + 1] = 0xad; buffer[i + 2] = 0xf0; buffer[i + 3] = 0x0d; } System.instance.context.readPixels(0, 0, tex.width, tex.height, tex.format, tex.dataType, buffer); return buffer; } } interface Binding { fbo: FrameBuffer; withAttachments: boolean; withMultSampling: boolean; } /** @internal */ export class FrameBufferStack { // FrameBuffers within this array are not owned, as this is only a storage device holding references private readonly _stack: Binding[] = []; private get _top() { return !this.isEmpty ? this._stack[this._stack.length - 1] : undefined; } public push(fbo: FrameBuffer, withAttachments: boolean, withMultSampling: boolean): void { if (undefined !== this._top) { this._top.fbo.suspend(); } assert(!fbo.isBound); fbo.bind(withAttachments, withMultSampling); assert(fbo.isBound); this._stack.push({ fbo, withAttachments, withMultSampling }); } public pop(): void { assert(!this.isEmpty); if (undefined === this._top) { return; } const fbo = this._top.fbo; this._stack.pop(); assert(fbo.isBound); fbo.unbind(); assert(!fbo.isBound); if (this.isEmpty) { System.instance.context.bindFramebuffer(GL.FrameBuffer.TARGET, null); } else { const top = this._top; assert(top.fbo.isSuspended); top.fbo.bind(top.withAttachments, top.withMultSampling); assert(top.fbo.isBound); } } public get currentColorBuffer(): TextureHandle | undefined { assert(!this.isEmpty); return undefined !== this._top ? this._top.fbo.getColor(0) : undefined; } public get currentFbMultisampled(): boolean { return undefined !== this._top ? this._top.fbo.isBoundMultisampled : false; } public get isEmpty(): boolean { return 0 === this._stack.length; } public execute(fbo: FrameBuffer, withAttachments: boolean, withMultSampling: boolean, func: () => void) { this.push(fbo, withAttachments, withMultSampling); func(); this.pop(); } public markTargetsDirty(): void { const top = this._top; if (undefined !== top) top.fbo.markTargetsDirty(); } public suspend(): void { if (undefined !== this._top) { this._top.fbo.suspend(); } } public resume(): void { if (undefined === this._top) { return; } if (this.isEmpty) { System.instance.context.bindFramebuffer(GL.FrameBuffer.TARGET, null); } else { const top = this._top; top.fbo.bind(top.withAttachments, top.withMultSampling); assert(top.fbo.isBound); } } }
the_stack
import path from 'path'; import { StructureDefinitionExporter, Package } from '../../src/export'; import { FSHTank, FSHDocument } from '../../src/import'; import { FHIRDefinitions, loadFromPath } from '../../src/fhirdefs'; import { Logical } from '../../src/fshtypes'; import { loggerSpy } from '../testhelpers/loggerSpy'; import { TestFisher } from '../testhelpers'; import { minimalConfig } from '../utils/minimalConfig'; import { AddElementRule, CardRule, CaretValueRule, ContainsRule, FlagRule } from '../../src/fshtypes/rules'; describe('LogicalExporter', () => { let defs: FHIRDefinitions; let doc: FSHDocument; let exporter: StructureDefinitionExporter; beforeAll(() => { defs = new FHIRDefinitions(); loadFromPath(path.join(__dirname, '..', 'testhelpers', 'testdefs'), 'r4-definitions', defs); }); beforeEach(() => { loggerSpy.reset(); doc = new FSHDocument('fileName'); const input = new FSHTank([doc], minimalConfig); const pkg = new Package(input.config); const fisher = new TestFisher(input, defs, pkg); exporter = new StructureDefinitionExporter(input, pkg, fisher); }); it('should output empty results with empty input', () => { const exported = exporter.export().logicals; expect(exported).toEqual([]); }); it('should export a single logical model', () => { const logical = new Logical('Foo'); doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); }); it('should export multiple logical models', () => { const logicalFoo = new Logical('Foo'); const logicalBar = new Logical('Bar'); doc.logicals.set(logicalFoo.name, logicalFoo); doc.logicals.set(logicalBar.name, logicalBar); const exported = exporter.export().logicals; expect(exported.length).toBe(2); }); it('should still export logical models if one fails', () => { const logicalFoo = new Logical('Foo'); logicalFoo.parent = 'Baz'; // invalid parent cause failure const logicalBar = new Logical('Bar'); doc.logicals.set(logicalFoo.name, logicalFoo); doc.logicals.set(logicalBar.name, logicalBar); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].name).toBe('Bar'); }); it('should export a single logical model with Base parent when parent not defined', () => { const logical = new Logical('Foo'); doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Base'); }); it('should export a single logical model with Base parent by id', () => { const logical = new Logical('Foo'); logical.parent = 'Base'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Base'); }); it('should export a single logical model with Base parent by url', () => { const logical = new Logical('Foo'); logical.parent = 'http://hl7.org/fhir/StructureDefinition/Base'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Base'); }); it('should export a single logical model with Element parent by id', () => { const logical = new Logical('Foo'); logical.parent = 'Element'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Element'); }); it('should export a single logical model with Element parent by url', () => { const logical = new Logical('Foo'); logical.parent = 'http://hl7.org/fhir/StructureDefinition/Element'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Element'); }); it('should export a single logical model with another logical model parent by id', () => { const logical = new Logical('Foo'); logical.parent = 'AlternateIdentification'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe( 'http://hl7.org/fhir/cda/StructureDefinition/AlternateIdentification' ); }); it('should export a single logical model with another logical model parent by url', () => { const logical = new Logical('Foo'); logical.parent = 'http://hl7.org/fhir/cda/StructureDefinition/AlternateIdentification'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe( 'http://hl7.org/fhir/cda/StructureDefinition/AlternateIdentification' ); }); it('should export a single logical model with a complex-type parent by id', () => { const logical = new Logical('Foo'); logical.parent = 'Address'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Address'); }); it('should export a single logical model with a complex-type parent by url', () => { const logical = new Logical('Foo'); logical.parent = 'http://hl7.org/fhir/StructureDefinition/Address'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Address'); }); it('should export a single logical model with a resource parent by id', () => { const logical = new Logical('Foo'); logical.parent = 'Appointment'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Appointment'); }); it('should export a single logical model with a resource parent by url', () => { const logical = new Logical('Foo'); logical.parent = 'http://hl7.org/fhir/StructureDefinition/Appointment'; doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals; expect(exported.length).toBe(1); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Appointment'); }); it('should log an error with source information when the parent is invalid', () => { const logical = new Logical('BadParent').withFile('BadParent.fsh').withLocation([2, 9, 4, 23]); logical.parent = 'actualgroup'; // Profile doc.logicals.set(logical.name, logical); exporter.export(); expect(loggerSpy.getLastMessage('error')).toMatch(/File: BadParent\.fsh.*Line: 2 - 4\D*/s); expect(loggerSpy.getLastMessage('error')).toMatch( /The parent of a logical model must be Element, Base, another logical model, a resource, or a type./s ); }); it('should log an error with source information when the parent is not found', () => { const logical = new Logical('Bogus').withFile('Bogus.fsh').withLocation([2, 9, 4, 23]); logical.parent = 'BogusParent'; doc.logicals.set(logical.name, logical); exporter.export(); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Bogus\.fsh.*Line: 2 - 4\D*/s); expect(loggerSpy.getLastMessage('error')).toMatch(/Parent BogusParent not found for Bogus/s); }); it('should export logical models with FSHy parents', () => { const logicalFoo = new Logical('Foo'); const logicalBar = new Logical('Bar'); logicalBar.parent = 'Foo'; doc.logicals.set(logicalFoo.name, logicalFoo); doc.logicals.set(logicalBar.name, logicalBar); const exported = exporter.export().logicals; expect(exported.length).toBe(2); expect(exported[0].name).toBe('Foo'); expect(exported[1].name).toBe('Bar'); expect(exported[1].baseDefinition === exported[0].url); }); it('should export logical models with the same FSHy parents', () => { const logicalFoo = new Logical('Foo'); const logicalBar = new Logical('Bar'); logicalBar.parent = 'Foo'; const logicalBaz = new Logical('Baz'); logicalBaz.parent = 'Foo'; doc.logicals.set(logicalFoo.name, logicalFoo); doc.logicals.set(logicalBar.name, logicalBar); doc.logicals.set(logicalBaz.name, logicalBaz); const exported = exporter.export().logicals; expect(exported.length).toBe(3); expect(exported[0].name).toBe('Foo'); expect(exported[1].name).toBe('Bar'); expect(exported[2].name).toBe('Baz'); expect(exported[1].baseDefinition === exported[0].url); expect(exported[2].baseDefinition === exported[0].url); }); it('should export logical models with deep FSHy parents', () => { const logicalFoo = new Logical('Foo'); const logicalBar = new Logical('Bar'); logicalBar.parent = 'Foo'; const logicalBaz = new Logical('Baz'); logicalBaz.parent = 'Bar'; doc.logicals.set(logicalFoo.name, logicalFoo); doc.logicals.set(logicalBar.name, logicalBar); doc.logicals.set(logicalBaz.name, logicalBaz); const exported = exporter.export().logicals; expect(exported.length).toBe(3); expect(exported[0].name).toBe('Foo'); expect(exported[1].name).toBe('Bar'); expect(exported[2].name).toBe('Baz'); expect(exported[1].baseDefinition === exported[0].url); expect(exported[2].baseDefinition === exported[1].url); }); it('should export logical models with out-of-order FSHy parents', () => { const logicalFoo = new Logical('Foo'); logicalFoo.parent = 'Bar'; const logicalBar = new Logical('Bar'); logicalBar.parent = 'Baz'; const logicalBaz = new Logical('Baz'); doc.logicals.set(logicalFoo.name, logicalFoo); doc.logicals.set(logicalBar.name, logicalBar); doc.logicals.set(logicalBaz.name, logicalBaz); const exported = exporter.export().logicals; expect(exported.length).toBe(3); expect(exported[0].name).toBe('Baz'); expect(exported[1].name).toBe('Bar'); expect(exported[2].name).toBe('Foo'); expect(exported[1].baseDefinition === exported[0].url); expect(exported[2].baseDefinition === exported[1].url); }); it('should include added element having logical model as datatype when parent is Base without regard to definition order - order Foo then Bar', () => { const logicalFoo = new Logical('Foo'); const addElementRuleBars = new AddElementRule('bars'); addElementRuleBars.min = 0; addElementRuleBars.max = '1'; addElementRuleBars.types = [{ type: 'Bar' }]; addElementRuleBars.short = 'short of property bars'; logicalFoo.rules.push(addElementRuleBars); doc.logicals.set(logicalFoo.name, logicalFoo); const logicalBar = new Logical('Bar'); const addElementRuleLength = new AddElementRule('length'); addElementRuleLength.min = 0; addElementRuleLength.max = '1'; addElementRuleLength.types = [{ type: 'Quantity' }]; addElementRuleLength.short = 'short of property length'; logicalBar.rules.push(addElementRuleLength); const addElementRuleWidth = new AddElementRule('width'); addElementRuleWidth.min = 0; addElementRuleWidth.max = '1'; addElementRuleWidth.types = [{ type: 'Quantity' }]; addElementRuleWidth.short = 'short of property width'; logicalBar.rules.push(addElementRuleWidth); doc.logicals.set(logicalBar.name, logicalBar); const exported = exporter.export().logicals; expect(exported.length).toBe(2); expect(exported[0].name).toBe('Foo'); expect(exported[1].name).toBe('Bar'); expect(exported[0].elements).toHaveLength(2); // 1 Base element + 1 added "bars" element expect(exported[0].elements[1].path).toBe('Foo.bars'); expect(exported[0].elements[1].base.path).toBe('Foo.bars'); expect(exported[0].elements[1].type[0].code).toBe( 'http://hl7.org/fhir/us/minimal/StructureDefinition/Bar' ); }); it('should include added element having logical model as datatype when parent is Base without regard to definition order - order Bar then Foo', () => { const logicalBar = new Logical('Bar'); const addElementRuleLength = new AddElementRule('length'); addElementRuleLength.min = 0; addElementRuleLength.max = '1'; addElementRuleLength.types = [{ type: 'Quantity' }]; addElementRuleLength.short = 'short of property length'; logicalBar.rules.push(addElementRuleLength); const addElementRuleWidth = new AddElementRule('width'); addElementRuleWidth.min = 0; addElementRuleWidth.max = '1'; addElementRuleWidth.types = [{ type: 'Quantity' }]; addElementRuleWidth.short = 'short of property width'; logicalBar.rules.push(addElementRuleWidth); doc.logicals.set(logicalBar.name, logicalBar); const logicalFoo = new Logical('Foo'); const addElementRuleBars = new AddElementRule('bars'); addElementRuleBars.min = 0; addElementRuleBars.max = '1'; addElementRuleBars.types = [{ type: 'Bar' }]; addElementRuleBars.short = 'short of property bars'; logicalFoo.rules.push(addElementRuleBars); doc.logicals.set(logicalFoo.name, logicalFoo); const exported = exporter.export().logicals; expect(exported.length).toBe(2); expect(exported[0].name).toBe('Bar'); expect(exported[1].name).toBe('Foo'); expect(exported[1].elements).toHaveLength(2); // 1 Base element + 1 added "bars" element expect(exported[1].elements[1].path).toBe('Foo.bars'); expect(exported[1].elements[1].base.path).toBe('Foo.bars'); expect(exported[1].elements[1].type[0].code).toBe( 'http://hl7.org/fhir/us/minimal/StructureDefinition/Bar' ); }); it('should include added element having logical model as datatype when parent is Element', () => { const logicalFoo = new Logical('Foo'); const addElementRuleBars = new AddElementRule('bars'); addElementRuleBars.min = 0; addElementRuleBars.max = '1'; addElementRuleBars.types = [{ type: 'Bar' }]; addElementRuleBars.short = 'short of property bars'; logicalFoo.rules.push(addElementRuleBars); doc.logicals.set(logicalFoo.name, logicalFoo); const logicalBar = new Logical('Bar'); logicalBar.parent = 'Element'; const addElementRuleLength = new AddElementRule('length'); addElementRuleLength.min = 0; addElementRuleLength.max = '1'; addElementRuleLength.types = [{ type: 'Quantity' }]; addElementRuleLength.short = 'short of property length'; logicalBar.rules.push(addElementRuleLength); const addElementRuleWidth = new AddElementRule('width'); addElementRuleWidth.min = 0; addElementRuleWidth.max = '1'; addElementRuleWidth.types = [{ type: 'Quantity' }]; addElementRuleWidth.short = 'short of property width'; logicalBar.rules.push(addElementRuleWidth); doc.logicals.set(logicalBar.name, logicalBar); const exported = exporter.export().logicals; expect(exported.length).toBe(2); expect(exported[0].name).toBe('Foo'); expect(exported[1].name).toBe('Bar'); expect(exported[0].elements).toHaveLength(2); // 1 Base element + 1 added "bars" element const barsElement = exported[0].findElement('Foo.bars'); expect(barsElement.path).toBe('Foo.bars'); expect(barsElement.base.path).toBe('Foo.bars'); expect(barsElement.type[0].code).toBe('http://hl7.org/fhir/us/minimal/StructureDefinition/Bar'); }); it('should include added element having logical model as datatype when parent is another logical model', () => { const logicalFoo = new Logical('Foo'); const addElementRuleBars = new AddElementRule('bars'); addElementRuleBars.min = 0; addElementRuleBars.max = '1'; addElementRuleBars.types = [{ type: 'Bar' }]; addElementRuleBars.short = 'short of property bars'; logicalFoo.rules.push(addElementRuleBars); doc.logicals.set(logicalFoo.name, logicalFoo); const logicalBar = new Logical('Bar'); logicalBar.parent = 'AlternateIdentification'; const addElementRuleLength = new AddElementRule('length'); addElementRuleLength.min = 0; addElementRuleLength.max = '1'; addElementRuleLength.types = [{ type: 'Quantity' }]; addElementRuleLength.short = 'short of property length'; logicalBar.rules.push(addElementRuleLength); const addElementRuleWidth = new AddElementRule('width'); addElementRuleWidth.min = 0; addElementRuleWidth.max = '1'; addElementRuleWidth.types = [{ type: 'Quantity' }]; addElementRuleWidth.short = 'short of property width'; logicalBar.rules.push(addElementRuleWidth); doc.logicals.set(logicalBar.name, logicalBar); const exported = exporter.export().logicals; expect(exported.length).toBe(2); expect(exported[0].name).toBe('Foo'); expect(exported[1].name).toBe('Bar'); expect(exported[0].elements).toHaveLength(2); // 1 Base element + 1 added "bars" element const barsElement = exported[0].findElement('Foo.bars'); expect(barsElement.path).toBe('Foo.bars'); expect(barsElement.base.path).toBe('Foo.bars'); expect(barsElement.type[0].code).toBe('http://hl7.org/fhir/us/minimal/StructureDefinition/Bar'); }); it('should have correct base and types for each nested logical model', () => { const logicalOther = new Logical('Other'); const addElementRuleThing = new AddElementRule('thing'); addElementRuleThing.min = 1; addElementRuleThing.max = '1'; addElementRuleThing.types = [{ type: 'boolean' }]; addElementRuleThing.short = 'Is it a thing?'; logicalOther.rules.push(addElementRuleThing); doc.logicals.set(logicalOther.name, logicalOther); const logicalFoo = new Logical('FooFromOther'); logicalFoo.parent = 'Other'; const addElementRuleBars = new AddElementRule('bars'); addElementRuleBars.min = 0; addElementRuleBars.max = '*'; addElementRuleBars.types = [{ type: 'BarFromOther' }]; addElementRuleBars.short = 'The bars of the foo'; logicalFoo.rules.push(addElementRuleBars); doc.logicals.set(logicalFoo.name, logicalFoo); const logicalBar = new Logical('BarFromOther'); logicalBar.parent = 'Other'; const addElementRuleHeight = new AddElementRule('height'); addElementRuleHeight.min = 1; addElementRuleHeight.max = '1'; addElementRuleHeight.types = [{ type: 'Quantity' }]; addElementRuleHeight.short = 'The height of the bar'; logicalBar.rules.push(addElementRuleHeight); doc.logicals.set(logicalBar.name, logicalBar); const exported = exporter.export().logicals; expect(exported.length).toBe(3); expect(exported[0].name).toBe('Other'); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Base'); expect(exported[1].name).toBe('FooFromOther'); expect(exported[1].baseDefinition).toBe( 'http://hl7.org/fhir/us/minimal/StructureDefinition/Other' ); expect(exported[2].name).toBe('BarFromOther'); expect(exported[2].baseDefinition).toBe( 'http://hl7.org/fhir/us/minimal/StructureDefinition/Other' ); const thingElement = exported[0].findElement('Other.thing'); expect(thingElement.type[0].code).toBe('boolean'); const barsElement = exported[1].findElement('FooFromOther.bars'); expect(barsElement.type[0].code).toBe( 'http://hl7.org/fhir/us/minimal/StructureDefinition/BarFromOther' ); const heightElement = exported[2].findElement('BarFromOther.height'); expect(heightElement.type[0].code).toBe('Quantity'); }); it('should log an error when an inline extension is used', () => { const logical = new Logical('MyModel'); logical.parent = 'Element'; const containsRule = new ContainsRule('extension') .withFile('MyModel.fsh') .withLocation([3, 8, 3, 25]); containsRule.items.push({ name: 'SomeExtension' }); logical.rules.push(containsRule); doc.logicals.set(logical.name, logical); exporter.export(); expect(loggerSpy.getLastMessage('error')).toMatch(/File: MyModel\.fsh.*Line: 3\D*/s); expect(loggerSpy.getLastMessage('error')).toMatch( /Use of 'ContainsRule' is not permitted for 'Logical'/s ); }); it('should allow constraints on newly added elements and sub-elements', () => { const logical = new Logical('ExampleModel'); logical.id = 'ExampleModel'; const addElementRule = new AddElementRule('name'); addElementRule.min = 0; addElementRule.max = '*'; addElementRule.types = [{ type: 'HumanName' }]; addElementRule.short = "A person's full name"; logical.rules.push(addElementRule); const topLevelCardRule = new CardRule('name'); topLevelCardRule.min = 1; topLevelCardRule.max = '1'; logical.rules.push(topLevelCardRule); const subElementCardRule = new CardRule('name.given'); subElementCardRule.min = 1; subElementCardRule.max = '1'; logical.rules.push(subElementCardRule); doc.logicals.set(logical.name, logical); exporter.export(); const logs = loggerSpy.getAllMessages('error'); expect(logs).toHaveLength(0); }); it('should allow constraints on root elements', () => { const logical = new Logical('ExampleModel'); logical.id = 'ExampleModel'; const rootElementRule = new CaretValueRule('.'); rootElementRule.caretPath = 'alias'; rootElementRule.value = 'ExampleAlias'; logical.rules.push(rootElementRule); doc.logicals.set(logical.name, logical); exporter.export(); const logs = loggerSpy.getAllMessages('error'); expect(logs).toHaveLength(0); }); it('should log an error when constraining a parent element', () => { const logical = new Logical('MyTestModel'); logical.parent = 'AlternateIdentification'; logical.id = 'MyModel'; const addElementRule1 = new AddElementRule('backboneProp'); addElementRule1.min = 0; addElementRule1.max = '*'; addElementRule1.types = [{ type: 'BackboneElement' }]; addElementRule1.short = 'short of backboneProp'; logical.rules.push(addElementRule1); const addElementRule2 = new AddElementRule('backboneProp.name'); addElementRule2.min = 1; addElementRule2.max = '1'; addElementRule2.types = [{ type: 'HumanName' }]; addElementRule2.short = 'short of backboneProp.name'; logical.rules.push(addElementRule2); const addElementRule3 = new AddElementRule('backboneProp.address'); addElementRule3.min = 0; addElementRule3.max = '*'; addElementRule3.types = [{ type: 'Address' }]; addElementRule3.short = 'short of backboneProp.address'; logical.rules.push(addElementRule3); const flagRule1 = new FlagRule('effectiveTime') .withFile('ConstrainParent.fsh') .withLocation([6, 1, 6, 16]); flagRule1.summary = true; logical.rules.push(flagRule1); const cardRule1 = new CardRule('effectiveTime') .withFile('ConstrainParent.fsh') .withLocation([7, 1, 7, 18]); cardRule1.min = 1; cardRule1.max = '1'; logical.rules.push(cardRule1); const flagRule2 = new FlagRule('backboneProp.address'); flagRule2.summary = true; logical.rules.push(flagRule2); const cardRule2 = new CardRule('backboneProp.address'); cardRule2.min = 1; cardRule2.max = '100'; logical.rules.push(cardRule2); doc.logicals.set(logical.name, logical); const exported = exporter.export().logicals[0]; const logs = loggerSpy.getAllMessages('error'); expect(logs).toHaveLength(2); logs.forEach(log => { expect(log).toMatch( /FHIR prohibits logical models and resources from constraining parent elements. Skipping.*at path 'effectiveTime'.*File: ConstrainParent\.fsh.*Line:\D*/s ); }); expect(exported.name).toBe('MyTestModel'); expect(exported.id).toBe('MyModel'); expect(exported.type).toBe('http://hl7.org/fhir/us/minimal/StructureDefinition/MyModel'); expect(exported.baseDefinition).toBe( 'http://hl7.org/fhir/cda/StructureDefinition/AlternateIdentification' ); expect(exported.elements).toHaveLength(9); // 6 AlternateIdentification elements + 3 added elements }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/listManagementTermListsMappers"; import * as Parameters from "../models/parameters"; import { ContentModeratorClientContext } from "../contentModeratorClientContext"; /** Class representing a ListManagementTermLists. */ export class ListManagementTermLists { private readonly client: ContentModeratorClientContext; /** * Create a ListManagementTermLists. * @param {ContentModeratorClientContext} client Reference to the service client. */ constructor(client: ContentModeratorClientContext) { this.client = client; } /** * Returns list Id details of the term list with list Id equal to list Id passed. * @param listId List Id of the image list. * @param [options] The optional parameters * @returns Promise<Models.ListManagementTermListsGetDetailsResponse> */ getDetails(listId: string, options?: msRest.RequestOptionsBase): Promise<Models.ListManagementTermListsGetDetailsResponse>; /** * @param listId List Id of the image list. * @param callback The callback */ getDetails(listId: string, callback: msRest.ServiceCallback<Models.TermList>): void; /** * @param listId List Id of the image list. * @param options The optional parameters * @param callback The callback */ getDetails(listId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TermList>): void; getDetails(listId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TermList>, callback?: msRest.ServiceCallback<Models.TermList>): Promise<Models.ListManagementTermListsGetDetailsResponse> { return this.client.sendOperationRequest( { listId, options }, getDetailsOperationSpec, callback) as Promise<Models.ListManagementTermListsGetDetailsResponse>; } /** * Deletes term list with the list Id equal to list Id passed. * @param listId List Id of the image list. * @param [options] The optional parameters * @returns Promise<Models.ListManagementTermListsDeleteMethodResponse> */ deleteMethod(listId: string, options?: msRest.RequestOptionsBase): Promise<Models.ListManagementTermListsDeleteMethodResponse>; /** * @param listId List Id of the image list. * @param callback The callback */ deleteMethod(listId: string, callback: msRest.ServiceCallback<string>): void; /** * @param listId List Id of the image list. * @param options The optional parameters * @param callback The callback */ deleteMethod(listId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<string>): void; deleteMethod(listId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<string>, callback?: msRest.ServiceCallback<string>): Promise<Models.ListManagementTermListsDeleteMethodResponse> { return this.client.sendOperationRequest( { listId, options }, deleteMethodOperationSpec, callback) as Promise<Models.ListManagementTermListsDeleteMethodResponse>; } /** * Updates an Term List. * @param listId List Id of the image list. * @param contentType The content type. * @param body Schema of the body. * @param [options] The optional parameters * @returns Promise<Models.ListManagementTermListsUpdateResponse> */ update(listId: string, contentType: string, body: Models.Body, options?: msRest.RequestOptionsBase): Promise<Models.ListManagementTermListsUpdateResponse>; /** * @param listId List Id of the image list. * @param contentType The content type. * @param body Schema of the body. * @param callback The callback */ update(listId: string, contentType: string, body: Models.Body, callback: msRest.ServiceCallback<Models.TermList>): void; /** * @param listId List Id of the image list. * @param contentType The content type. * @param body Schema of the body. * @param options The optional parameters * @param callback The callback */ update(listId: string, contentType: string, body: Models.Body, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TermList>): void; update(listId: string, contentType: string, body: Models.Body, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TermList>, callback?: msRest.ServiceCallback<Models.TermList>): Promise<Models.ListManagementTermListsUpdateResponse> { return this.client.sendOperationRequest( { listId, contentType, body, options }, updateOperationSpec, callback) as Promise<Models.ListManagementTermListsUpdateResponse>; } /** * Creates a Term List * @param contentType The content type. * @param body Schema of the body. * @param [options] The optional parameters * @returns Promise<Models.ListManagementTermListsCreateResponse> */ create(contentType: string, body: Models.Body, options?: msRest.RequestOptionsBase): Promise<Models.ListManagementTermListsCreateResponse>; /** * @param contentType The content type. * @param body Schema of the body. * @param callback The callback */ create(contentType: string, body: Models.Body, callback: msRest.ServiceCallback<Models.TermList>): void; /** * @param contentType The content type. * @param body Schema of the body. * @param options The optional parameters * @param callback The callback */ create(contentType: string, body: Models.Body, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TermList>): void; create(contentType: string, body: Models.Body, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TermList>, callback?: msRest.ServiceCallback<Models.TermList>): Promise<Models.ListManagementTermListsCreateResponse> { return this.client.sendOperationRequest( { contentType, body, options }, createOperationSpec, callback) as Promise<Models.ListManagementTermListsCreateResponse>; } /** * gets all the Term Lists * @param [options] The optional parameters * @returns Promise<Models.ListManagementTermListsGetAllTermListsResponse> */ getAllTermLists(options?: msRest.RequestOptionsBase): Promise<Models.ListManagementTermListsGetAllTermListsResponse>; /** * @param callback The callback */ getAllTermLists(callback: msRest.ServiceCallback<Models.TermList[]>): void; /** * @param options The optional parameters * @param callback The callback */ getAllTermLists(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TermList[]>): void; getAllTermLists(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TermList[]>, callback?: msRest.ServiceCallback<Models.TermList[]>): Promise<Models.ListManagementTermListsGetAllTermListsResponse> { return this.client.sendOperationRequest( { options }, getAllTermListsOperationSpec, callback) as Promise<Models.ListManagementTermListsGetAllTermListsResponse>; } /** * Refreshes the index of the list with list Id equal to list ID passed. * @param listId List Id of the image list. * @param language Language of the terms. * @param [options] The optional parameters * @returns Promise<Models.ListManagementTermListsRefreshIndexMethodResponse> */ refreshIndexMethod(listId: string, language: string, options?: msRest.RequestOptionsBase): Promise<Models.ListManagementTermListsRefreshIndexMethodResponse>; /** * @param listId List Id of the image list. * @param language Language of the terms. * @param callback The callback */ refreshIndexMethod(listId: string, language: string, callback: msRest.ServiceCallback<Models.RefreshIndex>): void; /** * @param listId List Id of the image list. * @param language Language of the terms. * @param options The optional parameters * @param callback The callback */ refreshIndexMethod(listId: string, language: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.RefreshIndex>): void; refreshIndexMethod(listId: string, language: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.RefreshIndex>, callback?: msRest.ServiceCallback<Models.RefreshIndex>): Promise<Models.ListManagementTermListsRefreshIndexMethodResponse> { return this.client.sendOperationRequest( { listId, language, options }, refreshIndexMethodOperationSpec, callback) as Promise<Models.ListManagementTermListsRefreshIndexMethodResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getDetailsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "contentmoderator/lists/v1.0/termlists/{listId}", urlParameters: [ Parameters.endpoint, Parameters.listId1 ], responses: { 200: { bodyMapper: Mappers.TermList }, default: { bodyMapper: Mappers.APIError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "contentmoderator/lists/v1.0/termlists/{listId}", urlParameters: [ Parameters.endpoint, Parameters.listId1 ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "String" } } }, default: { bodyMapper: Mappers.APIError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "contentmoderator/lists/v1.0/termlists/{listId}", urlParameters: [ Parameters.endpoint, Parameters.listId1 ], headerParameters: [ Parameters.contentType0 ], requestBody: { parameterPath: "body", mapper: { ...Mappers.Body, required: true } }, responses: { 200: { bodyMapper: Mappers.TermList }, default: { bodyMapper: Mappers.APIError } }, serializer }; const createOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "contentmoderator/lists/v1.0/termlists", urlParameters: [ Parameters.endpoint ], headerParameters: [ Parameters.contentType0 ], requestBody: { parameterPath: "body", mapper: { ...Mappers.Body, required: true } }, responses: { 200: { bodyMapper: Mappers.TermList }, default: { bodyMapper: Mappers.APIError } }, serializer }; const getAllTermListsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "contentmoderator/lists/v1.0/termlists", urlParameters: [ Parameters.endpoint ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "TermList" } } } } }, default: { bodyMapper: Mappers.APIError } }, serializer }; const refreshIndexMethodOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "contentmoderator/lists/v1.0/termlists/{listId}/RefreshIndex", urlParameters: [ Parameters.endpoint, Parameters.listId1 ], queryParameters: [ Parameters.language0 ], responses: { 200: { bodyMapper: Mappers.RefreshIndex }, default: { bodyMapper: Mappers.APIError } }, serializer };
the_stack
import { defaults, Chart, ScatterController, registry, LinearScale, PointElement, UpdateMode, TooltipItem, ChartMeta, ChartItem, ChartConfiguration, ControllerDatasetOptions, ScriptableAndArrayOptions, LineHoverOptions, PointPrefixedOptions, PointPrefixedHoverOptions, CartesianScaleTypeRegistry, CoreChartOptions, ScriptableContext, } from 'chart.js'; import { merge, clipArea, unclipArea, listenArrayEvents, unlistenArrayEvents } from 'chart.js/helpers'; import { EdgeLine, IEdgeLineOptions } from '../elements'; import interpolatePoints from './interpolatePoints'; import patchController from './patchController'; interface IExtendedChartMeta extends ChartMeta<PointElement> { edges: EdgeLine[]; _parsedEdges: ITreeEdge[]; } export interface ITreeNode extends IGraphDataPoint { x: number; y: number; index?: number; } export interface ITreeEdge { source: number; target: number; points?: { x: number; y: number }[]; } export class GraphController extends ScatterController { declare _cachedMeta: IExtendedChartMeta; declare _ctx: CanvasRenderingContext2D; declare _cachedDataOpts: any; declare _type: string; declare _data: any[]; declare _edges: any[]; declare _sharedOptions: any; declare _edgeSharedOptions: any; declare dataElementType: any; private _scheduleResyncLayoutId = -1; edgeElementType: any; private readonly _edgeListener = { _onDataPush: (...args: any[]) => { const count = args.length; const start = (this.getDataset() as any).edges.length - count; const parsed = this._cachedMeta._parsedEdges; args.forEach((edge) => { parsed.push(this._parseDefinedEdge(edge)); }); this._insertEdgeElements(start, count); }, _onDataPop: () => { this._cachedMeta.edges.pop(); this._cachedMeta._parsedEdges.pop(); this._scheduleResyncLayout(); }, _onDataShift: () => { this._cachedMeta.edges.shift(); this._cachedMeta._parsedEdges.shift(); this._scheduleResyncLayout(); }, _onDataSplice: (start: number, count: number, ...args: any[]) => { this._cachedMeta.edges.splice(start, count); this._cachedMeta._parsedEdges.splice(start, count); if (args.length > 0) { const parsed = this._cachedMeta._parsedEdges; parsed.splice(start, 0, ...args.map((edge) => this._parseDefinedEdge(edge))); this._insertEdgeElements(start, args.length); } else { this._scheduleResyncLayout(); } }, _onDataUnshift: (...args: any[]) => { const parsed = this._cachedMeta._parsedEdges; parsed.unshift(...args.map((edge) => this._parseDefinedEdge(edge))); this._insertEdgeElements(0, args.length); }, }; initialize(): void { const type = this._type; const defaultConfig = defaults.datasets[type as 'graph'] as any; this.edgeElementType = registry.getElement(defaultConfig.edgeElementType as string); super.initialize(); this.enableOptionSharing = true; this._scheduleResyncLayout(); } parse(start: number, count: number): void { const meta = this._cachedMeta; const data = this._data; const { iScale, vScale } = meta; for (let i = 0; i < count; i += 1) { const index = i + start; const d = data[index]; const v = (meta._parsed[index] || {}) as { x: number; y: number }; if (d && typeof d.x === 'number') { v.x = d.x; } if (d && typeof d.y === 'number') { v.y = d.y; } meta._parsed[index] = v; } if (meta._parsed.length > data.length) { meta._parsed.splice(data.length, meta._parsed.length - data.length); } this._cachedMeta._sorted = false; (iScale as any)._dataLimitsCached = false; (vScale as any)._dataLimitsCached = false; this._parseEdges(); } reset(): void { this.resetLayout(); super.reset(); } update(mode: UpdateMode): void { super.update(mode); const meta = this._cachedMeta; const edges = meta.edges || []; this.updateEdgeElements(edges, 0, mode); } destroy(): void { (ScatterController.prototype as any).destroy.call(this); if (this._edges) { unlistenArrayEvents(this._edges, this._edgeListener); } this.stopLayout(); } updateEdgeElements(edges: EdgeLine[], start: number, mode: UpdateMode): void { const bak = { _cachedDataOpts: this._cachedDataOpts, dataElementType: this.dataElementType, _sharedOptions: this._sharedOptions, }; this._cachedDataOpts = {}; this.dataElementType = this.edgeElementType; this._sharedOptions = this._edgeSharedOptions; const meta = this._cachedMeta; const nodes = meta.data; const data = meta._parsedEdges; const reset = mode === 'reset'; const firstOpts = this.resolveDataElementOptions(start, mode); const sharedOptions = this.getSharedOptions(firstOpts) ?? {}; const includeOptions = this.includeOptions(mode, sharedOptions); const { xScale, yScale } = meta; const base = { x: xScale?.getBasePixel() ?? 0, y: yScale?.getBasePixel() ?? 0, }; function copyPoint(point: { x: number; y: number; angle?: number }) { const x = reset ? base.x : xScale?.getPixelForValue(point.x, 0) ?? 0; const y = reset ? base.y : yScale?.getPixelForValue(point.y, 0) ?? 0; return { x, y, angle: point.angle, }; } for (let i = 0; i < edges.length; i += 1) { const edge = edges[i]; const index = start + i; const parsed = data[index]; const properties: any = { source: nodes[parsed.source], target: nodes[parsed.target], points: Array.isArray(parsed.points) ? parsed.points.map((p) => copyPoint(p)) : [], }; properties.points._source = nodes[parsed.source]; if (includeOptions) { properties.options = sharedOptions || this.resolveDataElementOptions(index, mode); } this.updateEdgeElement(edge, index, properties, mode); } this.updateSharedOptions(sharedOptions, mode, firstOpts); this._edgeSharedOptions = this._sharedOptions; Object.assign(this, bak); } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types updateEdgeElement(edge: EdgeLine, index: number, properties: any, mode: UpdateMode): void { super.updateElement(edge, index, properties, mode); } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types updateElement(point: PointElement, index: number, properties: any, mode: UpdateMode): void { if (mode === 'reset') { // start in center also in x const { xScale } = this._cachedMeta; // eslint-disable-next-line no-param-reassign properties.x = xScale?.getBasePixel() ?? 0; } super.updateElement(point, index, properties, mode); } resolveNodeIndex(nodes: any[], ref: string | number | any): number { if (typeof ref === 'number') { // index return ref; } if (typeof ref === 'string') { // label const labels = this.chart.data.labels as string[]; return labels.indexOf(ref); } const nIndex = nodes.indexOf(ref); if (nIndex >= 0) { // hit return nIndex; } const data = this.getDataset().data as any[]; const index = data.indexOf(ref); if (index >= 0) { return index; } // eslint-disable-next-line no-console console.warn('cannot resolve edge ref', ref); return -1; } buildOrUpdateElements(): void { const dataset = this.getDataset() as any; const edges = dataset.edges || []; // In order to correctly handle data addition/deletion animation (an thus simulate // real-time charts), we need to monitor these data modifications and synchronize // the internal meta data accordingly. if (this._edges !== edges) { if (this._edges) { // This case happens when the user replaced the data array instance. unlistenArrayEvents(this._edges, this._edgeListener); } if (edges && Object.isExtensible(edges)) { listenArrayEvents(edges, this._edgeListener); } this._edges = edges; } super.buildOrUpdateElements(); } draw(): void { const meta = this._cachedMeta; const edges = meta.edges || []; const elements = meta.data || []; const area = this.chart.chartArea; const ctx = this._ctx; if (edges.length > 0) { clipArea(ctx, area); edges.forEach((edge) => (edge.draw.call as any)(edge, ctx, area)); unclipArea(ctx); } elements.forEach((elem) => (elem.draw.call as any)(elem, ctx, area)); } protected _resyncElements(): void { (ScatterController.prototype as any)._resyncElements.call(this); const meta = this._cachedMeta; const edges = meta._parsedEdges; const metaEdges = meta.edges || (meta.edges = []); const numMeta = metaEdges.length; const numData = edges.length; if (numData < numMeta) { metaEdges.splice(numData, numMeta - numData); this._scheduleResyncLayout(); } else if (numData > numMeta) { this._insertEdgeElements(numMeta, numData - numMeta); } } getTreeRootIndex(): number { const ds = this.getDataset() as any; const nodes = ds.data as any[]; if (ds.derivedEdges) { // find the one with no parent return nodes.findIndex((d) => d.parent == null); } // find the one with no edge const edges = this._cachedMeta._parsedEdges || []; const nodeIndices = new Set(nodes.map((_, i) => i)); edges.forEach((edge) => { nodeIndices.delete(edge.target); }); return Array.from(nodeIndices)[0]; } getTreeRoot(): ITreeNode { const index = this.getTreeRootIndex(); const p = this.getParsed(index) as ITreeNode; p.index = index; return p; } getTreeChildren(node: { index?: number }): ITreeNode[] { const edges = this._cachedMeta._parsedEdges; const index = node.index ?? 0; return edges .filter((d) => d.source === index) .map((d) => { const p = this.getParsed(d.target) as ITreeNode; p.index = d.target; return p; }); } _parseDefinedEdge(edge: { source: number; target: number }): ITreeEdge { const ds = this.getDataset(); const { data } = ds; return { source: this.resolveNodeIndex(data, edge.source), target: this.resolveNodeIndex(data, edge.target), points: [], }; } _parseEdges(): ITreeEdge[] { const ds = this.getDataset() as any; const data = ds.data as { parent?: number }[]; const meta = this._cachedMeta; if (ds.edges) { const edges = ds.edges.map((edge: any) => this._parseDefinedEdge(edge)); meta._parsedEdges = edges; return edges; } const edges: ITreeEdge[] = []; meta._parsedEdges = edges as any; // try to derive edges via parent links data.forEach((node, i) => { if (node.parent != null) { // tree edge const parent = this.resolveNodeIndex(data, node.parent); edges.push({ source: parent, target: i, points: [], }); } }); return edges; } addElements(): void { super.addElements(); const meta = this._cachedMeta; const edges = this._parseEdges(); const metaData = new Array(edges.length); meta.edges = metaData; for (let i = 0; i < edges.length; i += 1) { // eslint-disable-next-line new-cap metaData[i] = new this.edgeElementType(); } } _resyncEdgeElements(): void { const meta = this._cachedMeta; const edges = this._parseEdges(); const metaData = meta.edges || (meta.edges = []); for (let i = 0; i < edges.length; i += 1) { // eslint-disable-next-line new-cap metaData[i] = metaData[i] || new this.edgeElementType(); } if (edges.length < metaData.length) { metaData.splice(edges.length, metaData.length); } } _insertElements(start: number, count: number): void { (ScatterController.prototype as any)._insertElements.call(this, start, count); if (count > 0) { this._resyncEdgeElements(); } } _removeElements(start: number, count: number): void { (ScatterController.prototype as any)._removeElements.call(this, start, count); if (count > 0) { this._resyncEdgeElements(); } } _insertEdgeElements(start: number, count: number): void { const elements = []; for (let i = 0; i < count; i += 1) { // eslint-disable-next-line new-cap elements.push(new this.edgeElementType()); } this._cachedMeta.edges.splice(start, 0, ...elements); this.updateEdgeElements(elements, start, 'reset'); this._scheduleResyncLayout(); } // eslint-disable-next-line class-methods-use-this reLayout(): void { // hook } // eslint-disable-next-line class-methods-use-this resetLayout(): void { // hook } // eslint-disable-next-line class-methods-use-this stopLayout(): void { // hook } _scheduleResyncLayout(): void { if (this._scheduleResyncLayoutId != null && this._scheduleResyncLayoutId >= 0) { return; } this._scheduleResyncLayoutId = requestAnimationFrame(() => { this._scheduleResyncLayoutId = -1; this.resyncLayout(); }); } // eslint-disable-next-line class-methods-use-this resyncLayout(): void { // hook } static readonly id: string = 'graph'; static readonly defaults: any = /* #__PURE__ */ merge({}, [ ScatterController.defaults, { clip: 10, // some space in combination with padding animations: { points: { fn: interpolatePoints, properties: ['points'], }, }, edgeElementType: EdgeLine.id, }, ]); static readonly overrides: any = /* #__PURE__ */ merge({}, [ (ScatterController as any).overrides, { layout: { padding: 10, }, scales: { x: { display: false, ticks: { maxTicksLimit: 2, precision: 100, minRotation: 0, maxRotation: 0, }, }, y: { display: false, ticks: { maxTicksLimit: 2, precision: 100, minRotation: 0, maxRotation: 0, }, }, }, plugins: { tooltips: { callbacks: { label(item: TooltipItem<'graph'>) { return item.chart.data?.labels?.[item.dataIndex]; }, }, }, }, }, ]); } export interface IGraphDataPoint { parent?: number; } export interface IGraphEdgeDataPoint { source: number; target: number; } export interface IGraphChartControllerDatasetOptions extends ControllerDatasetOptions, ScriptableAndArrayOptions<PointPrefixedOptions, ScriptableContext<'graph'>>, ScriptableAndArrayOptions<PointPrefixedHoverOptions, ScriptableContext<'graph'>>, ScriptableAndArrayOptions<IEdgeLineOptions, ScriptableContext<'graph'>>, ScriptableAndArrayOptions<LineHoverOptions, ScriptableContext<'graph'>> { edges: IGraphEdgeDataPoint[]; } declare module 'chart.js' { export interface ChartTypeRegistry { graph: { chartOptions: CoreChartOptions<'graph'>; datasetOptions: IGraphChartControllerDatasetOptions; defaultDataPoint: IGraphDataPoint; metaExtensions: Record<string, never>; parsedDataType: ITreeNode; scales: keyof CartesianScaleTypeRegistry; }; } } export class GraphChart<DATA extends unknown[] = IGraphDataPoint[], LABEL = string> extends Chart< 'graph', DATA, LABEL > { static id = GraphController.id; constructor(item: ChartItem, config: Omit<ChartConfiguration<'graph', DATA, LABEL>, 'type'>) { super(item, patchController('graph', config, GraphController, [EdgeLine, PointElement], LinearScale)); } }
the_stack
var Props = "width height margin-top margin-right margin-bottom margin-left padding-top padding-right padding-bottom padding-left border-top-width border-right-width border-bottom-width border-left-width float display text-align border-top-style border-right-style border-bottom-style border-left-style overflow-x overflow-y position top bottom left right box-sizing min-width max-width min-height max-height font-size font-family font-style font-weight text-indent clear color background-color line-height vertical-align".split(" "); var BadProps = "clear float direction min-height max-height max-width min-width overflow-x overflow-y position box-sizing white-space font-size text-indent vertical-align".split(" "); var BadTags = "img iframe input svg:svg button frame noframes".split(" "); class Box { children : Box[]; type : string; props : any; node : Node; constructor(type, node, props) { this.children = []; this.type = type; this.props = props; this.node = node; } } function curry(f, arg) { return function(arg1, arg2) { return new f(arg, arg1, arg2) }} var Block = curry(Box, "BLOCK"); var Line = curry(Box, "LINE") var Inline = curry(Box, "INLINE") var Page = curry(Box, "PAGE") var TextBox = curry(Box, "TEXT") var Magic = curry(Box, "MAGIC") var Anon = curry(Box, "ANON") Box.prototype.toString = function() { var s = "[" + this.type; for (var i in this.props) { var val = this.props[i]; s += " :" + i + " " + (typeof val === "number" ? f2r(val) : val); } return s + "]"; } var ERROR : (boolean | string) = false; var SKIP_NO_MATCH = false; var LETTER = ""; var ID = 0; var PADDING = "0000"; function gensym() { var s = "" + (++ID); return "e" + LETTER + PADDING.substring(0, PADDING.length - s.length) + s; } import { f2r, MIN_LENGTH, val2px, val2pct, val2em, cs, dump_string, is_comment } from "./util"; function is_text(elt) {return elt.nodeType == document.TEXT_NODE || elt.nodeType == document.CDATA_SECTION_NODE;} function is_inline(elt) {return cs(elt, "display") == "inline";} function is_iblock(elt) {return cs(elt, "display") == "inline-block";} function is_block(elt) { return cs(elt, "display") == "block" || (cs(elt, "display") == "list-item" && (cs(elt, "list-style-position") == "outside" || cs(elt, "list-style-type") == "none")); } function is_visible(elt) {return cs(elt, "display") != "none";} function is_flow_block(elt) { return elt.nodeType == document.ELEMENT_NODE && cs(elt, "float") === "none" && ["static", "relative"].indexOf(cs(elt, "position")) !== -1; } function get_fontsize(elt) { var fs = cs(elt, "font-size"); try { return val2px(fs, {}) } catch (e) {} try { return val2pct(fs, {}) * get_fontsize(elt.parentNode) / 100 } catch (e) {} try { return val2em(fs, {}) * get_fontsize(elt.parentNode) } catch (e) {} throw "Error weird font-size value " + fs; } function convert_margin(margin, elt) { try { return val2px(margin, {}) } catch (e) {} try { return val2pct(margin, {}) * elt.clientWidth } catch (e) {} try { return val2em(margin, {}) * get_fontsize(elt) } catch (e) {} throw "Error weird margin value `" + margin + "`"; } function convert_offset(offset, elt) { if (offset == "auto") { return 0; } else if (offset.match(/%$/)) { return val2pct(offset, {}) * elt.parentNode.clientHeight; } else { return val2px(offset, {}); } } function get_margins(elt) { while (elt.nodeType !== document.ELEMENT_NODE) elt = elt.parentNode; return { top: convert_margin(cs(elt, "margin-top"), elt), right: convert_margin(cs(elt, "margin-right"), elt), bottom: convert_margin(cs(elt, "margin-bottom"), elt), left: convert_margin(cs(elt, "margin-left"), elt) }; } function get_relative_offset(elt) { while (elt.nodeType !== document.ELEMENT_NODE) elt = elt.parentNode; return { top: convert_offset(cs(elt, "top"), elt), bottom: convert_offset(cs(elt, "bottom"), elt), left: convert_offset(cs(elt, "left"), elt), right: convert_offset(cs(elt, "right"), elt), } } function find_first_break(txt, loff, roff) { if (loff !== loff || roff !== roff) throw "Error"; if (roff - loff < 2) return roff; if (roff - loff == 2) { var r2 = new Range(); r2.setStart(txt, loff); r2.setEnd(txt, roff); if (r2.getClientRects().length > 1) return loff + 1; else return loff + 2; } var mid = Math.round(loff + (roff - loff) / 2); var r2 = new Range(); r2.setStart(txt, loff); r2.setEnd(txt, mid); if (r2.getClientRects().length > 1) { return find_first_break(txt, loff, mid); } else { return find_first_break(txt, mid - 1, roff); } } function get_lines(txt) { var ranges : Range[] = []; var cursor = 0; var r = new Range(); r.selectNode(txt); if (r.getClientRects().length == 0) return ranges; while (cursor < txt.length) { var new_cursor = find_first_break(txt, cursor, txt.length); var r = new Range(); r.setStart(txt, cursor); r.setEnd(txt, new_cursor); ranges.push(r); cursor = new_cursor; } return ranges; } function infer_anons(inputs) { var estack = [inputs]; var out : Box[] = []; var bstack = [out]; var block_mode = true; function reenter(estack) { var b = Anon(null, {}); bstack[0].push(b) bstack.push(b.children); for (var i = 0; i < estack.length - 1; i++) { var b = Inline(estack[i][0].node, estack[i][0].props); bstack[bstack.length - 1].push(b) bstack.push(b.children); } block_mode = false; } while (estack[0].length > 0) { if (estack[estack.length - 1].length > 0) { var e = estack[estack.length - 1][0]; if (e.type == "TEXT") { if (block_mode) reenter(estack); bstack[bstack.length - 1].push(e); estack[estack.length - 1].shift(); } else if (e.type == "INLINE" && cs(e.node, "display") == "inline-block") { if (block_mode) reenter(estack); bstack[bstack.length - 1].push(e); estack[estack.length - 1].shift(); } else if (e.type == "INLINE") { if (block_mode) reenter(estack); var b = Inline(e.node, e.props); bstack[bstack.length - 1].push(b); bstack.push(b.children); estack.push(e.children); } else if ((e.type == "BLOCK" || e.type == "MAGIC") && is_flow_block(e.node)) { bstack[0].push(e); estack[estack.length - 1].shift(); bstack = [bstack[0]]; block_mode = true; } else if ((e.type == "BLOCK" || e.type == "MAGIC")) { bstack[bstack.length - 1].push(e); estack[estack.length - 1].shift(); } else { throw "What happened? " + e; } } else { if (!block_mode) bstack.pop(); estack.pop(); estack[estack.length - 1].shift(); } } return out; } function infer_lines(box, parent) { function last_line() { if (parent.children.length === 0 || parent.children[parent.children.length - 1].type !== "LINE") { return null; } else { return parent.children[parent.children.length - 1]; } } function new_line() { // The line-height idea was cute, but doesn't actually work. var l = Line(null, {/*h: val2px(cs(parent.node)["line-height"])*/}); parent.children.push(l); last = false; return l; } function fits(txt, prev) { /* if (!line) return false; var prev = line; while (prev.children.length) { prev = prev.children[prev.children.length - 1]; } // HACK for the case of an empty INLINE or LINE element if (prev.type == "LINE" || prev.type == "INLINE") return true; */ if (!prev) return true; if (prev.props.br === "") return false; var ph = prev.props.h; var py = prev.props.y; var px = prev.props.x; var pw = prev.props.w; var m = get_margins(prev.node); ph += m.top + m.bottom; py -= m.top; if (prev.node.nodeType == document.ELEMENT_NODE) { // Ultimately we need a horizontal cursor, not this nonsense. pw += m.left + m.right px -= m.left; } var pos = get_relative_offset(prev.node); if (pos.top) py -= pos.top; else if (pos.bottom) py += pos.bottom; if (pos.left) px -= pos.left; else if (pos.right) px += pos.right; var th = txt.props.h; var ty = txt.props.y; var tx = txt.props.x; var m = get_margins(txt.node); th += m.top + m.bottom; ty -= m.top; if (txt.node.nodeType == document.ELEMENT_NODE) { tx -= m.left; } var pos = get_relative_offset(txt.node); if (pos.top) ty -= pos.top; else if (pos.bottom) ty += pos.bottom; if (pos.left) tx -= pos.left; else if (pos.right) tx += pos.right; var horiz_adj = (ty + th >= py && py >= ty || py + ph >= ty && ty >= py) // Note fuzziness return horiz_adj && tx >= px + pw - MIN_LENGTH; } function stackup(l, stack, sstack) { for (var i = 0; i < stack.length; i++) { if (!sstack[i]) { var newprops = Object.assign({}, stack[i].props); var sselt = new Box(stack[i].type, stack[i].node, newprops); (i == 0 ? l : sstack[i - 1]).children.push(sselt); sstack.push(sselt); } } } var stack : Box[] = []; var sstack : Box[] = []; var last = false; // Handles last in-flow element; skips floats/positioned function go(b) { if (b.type == "BLOCK") { // Handles case of floating block var l = last_line() || new_line(); stackup(l, stack, sstack); (sstack.length === 0 ? l : sstack[sstack.length-1]).children.push(b); } else if (b.type == "TEXT" || b.type == "MAGIC" || (b.type == "INLINE" && b.node && (is_replaced(b.node) || is_iblock(b.node)))) { var l = last_line() || new_line(); if (!fits(b, last)) { l = new_line(); sstack = []; } stackup(l, stack, sstack); (sstack.length === 0 ? l : sstack[sstack.length-1]).children.push(b); last = b; } else if (b.type == "INLINE") { stack.push(b); for (var i = 0; i < b.children.length; i++) { var child = b.children[i]; go(child); } stackup(last_line() || new_line(), stack, sstack); stack.pop(); sstack = sstack.slice(0, stack.length); if (b.node && b.node.tagName.toUpperCase() == "BR") { new_line(); sstack = []; } } else { console.warn("Unknown box type", b); ERROR = "Unknown box type: " + b; } } for (var i = 0; i < box.children.length; i++) { var child = box.children[i]; go(child); } } declare global { interface ClientRect { x: number; y: number; top: number; right: number; bottom: number; left: number; } } function extract_text(elt) { var outs : Box[] = []; var ranges = get_lines(elt); for (var i = 0; i < ranges.length; i++) { var rs = ranges[i].getClientRects(); if (rs.length > 1) throw "Error, multiple lines in one line: "+ranges[i].toString(); if (rs.length < 1) continue; var r = rs[0]; var box = TextBox(elt, {x: r.x, y: r.y, w: r.width, h: r.height}); box.props.text = dump_string(ranges[i].toString().replace(/\s+/g, " ")); outs.push(box); } for (var i = 0; i < outs.length - 1; i++) { outs[i].props.br = ""; } return outs; } function extract_block(elt, children, features) { var r = elt.getBoundingClientRect(); children = infer_anons(children); for (var i = 0; i < children.length; i++) { if (children[i].type == "ANON") { var b = children[i]; var b2 = Anon(b.node, b.props); infer_lines(b, b2); children[i] = b2; } } if (children.length == 1 && children[0].type == "ANON") { children = children[0].children; } var box = Block(elt, {x: r.x, y: r.y, w: r.width, h: r.height}); if (elt.tagName.toUpperCase() == "OPTION") box.props.x -= 1; box.children = children; if (cs(elt, "display") == "list-item" && children.length == 0) { children.push(Line(null, {})); } try { annotate_inlines(box); } catch { features["inlines:weird"] = true; } return box; } function annotate_inlines(box) { var elements : Element[] = []; var boxes : Box[][] = []; function collect_by_elt(b) { for (var i = 0; i < b.children.length; i++) { // Skip blocks that we've already gone and annotated if (b.children[i].type == "BLOCK") continue; collect_by_elt(b.children[i]); } if (!b.node) return; if (b.type != "INLINE") return; var idx = elements.indexOf(b.node); if (idx === -1) { idx = elements.length; elements.push(b.node); boxes.push([]); } boxes[idx].push(b); } collect_by_elt(box); for (var i = 0; i < elements.length; i++) { var rects = elements[i].getClientRects(); if (rects.length !== boxes[i].length) { throw "Rect/box invariant does not hold for #" + elements[i].id + " " + rects.length + " " + boxes[i].length; } for (var j = 0; j < boxes[i].length; j++) { var p = boxes[i][j].props; var r = rects[j]; // For replaced elements, this overwrites existing values Object.assign(p, {x: r.x, y: r.y, w: r.width, h: r.height}); } } } function extract_inline(elt, children) { // Inline sizes are handled by annotate_inlines after line breaking; // however, for replaced elements we need sizes for line breaking. var rects = elt.getClientRects(); var props = {}; if (rects.length == 1) { props = { x: rects[0].x, y: rects[0].y, w: rects[0].width, h: rects[0].height }; } var box = Inline(elt, props); box.children = children; return box; } function extract_magic(elt, children) { var r = elt.getBoundingClientRect(); var box = Magic(elt, { x: r.x, y: r.y, w: r.width, h: r.height }); box.children = children; return box; } function make_boxes(elt, styles, features) { if (elt.tagName && BadTags.indexOf(elt.tagName.toLowerCase()) !== -1) { features["tag:" + elt.tagName.toLowerCase()] = true; } if (elt.style && elt.style.length) { var eid = elt.id || gensym(); if (!elt.id) elt.id = eid; styles[eid] = elt.style; } if (elt.nodeType !== document.ELEMENT_NODE) { // ok } else if (["none", "inline", "block"].indexOf(cs(elt, "display")) !== -1) { // ok } else if (cs(elt, "display").substr(0, 5) == "table") { features["display:table"] = true; } else if (cs(elt, "display") == "inline-block") { features["display:inline-block"] = true; } else if (cs(elt, "display") == "list-item") { features["display:list-item"] = true; } else { console.warn("Unclear element-like value, display: " + cs(elt, "display"), elt.nodeType, elt); features["display:unknown"] = true; } if (elt.nodeType == document.ELEMENT_NODE && cs(elt, "display") == "list-item" && cs(elt, "list-style-position") == "inside" && cs(elt, "list-style-type") != "none") { features["list:inside"] = true; } var children : Box[] = []; for (var i = 0; i < elt.childNodes.length; i++) { children = children.concat(make_boxes(elt.childNodes[i], styles, features)); } if (is_comment(elt)) { return []; } else if (elt.dataset && elt.dataset["cassius"] == "magic") { return [extract_magic(elt, children)]; } else if (is_text(elt)) { var out = extract_text(elt); var out2 = out.filter(function(x) {return x.props.w !== 0 || x.props.h !== 0}); if (out.length !== out2.length) features["empty-text"] = true; return out2; } else if (!is_visible(elt)) { return []; } else if ((is_block(elt) || is_iblock(elt))) { var box = extract_block(elt, children, features); if (is_iblock(elt)) box.type = "INLINE"; return [box]; } else if (is_inline(elt)) { return [extract_inline(elt, children)]; } else { return [extract_magic(elt, children)]; } } function get_boxes(style, features) { window.scrollTo(0, 0); var view = Page(document, {w: window.innerWidth, h: window.innerHeight}); view.children = make_boxes(document.documentElement, style, features); return view; } function dump_selector(sel) { sel = sel.trim(); if (sel.indexOf(",") !== -1) { var sub = sel.split(",").map(dump_selector); if (sub.indexOf(false) !== -1) return false; return "(or " + sub.join(" ") + ")"; } else if (sel.indexOf(">") !== -1) { var sub = sel.split(" "); // This one is complicated var in_desc = true; var previous = [dump_selector(sub[0])]; if (!previous[0]) return false; for (var i = 1; i < sub.length; i++) { if (sub[i] == "") continue; if (sub[i] == ">") { i++; var next = dump_selector(sub[i]); if (!next) return false; if (in_desc && previous.length > 1) { previous = ["(desc " + previous.join(" ") + ")"]; } previous.push(next); in_desc = false; } else { var next = dump_selector(sub[i]); if (!next) return false; if (!in_desc && previous.length > 1) { previous = ["(child " + previous.join(" ") + ")"]; } previous.push(next); in_desc = true; } } if (previous.length > 1) { return "(" + (in_desc ? "desc" : "child") + " " + previous.join(" ") + ")"; } else { return previous[0]; } } else if (sel.indexOf(" ") !== -1) { var sub = sel.split(/\s+/).map(dump_selector); if (sub.indexOf(false) !== -1) return false; return "(desc " + sub.join(" ") + ")"; } else if (sel.match(/^([\w-]+|\*)?((::?|\.|\#)[\w-]+|\[type=\"[\w-]+\"\])*$/)) { var sub = sel.replace(/\[|\.|\#|::?/g, "\0$&").split("\0"); if (sub[0] === "") sub.shift(); sub = sub.map(dump_primitive_selector); if (sub.indexOf(false) !== -1) return false; return sub.length == 1 ? sub[0] : ("(and " + sub.join(" ") + ")"); } else { return false; } } function dump_primitive_selector(sel) { var match; if (match = sel.match(/^\.([\w-]+)$/)) { return "(class " + match[1] + ")"; } else if (match = sel.match(/^:([\w-]+)$/)) { if (["first-child", "last-child", "hover", "last-of-type", "first-of-type"].indexOf(match[1]) !== -1) { return "(pseudo-class " + match[1] + ")"; } else { return false; } } else if (match = sel.match(/^::([\w-]+)$/)) { return false; } else if (match = sel.match(/^#([\w-]+)$/)) { return "(id " + match[1] + ")"; } else if (match = sel.match(/^([\w-]+)$/)) { return "(tag " + match[1].toLowerCase() + ")"; } else if (match = sel.match(/^\*$/)) { return "*"; } else if (match = sel.match(/^\[type=\"([\w-]+)\"\]$/)) { return "(type " + match[1] + ")"; } else { return false; } } function rescue_selector(sel) { var matched = document.querySelectorAll(sel); var ids : string[] = []; for (var i = 0; i < matched.length; i++) { if (matched[i].id) { ids.push(matched[i].id); } else { var id = gensym(); ids.push(id); matched[i].id = id; } } if (ids.length) { return "(fake " + dump_string(sel) + " (id " + ids.join(") (id ") + "))"; } else { return "(fake " + dump_string(sel) + ")"; } } function dump_length(val, features) { if (val.match(/%$/)) { val = "(% " + val2pct(val, features) + ")"; } else if (val.match(/[0-9.]e[mx]$/)) { val = "(em " + val2em(val, features) + ")"; } else if (val.match(/[0-9.]rem$/)) { val = "(rem " + val2em(val, features) + ")"; } else if (val.match(/[0-9.]s$/)) { val = "(s " + val.slice(0,-1) + ")"; // Not supported, just to avoid error message } else { val = "(px " + f2r(val2px(val, features)) + ")"; } return val; } function dump_color(val, features) { var match if (match = val.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)) { return "(rgb " + match[1] + " " + match[2] + " " + match[3] + ")"; } else if (match = val.match(/^rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)$/)) { if (match[4] == "1" || match[4] == "1.0") { return "(rgb " + match[1] + " " + match[2] + " " + match[3] + ")"; } else if (match[4] == "0" || match[4] == "0.0") { return "transparent"; } else { features["color:rgba"] = true; return "(rgba " + match[1] + " " + match[2] + " " + match[3] + " " + match[4] + ")"; } } else { features["color:" + val.split("(", 1)[0]] = true; throw "Invalid color " + val; } } function dump_rule(sel, style, features, is_from_style, media) { var nodes; try { nodes = document.querySelectorAll(sel); } catch (e) { console.warn("Invalid selector syntax, this shouldn't happen:", sel); features["invalid-selector"] = true return ""; } if (SKIP_NO_MATCH) if (nodes.length == 0) return ""; if (sel.indexOf(":after") !== -1 || sel.indexOf(":before") !== -1) { features["css:before-after"] = true; } var text = ""; var has_good_prop = false; for (var i = 0; i < style.length; i++) { var sname = style[i]; if (sname.startsWith("-")) continue; // Skip browser-specific styles for now. if (BadProps.indexOf(sname) !== -1) { features["css:" + sname] = true; } var val = style[sname]; var _features = Props.indexOf(sname) !== -1 ? features : {}; if (val == "inherit") { _features["css:inherit"] = true; } else if (val.startsWith("rgb") && val.endsWith(")")) { val = dump_color(val, _features); } else if (sname === "font-family") { val = dump_string(val); } else if (val.match(/^calc\(/)) { features["unit:calc"] = true; val = "0" } else if (val.match(/^[a-z]+$/)) { // skip } else if (val.match(/^([-+0-9.e]+)([a-z%]+)$/)) { try { val = dump_length(val, _features); } catch (e) { console.warn(sel, e); ERROR = e; } } if (Props.indexOf(sname) !== -1) { has_good_prop = true; var priority = style.getPropertyPriority(sname); if (priority !== "") { features["priority:" + priority] = true; text += "\n [" + sname + " " + val + " :" + priority + "]"; } else { text += "\n [" + sname + " " + val + "]"; } } else { text += "\n #;[" + sname + " " + val + "]"; } if ((sname == "overflow-x" || sname == "overflow-y") && val == "auto") { features["overflow:auto"] = true; } } if (!has_good_prop) return ""; var sels = sel.split(","); var out = ""; for (var i = 0; i < sels.length; i++) { var sel_text = dump_selector(sels[i]); if (!sel_text) { features["unknown-selector"] = true; sel_text = rescue_selector(sels[i]); } if (media && media.mediaText) { features["@media"] = true; sel_text = "(media " + dump_media_query(media, features) + " " + sel_text + ")"; } out += "\n (" + sel_text + (is_from_style ? " :style" : "") + text + ")"; } return out; } function dump_media_query(media, features) { var ors = media.mediaText.split(/,\s*/); for (var i = 0; i < ors.length; i++) { var query = ors[i].trim(); var words = query.split(/\s/, 2); if (words[0] == "only" || words[0] == "not") { query = query.substring(words[0].length).trim(); } var ands = query.split(/\band\b/); for (var j = 0; j < ands.length; j++) { var part = ands[j].trim(); var match; if (match = part.match(/^\(\s*([a-zA-Z0-9\-]+)\s*:\s*(.*)\)$/)) { ands[j] = "(" + match[1] + " " + dump_length(match[2], features) + ")"; } else if (match = part.match(/^\(\s*([a-zA-Z0-9\-]+)\s*\)$/)) { ands[j] = "(" + match[1] + ")"; } else if (match = part.match(/^([a-zA-Z0-9\-]+)$/)) { ands[j] = match[1]; } else { console.warn("Unknown media query component", part); features["unknown-media"] = true } } if (words[0] == "only") { ands.prefix = "only"; } else if (words[0] == "not") { ands.prefix = "not"; } else { ands.prefix = false; } ors[i] = ands; } var text = ""; if (ors.length > 1) text += "(or "; for (var i = 0; i < ors.length; i++) { var ands = ors[i]; if (i > 0) text += " "; if (ands.prefix) text += "(" + ands.prefix + " "; if (ands.length > 1) text += "(and "; for (var j = 0; j < ands.length; j++) { if (j > 0) text += " "; text += ands[j]; } if (ands.length > 1) text += ")"; if (ands.prefix) text += ")"; } if (ors.length > 1) text += ")"; return text; } function dump_features(features) { var text = ""; for (var f in features) { if (!features.hasOwnProperty(f)) continue; text += f + " "; } return text.trim(); } function dump_tree(page) { var text = ""; var indent = " "; function recurse(box) { if (typeof box === "object") { text += "\n" + indent + "(" + box.toString(); var idt = indent; indent += " "; for (var i = 0; i < box.children.length; i++) recurse(box.children[i]); indent = idt; text += ")"; } else if (typeof box === "string") { text += " " + dump_string(box) } } recurse(page); return text; } function dump_stylesheet(ss, features, media) { var text = ""; for (var rid in ss.cssRules) { if (!ss.cssRules.hasOwnProperty(rid)) continue; var r = ss.cssRules[rid]; try { if (r.type === CSSRule.IMPORT_RULE) { console.warn("Skipping non-style rule", r); features["css:@import"] = true continue; } else if (r.type === CSSRule.MEDIA_RULE) { text += dump_stylesheet(r, features, r.media); } else if (r.type === CSSRule.STYLE_RULE) { text += dump_rule(r.selectorText, r.style, features, false, media); } else if ( r.type === CSSRule.KEYFRAMES_RULE || r.type === CSSRule.KEYFRAME_RULE || r.type === CSSRule.FONT_FACE_RULE) { // Don't need these... } else { console.warn("Unknown rule type", r); features["css:type-" + r.type + "-rule"] = true; } } catch (e) { console.warn(r, e); ERROR = e; features["unknown-error"] = true; } } return text; } function get_inherent_size(e) { return { w: e.getBoundingClientRect().width, h: e.getBoundingClientRect().height, }; } var RTL_CHARS = /[\u0591-\u07FF\uFB1d-\uFDFD\uFE70-\uFEFC]/; function is_replaced(elt) { return (["IMG", "OBJECT", "INPUT", "IFRAME", "TEXTAREA"].indexOf(elt.tagName.toUpperCase()) !== -1); } function dump_document(features) { var elt = document.documentElement; var ELTS : Node[] = [] function recurse(elt) { if (is_comment(elt)) { return false; } else if (is_text(elt)) { if (RTL_CHARS.test(elt.textContent)) { features["unicode:rtl"] = true; } var r = new Range(); r.selectNode(elt); if (r.getClientRects().length == 0) { return false; } else { return elt.textContent.replace(/\s+/g, " "); } } else if (typeof(elt.dataset) === "undefined"){ console.log("Weird element", elt); var rec = new Box(elt.tagName.toLowerCase(), elt, {}); features["weird-element"] = true; return rec; } else { var num = ELTS.length; elt.dataset["num"] = num; ELTS.push(elt); var rec = new Box(elt.tagName.toLowerCase(), elt, {num: num}); if (elt.id) rec.props["id"] = elt.id; if (elt.classList.length) rec.props["class"] = ("(" + elt.classList + ")").replace(/#/g, ""); if (is_replaced(elt)) { var v = get_inherent_size(elt); rec.props["w"] = v.w; rec.props["h"] = v.h; } if (elt.tagName.toUpperCase() === "INPUT") { rec.props["type"] = elt.type; } if (elt.dir) { rec.props["dir"] = elt.dir; features["attr:dir"] = true; } if (elt.tagName.toUpperCase() === "HR" && elt.size) { rec.props["size"] = elt.size; features["hr:size"] = true; } for (var i = 0; i < elt.childNodes.length; i++) { if (is_comment(elt.childNodes[i])) continue; var b = recurse(elt.childNodes[i]); if (b) rec.children.push(b); } return rec; } } var s = recurse(elt); return s; } function annotate_box_elt(box) { if (box.node && box.node.nodeType === document.ELEMENT_NODE) { if (typeof(box.node.dataset) !== "undefined") { box.props.elt = box.node.dataset["num"]; } } for (var i = 0; i < box.children.length; i++) { annotate_box_elt(box.children[i]); } } import { MAX, compute_flt_pointer, check_float_registers } from "./ezone"; import { dump_fonts } from "./fonts"; import { dump_browser } from "./browser"; import { dump_script } from "./scripts" export function page2text(name) { LETTER = name; var features = {}; var text = ""; text += "(define-stylesheet " + name; for (var sheet of document.styleSheets) { try { text += dump_stylesheet(sheet, features, sheet.media); } catch (e) { console.warn(sheet, e); ERROR = e; features["unknown-error"] = true; } } var style = {} var page = get_boxes(style, features); var doc = dump_document(features); annotate_box_elt(page); compute_flt_pointer(page, null, null); features["float:" + MAX] = true; check_float_registers(page, features); for (var eid in style) { if (!style.hasOwnProperty(eid)) continue; text += dump_rule("#" + eid, style[eid], features, true, false); } text += ")\n\n"; text += dump_fonts(name, features) + "\n"; text += dump_browser(name, features) + "\n"; text += "(define-document " + name; text += dump_tree(doc); text += ")\n\n"; text += "(define-layout " + name + " (" + name + " " + name + ")\n"; text += " ([VIEW :w " + page.props.w + "]"; text += dump_tree(page.children[0]); text += "))\n\n"; for (var script of document.querySelectorAll("script")) { if (script.src) continue; text += "(define-script " + name +"\n"; text += dump_script(script.textContent); text += ")\n\n"; } text += "(define-problem " + name; text += "\n :title " + dump_string(document.title); text += "\n :url " + dump_string("" + location); text += "\n :sheets firefox " + name; text += "\n :fonts " + name; text += "\n :layouts " + name; text += "\n :script " + name; if (ERROR) { text += "\n :error " + dump_string(ERROR + ""); features["unknown-error"] = true; } text += "\n :features " + dump_features(features) + ")"; return text; }
the_stack
import turfLength from '@turf/length'; import turfArea from '@turf/area'; import { convertArea } from '@turf/helpers'; import mapboxgl from 'vue-iclient/static/libs/mapboxgl/mapbox-gl-enhance'; import drawEvent from 'vue-iclient/src/mapboxgl/_types/draw-event'; import { geti18n } from 'vue-iclient/src/common/_lang/index'; /** * @class DrawViewModel * @description 绘制 viewModel. * @param {Object} webmap - webmap实例对象。 * @extends mapboxgl.Evented */ export default class DrawViewModel extends mapboxgl.Evented { map: mapboxglTypes.Map; mapTarget: string; componentName: string; featureIds: Array<string>; activeFeature: any; dashedLayerIds: Array<string>; layerStyleList: Object; linesStaticFilter: Array<string>; defaultStyle: any; fire: any; draw: any; constructor(componentName: string) { super(); this.componentName = componentName; this.featureIds = []; // 收集当前draw所画的点线面的id this.activeFeature = {}; this.dashedLayerIds = []; // 收集虚线图层的id 信息 this.layerStyleList = {}; // 收集虚线图层的修改的样式信息 } setMap(mapInfo: mapInfoType) { const { map, mapTarget } = mapInfo; this.map = map; this.mapTarget = mapTarget; this._addDrawControl(); } _addDrawControl() { // @ts-ignore this.draw = drawEvent.$options.getDraw(this.mapTarget); // @ts-ignore drawEvent.$options.setDrawingState(this.mapTarget, this.componentName, false); this.map.on('draw.create', this._drawCreate.bind(this)); this.map.on('draw.selectionchange', this._selectionChange.bind(this)); this.map.on('mouseover', 'draw-line-static.cold', e => { const feature = e.features[0]; const id = feature.properties.id; if (this.featureIds.includes(id)) { this.map.setFilter('draw-line-hover.cold', ['all', ['==', '$type', 'LineString'], ['==', 'id', id]]); this.map.setFilter('draw-line-hover.hot', ['all', ['==', '$type', 'LineString'], ['==', 'id', id]]); } }); this.map.on('mouseout', 'draw-line-hover.cold', () => { this.map.setFilter('draw-line-hover.cold', ['all', ['==', '$type', 'LineString'], ['==', 'id', '']]); this.map.setFilter('draw-line-hover.hot', ['all', ['==', '$type', 'LineString'], ['==', 'id', '']]); }); } _drawCreate(e) { if (this._isDrawing()) { const { features } = e; const feature = features[0] || {}; this.featureIds.push(feature.id); } } _selectionChange(e) { if (this._isDrawing()) { const { features } = e; const feature = features[0]; if (feature) { this._getDefaultStyle(); this.activeFeature = feature; this._calcResult(feature); } } } _calcResult(feature) { // 计算长度和面积的结果 const { geometry = {} } = feature; const coordinates = geometry.coordinates; let result: number; let unit: string; let coordinateOfMaxLatitude = []; if (geometry.type === 'Point') { result = turfLength(feature, { units: 'kilometers' }); coordinateOfMaxLatitude = coordinates; } else if (geometry.type === 'LineString') { result = turfLength(feature, { units: 'kilometers' }); unit = geti18n().t('unit.kilometers'); coordinateOfMaxLatitude = this._calcMaxLatitudeInCoordinate(coordinates); } else if (geometry.type === 'Polygon') { let area = turfArea(feature); result = convertArea(area, 'meters', 'kilometers'); unit = geti18n().t('unit.squarekilometers'); coordinateOfMaxLatitude = this._calcMaxLatitudeInCoordinate(coordinates[0]); } const layerStyle = this._getFetureStyle(feature.id); /** * @event DrawViewModel#drawcreated * @description 绘制完成。 */ this.fire('draw-create', { popupInfo: { resultInfo: { feature, layerStyle, result, unit }, trash: this.trash.bind(this), map: this.map, coordinate: coordinateOfMaxLatitude } }); } _calcMaxLatitudeInCoordinate(data = []) { let indexOfMax = 0; let compareNum = data[indexOfMax] && data[indexOfMax][1]; for (let i = 0; i < data.length; i++) { if (data[i] && data[i][1] > compareNum) { compareNum = data[i][1]; indexOfMax = i; } } return data[indexOfMax]; } _getFetureStyle(id: string) { let layerStyle; for (let key in this.layerStyleList) { if (this.layerStyleList[key] && this.layerStyleList[key][id]) { layerStyle = Object.assign(this.layerStyleList[key][id], layerStyle); } } return layerStyle; } // 开启绘制 openDraw(mode: string) { // @ts-ignore drawEvent.$options.setDrawingState(this.mapTarget, this.componentName, true); // 绘画线或面 this.draw.changeMode(mode); } trash(id: string) { if (id) { // 给外部调用的API 如天地图传入一个id 删除指定点线面 this.draw.delete(id); for (let key in this.layerStyleList) { if (this.layerStyleList[key] && this.layerStyleList[key][id]) { delete this.layerStyleList[key][id]; break; } } const matchIndex = this.dashedLayerIds.findIndex(item => item === id); matchIndex > -1 && this.dashedLayerIds.splice(matchIndex, 1); return; } const selectedIds = this.draw.getSelectedIds(); selectedIds.forEach((item: string) => { const matchIndex = this.featureIds.findIndex(id => id === item); if (matchIndex > -1) { this.featureIds.splice(matchIndex, 1); this.draw.delete(item); } }); } setLayerStyle(layerStyle) { const { id } = this.activeFeature; if (!id) return; for (let key in layerStyle) { const paint = layerStyle[key]; this.layerStyleList[key] = this.layerStyleList[key] || {}; this.layerStyleList[key][id] = Object.assign(this.layerStyleList[id] || {}, layerStyle[key]); const isDashedLayer = Object.keys(paint).includes('line-dasharray'); const matchIndex = this.dashedLayerIds.findIndex(item => item === id); if (isDashedLayer) { matchIndex < 0 && this.dashedLayerIds.push(id); } else { key === 'LineString' && matchIndex > -1 && this.dashedLayerIds.splice(matchIndex, 1); } this.setFilter(); this.setPaintProperty(key, paint, isDashedLayer); } } setDashFilterData(init: Array<string>) { const newFilter = this.dashedLayerIds.reduce(function (filter, layerId) { filter.push(layerId); return filter; }, init); return newFilter; } setFilter() { if (!this.linesStaticFilter) { // 获取初始的Filter this.linesStaticFilter = this.map.getFilter('draw-line-static.cold'); } const notDashedFilter = this.setDashFilterData(['!in', 'id']); const dashedFilter = this.setDashFilterData(['in', 'id']); this.map.setFilter('draw-line-dashed.cold', dashedFilter); this.map.setFilter('draw-line-dashed.hot', dashedFilter); this.map.setFilter('draw-line-static.cold', ['all', this.linesStaticFilter, notDashedFilter]); this.map.setFilter('draw-line-static.hot', ['all', this.linesStaticFilter, notDashedFilter]); } setPaintProperty(key: string, paint, isDashedLayer: boolean) { for (let name in paint) { const value = this.setValueOfPaintKey(key, name); switch (key) { case 'LineString': if (name === 'line-color') { const vertexValue = value.slice(); vertexValue[1] = ['get', 'parent']; this.map.setPaintProperty('draw-vertex-active.hot', 'circle-color', vertexValue); this.map.setPaintProperty('draw-vertex-active.cold', 'circle-color', vertexValue); this.map.setPaintProperty('draw-line-hover.cold', name, value); this.map.setPaintProperty('draw-line-hover.hot', name, value); } if (isDashedLayer) { this.map.setPaintProperty('draw-line-dashed.cold', name, value); this.map.setPaintProperty('draw-line-dashed.hot', name, value); continue; } this.map.setPaintProperty('draw-line-static.cold', name, value); this.map.setPaintProperty('draw-line-static.hot', name, value); break; case 'Polygon': this.map.setPaintProperty('draw-polygon-static.cold', name, value); this.map.setPaintProperty('draw-polygon-static.hot', name, value); break; case 'Point': this.map.setPaintProperty('draw-point-static.cold', name, value); this.map.setPaintProperty('draw-point-static.hot', name, value); break; default: break; } } } setValueOfPaintKey(key: string, name: string) { let data = []; const featureStyle = this.layerStyleList[key]; for (let id in featureStyle) { const info = featureStyle[id]; data.push(id); data.push(info[name]); } switch (name) { // 这里的默认值应该和初始化的地方保持一致 case 'circle-color': case 'line-color': case 'fill-color': case 'fill-outline-color': return ['match', ['get', 'id'], ...data, this.defaultStyle['line-color']]; case 'line-dasharray': return featureStyle[this.activeFeature.id][name] || this.defaultStyle[name]; default: return ['match', ['get', 'id'], ...data, this.defaultStyle[name]]; } } _getDefaultStyle() { if (!this.defaultStyle) { let defaultStyle = {}; defaultStyle['line-color'] = this.map.getPaintProperty('draw-line-static.cold', 'line-color'); defaultStyle['line-width'] = this.map.getPaintProperty('draw-line-static.cold', 'line-width'); defaultStyle['line-dasharray'] = this.map.getPaintProperty('draw-line-static.cold', 'line-dasharray'); defaultStyle['fill-opacity'] = this.map.getPaintProperty('draw-polygon-static.cold', 'fill-opacity'); defaultStyle['circle-radius'] = this.map.getPaintProperty('draw-point-static.cold', 'circle-radius'); this.defaultStyle = defaultStyle; } } removed() { this.clearAllFeatures(); this.draw = null; } clearAllFeatures() { this.featureIds && this.draw.delete(this.featureIds); this.featureIds = []; this.activeFeature = {}; this.dashedLayerIds = []; this.layerStyleList = {}; } _isDrawing() { // @ts-ignore return this.draw && drawEvent.$options.getDrawingState(this.mapTarget, this.componentName); } }
the_stack
import { Color } from '../../Color'; import { BoundingBox } from '../BoundingBox'; import { EdgeCollider } from './EdgeCollider'; import { CollisionJumpTable } from './CollisionJumpTable'; import { CircleCollider } from './CircleCollider'; import { CollisionContact } from '../Detection/CollisionContact'; import { Projection } from '../../Math/projection'; import { Line } from '../../Math/line'; import { Vector } from '../../Math/vector'; import { Ray } from '../../Math/ray'; import { ClosestLineJumpTable } from './ClosestLineJumpTable'; import { Transform, TransformComponent } from '../../EntityComponentSystem'; import { Collider } from './Collider'; import { ExcaliburGraphicsContext } from '../..'; export interface PolygonColliderOptions { /** * Pixel offset relative to a collider's body transform position. */ offset?: Vector; /** * Points in the polygon in order around the perimeter in local coordinates. These are relative from the body transform position. */ points: Vector[]; /** * Whether points are specified in clockwise or counter clockwise order, default counter-clockwise */ clockwiseWinding?: boolean; } /** * Polygon collider for detecting collisions */ export class PolygonCollider extends Collider { /** * Pixel offset relative to a collider's body transform position. */ public offset: Vector; /** * Points in the polygon in order around the perimeter in local coordinates. These are relative from the body transform position. */ public points: Vector[]; private _transform: Transform; private _transformedPoints: Vector[] = []; private _axes: Vector[] = []; private _sides: Line[] = []; private _localSides: Line[] = []; constructor(options: PolygonColliderOptions) { super(); this.offset = options.offset ?? Vector.Zero; const winding = !!options.clockwiseWinding; this.points = (winding ? options.points.reverse() : options.points) || []; // calculate initial transformation this._calculateTransformation(); } /** * Returns a clone of this ConvexPolygon, not associated with any collider */ public clone(): PolygonCollider { return new PolygonCollider({ offset: this.offset.clone(), points: this.points.map((p) => p.clone()) }); } /** * Returns the world position of the collider, which is the current body transform plus any defined offset */ public get worldPos(): Vector { if (this._transform) { return this._transform.pos.add(this.offset); } return this.offset; } /** * Get the center of the collider in world coordinates */ public get center(): Vector { return this.bounds.center; } /** * Calculates the underlying transformation from the body relative space to world space */ private _calculateTransformation() { const transform = this._transform as TransformComponent; const pos = transform ? transform.globalPos.add(this.offset) : this.offset; const angle = transform ? transform.globalRotation : 0; const scale = transform ? transform.globalScale : Vector.One; const len = this.points.length; this._transformedPoints.length = 0; // clear out old transform for (let i = 0; i < len; i++) { this._transformedPoints[i] = this.points[i].scale(scale).rotate(angle).add(pos); } } /** * Gets the points that make up the polygon in world space, from actor relative space (if specified) */ public getTransformedPoints(): Vector[] { this._calculateTransformation(); return this._transformedPoints; } /** * Gets the sides of the polygon in world space */ public getSides(): Line[] { if (this._sides.length) { return this._sides; } const lines = []; const points = this.getTransformedPoints(); const len = points.length; for (let i = 0; i < len; i++) { // This winding is important lines.push(new Line(points[i], points[(i + 1) % len])); } this._sides = lines; return this._sides; } /** * Returns the local coordinate space sides */ public getLocalSides(): Line[] { if (this._localSides.length) { return this._localSides; } const lines = []; const points = this.points; const len = points.length; for (let i = 0; i < len; i++) { // This winding is important lines.push(new Line(points[i], points[(i + 1) % len])); } this._localSides = lines; return this._localSides; } /** * Given a direction vector find the world space side that is most in that direction * @param direction */ public findSide(direction: Vector): Line { const sides = this.getSides(); let bestSide = sides[0]; let maxDistance = -Number.MAX_VALUE; for (let side = 0; side < sides.length; side++) { const currentSide = sides[side]; const sideNormal = currentSide.normal(); const mostDirection = sideNormal.dot(direction); if (mostDirection > maxDistance) { bestSide = currentSide; maxDistance = mostDirection; } } return bestSide; } /** * Given a direction vector find the local space side that is most in that direction * @param direction */ public findLocalSide(direction: Vector): Line { const sides = this.getLocalSides(); let bestSide = sides[0]; let maxDistance = -Number.MAX_VALUE; for (let side = 0; side < sides.length; side++) { const currentSide = sides[side]; const sideNormal = currentSide.normal(); const mostDirection = sideNormal.dot(direction); if (mostDirection > maxDistance) { bestSide = currentSide; maxDistance = mostDirection; } } return bestSide; } /** * Get the axis associated with the convex polygon */ public get axes(): Vector[] { if (this._axes.length) { return this._axes; } const axes = this.getSides().map((s) => s.normal()); this._axes = axes; return this._axes; } public update(transform: Transform): void { this._transform = transform; this._sides.length = 0; this._localSides.length = 0; this._axes.length = 0; this._transformedPoints.length = 0; this.getTransformedPoints(); this.getSides(); this.getLocalSides(); } /** * Tests if a point is contained in this collider in world space */ public contains(point: Vector): boolean { // Always cast to the right, as long as we cast in a consistent fixed direction we // will be fine const testRay = new Ray(point, new Vector(1, 0)); const intersectCount = this.getSides().reduce(function (accum, side) { if (testRay.intersect(side) >= 0) { return accum + 1; } return accum; }, 0); if (intersectCount % 2 === 0) { return false; } return true; } public getClosestLineBetween(collider: Collider): Line { if (collider instanceof CircleCollider) { return ClosestLineJumpTable.PolygonCircleClosestLine(this, collider); } else if (collider instanceof PolygonCollider) { return ClosestLineJumpTable.PolygonPolygonClosestLine(this, collider); } else if (collider instanceof EdgeCollider) { return ClosestLineJumpTable.PolygonEdgeClosestLine(this, collider); } else { throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof collider}`); } } /** * Returns a collision contact if the 2 colliders collide, otherwise collide will * return null. * @param collider */ public collide(collider: Collider): CollisionContact[] { if (collider instanceof CircleCollider) { return CollisionJumpTable.CollideCirclePolygon(collider, this); } else if (collider instanceof PolygonCollider) { return CollisionJumpTable.CollidePolygonPolygon(this, collider); } else if (collider instanceof EdgeCollider) { return CollisionJumpTable.CollidePolygonEdge(this, collider); } else { throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof collider}`); } } /** * Find the point on the collider furthest in the direction specified */ public getFurthestPoint(direction: Vector): Vector { const pts = this.getTransformedPoints(); let furthestPoint = null; let maxDistance = -Number.MAX_VALUE; for (let i = 0; i < pts.length; i++) { const distance = direction.dot(pts[i]); if (distance > maxDistance) { maxDistance = distance; furthestPoint = pts[i]; } } return furthestPoint; } /** * Find the local point on the collider furthest in the direction specified * @param direction */ public getFurthestLocalPoint(direction: Vector): Vector { const pts = this.points; let furthestPoint = pts[0]; let maxDistance = -Number.MAX_VALUE; for (let i = 0; i < pts.length; i++) { const distance = direction.dot(pts[i]); if (distance > maxDistance) { maxDistance = distance; furthestPoint = pts[i]; } } return furthestPoint; } /** * Finds the closes face to the point using perpendicular distance * @param point point to test against polygon */ public getClosestFace(point: Vector): { distance: Vector; face: Line } { const sides = this.getSides(); let min = Number.POSITIVE_INFINITY; let faceIndex = -1; let distance = -1; for (let i = 0; i < sides.length; i++) { const dist = sides[i].distanceToPoint(point); if (dist < min) { min = dist; faceIndex = i; distance = dist; } } if (faceIndex !== -1) { return { distance: sides[faceIndex].normal().scale(distance), face: sides[faceIndex] }; } return null; } /** * Get the axis aligned bounding box for the polygon collider in world coordinates */ public get bounds(): BoundingBox { const tx = this._transform as TransformComponent; const scale = tx?.globalScale ?? Vector.One; const rotation = tx?.globalRotation ?? 0; const pos = (tx?.globalPos ?? Vector.Zero).add(this.offset); return this.localBounds.scale(scale).rotate(rotation).translate(pos); } /** * Get the axis aligned bounding box for the polygon collider in local coordinates */ public get localBounds(): BoundingBox { return BoundingBox.fromPoints(this.points); } /** * Get the moment of inertia for an arbitrary polygon * https://en.wikipedia.org/wiki/List_of_moments_of_inertia */ public getInertia(mass: number): number { let numerator = 0; let denominator = 0; for (let i = 0; i < this.points.length; i++) { const iplusone = (i + 1) % this.points.length; const crossTerm = this.points[iplusone].cross(this.points[i]); numerator += crossTerm * (this.points[i].dot(this.points[i]) + this.points[i].dot(this.points[iplusone]) + this.points[iplusone].dot(this.points[iplusone])); denominator += crossTerm; } return (mass / 6) * (numerator / denominator); } /** * Casts a ray into the polygon and returns a vector representing the point of contact (in world space) or null if no collision. */ public rayCast(ray: Ray, max: number = Infinity) { // find the minimum contact time greater than 0 // contact times less than 0 are behind the ray and we don't want those const sides = this.getSides(); const len = sides.length; let minContactTime = Number.MAX_VALUE; let contactIndex = -1; for (let i = 0; i < len; i++) { const contactTime = ray.intersect(sides[i]); if (contactTime >= 0 && contactTime < minContactTime && contactTime <= max) { minContactTime = contactTime; contactIndex = i; } } // contact was found if (contactIndex >= 0) { return ray.getPoint(minContactTime); } // no contact found return null; } /** * Project the edges of the polygon along a specified axis */ public project(axis: Vector): Projection { const points = this.getTransformedPoints(); const len = points.length; let min = Number.MAX_VALUE; let max = -Number.MAX_VALUE; for (let i = 0; i < len; i++) { const scalar = points[i].dot(axis); min = Math.min(min, scalar); max = Math.max(max, scalar); } return new Projection(min, max); } public draw(ctx: CanvasRenderingContext2D, color: Color = Color.Green, pos: Vector = Vector.Zero) { const effectiveOffset = pos.add(this.offset); ctx.beginPath(); ctx.fillStyle = color.toString(); const firstPoint = this.points[0].add(effectiveOffset); ctx.moveTo(firstPoint.x, firstPoint.y); // Points are relative this.points .map((p) => p.add(effectiveOffset)) .forEach(function (point) { ctx.lineTo(point.x, point.y); }); ctx.lineTo(firstPoint.x, firstPoint.y); ctx.closePath(); ctx.fill(); } public debug(ex: ExcaliburGraphicsContext, color: Color) { const firstPoint = this.getTransformedPoints()[0]; const points = [firstPoint, ...this.getTransformedPoints(), firstPoint]; for (let i = 0; i < points.length - 1; i++) { ex.drawLine(points[i], points[i + 1], color, 2); ex.drawCircle(points[i], 2, color); ex.drawCircle(points[i + 1], 2, color); } } /* istanbul ignore next */ public debugDraw(ctx: CanvasRenderingContext2D, color: Color = Color.Red) { ctx.beginPath(); ctx.strokeStyle = color.toString(); // Iterate through the supplied points and construct a 'polygon' const firstPoint = this.getTransformedPoints()[0]; ctx.moveTo(firstPoint.x, firstPoint.y); this.getTransformedPoints().forEach(function (point) { ctx.lineTo(point.x, point.y); }); ctx.lineTo(firstPoint.x, firstPoint.y); ctx.closePath(); ctx.stroke(); } }
the_stack
import React from 'react'; import { DualListSelector, DualListSelectorPane, DualListSelectorList, DualListSelectorControlsWrapper, DualListSelectorControl, DualListSelectorTree, DualListSelectorTreeItemData, SearchInput } from '@patternfly/react-core'; import AngleDoubleLeftIcon from '@patternfly/react-icons/dist/esm/icons/angle-double-left-icon'; import AngleLeftIcon from '@patternfly/react-icons/dist/esm/icons/angle-left-icon'; import AngleDoubleRightIcon from '@patternfly/react-icons/dist/esm/icons/angle-double-right-icon'; import AngleRightIcon from '@patternfly/react-icons/dist/esm/icons/angle-right-icon'; interface FoodNode { id: string; text: string; children?: FoodNode[]; } interface ExampleProps { data: FoodNode[]; } export const ComposableDualListSelectorTree: React.FunctionComponent<ExampleProps> = ({ data }: ExampleProps) => { const [checkedLeafIds, setCheckedLeafIds] = React.useState<string[]>([]); const [chosenLeafIds, setChosenLeafIds] = React.useState<string[]>(['beans', 'beef', 'chicken', 'tofu']); const [chosenFilter, setChosenFilter] = React.useState<string>(''); const [availableFilter, setAvailableFilter] = React.useState<string>(''); let hiddenChosen: string[] = []; let hiddenAvailable: string[] = []; // helper function to build memoized lists const buildTextById = (node: FoodNode): { [key: string]: string } => { let textById = {}; if (!node) { return textById; } textById[node.id] = node.text; if (node.children) { node.children.forEach(child => { textById = { ...textById, ...buildTextById(child) }; }); } return textById; }; // helper function to build memoized lists const getDescendantLeafIds = (node: FoodNode): string[] => { if (!node.children || !node.children.length) { return [node.id]; } else { let childrenIds = []; node.children.forEach(child => { childrenIds = [...childrenIds, ...getDescendantLeafIds(child)]; }); return childrenIds; } }; // helper function to build memoized lists const getLeavesById = (node: FoodNode): { [key: string]: string[] } => { let leavesById = {}; if (!node.children || !node.children.length) { leavesById[node.id] = [node.id]; } else { node.children.forEach(child => { leavesById[node.id] = getDescendantLeafIds(node); leavesById = { ...leavesById, ...getLeavesById(child) }; }); } return leavesById; }; // Builds a map of child leaf nodes by node id - memoized so that it only rebuilds the list if the data changes. const { memoizedLeavesById, memoizedAllLeaves, memoizedNodeText } = React.useMemo(() => { let leavesById = {}; let allLeaves = []; let nodeTexts = {}; data.forEach(foodNode => { nodeTexts = { ...nodeTexts, ...buildTextById(foodNode) }; leavesById = { ...leavesById, ...getLeavesById(foodNode) }; allLeaves = [...allLeaves, ...getDescendantLeafIds(foodNode)]; }); return { memoizedLeavesById: leavesById, memoizedAllLeaves: allLeaves, memoizedNodeText: nodeTexts }; }, [data]); const moveChecked = (toChosen: boolean) => { setChosenLeafIds( prevChosenIds => toChosen ? [...prevChosenIds, ...checkedLeafIds] // add checked ids to chosen list : [...prevChosenIds.filter(x => !checkedLeafIds.includes(x))] // remove checked ids from chosen list ); // uncheck checked ids that just moved setCheckedLeafIds(prevChecked => toChosen ? [...prevChecked.filter(x => chosenLeafIds.includes(x))] : [...prevChecked.filter(x => !chosenLeafIds.includes(x))] ); }; const moveAll = (toChosen: boolean) => { if (toChosen) { setChosenLeafIds(memoizedAllLeaves); } else { setChosenLeafIds([]); } }; const areAllDescendantsSelected = (node: FoodNode, isChosen: boolean) => memoizedLeavesById[node.id].every( id => checkedLeafIds.includes(id) && (isChosen ? chosenLeafIds.includes(id) : !chosenLeafIds.includes(id)) ); const areSomeDescendantsSelected = (node: FoodNode, isChosen: boolean) => memoizedLeavesById[node.id].some( id => checkedLeafIds.includes(id) && (isChosen ? chosenLeafIds.includes(id) : !chosenLeafIds.includes(id)) ); const isNodeChecked = (node: FoodNode, isChosen: boolean) => { if (areAllDescendantsSelected(node, isChosen)) { return true; } if (areSomeDescendantsSelected(node, isChosen)) { return null; } return false; }; const onOptionCheck = ( event: React.MouseEvent | React.ChangeEvent<HTMLInputElement> | React.KeyboardEvent, isChecked: boolean, node: DualListSelectorTreeItemData, isChosen: boolean ) => { const nodeIdsToCheck = memoizedLeavesById[node.id].filter(id => isChosen ? chosenLeafIds.includes(id) && !hiddenChosen.includes(id) : !chosenLeafIds.includes(id) && !hiddenAvailable.includes(id) ); if (isChosen) { hiddenChosen = []; } else { hiddenAvailable = []; } setCheckedLeafIds(prevChecked => { const otherCheckedNodeNames = prevChecked.filter(id => !nodeIdsToCheck.includes(id)); return !isChecked ? otherCheckedNodeNames : [...otherCheckedNodeNames, ...nodeIdsToCheck]; }); }; // builds a search input - used in each dual list selector pane const buildSearchInput = (isChosen: boolean) => { const onChange = value => (isChosen ? setChosenFilter(value) : setAvailableFilter(value)); return ( <SearchInput value={isChosen ? chosenFilter : availableFilter} onChange={onChange} onClear={() => onChange('')} /> ); }; // Builds the DualListSelectorTreeItems from the FoodNodes const buildOptions = ( isChosen: boolean, [node, ...remainingNodes]: FoodNode[], hasParentMatch: boolean ): DualListSelectorTreeItemData[] => { if (!node) { return []; } const isChecked = isNodeChecked(node, isChosen); const filterValue = isChosen ? chosenFilter : availableFilter; const descendentLeafIds = memoizedLeavesById[node.id]; const descendentsOnThisPane = isChosen ? descendentLeafIds.filter(id => chosenLeafIds.includes(id)) : descendentLeafIds.filter(id => !chosenLeafIds.includes(id)); const hasMatchingChildren = filterValue && descendentsOnThisPane.some(id => memoizedNodeText[id].includes(filterValue)); const isFilterMatch = filterValue && node.text.includes(filterValue) && descendentsOnThisPane.length > 0; // A node is displayed if either of the following is true: // - There is no filter value and this node or its descendents belong on this pane // - There is a filter value and this node or one of this node's descendents or ancestors match on this pane const isDisplayed = (!filterValue && descendentsOnThisPane.length > 0) || hasMatchingChildren || (hasParentMatch && descendentsOnThisPane.length > 0) || isFilterMatch; if (!isDisplayed) { if (isChosen) { hiddenChosen.push(node.id); } else { hiddenAvailable.push(node.id); } } return [ ...(isDisplayed ? [ { id: node.id, text: node.text, isChecked, checkProps: { 'aria-label': `Select ${node.text}` }, hasBadge: node.children && node.children.length > 0, badgeProps: { isRead: true }, defaultExpanded: isChosen ? !!chosenFilter : !!availableFilter, children: node.children ? buildOptions(isChosen, node.children, isFilterMatch || hasParentMatch) : undefined } ] : []), ...(!isDisplayed && node.children && node.children.length ? buildOptions(isChosen, node.children, hasParentMatch) : []), ...(remainingNodes ? buildOptions(isChosen, remainingNodes, hasParentMatch) : []) ]; }; const buildPane = (isChosen: boolean): React.ReactNode => { const options: DualListSelectorTreeItemData[] = buildOptions(isChosen, data, false); const numOptions = isChosen ? chosenLeafIds.length : memoizedAllLeaves.length - chosenLeafIds.length; const numSelected = checkedLeafIds.filter(id => isChosen ? chosenLeafIds.includes(id) : !chosenLeafIds.includes(id) ).length; const status = `${numSelected} of ${numOptions} options selected`; return ( <DualListSelectorPane title={isChosen ? 'Chosen' : 'Available'} status={status} searchInput={buildSearchInput(isChosen)} isChosen={isChosen} > <DualListSelectorList> <DualListSelectorTree data={options} onOptionCheck={(e, isChecked, itemData) => onOptionCheck(e, isChecked, itemData, isChosen)} /> </DualListSelectorList> </DualListSelectorPane> ); }; return ( <DualListSelector isTree> {buildPane(false)} <DualListSelectorControlsWrapper aria-label="Selector controls"> <DualListSelectorControl isDisabled={!checkedLeafIds.filter(x => !chosenLeafIds.includes(x)).length} onClick={() => moveChecked(true)} aria-label="Add selected" > <AngleRightIcon /> </DualListSelectorControl> <DualListSelectorControl isDisabled={chosenLeafIds.length === memoizedAllLeaves.length} onClick={() => moveAll(true)} aria-label="Add all" > <AngleDoubleRightIcon /> </DualListSelectorControl> <DualListSelectorControl isDisabled={chosenLeafIds.length === 0} onClick={() => moveAll(false)} aria-label="Remove all" > <AngleDoubleLeftIcon /> </DualListSelectorControl> <DualListSelectorControl onClick={() => moveChecked(false)} isDisabled={!checkedLeafIds.filter(x => !!chosenLeafIds.includes(x)).length} aria-label="Remove selected" > <AngleLeftIcon /> </DualListSelectorControl> </DualListSelectorControlsWrapper> {buildPane(true)} </DualListSelector> ); }; export const ComposableDualListSelectorTreeExample: React.FunctionComponent = () => ( <ComposableDualListSelectorTree data={[ { id: 'fruits', text: 'Fruits', children: [ { id: 'apple', text: 'Apple' }, { id: 'berries', text: 'Berries', children: [ { id: 'blueberry', text: 'Blueberry' }, { id: 'strawberry', text: 'Strawberry' } ] }, { id: 'banana', text: 'Banana' } ] }, { id: 'bread', text: 'Bread' }, { id: 'vegetables', text: 'Vegetables', children: [ { id: 'broccoli', text: 'Broccoli' }, { id: 'cauliflower', text: 'Cauliflower' } ] }, { id: 'proteins', text: 'Proteins', children: [ { id: 'beans', text: 'Beans' }, { id: 'meats', text: 'Meats', children: [ { id: 'beef', text: 'Beef' }, { id: 'chicken', text: 'Chicken' } ] }, { id: 'tofu', text: 'Tofu' } ] } ]} /> );
the_stack
import {PrintPreviewModelElement, PrintPreviewScalingSettingsElement, ScalingType} from 'chrome://print/print_preview.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {fakeDataBind} from 'chrome://webui-test/test_util.js'; import {selectOption, triggerInputEvent} from './print_preview_test_utils.js'; const scaling_settings_test = { suiteName: 'ScalingSettingsTest', TestNames: { ShowCorrectDropdownOptions: 'show correct dropdown options', SetScaling: 'set scaling', InputNotDisabledOnValidityChange: 'input not disabled on validity change', }, }; Object.assign(window, {scaling_settings_test: scaling_settings_test}); suite(scaling_settings_test.suiteName, function() { let scalingSection: PrintPreviewScalingSettingsElement; let model: PrintPreviewModelElement; setup(function() { document.body.innerHTML = ''; model = document.createElement('print-preview-model'); document.body.appendChild(model); scalingSection = document.createElement('print-preview-scaling-settings'); scalingSection.settings = model.settings; scalingSection.disabled = false; setDocumentPdf(false); fakeDataBind(model, scalingSection, 'settings'); document.body.appendChild(scalingSection); }); test( assert(scaling_settings_test.TestNames.ShowCorrectDropdownOptions), function() { // Not a PDF document -> No fit to page or fit to paper options. const fitToPageOption = scalingSection.shadowRoot!.querySelector<HTMLOptionElement>( `[value="${ScalingType.FIT_TO_PAGE}"]`)!; const fitToPaperOption = scalingSection.shadowRoot!.querySelector<HTMLOptionElement>( `[value="${ScalingType.FIT_TO_PAPER}"]`)!; const defaultOption = scalingSection.shadowRoot!.querySelector<HTMLOptionElement>( `[value="${ScalingType.DEFAULT}"]`)!; const customOption = scalingSection.shadowRoot!.querySelector<HTMLOptionElement>( `[value="${ScalingType.CUSTOM}"]`)!; assertTrue(fitToPageOption.hidden && fitToPageOption.disabled); assertTrue(fitToPaperOption.hidden && fitToPaperOption.disabled); assertFalse(defaultOption.hidden && !defaultOption.disabled); assertFalse(customOption.hidden && !customOption.disabled); // Fit to page and paper available -> All 4 options. setDocumentPdf(true); assertFalse(fitToPageOption.hidden && !fitToPageOption.disabled); assertFalse(fitToPaperOption.hidden && !fitToPaperOption.disabled); assertFalse(defaultOption.hidden && !defaultOption.disabled); assertFalse(customOption.hidden && !customOption.disabled); }); /** * @param expectedScaling The expected scaling value. * @param valid Whether the scaling setting is valid. * @param scalingType Expected scaling type for modifiable content. * @param scalingTypePdf Expected scaling type for PDFs. * @param scalingDisplayValue The value that should be displayed in * the UI for scaling. */ function validateState( expectedScaling: string, valid: boolean, scalingType: ScalingType, scalingTypePdf: ScalingType, scalingDisplayValue: string) { // Validate the settings were set as expected. assertEquals(expectedScaling, scalingSection.getSettingValue('scaling')); assertEquals(valid, scalingSection.getSetting('scaling').valid); assertEquals(scalingType, scalingSection.getSetting('scalingType').value); assertEquals( scalingTypePdf, scalingSection.getSetting('scalingTypePdf').value); // Validate UI values that are set by JS. const scalingInput = scalingSection.shadowRoot! .querySelector('print-preview-number-settings-section')!.getInput(); const expectedCollapseOpened = (scalingSection.getSettingValue('scalingType') === ScalingType.CUSTOM) || (scalingSection.getSettingValue('scalingTypePdf') === ScalingType.CUSTOM); const collapse = scalingSection.shadowRoot!.querySelector('iron-collapse')!; assertEquals(!valid, scalingInput.invalid); assertEquals(scalingDisplayValue, scalingInput.value); assertEquals(expectedCollapseOpened, collapse.opened); } /** * @param isPdf Whether the document is a PDF */ function setDocumentPdf(isPdf: boolean) { model.set('settings.scalingType.available', !isPdf); model.set('settings.scalingTypePdf.available', isPdf); scalingSection.isPdf = isPdf; } // Verifies that setting the scaling value using the dropdown and/or the // custom input works correctly. test(assert(scaling_settings_test.TestNames.SetScaling), async () => { // Default is 100 const scalingInput = scalingSection.shadowRoot! .querySelector('print-preview-number-settings-section')!.$.userValue .inputElement; // Make fit to page and fit to paper available. setDocumentPdf(true); // Default is 100 validateState('100', true, ScalingType.DEFAULT, ScalingType.DEFAULT, '100'); assertFalse(scalingSection.getSetting('scaling').setFromUi); assertFalse(scalingSection.getSetting('scalingType').setFromUi); assertFalse(scalingSection.getSetting('scalingTypePdf').setFromUi); // Select custom await selectOption(scalingSection, ScalingType.CUSTOM.toString()); validateState('100', true, ScalingType.CUSTOM, ScalingType.CUSTOM, '100'); assertTrue(scalingSection.getSetting('scalingType').setFromUi); assertTrue(scalingSection.getSetting('scalingTypePdf').setFromUi); await triggerInputEvent(scalingInput, '105', scalingSection); validateState('105', true, ScalingType.CUSTOM, ScalingType.CUSTOM, '105'); assertTrue(scalingSection.getSetting('scaling').setFromUi); // Change to fit to page. await selectOption(scalingSection, ScalingType.FIT_TO_PAGE.toString()); validateState( '105', true, ScalingType.CUSTOM, ScalingType.FIT_TO_PAGE, '105'); // Change to fit to paper. await selectOption(scalingSection, ScalingType.FIT_TO_PAPER.toString()); validateState( '105', true, ScalingType.CUSTOM, ScalingType.FIT_TO_PAPER, '105'); // Go back to custom. Restores 105 value. await selectOption(scalingSection, ScalingType.CUSTOM.toString()); validateState('105', true, ScalingType.CUSTOM, ScalingType.CUSTOM, '105'); // Set scaling to something invalid. Should change setting validity // but not value. await triggerInputEvent(scalingInput, '5', scalingSection); validateState('105', false, ScalingType.CUSTOM, ScalingType.CUSTOM, '5'); // Select fit to page. Should clear the invalid value. await selectOption(scalingSection, ScalingType.FIT_TO_PAGE.toString()); validateState( '105', true, ScalingType.CUSTOM, ScalingType.FIT_TO_PAGE, '105'); // Custom scaling should set to last valid. await selectOption(scalingSection, ScalingType.CUSTOM.toString()); validateState('105', true, ScalingType.CUSTOM, ScalingType.CUSTOM, '105'); // Set scaling to something invalid. Should change setting validity // but not value. await triggerInputEvent(scalingInput, '500', scalingSection); validateState('105', false, ScalingType.CUSTOM, ScalingType.CUSTOM, '500'); // Pick default scaling. This should clear the error. await selectOption(scalingSection, ScalingType.DEFAULT.toString()); validateState('105', true, ScalingType.DEFAULT, ScalingType.DEFAULT, '105'); // Custom scaling should set to last valid. await selectOption(scalingSection, ScalingType.CUSTOM.toString()); validateState('105', true, ScalingType.CUSTOM, ScalingType.CUSTOM, '105'); // Enter a blank value in the scaling field. This should not // change the stored value of scaling or scaling type, to avoid an // unnecessary preview regeneration. await triggerInputEvent(scalingInput, '', scalingSection); validateState('105', true, ScalingType.CUSTOM, ScalingType.CUSTOM, ''); }); // Verifies that the input is never disabled when the validity of the // setting changes. test( assert(scaling_settings_test.TestNames.InputNotDisabledOnValidityChange), async () => { const numberSection = scalingSection.shadowRoot!.querySelector( 'print-preview-number-settings-section')!; const input = numberSection.getInput(); // In the real UI, the print preview app listens for this event from // this section and others and sets disabled to true if any change from // true to false is detected. Imitate this here. Since we are only // interacting with the scaling input, at no point should the input be // disabled, as it will lose focus. model.addEventListener('setting-valid-changed', function() { assertFalse(input.disabled); }); await selectOption(scalingSection, ScalingType.CUSTOM.toString()); await triggerInputEvent(input, '90', scalingSection); validateState('90', true, ScalingType.CUSTOM, ScalingType.CUSTOM, '90'); // Set invalid input await triggerInputEvent(input, '9', scalingSection); validateState('90', false, ScalingType.CUSTOM, ScalingType.CUSTOM, '9'); // Restore valid input await triggerInputEvent(input, '90', scalingSection); validateState('90', true, ScalingType.CUSTOM, ScalingType.CUSTOM, '90'); // Invalid input again await triggerInputEvent(input, '9', scalingSection); validateState('90', false, ScalingType.CUSTOM, ScalingType.CUSTOM, '9'); // Clear input await triggerInputEvent(input, '', scalingSection); validateState('90', true, ScalingType.CUSTOM, ScalingType.CUSTOM, ''); // Set valid input await triggerInputEvent(input, '50', scalingSection); validateState('50', true, ScalingType.CUSTOM, ScalingType.CUSTOM, '50'); }); });
the_stack
import { Component, OnInit, AfterContentInit, AfterViewChecked, ElementRef, ViewChild, OnDestroy } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs'; import { BackendService, ServerStatus, MemberStatus, Connect } from './backend.service'; export class KeyValue { Key: string; Value: string; constructor(key: string, value: string) { this.Key = key; this.Value = value; } } export class ClientRequest { Action: string; // 'write', 'stress', 'get', 'delete', 'stop-node', 'restart-node' RangePrefix: boolean; // 'get', 'delete' Endpoints: string[]; KeyValue: KeyValue; constructor( act: string, prefix: boolean, eps: string[], key: string, value: string, ) { this.Action = act; this.RangePrefix = prefix; this.Endpoints = eps; this.KeyValue = new KeyValue(key, value); } } export class ClientResponse { ClientRequest: ClientRequest; Success: boolean; Result: string; ResultLines: string[]; KeyValues: KeyValue[]; constructor( clientRequest: ClientRequest, success: boolean, rs: string, rlines: string[], kvs: KeyValue[], ) { this.ClientRequest = clientRequest; this.Success = success; this.Result = rs; this.ResultLines = rlines; this.KeyValues = kvs; } } export class LogLine { index: number; logLevel: string; prefix: string; text: string; constructor(index: number, logLevel: string, text: string) { this.index = index; this.logLevel = logLevel; let date = new Date(); let yr = date.getFullYear(); let mo = date.getMonth() + 1; let da = date.getDate(); let timestamp = date.toTimeString().substring(0, 8); let moTxt = String(mo); if (moTxt.length === 1) { moTxt = '0' + moTxt; } let daTxt = String(da); if (daTxt.length === 1) { daTxt = '0' + daTxt; } let timePrefix = String(yr) + '-' + moTxt + '-' + daTxt + ' ' + timestamp; if (logLevel.length === 0) { logLevel = 'WARN'; } this.prefix = '[' + timePrefix + ' ' + logLevel + ']'; this.text = text; } } @Component({ selector: 'app-play', templateUrl: 'play.component.html', styleUrls: ['play.component.css'], providers: [BackendService], }) export class PlayComponent implements OnInit, AfterContentInit, AfterViewChecked, OnDestroy { // $("#logContainer").scrollTop($("#logContainer")[0].scrollHeight); @ViewChild('logContainer') private logScrollContainer: ElementRef; mode = 'Observable'; private clientRequestEndpoint = 'client-request'; logOutputLines: LogLine[]; selectedTab: number; selectedNodes = [true, false, false, false, false]; playgroundActive: boolean; serverUptime: string; serverVisits: number; userN: number; users: string[]; memberStatuses: MemberStatus[]; connect: Connect; connectErrorMessage: string; serverStatusErrorMessage: string; serverStatusHandler; inputKey: string; inputValue: string; deleteReadByPrefix: boolean; clientResponse: ClientResponse; clientResponseError: string; writeResult: string; deleteResult: string; readResult: string; connected: boolean; showUser: boolean; constructor(private backendService: BackendService, private http: Http) { this.logOutputLines = []; this.selectedTab = 0; this.connect = backendService.connect; this.connectErrorMessage = ''; this.serverStatusErrorMessage = ''; this.playgroundActive = backendService.serverStatus.PlaygroundActive; this.serverUptime = backendService.serverStatus.ServerUptime; this.serverVisits = backendService.serverStatus.ServerVisits; this.userN = backendService.serverStatus.UserN; this.users = backendService.serverStatus.Users; this.memberStatuses = backendService.serverStatus.MemberStatuses; this.inputKey = ''; this.inputValue = ''; this.deleteReadByPrefix = false; } ngOnInit(): void { this.playgroundActive = false; this.scrollToBottom(); } ngAfterContentInit() { console.log('getting initial server status'); this.clickConnect(); } ngAfterViewChecked() { this.scrollToBottom(); } // user leaves the template ngOnDestroy() { console.log('Disconnected from cluster (user left the page)!'); this.closeConnect(); clearInterval(this.serverStatusHandler); return; } scrollToBottom(): void { try { this.logScrollContainer.nativeElement.scrollTop = this.logScrollContainer.nativeElement.scrollHeight; } catch (err) { } } selectTab(num: number) { this.selectedTab = num; } getSelectedNodeIndexes() { let idxs = []; for (let _i = 0; _i < this.selectedNodes.length; _i++) { if (this.selectedNodes[_i]) { idxs.push(_i); } } return idxs; } getSelectedNodeEndpoints() { let idxs = this.getSelectedNodeIndexes(); let eps = []; for (let _i = 0; _i < idxs.length; _i++) { eps.push(this.memberStatuses[idxs[_i]].Endpoint); } return eps; } getSelectedNodeEndpointsTxt() { let eps = this.getSelectedNodeEndpoints(); let txt = 'no endpoint is selected...'; if (eps.length > 0) { txt = 'selected endpoints: '; for (let _i = 0; _i < eps.length; _i++) { if (_i > 0) { txt += ','; } txt += eps[_i]; } } return txt; } sendLogLine(logLevel: string, txt: string) { this.logOutputLines.push(new LogLine(this.logOutputLines.length, logLevel, txt)); } // https://angular.io/docs/ts/latest/guide/template-syntax.html trackByLineIndex(index: number, line: LogLine) { return line.index; } /////////////////////////////////////////////////////// processConnectResponse(resp: Connect) { this.connect = resp; this.connectErrorMessage = ''; } startConnect() { let connectResult: Connect; this.backendService.fetchConnect().subscribe( connect => connectResult = connect, error => this.connectErrorMessage = <any>error, () => this.processConnectResponse(connectResult), ); } closeConnect() { let connectResult: Connect; this.backendService.deleteConnect().subscribe( connect => connectResult = connect, error => this.connectErrorMessage = <any>error, () => this.processConnectResponse(connectResult), ); } clickConnect() { if (this.playgroundActive) { this.sendLogLine('INFO', 'Already connected to cluster!'); return; } this.playgroundActive = true; this.sendLogLine('OK', 'Hello World!'); this.sendLogLine('INFO', 'This is an actual etcd cluster.'); this.sendLogLine('WARN', 'IPs and user agents are used only to prevent abuse.'); this.startConnect(); let host = window.location.hostname; let port = ':' + String(this.connect.WebPort); let backendURL = host + port; this.sendLogLine('INFO', 'Connected to backend ' + backendURL); this.connected = true; // (X) setInterval(this.getServerStatus, 1000); this.serverStatusHandler = setInterval(() => this.getServerStatus(), 1000); } clickDisconnect() { if (!this.playgroundActive) { this.sendLogLine('WARN', 'Already disconnected!'); return; } this.playgroundActive = false; this.sendLogLine('WARN', 'Disconnected from etcd cluster!'); this.connected = false; this.closeConnect(); clearInterval(this.serverStatusHandler); } /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// processServerStatusResponse(resp: ServerStatus) { this.serverStatusErrorMessage = ''; this.playgroundActive = resp.PlaygroundActive; this.serverUptime = resp.ServerUptime; this.serverVisits = resp.ServerVisits; this.userN = resp.UserN; this.users = resp.Users; this.memberStatuses = resp.MemberStatuses; if (!this.playgroundActive) { this.closeConnect(); clearInterval(this.serverStatusHandler); }; }; // getServerStatus fetches server status from backend. // memberStatus is true to get the status of all nodes. getServerStatus() { let serverStatusResult: ServerStatus; this.backendService.fetchServerStatus().subscribe( serverStatus => serverStatusResult = serverStatus, error => this.serverStatusErrorMessage = <any>error, () => this.processServerStatusResponse(serverStatusResult), ); } /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// processClientResponse(resp: ClientResponse) { this.clientResponse = resp; let logLevel = 'OK'; if (!this.clientResponse.Success) { logLevel = 'WARN'; } if (this.clientResponse.ClientRequest.Action === 'stop-node') { logLevel = 'WARN'; } if (this.clientResponse.ClientRequest.Action === 'restart-node') { logLevel = 'INFO'; } switch (this.clientResponse.ClientRequest.Action) { case 'stress': // fallthrough case 'write': this.writeResult = this.clientResponse.Result; break; case 'delete': this.deleteResult = this.clientResponse.Result; break; case 'get': this.readResult = this.clientResponse.Result; break; } this.sendLogLine(logLevel, this.clientResponse.Result); if (this.clientResponse.ClientRequest.Action !== 'stop-node' && this.clientResponse.ClientRequest.Action !== 'restart-node') { for (let _i = 0; _i < this.clientResponse.ResultLines.length; _i++) { this.sendLogLine(logLevel, this.clientResponse.ResultLines[_i]); } } } processHTTPResponseClient(res: Response) { let jsonBody = res.json(); let clientResponse = <ClientResponse>jsonBody; return clientResponse || {}; } processHTTPErrorClient(error: any) { let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; console.error(errMsg); this.clientResponseError = errMsg; return Observable.throw(errMsg); } postClientRequest(clientRequest: ClientRequest): Observable<ClientResponse> { let body = JSON.stringify(clientRequest); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); // this returns without waiting for POST response let obser = this.http.post(this.clientRequestEndpoint, body, options) .map(this.processHTTPResponseClient) .catch(this.processHTTPErrorClient); return obser; } processClientRequest(act: string) { if (!this.playgroundActive) { this.sendLogLine('WARN', 'Not connected to cluster! (Please click "Connect" button.)'); return; } let eps = this.getSelectedNodeEndpoints(); let prefix = this.deleteReadByPrefix; let key = this.inputKey; let val = this.inputValue; let nodeIndex = this.selectedTab - 3; if (act === 'stop-node' || act === 'restart-node') { eps = [this.memberStatuses[nodeIndex].Endpoint]; prefix = false; key = ''; val = ''; this.sendLogLine('OK', 'requested "' + act + '" ' + this.memberStatuses[nodeIndex].Name); } else { this.sendLogLine('OK', 'requested "' + act + '" (' + this.getSelectedNodeEndpointsTxt() + ')'); } let clientRequest = new ClientRequest(act, prefix, eps, key, val); let clientResponseFromSubscribe: ClientResponse; this.postClientRequest(clientRequest).subscribe( clientResponse => clientResponseFromSubscribe = clientResponse, error => this.clientResponseError = <any>error, () => this.processClientResponse(clientResponseFromSubscribe), // on-complete ); } /////////////////////////////////////////////////////// clickShowUser() { this.showUser = !this.showUser; } }
the_stack
import React, { useState, useRef, useMemo, useCallback } from 'react'; import { Popover as UUIPopover, PopoverPlacement, PopoverPlacementPropTypes } from '../Popover'; import { Tag as UUITag } from '../Tag'; import { TextField as UUITextField } from '../Input'; import { flatMap, compact } from 'lodash-es'; import { Icons } from '../../icons/Icons'; import { LoadingSpinner } from '../Loading/LoadingSpinner'; import { KeyCode } from '../../utils/keyboardHelper'; import { ListBox as UUIListBox, ListBoxItem } from '../ListBox'; import { UUIFunctionComponent, UUIComponentProps, UUIFunctionComponentProps } from '../../core'; import { createComponentPropTypes, PropTypes, ExtraPropTypes } from '../../utils/createPropTypes'; export interface SelectOption { key: string; label: string; content?: React.ReactNode; value: string; /** * Whether the option of select is non-interactive. * @default false */ disabled?: boolean; static?: boolean; } interface SelectOptionsProps { /** * Options of Select. */ options: SelectOption[]; } interface SelectSectionsProps { /** * Sections of Options of Select. */ sections: { key: string; label?: React.ReactNode; options: SelectOption[]; }[]; } interface SelectValueProps< X extends true | false | boolean | undefined = undefined, Y = (X extends undefined ? string : (X extends true ? string[] : string)), T = Y | null, > { /** * Selected item. */ value: T | null; /** * Callback invoked when an item is selected. */ onChange: (value: T) => void; /** * */ multiple?: X; } type SelectSectionOptionProps = SelectSectionsProps | SelectOptionsProps interface BaseSelectFeatureProps { /** * Placeholder text when there is no value. * @default none */ placeholder?: string; /** * Whether the control is non-interactive. * @default false */ disabled?: boolean; /** * enable inputting text to search options. */ searchable?: boolean; searchPlaceholder?: string; /** * The custom search function, it invoked per option iteration. */ onSearch?: (option: SelectOption, q: string) => boolean; /** * dropdown placement */ dropdownPlacement?: PopoverPlacement; /** * Whether the control is loading. * @default false */ loading?: boolean; /** * Whether the content of Select should be rendered inside a `Portal` where appending inside `portalContainer`(if it provided) or `document.body`. * @default false */ usePortal?: boolean; /** * The container element into which the overlay renders its contents, when `usePortal` is `true`. * This prop is ignored if `usePortal` is `false`. * @default document.body */ portalContainer?: HTMLElement; onFocus?: React.FocusEventHandler<HTMLDivElement>; onBlur?: React.FocusEventHandler<HTMLDivElement>; } export type SelectFeatureProps<X extends true | false | boolean | undefined = undefined> = SelectValueProps<X> & SelectSectionOptionProps & BaseSelectFeatureProps export const SelectOptionPropTypes = createComponentPropTypes<SelectOption>({ key: PropTypes.string.isRequired, label: PropTypes.string.isRequired, content: PropTypes.node, value: PropTypes.string.isRequired, disabled: PropTypes.bool, static: PropTypes.bool, }) export const SelectPropTypes = createComponentPropTypes<SelectFeatureProps<any>>({ placeholder: PropTypes.string, disabled: PropTypes.bool, searchable: PropTypes.bool, searchPlaceholder: PropTypes.string, onSearch: PropTypes.func, dropdownPlacement: PopoverPlacementPropTypes, loading: PropTypes.bool, usePortal: PropTypes.bool, portalContainer: PropTypes.any, onFocus: PropTypes.func, onBlur: PropTypes.func, options: PropTypes.arrayOf(PropTypes.shape(SelectOptionPropTypes)), sections: PropTypes.arrayOf(PropTypes.shape({ key: PropTypes.string.isRequired, label: PropTypes.node, options: PropTypes.arrayOf(PropTypes.shape(SelectOptionPropTypes)).isRequired, })), value: ExtraPropTypes.nullable(PropTypes.oneOfType([ PropTypes.string, PropTypes.arrayOf(PropTypes.string), ]).isRequired), onChange: PropTypes.func.isRequired, multiple: PropTypes.bool, }) const SelectNodes = { Root: 'div', Activator: 'div', Placeholder: 'div', Result: 'div', Dropdown: UUIPopover, DropdownIcon: Icons.ChevronDown, TagInputContainer: 'div', Tag: UUITag, SearchMatched: 'span', ActionBox: 'div', LoadingSpinner: LoadingSpinner, OptionList: UUIListBox, Section: 'div', Option: 'div', SearchInput: UUITextField, SearchIcon: Icons.Search, SearchList: UUIListBox, } as const export const BaseSelect = UUIFunctionComponent({ name: 'Select', nodes: SelectNodes, propTypes: SelectPropTypes, }, (props: SelectFeatureProps<boolean | undefined>, { nodes, NodeDataProps }) => { const { Root, Dropdown, DropdownIcon, Activator, Result, Placeholder, TagInputContainer, ActionBox, OptionList, Section, Option, SearchList, SearchInput, SearchIcon, LoadingSpinner, Tag, } = nodes const finalProps = { disabled: props.disabled === undefined ? false : props.disabled, searchable: props.searchable === undefined ? false : props.searchable, placeholder: props.placeholder || 'select options...', searchPlaceholder: props.searchPlaceholder || 'Search options...', dropdownPlacement: props.dropdownPlacement === undefined ? 'bottom-start' : props.dropdownPlacement } const [active, setActive] = useState<boolean>(false) const [searchInputValue, setSearchInputValue] = useState('') const ref = useRef<any>(null) const allOptions = useMemo(() => { if (isNormalOptions(props)) return props.options if (isSectionedOptions(props)) { return flatMap(props.sections, (i) => i.options) } return [] }, [props]) const openDropdown = useCallback(() => { setActive(true) }, []) const closeDropdown = useCallback(() => { setActive(false) setSearchInputValue('') }, []) /** * ListBox */ const displayResult = useMemo(() => { return props.value && props.value.length > 0 ? ( <Result> {isMultipleValue(props) ? ( <TagInputContainer> { props.value && props.value.length > 0 && compact(props.value.map((v) => allOptions?.find((i) => i.value === v))) .map((option) => { return ( <Tag key={option.key}>{option.label}</Tag> ) }) } </TagInputContainer> ) : ( allOptions?.find((i) => i.value === props.value)?.label )} </Result> ) : ( <Placeholder>{finalProps.placeholder}</Placeholder> ) }, [Placeholder, Result, Tag, TagInputContainer, allOptions, finalProps.placeholder, props]) const optionListItems = useMemo<ListBoxItem[]>(() => { const getOptionData = (i: SelectOption) => ({ id: i.key, content: <Option>{i.content || i.label}</Option>, }) const getSectionData = (i: { key: string | number; label?: React.ReactNode; options: SelectOption[]; }) => { return [ { id: i.key, content: <Section>{i.label}</Section>, disabled: true }, ...i.options.map(getOptionData), ] } if (isNormalOptions(props)) { return props.options.map(getOptionData) as any[] } else if (isSectionedOptions(props)) { return flatMap(props.sections.map(getSectionData)) as any[] } else { return [] as any[] } }, [Option, Section, props]) const optionListSelectedIds = useMemo(() => { if (!props.value) return [] if (isMultipleValue(props)) { return compact(props.value.map((i) => allOptions && allOptions.find((j) => j.value === i)?.key)) } else { return compact([allOptions && allOptions.find((j) => j.value === props.value)?.key]) } }, [props, allOptions]) const optionListHandleOnSelect = useCallback((selectedIds: string[]) => { if (isMultipleValue(props)) { if (selectedIds.length === 0) { props.onChange([]) } else { props.onChange(compact(selectedIds.map((i) => allOptions && allOptions.find((j) => j.key === i)?.value))) } } if (isSingleValue(props)) { if (selectedIds.length === 0) { props.onChange(null) } else { props.onChange((allOptions && allOptions.find((j) => j.key === selectedIds[0])?.value) || null) } closeDropdown() } }, [allOptions, closeDropdown, props]) const searchListItems = useMemo(() => { if (!searchInputValue) return null const matchedOptions = searchInOptions(searchInputValue, allOptions, props.onSearch) return matchedOptions.map((option) => { return { id: option.key, content: ( <Option>{option.label}</Option> ), } }) }, [Option, allOptions, props.onSearch, searchInputValue]) const searchListSelectedIds = useMemo(() => { return optionListSelectedIds.filter((id) => { return !!searchListItems?.find((item) => item.id === id) }) }, [optionListSelectedIds, searchListItems]) const searchListHandleOnSelect = useCallback((selectedId: string) => { if (!searchInputValue) return const option = allOptions.find((i) => i.key === selectedId) if (option) { if (isMultipleValue(props)) { const newValue = Array.from(props.value || []) newValue.push(option.value) props.onChange(newValue) } if (isSingleValue(props)) { props.onChange(option.value) } } }, [allOptions, props, searchInputValue]) const searchListHandleOnUnselect = useCallback((selectedId: string) => { if (!searchInputValue) return const option = allOptions.find((i) => i.key === selectedId) if (option) { if (isMultipleValue(props) && props.value) { const index = props.value.findIndex((i) => i === selectedId) const newValue = Array.from(props.value) newValue.splice(index, 1) props.onChange(newValue) } else { props.onChange(null) } } }, [allOptions, props, searchInputValue]) return ( <Root ref={ref} role="select" tabIndex={finalProps.disabled ? -1 : 0} {...NodeDataProps({ 'disabled': !!finalProps.disabled, 'active': !!active, 'loading': !!props.loading, 'searchable': !!finalProps.searchable, })} onKeyDown={(event) => { if (finalProps.disabled) return; switch (event.keyCode) { case KeyCode.Enter: case KeyCode.SpaceBar: if (!active) { openDropdown() } break case KeyCode.Escape: closeDropdown() break default: // do nothing } }} onFocus={props.onFocus} onBlur={props.onBlur} > <Dropdown usePortal={props.usePortal} portalContainer={props.portalContainer} active={active} placement={finalProps.dropdownPlacement} referenceElement={ref.current} onClickAway={() => { if (finalProps.disabled) return; closeDropdown() }} // modifiers for fix dropdown dynamic offset update modifiers={[{ name: "dynamic_offset", enabled: true, phase: "beforeWrite", requires: ["computeStyles"], fn: () => { /** */ }, effect: () => { return () => { /** */ } }, }]} activator={ <Activator onClick={() => { if (finalProps.disabled) return; if (!active) openDropdown() else closeDropdown() }} > {displayResult} {props.loading && ( <LoadingSpinner width={16} height={16} /> )} <DropdownIcon width={20} height={20} svgrProps={{ strokeWidth: 1 }} /> </Activator> } > <ActionBox> {props.searchable && ( <SearchInput value={searchInputValue} onChange={(value) => { setSearchInputValue(value) }} placeholder={finalProps.searchPlaceholder} customize={{ Root: { extendChildrenBefore: ( <SearchIcon /> ) } }} /> )} {(searchListItems) ? ( <SearchList items={searchListItems} selectedIds={searchListSelectedIds} onSelect={searchListHandleOnSelect} onUnselect={searchListHandleOnUnselect} multiple={props.multiple} /> ) : ( <OptionList items={optionListItems} disabled={!active} selectedIds={optionListSelectedIds} onSelected={optionListHandleOnSelect} multiple={props.multiple} /> )} </ActionBox> </Dropdown> </Root> ) }) const isSectionedOptions = (props: any): props is SelectSectionsProps => { if ((props as any)['sections']) return true else return false } const isNormalOptions = (props: any): props is SelectOptionsProps => { if ((props as any)['options']) return true else return false } const isMultipleValue = (props: any): props is SelectFeatureProps<true> => { if (props['multiple'] === true) return true else return false } const isSingleValue = (props: any): props is SelectFeatureProps<false> => { if (props['multiple'] === undefined || props['multiple'] === false) return true else return false } function searchInOptions(q: string, options: SelectOption[], predicate?: SelectFeatureProps<boolean | undefined>['onSearch']) { return options.filter((i) => predicate ? predicate(i, q) : i.label.includes(q) ) } export function Select<X extends true | false | boolean | undefined = undefined>(props: UUIComponentProps<SelectFeatureProps<X>, typeof SelectNodes>) { const _BaseSelect = BaseSelect as any return <_BaseSelect {...props} /> } Select.displayName = `<UUI> [GenericComponent] Radio` export type SelectProps = UUIFunctionComponentProps<typeof Select>
the_stack
import AParsing from "../parsing/AParsing"; import { utils } from "../utils/utils"; import { message } from "./message" export default class Popup { //#region "singleton" static getInstance(): Popup { if (Popup.#instance === null) { Popup.#instance = new Popup(); } return Popup.#instance; } static #instance: Popup | null = null //#endregion "singleton" // Update progress bar on the preview popup updateProgress(progress: number, doujinshiName: string, isZipping: boolean) { if (isZipping && progress == 100) { // File is being downloaded document.getElementById('action')!.innerHTML = message.downloadDone(); } else { // Download done document.getElementById('action')!.innerHTML = message.downloadProgress(isZipping ? "Zipping" : "Downloading", doujinshiName, progress); } document.getElementById('buttonBack')!.addEventListener('click', function() { let popup = Popup.getInstance(); (chrome.extension.getBackgroundPage() as any).goBack(); popup.updatePreviewAsync(popup.url); }); } // #region "single download" async updatePreviewAsync(newUrl: string) { let self = Popup.getInstance(); self.url = newUrl; let match = /https:\/\/nhentai.net\/g\/([0-9]+)\/([/0-9a-z]+)?/.exec(self.url) if (match !== null) { await self.#doujinshiPreviewAsync(match[1]); } else if (self.url.startsWith("https://nhentai.net")) { // @ts-ignore chrome.tabs.executeScript(null, { file: "js/getHtml.js" // Get the HTML of the page }); } else { document.getElementById('action')!.innerHTML = message.invalidPage(); } } // Display popup for a doujinshi async #doujinshiPreviewAsync(id: string) { const resp = await fetch(this.parsing!.GetUrl(id)); if (resp.status == 403) { document.getElementById('action')!.innerHTML = message.invalidPage(); } else if (!resp.ok) { document.getElementById('action')!.innerHTML = message.errorOther(resp.status, resp.statusText); } else { let json = await this.parsing!.GetJsonAsync(resp); let self = this; chrome.storage.sync.get({ useZip: "zip", downloadName: "{pretty}", replaceSpaces: true }, function(elems) { let extension = ""; if (elems.useZip == "zip") extension = ".zip"; else if (elems.useZip == "cbz") extension = ".cbz"; let title = utils.getDownloadName(elems.downloadName, json.title.pretty === "" ? json.title.english.replace(/\[[^\]]+\]/g, '').replace(/\([^\)]+\)/g, '') : json.title.pretty, json.title.english, json.title.japanese, id, json.tags); document.getElementById('action')!.innerHTML = message.downloadInfo(title, json.images.pages.length, extension); (document.getElementById('path') as HTMLInputElement).value = utils.cleanName(title, elems.replaceSpaces); document.getElementById('button')!.addEventListener('click', function() { (chrome.extension.getBackgroundPage() as any).downloadDoujinshi(json, (document.getElementById('path') as HTMLInputElement).value, function(error: string) { document.getElementById('action')!.innerHTML = message.errorDownload(error); }, self.updateProgress, title); self.updateProgress(0, title, false); }); }); } } //#endregion "single download" //#region "multiple download" updatePreviewAll(sourceHtml: string, downloadName: string, useZip: string, replaceSpaces: boolean) { let self = Popup.getInstance(); // Get doujins on the page let matchs = /<a href="\/g\/([0-9]+)\/".+<div class="caption">([^<]+)((<br>)+<input [^>]+>[^<]+<br>[^<]+<br>[^<]+)?<\/div>/g let match; let finalHtml = ""; let allIds: Array<string> = []; let i = 0; let pageHtml = sourceHtml.replace(/<\/a>/g, '\n'); do { match = matchs.exec(pageHtml); if (match !== null) { let isChecked = false; if (match[4] !== undefined ) { // For each doujin, we check if our custom checkbox is ticked var testMatch = pageHtml.match('<input id="' + match[1] + '" type="checkbox"( value="(true|false)")?>'); try { isChecked = testMatch![2] === "true"; } catch (_) { isChecked = false; } } let tmpName; if (downloadName === "{pretty}") { tmpName = match[2].replace(/\[[^\]]+\]/g, "").replace(/\([^\)]+\)/g, "").replace(/\{[^\}]+\}/g, "").trim(); } else { tmpName = match[2].trim(); } // Then we add a checkbox on the extension (preticked or not depending of previous result) finalHtml += '<input id="' + match[1] + '" name="' + tmpName + '" type="checkbox" ' + (isChecked ? "checked" : "") + '/>' + tmpName + '<br/>'; allIds.push(match[1]); i++; } } while (match); if (finalHtml === "") { document.getElementById('action')!.innerHTML = message.invalidPage(); return; } // Use URL for default download name let parts = self.url.split('/') let name; if (parts[parts.length - 1] === "" || parts[parts.length - 1].startsWith("?page=")) name = parts[parts.length - 2]; else name = parts[parts.length - 1]; name = name.replace("q=", ""); // Artifact when doing a search // Appends the extension (none is raw download) let extension = ""; if (useZip != "raw") { extension = "." + useZip; } // Add the HTML let nbDownload = 0; let currPage = 0; let maxPage = 0; let html = '<h3 id="center">' + i + ' doujinshi' + (i > 1 ? 's' : '') + ' found</h3>' + finalHtml + '<input type="button" id="invert" value="Invert all"/><input type="button" id="remove" value="Clear all"/><br/><br/><input type="button" id="button" value="Download"/>'; let lastMatch = /page=([0-9]+)" class="last">/.exec(pageHtml) // Get the number of pages if (lastMatch !== null) { currPage = parseInt(/page=([0-9]+)" class="page current">/.exec(pageHtml)![1]); maxPage = parseInt(lastMatch[1]); nbDownload = maxPage - currPage + 1; html += '<br/><input type="button" id="buttonAll" value="Download all (' + nbDownload + ' pages)"/><br/><input type="text" id="downloadInput"/><input type="button" id="buttonHelp" value="?"/>'; } html += '<br/><br/>Downloads/<input type="text" id="path"/>' + extension; document.getElementById('action')!.innerHTML = html; (document.getElementById('path') as HTMLInputElement).value = utils.cleanName(name, replaceSpaces); if (lastMatch !== null) { (document.getElementById('downloadInput') as HTMLInputElement).value = currPage + "-" + maxPage; document.getElementById('buttonHelp')!.addEventListener('click', function() { alert("Input the pages you want to download for the \"Download all\" feature\nWrite your pages separated by comma ',', you can also write range of number by separating them by a dash '-'\n" + "Example: 2,4,6-10 will download the pages 2, 4 and 6 to 10 (included)"); }); } // Invert all checkbox document.getElementById('invert')!.addEventListener('click', function() { let storageAllIds; chrome.storage.local.get({ allIds: [] }, function(elemsLocal) { // Iterate on all checkboxs and reverse the value storageAllIds = elemsLocal.allIds; for (let i = 0; i < allIds.length; i++) { let id = allIds[i]; let elem = (document.getElementById(id) as HTMLInputElement); elem.checked = !elem.checked; storageAllIds = self.#saveIdInLocalStorage(id, storageAllIds, elem.checked); } chrome.storage.local.set({ allIds: storageAllIds }); // @ts-ignore chrome.tabs.executeScript(null, { file: "js/updateContent.js" // Update the checkboxs of the page }); }); }); // Clear all checkboxs document.getElementById('remove')!.addEventListener('click', function() { // Just uncheck everything and empty local storage allIds.forEach(function(id) { (document.getElementById(id) as HTMLInputElement).checked = false; }); chrome.storage.local.set({ allIds: [] }); // @ts-ignore chrome.tabs.executeScript(null, { file: "js/updateContent.js" // Update the checkboxs of the page }); }); // Download button document.getElementById('button')!.addEventListener('click', function() { let allDoujinshis : Record<string, string> = {}; allIds.forEach(function(id) { let elem = document.getElementById(id) as HTMLInputElement; if (elem.checked) { allDoujinshis[id] = elem.name; } }); if (Object.keys(allDoujinshis).length > 0) { // There is at least one element selected, we launch download let finalName = (document.getElementById('path') as HTMLInputElement).value; (chrome.extension.getBackgroundPage() as any).downloadAllDoujinshis(allDoujinshis, finalName, function(error: string) { document.getElementById('action')!.innerHTML = message.errorDownload(error); }, Popup.getInstance().updateProgress); self.updateProgress(0, finalName, false); } else { document.getElementById('action')!.innerHTML = "You must select at least one element to download."; } }); if (nbDownload > 0) { // User input saying how many pages he wants to download document.getElementById('downloadInput')!.addEventListener('change', function() { let pages = self.#parseDownloadAll(maxPage); if (pages.length !== 0) { (document.getElementById("buttonAll") as HTMLInputElement).value = 'Download all (' + pages.length + ' pages)'; } }); // Download many pages at once document.getElementById('buttonAll')!.addEventListener('click', function() { let allDoujinshis : Record<string, string> = {}; allIds.forEach(function(id) { let elem = (document.getElementById(id) as HTMLInputElement); allDoujinshis[id] = elem.name; }); let pages = self.#parseDownloadAll(maxPage); if (typeof pages === "string") { alert(pages); (document.getElementById('downloadInput') as HTMLInputElement).value = currPage + "-" + nbDownload; } else { let choice = confirm("You are going to download " + pages.length + " pages of doujinshi. Are you sure you want to continue?"); if (choice) { let finalName = (document.getElementById('path') as HTMLInputElement).value; (chrome.extension.getBackgroundPage() as any).downloadAllPages(allDoujinshis, pages, finalName, function(error: string) { document.getElementById('action')!.innerHTML = 'An error occured while downloading the doujinshi: <b>' + error + '</b>'; }, self.updateProgress, self.url); self.updateProgress(0, finalName, false); } } }); } // We listen to all checkboxs on the page allIds.forEach(function(id) { (document.getElementById(id) as HTMLInputElement).addEventListener('change', function() { let checked = this.checked; chrome.storage.local.get({ allIds: [] }, function(elemsLocal) { // Add the ids in local storage so we can easily find them back from anywhere (even if page is reloaded etc) chrome.storage.local.set({ allIds: self.#saveIdInLocalStorage(id, elemsLocal.allIds, checked) }); }); // @ts-ignore chrome.tabs.executeScript(null, { file: "js/updateContent.js" // Update the checkboxs of the page }); }); chrome.storage.local.get({ allIds: [] }, function(elemsLocal) { if (elemsLocal.allIds.includes(id)) { (document.getElementById(id) as HTMLInputElement).checked = true; } }); }); } #saveIdInLocalStorage(id: string, allIds: Array<string>, checked: boolean) { if (checked) { allIds.push(id); } else { let index = allIds.indexOf(id); if (index !== -1) { allIds.splice(index, 1); } } return allIds; } #parseDownloadAll(maxPage: number) : Array<number> | string { let pages: Array<number> = [] let pageText = (document.getElementById('downloadInput') as HTMLInputElement).value; pageText.split(',').forEach(function(e: string) { let elem = e.trim(); let dash = elem.split('-'); if (dash.length > 1) { // There is a dash in the number (ex: 1-5) let lower = dash[0].trim(); let upper = dash[1].trim(); let lowerNb = parseInt(lower); let upperNb = parseInt(upper); if (lower !== '' + lowerNb || upper !== '' + upperNb) { return message.invalidSyntax(); } if (lowerNb < 0 || upperNb < 0 || lowerNb > maxPage || upperNb > maxPage) { return message.invalidPageNumber(maxPage); } if (upperNb <= lowerNb) { return message.invalidBounds(); } for (let i = lowerNb; i <= upperNb; i++) { if (!pages.includes(i)) pages.push(i); } } else { let pageNb = parseInt(elem); if (elem !== '' + pageNb) { return message.invalidSyntax(); } if (pageNb < 0 || pageNb > maxPage) { return message.invalidPageNumber(maxPage); } if (!pages.includes(pageNb)) pages.push(pageNb); } }); return pages; } //#endregion "multiple download" url: string; parsing: AParsing | null = null }
the_stack
import { Platform, AppState, NativeModules, Linking } from 'react-native' import { delay } from 'redux-saga' import { call, put, take, takeEvery, takeLatest, all, select } from 'redux-saga/effects' import { ActionType, getType } from 'typesafe-actions' import Textile, { Notification, INotificationList } from '@textile/react-native-sdk' import NavigationService from '../../Services/NavigationService' import { cafesActions } from '../cafes' import * as cafeSelectors from '../cafes/selectors' import { groupActions } from '../group' import ThreadsActions from '../../Redux/ThreadsRedux' import { ThreadData } from '../../Redux/GroupsRedux' import { threadDataByThreadId, allThreadIds } from '../../Redux/GroupsSelectors' import PhotoViewingActions from '../../Redux/PhotoViewingRedux' import { PreferencesSelectors, ServiceType } from '../../Redux/PreferencesRedux' import * as actions from './actions' import * as selectors from './selectors' import TextileEventsActions, { TextileEventsSelectors } from '../../Redux/TextileEventsRedux' import * as NotificationsServices from '../../Services/Notifications' import { logNewEvent } from '../../Sagas/DeviceLogs' import { RootState } from '../../Redux/Types' import { LocalAlertType } from './models' import VersionNumber from 'react-native-version-number' import { contactsActions, contactsSelectors } from '../contacts' export function* waitUntilOnline(ms: number) { let ttw = ms let online = yield select(TextileEventsSelectors.online) while (!online && ttw > 0) { yield delay(50) online = yield select(TextileEventsSelectors.online) ttw -= 50 } return online } export function* enable() { yield call(NotificationsServices.enable) } export function* readAllNotifications( action: ActionType<typeof actions.readAllNotificationsRequest> ) { try { yield call(Textile.notifications.readAll) } catch (error) { yield put( TextileEventsActions.newErrorMessage( 'readAllNotifications', error.message ) ) } } export function* handleNewNotification( action: ActionType<typeof actions.newNotificationRequest> ) { yield call(logNewEvent, 'Notifications', 'new request') try { const service = yield select(PreferencesSelectors.service, 'notifications') // if No notifications enabled, return if (!service || service.status !== true) { return } const { notification } = action.payload const type = notification.type // if notifications for this type are not enabled, return const typeString = NotificationsServices.notificationTypeToString(type) const preferences = yield select( PreferencesSelectors.service, typeString as ServiceType ) if (!preferences || preferences.status !== true) { return } // Ensure we aren't in the foreground (Android only req) // const queriedAppState = yield select(TextileNodeSelectors.appState) const queriedAppState = AppState.currentState if (Platform.OS === 'ios' || queriedAppState.match(/background/)) { // fire the notification yield call(logNewEvent, 'Notifications', 'creating local') yield call(NotificationsServices.createNew, notification) } else { yield call(logNewEvent, 'Notifications', 'creating local') } } catch (error) { const message = typeof error === 'string' ? error : error.message yield call(logNewEvent, 'Notifications', message, true) } } export function* handleEngagement( action: ActionType<typeof actions.notificationEngagement> ) { // Deals with the Engagement response from clicking a native notification const data: any = action.payload.engagement.data try { if (!data || !data.hasOwnProperty('notification')) { return } yield call(delay, 350) yield put(actions.notificationSuccess(data.notification)) } catch (error) { // Nothing to do } } function* requestAndNavigateTo(threadId: string, photoBlock?: string) { // Cache our thread data in redux yield put(groupActions.feed.loadFeedItems.request({ id: threadId })) // Select the thread yield put(PhotoViewingActions.viewThread(threadId)) if (photoBlock) { // if photo supplied, select and navigate to it yield put(PhotoViewingActions.viewPhoto(photoBlock)) yield call(NavigationService.navigate, 'PhotoScreen') } else { // if no photo, navigate to the thread only yield call(NavigationService.navigate, 'ViewThread', { threadId }) } } export function* notificationView( action: ActionType<typeof actions.notificationSuccess> ) { // Handles a view request for in App notification clicking or Engagement notification clicking // Avoids duplicating the below logic about where to send people for each notification type const { notification } = action.payload try { yield call(Textile.notifications.read, notification.id) switch (notification.type) { case Notification.Type.LIKE_ADDED: case Notification.Type.COMMENT_ADDED: { const threadData: ThreadData | undefined = yield select( threadDataByThreadId, notification.threadId ) if (threadData) { // notification.target of a COMMENT_ADDED / LIKE_ADDED is the photo block, so where we want to navigate yield call(requestAndNavigateTo, threadData.id, notification.target) } break } case Notification.Type.FILES_ADDED: { const threadData: ThreadData | undefined = yield select( threadDataByThreadId, notification.threadId ) if (threadData) { // notification.block of a FILES_ADDED is the photo block, so where we want to navigate yield call(requestAndNavigateTo, threadData.id, notification.block) } break } case Notification.Type.MESSAGE_ADDED: case Notification.Type.PEER_JOINED: case Notification.Type.PEER_LEFT: { const threadData: ThreadData | undefined = yield select( threadDataByThreadId, notification.threadId ) if (threadData) { yield call(requestAndNavigateTo, threadData.id) } break } case Notification.Type.INVITE_RECEIVED: { yield* waitUntilOnline(1000) yield put(actions.reviewNotificationThreadInvite(notification)) break } } } catch (error) { yield put(actions.notificationFailure(notification)) } } export function* refreshNotifications() { try { const busy: boolean = yield select((state: RootState) => selectors.refreshing(state.updates) ) // skip multi-request back to back if (busy) { return } yield* waitUntilOnline(1000) yield put(actions.refreshNotificationsStart()) const notificationResponse: INotificationList = yield call( Textile.notifications.list, '', 50 ) // TODO: offset? const appThreadIds = yield select(allThreadIds) const typedNotifs = notificationResponse.items .map(notificationData => NotificationsServices.toTypedNotification(notificationData) ) .filter(notification => { // converts the notification to Any since not all notifications have a threadId const { threadId } = notification as any if (threadId === undefined) { // These are device adds or new thread invites (not easy to know which app yet) return true } else { return appThreadIds.indexOf(threadId) > -1 } }) yield put(actions.refreshNotificationsSuccess(typedNotifs)) } catch (error) { yield put( TextileEventsActions.newErrorMessage( 'refreshNotifications', error.message ) ) yield put(actions.refreshNotificationsFailure()) } } export function* reviewThreadInvite( action: ActionType<typeof actions.reviewNotificationThreadInvite> ) { const { notification } = action.payload try { const payload = NotificationsServices.toPayload(notification) if (!payload) { return } yield call(NotificationsServices.displayInviteAlert, payload.message) yield put( ThreadsActions.acceptInviteRequest( notification.id, notification.threadName, false ) ) } catch (error) { // Ignore invite } } /** * Checks if the user has a storage bot added to their account. If none * then it creates a LocalAlert. * Run each time the app starts up and finishes checking cafe sessions. */ export function* updateCafeAlert() { const cafes = yield select((state: RootState) => cafeSelectors.registeredCafes(state.cafes) ) if (cafes.length > 0) { yield put(actions.removeAlert(LocalAlertType.NoStorageBot)) } else { yield put(actions.insertAlert(LocalAlertType.NoStorageBot, 5)) } } /** * Checks what the latest release is via URL. If the release is newer * than the current install, it will create a LocalAlert for the user. * Run each time the app starts up and finishes checking cafe sessions. */ export function* updateReleasesAlert() { // Only supported on iOS right now if (Platform.OS !== 'ios') { return } // Compares a semver, returns True of a < b function outOfDate(a: string, b: string) { let i const regExStrip0 = /(\.+)+$/ const segmentsA = a .replace('v', '') .replace(regExStrip0, '') .split('.') const segmentsB = b .replace('v', '') .replace(regExStrip0, '') .split('.') const l = Math.min(segmentsA.length, segmentsB.length) for (i = 0; i < l; i++) { const semA = parseInt(segmentsA[i], 10) const semB = parseInt(segmentsB[i], 10) if (semA === semB) { continue } else { return semA < semB } } return segmentsA.length < segmentsB.length } try { // Attempt to check latest releasae in the user's region const locale = NativeModules.SettingsManager.settings.AppleLocale // "fr_FR" const iso = locale .split('_') .reverse()[0] .toLowerCase() const country = iso && iso.length === 2 ? `&country=${iso}` : '' const query = yield call( fetch, `https://itunes.apple.com/lookup?id=1366428460${country}` ) const result = yield call([query, query.json]) // Continue only if data returned if (result.results && result.results.length > 0) { const version = yield call(Textile.version) const needUpgrade = outOfDate(version, result.results[0].version) // Check app store version against local API version if (needUpgrade) { yield put(actions.insertAlert(LocalAlertType.UpgradeNeeded, 3)) return } else { yield put(actions.removeAlert(LocalAlertType.UpgradeNeeded)) } } } catch (err) { // Default no alert yield put(actions.removeAlert(LocalAlertType.UpgradeNeeded)) } } /** * Checks if the user has any contacts. If none, then it will create * a LocalAlert for the user. * Run each time interface updates the contact list. */ export function* updateContactsAlert( action: ActionType<typeof contactsActions.getContactsSuccess> ) { const { contacts } = action.payload if (contacts.length > 0) { yield put(actions.removeAlert(LocalAlertType.NoContacts)) } else { yield put(actions.insertAlert(LocalAlertType.NoContacts, 2)) } } function* watchForContactUpdates() { const contacts = yield select((state: RootState) => state.contacts.contacts) const threads = yield select((state: RootState) => state.groups.threads) if (contacts.length > 0 || threads.length > 0) { // Don't bother showing it if the user is already creating threads. // This is in case they plan to use the app without contacts. yield put(actions.removeAlert(LocalAlertType.NoContacts)) } else { yield put(actions.insertAlert(LocalAlertType.NoContacts, 2)) yield takeLatest( getType(contactsActions.getContactsSuccess), updateContactsAlert ) } } export function* refreshAlerts() { yield all([ updateReleasesAlert(), updateCafeAlert(), watchForContactUpdates() ]) } export default function*() { yield all([ takeEvery(getType(cafesActions.getCafeSessions.success), refreshAlerts), takeEvery(getType(actions.newNotificationRequest), handleNewNotification), takeEvery(getType(actions.notificationEngagement), handleEngagement), takeEvery(getType(actions.notificationSuccess), notificationView), takeEvery( getType(actions.refreshNotificationsRequest), refreshNotifications ), takeEvery( getType(actions.reviewNotificationThreadInvite), reviewThreadInvite ), takeEvery( getType(actions.readAllNotificationsRequest), readAllNotifications ) ]) }
the_stack
import TileSetRenderer from "../../components/TileSetRenderer"; import TileSetRendererUpdater from "../../components/TileSetRendererUpdater"; import * as TreeView from "dnd-tree-view"; import * as ResizeHandle from "resize-handle"; let data: { projectClient: SupClient.ProjectClient; tileSetUpdater: TileSetRendererUpdater; selectedTile: { x: number; y: number; } }; let ui: any = {}; let socket: SocketIOClient.Socket; let hasStarted = false; let isTabActive = true; let animationFrame: number; window.addEventListener("message", (event) => { if (event.data.type === "deactivate" || event.data.type === "activate") { isTabActive = event.data.type === "activate"; onChangeActive(); } }); function onChangeActive() { const stopRendering = !hasStarted || !isTabActive; if (stopRendering) { if (animationFrame != null) { cancelAnimationFrame(animationFrame); animationFrame = null; } } else if (animationFrame == null) { animationFrame = requestAnimationFrame(tick); } } function start() { socket = SupClient.connect(SupClient.query.project); socket.on("connect", onConnected); socket.on("disconnect", SupClient.onDisconnected); // Drawing ui.gameInstance = new SupEngine.GameInstance(<HTMLCanvasElement>document.querySelector("canvas")); ui.gameInstance.threeRenderer.setClearColor(0xbbbbbb); const cameraActor = new SupEngine.Actor(ui.gameInstance, "Camera"); cameraActor.setLocalPosition(new SupEngine.THREE.Vector3(0, 0, 10)); ui.cameraComponent = new SupEngine.componentClasses["Camera"](cameraActor); ui.cameraComponent.setOrthographicMode(true); ui.cameraControls = new SupEngine.editorComponentClasses["Camera2DControls"]( cameraActor, ui.cameraComponent, { zoomSpeed: 1.5, zoomMin: 0.1, zoomMax: 10000 }, () => { data.tileSetUpdater.tileSetRenderer.gridRenderer.setOrthgraphicScale(ui.cameraComponent.orthographicScale); } ); // Sidebar new ResizeHandle(document.querySelector(".sidebar") as HTMLElement, "right"); const fileSelect = <HTMLInputElement>document.querySelector("input.file-select"); fileSelect.addEventListener("change", onFileSelectChange); document.querySelector("button.upload").addEventListener("click", () => { fileSelect.click(); }); document.querySelector("button.download").addEventListener("click", onDownloadTileset); ui.gridWidthInput = document.querySelector("input.grid-width"); ui.gridWidthInput.addEventListener("change", () => { data.projectClient.editAsset(SupClient.query.asset, "setProperty", "grid.width", parseInt(ui.gridWidthInput.value, 10)); }); ui.gridHeightInput = document.querySelector("input.grid-height"); ui.gridHeightInput.addEventListener("change", () => { data.projectClient.editAsset(SupClient.query.asset, "setProperty", "grid.height", parseInt(ui.gridHeightInput.value, 10)); }); ui.selectedTileInput = document.querySelector("input.selected-tile-number"); // Tile properties ui.propertiesTreeView = new TreeView(document.querySelector(".properties-tree-view") as HTMLElement, { multipleSelection: false }); ui.propertiesTreeView.on("selectionChange", onPropertySelect); document.querySelector("button.new-property").addEventListener("click", onNewPropertyClick); document.querySelector("button.rename-property").addEventListener("click", onRenamePropertyClick); document.querySelector("button.delete-property").addEventListener("click", onDeletePropertyClick); hasStarted = true; onChangeActive(); } // Network callbacks const onEditCommands: { [command: string]: Function; } = {}; function onConnected() { data = {} as any; data.projectClient = new SupClient.ProjectClient(socket, { subEntries: false }); const tileSetActor = new SupEngine.Actor(ui.gameInstance, "Tile Set"); const tileSetRenderer = new TileSetRenderer(tileSetActor); const config = { tileSetAssetId: SupClient.query.asset }; const subscriber: SupClient.AssetSubscriber = { onAssetReceived: onAssetReceived, onAssetEdited: (assetId, command, ...args) => { if (onEditCommands[command] != null) onEditCommands[command](...args); }, onAssetTrashed: SupClient.onAssetTrashed }; data.tileSetUpdater = new TileSetRendererUpdater(data.projectClient, tileSetRenderer, config, subscriber); } function onAssetReceived(err: string, asset: any) { setupProperty("grid-width", data.tileSetUpdater.tileSetAsset.pub.grid.width); setupProperty("grid-height", data.tileSetUpdater.tileSetAsset.pub.grid.height); selectTile({ x: 0, y: 0 }); } onEditCommands["upload"] = () => { selectTile({ x: 0, y: 0 }); }; onEditCommands["setProperty"] = (key: string, value: any) => { setupProperty(key, value); selectTile({ x: 0, y: 0 }); }; onEditCommands["addTileProperty"] = (tile: { x: number; y: number; }, name: string) => { if (tile.x !== data.selectedTile.x && tile.y !== data.selectedTile.y) return; addTileProperty(name); }; onEditCommands["renameTileProperty"] = (tile: { x: number; y: number; }, name: string, newName: string) => { if (tile.x !== data.selectedTile.x && tile.y !== data.selectedTile.y) return; const liElt = ui.propertiesTreeView.treeRoot.querySelector(`li[data-name="${name}"]`); liElt.querySelector(".name").textContent = newName; liElt.dataset["name"] = newName; const properties = Object.keys(data.tileSetUpdater.tileSetAsset.pub.tileProperties[`${tile.x}_${tile.y}`]); properties.sort(); ui.propertiesTreeView.remove(liElt); ui.propertiesTreeView.insertAt(liElt, "item", properties.indexOf(newName)); if (ui.selectedProperty === name) { ui.selectedProperty = newName; ui.propertiesTreeView.addToSelection(liElt); } }; onEditCommands["deleteTileProperty"] = (tile: { x: number; y: number; }, name: string) => { if (tile.x !== data.selectedTile.x && tile.y !== data.selectedTile.y) return; ui.propertiesTreeView.remove(ui.propertiesTreeView.treeRoot.querySelector(`li[data-name="${name}"]`)); }; onEditCommands["editTileProperty"] = (tile: { x: number; y: number; }, name: string, value: string) => { if (tile.x !== data.selectedTile.x && tile.y !== data.selectedTile.y) return; const liElt = ui.propertiesTreeView.treeRoot.querySelector(`li[data-name="${name}"]`); liElt.querySelector(".value").value = value; }; function setupProperty(key: string, value: any) { switch (key) { case "grid-width": ui.gridWidthInput.value = value; break; case "grid-height": ui.gridHeightInput.value = value; break; } } function selectTile(tile: { x: number; y: number; }) { data.selectedTile = tile; const pub = data.tileSetUpdater.tileSetAsset.pub; const tilePerRow = (pub.texture != null) ? Math.floor(pub.texture.image.width / pub.grid.width) : 1; ui.selectedTileInput.value = tile.x + tile.y * tilePerRow; while (ui.propertiesTreeView.treeRoot.children.length !== 0) { ui.propertiesTreeView.remove(ui.propertiesTreeView.treeRoot.children[0]); } if (pub.tileProperties[`${tile.x}_${tile.y}`] == null) return; const properties = Object.keys(pub.tileProperties[`${tile.x}_${tile.y}`]); properties.sort(); for (const propertyName of properties) { addTileProperty(propertyName, pub.tileProperties[`${tile.x}_${tile.y}`][propertyName]); } } function addTileProperty(name: string, value = "") { const liElt = document.createElement("li"); liElt.dataset["name"] = name; const nameSpan = document.createElement("span"); nameSpan.className = "name"; nameSpan.textContent = name; liElt.appendChild(nameSpan); const valueInput = document.createElement("input"); valueInput.type = "string"; valueInput.className = "value"; valueInput.value = value; valueInput.addEventListener("input", () => { data.projectClient.editAsset(SupClient.query.asset, "editTileProperty", data.selectedTile, ui.selectedProperty, valueInput.value); }); liElt.appendChild(valueInput); ui.propertiesTreeView.insertAt(liElt, "item"); } // User interface function onFileSelectChange(event: Event) { if ((<HTMLInputElement>event.target).files.length === 0) return; const reader = new FileReader; reader.onload = (event) => { data.projectClient.editAsset(SupClient.query.asset, "upload", reader.result); }; reader.readAsArrayBuffer((<HTMLInputElement>event.target).files[0]); (<HTMLFormElement>(<HTMLInputElement>event.target).parentElement).reset(); } function onDownloadTileset(event: Event) { function triggerDownload(name: string) { const anchor = document.createElement("a"); document.body.appendChild(anchor); anchor.style.display = "none"; anchor.href = data.tileSetUpdater.tileSetAsset.url; // Not yet supported in IE and Safari (http://caniuse.com/#feat=download) (anchor as any).download = `${name}.png`; anchor.click(); document.body.removeChild(anchor); } const options = { initialValue: SupClient.i18n.t("tileSetEditor:texture.downloadInitialValue"), validationLabel: SupClient.i18n.t("common:actions.download") }; if (SupApp != null) { triggerDownload(options.initialValue); } else { new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("tileSetEditor:texture.downloadPrompt"), options, (name) => { if (name == null) return; triggerDownload(name); }); } } function onPropertySelect() { if (ui.propertiesTreeView.selectedNodes.length === 1) { ui.selectedProperty = ui.propertiesTreeView.selectedNodes[0].dataset["name"]; (<HTMLButtonElement>document.querySelector("button.rename-property")).disabled = false; (<HTMLButtonElement>document.querySelector("button.delete-property")).disabled = false; } else { ui.selectedProperty = null; (<HTMLButtonElement>document.querySelector("button.rename-property")).disabled = true; (<HTMLButtonElement>document.querySelector("button.delete-property")).disabled = true; } } function onNewPropertyClick() { const options = { initialValue: SupClient.i18n.t("tileSetEditor:newPropertyInitialValue"), validationLabel: SupClient.i18n.t("common:actions.create") }; new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("tileSetEditor:newPropertyPrompt"), options, (name) => { if (name == null) return; data.projectClient.editAsset(SupClient.query.asset, "addTileProperty", data.selectedTile, name, () => { ui.selectedProperty = name; ui.propertiesTreeView.clearSelection(); const liElt = ui.propertiesTreeView.treeRoot.querySelector(`li[data-name="${ui.selectedProperty}"]`); ui.propertiesTreeView.addToSelection(liElt); (<HTMLInputElement>liElt.querySelector("input")).focus(); (<HTMLButtonElement>document.querySelector("button.rename-property")).disabled = false; (<HTMLButtonElement>document.querySelector("button.delete-property")).disabled = false; }); }); } function onRenamePropertyClick() { if (ui.propertiesTreeView.selectedNodes.length !== 1) return; const options = { initialValue: ui.selectedProperty, validationLabel: SupClient.i18n.t("common:actions.rename") }; new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("tileSetEditor:renamePropertyPrompt"), options, (newName) => { if (newName == null) return; data.projectClient.editAsset(SupClient.query.asset, "renameTileProperty", data.selectedTile, ui.selectedProperty, newName); }); } function onDeletePropertyClick() { if (ui.selectedProperty == null) return; const confirmLabel = SupClient.i18n.t("tileSetEditor:deletePropertyConfirm"); const validationLabel = SupClient.i18n.t("common:actions.delete"); new SupClient.Dialogs.ConfirmDialog(confirmLabel, { validationLabel }, (confirm) => { if (!confirm) return; data.projectClient.editAsset(SupClient.query.asset, "deleteTileProperty", data.selectedTile, ui.selectedProperty); }); } // Drawing let lastTimestamp = 0; let accumulatedTime = 0; function tick(timestamp = 0) { animationFrame = requestAnimationFrame(tick); accumulatedTime += timestamp - lastTimestamp; lastTimestamp = timestamp; const { updates, timeLeft } = ui.gameInstance.tick(accumulatedTime, handleTilesetArea); accumulatedTime = timeLeft; if (updates > 0) ui.gameInstance.draw(); } function handleTilesetArea() { if (data == null || data.tileSetUpdater.tileSetAsset == null) return; const pub = data.tileSetUpdater.tileSetAsset.pub; if (pub.texture == null) return; if (ui.gameInstance.input.mouseButtons[0].wasJustReleased) { const mousePosition = ui.gameInstance.input.mousePosition; const [ mouseX, mouseY ] = ui.cameraControls.getScenePosition(mousePosition.x, mousePosition.y); const x = Math.floor(mouseX); const ratio = data.tileSetUpdater.tileSetAsset.pub.grid.width / data.tileSetUpdater.tileSetAsset.pub.grid.height; const y = Math.floor(mouseY * ratio); if (x >= 0 && x < pub.texture.image.width / pub.grid.width && y >= 0 && y < pub.texture.image.height / pub.grid.height && (x !== data.selectedTile.x || y !== data.selectedTile.y)) { data.tileSetUpdater.tileSetRenderer.select(x, y); selectTile({ x, y }); } } } SupClient.i18n.load([{ root: `${window.location.pathname}/../..`, name: "tileSetEditor" }], start);
the_stack
import { IS_PROXY, ProxyStateTree } from './' describe('CREATION', () => { test('should create a ProxyStateTree instance', () => { const tree = new ProxyStateTree({}) expect(tree).toBeInstanceOf(ProxyStateTree) }) }) describe('TrackStateTree', () => { test('should create proxy of root state', () => { const state = {} const tree = new ProxyStateTree(state) expect( tree.getTrackStateTree().track(() => {}).state[IS_PROXY] ).toBeTruthy() }) test('should not cache proxies in SSR', () => { const state = { foo: {}, } const tree = new ProxyStateTree(state, { ssr: true, }) const trackStateTree = tree.getTrackStateTree() trackStateTree.track(() => { trackStateTree.state.foo }) expect( // @ts-ignore trackStateTree.state.foo[trackStateTree.proxifier.CACHED_PROXY] ).toBeFalsy() }) test('should not create nested proxies when initialized', () => { const state = { foo: {}, } new ProxyStateTree(state) // eslint-disable-line expect(state.foo[IS_PROXY]).not.toBeTruthy() }) test('should allow tracking by flush', () => { let reactionCount = 0 const tree = new ProxyStateTree({ foo: 'bar', }) const accessTree = tree .getTrackStateTree() .track((mutations, paths, flushId) => { reactionCount++ expect(flushId).toBe(0) }) accessTree.state.foo const mutationTree = tree.getMutationTree() mutationTree.state.foo = 'bar2' mutationTree.flush() expect(reactionCount).toBe(1) }) test('should allow tracking by mutation', () => { let reactionCount = 0 const tree = new ProxyStateTree({ foo: 'bar', }) tree.onMutation((mutation) => { reactionCount++ expect(mutation).toEqual({ method: 'set', path: 'foo', args: ['bar2'], hasChangedValue: true, delimiter: '.', }) }) const mutationTree = tree.getMutationTree() mutationTree.state.foo = 'bar2' expect(reactionCount).toBe(1) }) test('should stop tracking on command', () => { let reactionCount = 0 const tree = new ProxyStateTree({ foo: 'bar', bar: 'baz', }) const accessTree = tree .getTrackStateTree() .track((mutations, paths, flushId) => { reactionCount++ expect(flushId).toBe(0) }) accessTree.state.foo accessTree.stopTracking() accessTree.state.bar const mutationTree = tree.getMutationTree() mutationTree.state.foo = 'bar2' mutationTree.flush() mutationTree.state.bar = 'baz2' mutationTree.flush() expect(reactionCount).toBe(1) }) test('should allow tracking trees individually', () => { const tree = new ProxyStateTree({ foo: 'bar', bar: 'baz', }) const accessTreeA = tree.getTrackStateTreeWithProxifier() const accessTreeB = tree.getTrackStateTreeWithProxifier() accessTreeA.track(() => {}) accessTreeB.track(() => {}) accessTreeA.state.foo accessTreeB.state.bar return Promise.resolve().then(() => { accessTreeB.state.foo expect(Array.from(accessTreeA.pathDependencies)).toEqual(['foo']) expect(Array.from(accessTreeB.pathDependencies)).toEqual(['bar', 'foo']) }) }) test('should track native classes', () => { const tree = new ProxyStateTree({ date: new Date(), map: new Map() }) const trackStateTree = tree.getTrackStateTree() trackStateTree.track() trackStateTree.state.date trackStateTree.state.map expect(Array.from(trackStateTree.pathDependencies)).toEqual(['date', 'map']) }) }) describe('TrackMutationTree', () => {}) describe('CLASSES', () => { describe('ACCESS', () => { test('should create proxy when accessed', () => { class User { name = 'Bob' } const state = { user: new User(), } const tree = new ProxyStateTree(state) const trackStateTree = tree.getTrackStateTree().track(() => {}) expect(trackStateTree.state.user[IS_PROXY]).toBeTruthy() }) test('should access properties', () => { class User { name = 'Bob' } const state = { user: new User(), } const tree = new ProxyStateTree(state) expect(tree.getTrackStateTree().track(() => {}).state.user.name).toBe( 'Bob' ) }) test('should track access properties', () => { class User { name = 'Bob' } const state = { user: new User(), } const tree = new ProxyStateTree(state) const trackStateTree = tree.getTrackStateTree().track(() => {}) expect(trackStateTree.state.user.name).toBe('Bob') expect(Object.keys((tree as any).pathDependencies)).toEqual([ 'user', 'user.name', ]) }) test('should track getters', () => { class User { private firstName = 'Bob' private lastName = 'Saget' get name() { return this.firstName + ' ' + this.lastName } } const state = { user: new User(), } const tree = new ProxyStateTree(state) const trackStateTree = tree.getTrackStateTree().track(() => {}) expect(trackStateTree.state.user.name).toBe('Bob Saget') expect(Object.keys((tree as any).pathDependencies)).toEqual([ 'user', 'user.firstName', 'user.lastName', ]) }) }) describe('MUTATIONS', () => { test('should throw when mutating without tracking', () => { class User { name = 'Bob' } const state = { user: new User(), } const tree = new ProxyStateTree(state) expect(() => { tree.getTrackStateTree().track(() => {}).state.user.name = 'bar2' }).toThrow() }) test('should throw if parts of state are nested', () => { class User { name = 'Bob' } const state = { user: new User(), } const tree = new ProxyStateTree(state) expect(() => { const mutationTree = tree.getMutationTree() mutationTree.state.user = mutationTree.state.user // eslint-disable-line }).toThrowError(/exists in the state tree on path "user"/i) }) test('should not notify changes to same value', () => { let renderCount = 0 class User { name = 'Bob' } const state = { user: new User(), } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() const accessTree = tree.getTrackStateTree().track(() => { renderCount++ }) accessTree.addTrackingPath('user.name') mutationTree.state.user.name = 'bar' expect(mutationTree.mutations).toEqual([ { method: 'set', path: 'user.name', args: ['bar'], hasChangedValue: true, delimiter: '.', }, ]) expect(renderCount).toBe(0) }) test('should track SET mutations', () => { class User { name = 'Bob' } const state = { user: new User(), } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() mutationTree.state.user.name = 'bar2' expect(mutationTree.mutations).toEqual([ { method: 'set', path: 'user.name', args: ['bar2'], hasChangedValue: true, delimiter: '.', }, ]) expect(mutationTree.state.user.name).toBe('bar2') }) test('should allow custom delimiter', () => { class User { name = 'Bob' } const state = { user: new User(), } const tree = new ProxyStateTree(state, { delimiter: ' ', }) const mutationTree = tree.getMutationTree() mutationTree.state.user.name = 'bar2' expect(mutationTree.mutations).toEqual([ { method: 'set', path: 'user name', args: ['bar2'], hasChangedValue: true, delimiter: ' ', }, ]) expect(mutationTree.state.user.name).toBe('bar2') }) test('should track mutations through methods', () => { class User { name = 'Bob' changeName() { this.name = 'Bob2' } } const state = { user: new User(), } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() mutationTree.state.user.changeName() expect(mutationTree.mutations).toEqual([ { method: 'set', path: 'user.name', args: ['Bob2'], hasChangedValue: true, delimiter: '.', }, ]) expect(mutationTree.state.user.name).toBe('Bob2') }) }) }) describe('OBJECTS', () => { describe('ACCESS', () => { test('should create proxy when accessed', () => { const state = { foo: {}, } const tree = new ProxyStateTree(state) const trackStateTree = tree.getTrackStateTree().track(() => {}) expect(trackStateTree.state.foo[IS_PROXY]).toBeTruthy() }) test('should access properties', () => { const state = { foo: { bar: 'baz', }, } const tree = new ProxyStateTree(state) expect(tree.getTrackStateTree().track(() => {}).state.foo.bar).toBe('baz') }) test('should track access properties', () => { const state = { foo: { bar: 'baz', }, } const tree = new ProxyStateTree(state) const trackStateTree = tree.getTrackStateTree().track(() => {}) expect(trackStateTree.state.foo.bar).toBe('baz') expect(Object.keys((tree as any).pathDependencies)).toEqual([ 'foo', 'foo.bar', ]) }) }) describe('MUTATIONS', () => { test('should throw when mutating without tracking', () => { const state = { foo: 'bar', } const tree = new ProxyStateTree(state) expect(() => { tree.getTrackStateTree().track(() => {}).state.foo = 'bar2' }).toThrow() }) test('should throw if parts of state are nested', () => { const state = { foo: { nested: 'bar', }, } const tree = new ProxyStateTree(state) expect(() => { const mutationTree = tree.getMutationTree() mutationTree.state.foo = mutationTree.state.foo // eslint-disable-line }).toThrowError(/exists in the state tree on path "foo"/i) }) test('should not notify changes to same value', () => { let renderCount = 0 const state = { foo: 'bar', } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() const accessTree = tree.getTrackStateTree().track(() => { renderCount++ }) accessTree.addTrackingPath('foo') mutationTree.state.foo = 'bar' expect(mutationTree.mutations).toEqual([ { method: 'set', path: 'foo', args: ['bar'], hasChangedValue: false, delimiter: '.', }, ]) expect(renderCount).toBe(0) }) test('should track SET mutations', () => { const state = { foo: 'bar', } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() mutationTree.state.foo = 'bar2' expect(mutationTree.mutations).toEqual([ { method: 'set', path: 'foo', args: ['bar2'], hasChangedValue: true, delimiter: '.', }, ]) expect(mutationTree.state.foo).toBe('bar2') }) test('should track UNSET mutations', () => { const state = { foo: 'bar', } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() delete mutationTree.state.foo expect(mutationTree.mutations).toEqual([ { method: 'unset', path: 'foo', args: [], hasChangedValue: true, delimiter: '.', }, ]) expect(mutationTree.state.foo).toBe(undefined) }) }) }) describe('ARRAYS', () => { describe('ACCESS', () => { test('should create proxies of arrays', () => { const state = { foo: [], } const tree = new ProxyStateTree(state) const trackStateTree = tree.getTrackStateTree().track(() => {}) const foo = trackStateTree.state.foo expect(foo[IS_PROXY]).toBeTruthy() }) test('should access properties', () => { const state = { foo: 'bar', } const tree = new ProxyStateTree(state) expect(tree.getTrackStateTree().track(() => {}).state.foo[0]).toBe('b') }) test('should track access properties', () => { const state = { foo: ['bar'], } const tree = new ProxyStateTree(state) const accessTree = tree.getTrackStateTree().track(() => {}) expect(accessTree.state.foo[0]).toBe('bar') expect(Object.keys((tree as any).pathDependencies)).toEqual([ 'foo', 'foo.0', ]) }) test('should allow nested tracking', () => { const tree = new ProxyStateTree({ foo: [ { title: 'foo', }, ], bar: 'baz', }) tree.getTrackStateTree().trackScope( (treeA) => { treeA.state.foo.forEach((item) => { tree.getTrackStateTree().trackScope( (treeB) => { item.title // eslint-disable-line expect(treeB.pathDependencies).toEqual(new Set(['foo.0.title'])) }, () => {} ) }) treeA.state.bar expect(treeA.pathDependencies).toEqual( new Set(['foo', 'foo.0', 'bar']) ) }, () => {} ) }) test('should correctly keep track of changing indexes', () => { expect.assertions(4) let iterations = 0 const tree = new ProxyStateTree({ items: [], }) const accessTree = tree.getTrackStateTree() function trackPaths() { accessTree.track(trackPaths) accessTree.state.items.map((item) => item.title) if (iterations === 1) { expect(Array.from(accessTree.pathDependencies)).toEqual([ 'items', 'items.0', 'items.0.title', ]) } else if (iterations === 2) { expect(Array.from(accessTree.pathDependencies)).toEqual([ 'items', 'items.0', 'items.0.title', 'items.1', 'items.1.title', ]) } else if (iterations === 3) { expect(Array.from(accessTree.pathDependencies)).toEqual([ 'items', 'items.0', 'items.0.title', 'items.1', 'items.1.title', ]) } iterations++ } trackPaths() const mutationTree = tree.getMutationTree() mutationTree.state.items.unshift({ title: 'foo', }) const currentProxy = mutationTree.state.items[0] mutationTree.flush() mutationTree.state.items.unshift({ title: 'bar', }) mutationTree.flush() mutationTree.state.items[1].title = 'wapah' const newProxy = mutationTree.state.items[1] mutationTree.flush() expect(currentProxy).not.toBe(newProxy) }) }) test('should create proxies of arrays', () => { const state = { foo: [], } const tree = new ProxyStateTree(state) const trackStateTree = tree.getTrackStateTree().track(() => {}) const foo = trackStateTree.state.foo expect(foo[IS_PROXY]).toBeTruthy() }) describe('MUTATIONS', () => { test('should throw when mutating without tracking mutations', () => { const state = { foo: [], } const tree = new ProxyStateTree(state) expect(() => { tree.getTrackStateTree().state.foo.push('foo') }).toThrow() }) test('should throw if parts of state are nested', () => { const state = { foo: [undefined], bar: { nested: 'baz', }, } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() // Property mutation expect(() => { mutationTree.state.foo[0] = mutationTree.state.bar }).toThrowError(/exists in the state tree on path "bar"/i) }) test('should track PUSH mutations', () => { const state = { foo: [], } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() mutationTree.state.foo.push('bar') expect(mutationTree.mutations).toEqual([ { method: 'push', path: 'foo', args: ['bar'], hasChangedValue: true, delimiter: '.', }, ]) expect([...mutationTree.state.foo]).toEqual(['bar']) }) test('should track POP mutations', () => { const state = { foo: ['foo'], } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() mutationTree.state.foo.pop() expect(mutationTree.mutations).toEqual([ { method: 'pop', path: 'foo', args: [], hasChangedValue: true, delimiter: '.', }, ]) expect(state.foo.length).toBe(0) }) test('should track SHIFT mutations', () => { const state = { foo: ['foo'], } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() mutationTree.state.foo.shift() expect(mutationTree.mutations).toEqual([ { method: 'shift', path: 'foo', args: [], hasChangedValue: true, delimiter: '.', }, ]) expect(state.foo.length).toBe(0) }) test('should track UNSHIFT mutations', () => { const state = { foo: [], } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() mutationTree.state.foo.unshift('foo') expect(mutationTree.mutations).toEqual([ { method: 'unshift', path: 'foo', args: ['foo'], hasChangedValue: true, delimiter: '.', }, ]) expect(state.foo[0]).toBe('foo') }) test('should track SPLICE mutations', () => { const state = { foo: ['foo'], } const tree = new ProxyStateTree(state) const mutationTree = tree.getMutationTree() mutationTree.state.foo.splice(0, 1, 'bar') expect(mutationTree.mutations).toEqual([ { method: 'splice', path: 'foo', args: [0, 1, 'bar'], hasChangedValue: true, delimiter: '.', }, ]) expect(state.foo[0]).toBe('bar') }) }) test('should allow indexOf using proxy values', () => { const state = { things: [{ some: 'thing' }], ids: [2, 1, 1, 1, 2], } const tree = new ProxyStateTree(state) expect(tree.state.things.indexOf(tree.state.things[0])).toEqual(0) expect(tree.state.ids.indexOf(2)).toEqual(0) expect(tree.state.ids.indexOf(2, 1)).toEqual(4) }) }) describe('FUNCTIONS', () => { test('should call functions in the tree when accessed', () => { const state = { foo: () => 'bar', } const tree = new ProxyStateTree(state) const accessTree = tree.getTrackStateTree().track(() => {}) expect(accessTree.state.foo).toBe('bar') }) test('should pass proxy-state-tree instance and path', () => { const state = { foo: (proxyStateTree, path) => { expect(proxyStateTree === tree) expect(path).toEqual('foo') return 'bar' }, } const tree = new ProxyStateTree(state) const accessTree = tree.getTrackStateTree().track(() => {}) expect(accessTree.state.foo).toBe('bar') }) test('should be able to inject a wrapper around functions', () => { const state = { foo: (foo, proxyStateTree, path) => { expect(foo).toBe('foo') expect(proxyStateTree === tree) expect(path).toEqual('foo') return 'bar' }, } const tree = new ProxyStateTree(state, { onGetFunction: (proxyStateTree, path, target, prop) => target[prop]('foo', proxyStateTree, path), }) const accessTree = tree.getTrackStateTree().track(() => {}) expect(accessTree.state.foo).toBe('bar') }) test('should track state values from within derived', () => { let reactionCount = 0 const tree = new ProxyStateTree({ items: [ { title: 'foo', }, ], foo: (proxyStateTree) => { return proxyStateTree.state.items.map((item) => item) }, }) const accessTree = tree .getTrackStateTree() .track((mutations, paths, flushId) => { reactionCount++ expect(flushId).toBe(0) }) const mutationTree = tree.getMutationTree() // @ts-ignore accessTree.state.foo.forEach((item) => { item.title }) mutationTree.state.items.push({ title: 'bar', }) mutationTree.flush() expect(reactionCount).toBe(1) }) }) describe('REACTIONS', () => { test('should be able to register a listener using paths', () => { expect.assertions(2) let reactionCount = 0 const tree = new ProxyStateTree({ foo: 'bar', }) const accessTree = tree .getTrackStateTree() .track((mutations, paths, flushId) => { reactionCount++ expect(flushId).toBe(0) }) const mutationTree = tree.getMutationTree() accessTree.state.foo // eslint-disable-line mutationTree.state.foo = 'bar2' mutationTree.flush() expect(reactionCount).toBe(1) }) test('should be able to register a global listener', () => { expect.assertions(1) const tree = new ProxyStateTree({ foo: 'bar', }) const mutationTree = tree.getMutationTree() tree.onMutation((mutation) => { expect(mutation).toEqual({ method: 'set', path: 'foo', args: ['bar2'], hasChangedValue: true, delimiter: '.', }) }) mutationTree.state.foo = 'bar2' mutationTree.flush() }) test('should be able to manually add a path to the current tracking', () => { let renderCount = 0 const tree = new ProxyStateTree({ foo: 'bar', }) function render() { renderCount++ } const mutationTree = tree.getMutationTree() const accessTree = tree.getTrackStateTree().track(render) accessTree.addTrackingPath('foo') mutationTree.state.foo = 'bar2' mutationTree.flush() expect(renderCount).toBe(1) }) test('should only trigger ones when multiple paths mutated', () => { let reactionCount = 0 const tree = new ProxyStateTree({ foo: 'bar', bar: 'baz', }) const accessTree = tree.getTrackStateTree().track(() => { reactionCount++ }) const mutationTree = tree.getMutationTree() accessTree.state.foo // eslint-disable-line accessTree.state.bar // eslint-disable-line mutationTree.state.foo = 'bar2' mutationTree.state.bar = 'baz2' mutationTree.flush() expect(reactionCount).toBe(1) }) test('should be able to update listener using paths', () => { const tree = new ProxyStateTree({ foo: 'bar', bar: 'baz', }) const accessTree = tree.getTrackStateTree().track(render) const mutationTree = tree.getMutationTree() function render() { if (accessTree.state.foo === 'bar') { return } accessTree.state.bar // eslint-disable-line } render() mutationTree.state.foo = 'bar2' mutationTree.flush() expect((tree.pathDependencies as any).foo.size).toBe(1) expect((tree.pathDependencies as any).bar.size).toBe(1) }) test('should be able to dispose tree', () => { const tree = new ProxyStateTree({ foo: 'bar', bar: 'baz', }) const accessTree = tree.getTrackStateTree().track(render) const mutationTree = tree.getMutationTree() function render() { if (accessTree.state.foo === 'bar') { return } accessTree.state.bar // eslint-disable-line } render() mutationTree.state.foo = 'bar2' mutationTree.flush() tree.disposeTree(accessTree) expect(tree.pathDependencies).toEqual({}) }) test('should allow subsequent mutation tracking and return all on flush', () => { const tree = new ProxyStateTree({ foo: 'bar', }) const mutationTree = tree.getMutationTree() const mutationTree2 = tree.getMutationTree() mutationTree.state.foo = 'bar2' mutationTree2.state.foo = 'bar3' const flushResult = tree.flush([mutationTree, mutationTree2]) expect(flushResult).toEqual({ flushId: 0, mutations: [ { path: 'foo', method: 'set', args: ['bar2'], hasChangedValue: true, delimiter: '.', }, { path: 'foo', method: 'set', args: ['bar3'], hasChangedValue: true, delimiter: '.', }, ], }) }) }) describe('ITERATIONS', () => { test('should track paths when using array iteration methods', () => { const tree = new ProxyStateTree({ items: [ { title: 'foo', }, { title: 'bar', }, ], }) const accessTree = tree.getTrackStateTree().track(() => {}) accessTree.state.items.forEach((item) => { item.title // eslint-disable-line }) expect(accessTree.pathDependencies).toEqual( new Set(['items', 'items.0', 'items.0.title', 'items.1', 'items.1.title']) ) }) test('should track paths when using Object.keys', () => { const tree = new ProxyStateTree({ items: { foo: 'bar', bar: 'baz', }, }) const accessTree = tree.getTrackStateTree().track(() => {}) Object.keys(accessTree.state.items).forEach((key) => { accessTree.state.items[key] // eslint-disable-line }) expect(accessTree.pathDependencies).toEqual( new Set(['items', 'items.foo', 'items.bar']) ) }) test('should track new and deleted props on objects', () => { let runCount = 0 expect.assertions(3) const tree = new ProxyStateTree({ items: {} as any, }) const accessTree = tree.getTrackStateTree().track(update) const mutationTree = tree.getMutationTree() function update() { accessTree.state.items // eslint-disable-line if (runCount === 1) { expect(accessTree.pathDependencies).toEqual(new Set(['items'])) } if (runCount === 2) { expect(accessTree.pathDependencies).toEqual(new Set(['items'])) } if (runCount === 3) { expect(accessTree.pathDependencies).toEqual(new Set(['items'])) } runCount++ } update() mutationTree.state.items.foo = 'bar' mutationTree.flush() mutationTree.state.items.bar = 'baz' mutationTree.flush() delete mutationTree.state.items.foo mutationTree.flush() }) test('should react to array mutation methods', () => { let reactionCount = 0 const tree = new ProxyStateTree({ items: [ { title: 'foo', }, { title: 'bar', }, ], }) const accessTree = tree.getTrackStateTree().track(() => { reactionCount++ }) const mutationTree = tree.getMutationTree() accessTree.state.items.map((item) => item.title) expect(accessTree.pathDependencies).toEqual( new Set(['items', 'items.0', 'items.0.title', 'items.1', 'items.1.title']) ) mutationTree.state.items.push({ title: 'mip', }) mutationTree.flush() expect(reactionCount).toBe(1) }) test('should react to object array item value mutation', () => { let reactionCount = 0 const tree = new ProxyStateTree({ items: [ { title: 'foo', }, { title: 'bar', }, ], }) const accessTree = tree.getTrackStateTree().track(() => { reactionCount++ }) const mutationTree = tree.getMutationTree() accessTree.state.items.map((item) => item.title) expect(accessTree.pathDependencies).toEqual( new Set(['items', 'items.0', 'items.0.title', 'items.1', 'items.1.title']) ) mutationTree.state.items[0].title = 'baz' mutationTree.flush() expect(reactionCount).toBe(1) }) test('should react to int array item mutation', () => { let reactionCount = 0 const tree = new ProxyStateTree({ items: [1, 2], }) const accessTree = tree.getTrackStateTree().track(() => { reactionCount++ }) const mutationTree = tree.getMutationTree() accessTree.state.items.map((item) => item) expect(accessTree.pathDependencies).toEqual( new Set(['items', 'items.0', 'items.1']) ) mutationTree.state.items[0] = 99 mutationTree.flush() expect(reactionCount).toBe(1) }) }) describe('RESCOPING', () => { it('should be able to change scope of state', () => { const tree = new ProxyStateTree({ foo: 'bar', }) const accessTree = tree.getTrackStateTree().track(() => {}) const mutationTree = tree.getMutationTree() const state = accessTree.state const rescoped = tree.rescope(state, mutationTree) rescoped.foo = 'bar2' expect(tree.state.foo).toBe('bar2') }) }) describe('GETTER', () => { it('should be able to define and track getters in the tree', () => { let renderCount = 0 const tree = new ProxyStateTree({ user: { firstName: 'Bob', lastName: 'Goodman', get fullName() { return this.firstName + ' ' + this.lastName }, }, }) const accessTree = tree.getTrackStateTree() const mutationTree = tree.getMutationTree() function render() { accessTree.track(render) accessTree.state.user.fullName renderCount++ } render() mutationTree.state.user.firstName = 'Bob2' mutationTree.flush() expect(renderCount).toBe(2) }) })
the_stack
import { Sparkline, ISparklineLoadedEventArgs, SparklineTooltip } from '../../src/sparkline/index'; import { removeElement, getIdElement, Rect } from '../../src/sparkline/utils/helper'; import { createElement, isNullOrUndefined } from '@syncfusion/ej2-base'; import {profile , inMB, getMemoryProfile} from '../common.spec'; import { MouseEvents } from './events.spec'; Sparkline.Inject(SparklineTooltip); describe('Sparkline tooltip and tracker checking Spec', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('Sparkline default theme Spec', () => { let trigger: MouseEvents = new MouseEvents(); let element: Element; let sparkline: Sparkline; let id: string = 'sparks'; let ele: Element; let rect: Rect; let d: string[]; beforeAll(() => { element = createElement('div', { id: id }); document.body.appendChild(element); sparkline = new Sparkline({ width: '400', height: '100', type: 'Column', containerArea: { border: { width: 4 } }, dataSource: [ { id: 10, value: 50 }, { id: 20, value: 30 }, { id: 30, value: -40 }, { id: 40, value: 10 }, { id: 50, value: -60 }, { id: 60, value: 20 }, { id: 70, value: 70 }, { id: 80, value: -55 }, { id: 90, value: 80 }, { id: 100, value: 45 } ], yName: 'value', xName: 'id', axisSettings:{ lineSettings:{ visible: true } }, rangeBandSettings: [ { startRange: 1, endRange: 3, } ], dataLabelSettings:{ visible: ['All'] }, tooltipSettings: { visible: true, trackLineSettings: { visible: true, width: 2 } } }); }); afterAll(() => { sparkline.destroy(); removeElement(id); }); it('Sparkline tracker line checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { args.sparkline.loaded = () => { /* null function */ }; ele = getIdElement(id + '_sparkline_column_1'); trigger.mousemoveEvent(ele, 0, 0, 30, 30); ele = getIdElement(id + '_sparkline_tracker'); expect(ele.getAttribute('fill')).toBe('transparent'); expect(ele.getAttribute('stroke')).toBe('#000000'); }; sparkline.appendTo('#' + id); }); it('Sparkline tooltip checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { args.sparkline.loaded = () => { /* null function */ }; ele = getIdElement(id + '_sparkline_column_1'); trigger.mousemoveEvent(ele, 0, 0, 30, 30); ele = getIdElement(id + '_sparkline_tooltip_div_text'); expect(ele.firstChild.textContent).toBe('50'); expect(ele.lastChild.textContent).toBe('50'); ele = getIdElement(id + '_sparkline_tracker'); expect(ele.getAttribute('fill')).toBe('transparent'); expect(ele.getAttribute('stroke')).toBe('#000000'); }; sparkline.appendTo('#' + id); }); it('Sparkline tooltip fill checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { args.sparkline.loaded = () => { /* null function */ }; ele = getIdElement(id + '_sparkline_column_1'); trigger.mousemoveEvent(ele, 0, 0, 30, 30); ele = getIdElement(id + '_sparkline_tooltip_div_path'); expect(ele.getAttribute('fill')).toBe('#363F4C'); }; sparkline.appendTo('#' + id); }); it('checking the axisLineColor',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_Sparkline_XAxis'); expect(ele.getAttribute('stroke')).toBe('#000000'); } sparkline.appendTo('#' + id); }) it('checking the dataLabelColor',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_sparkline_label_text_0'); expect(ele.getAttribute('fill')).toBe('#424242'); } sparkline.appendTo('#' + id); }) it('checking the rangeBandColor',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_rangeBand_0'); expect(ele.getAttribute('fill')).toBe('#000000'); } sparkline.appendTo('#' + id); }) it('checking the background',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_SparklineBorder'); expect(ele.getAttribute('fill')).toBe('#FFFFFF'); } sparkline.appendTo('#' + id); }) }); describe('Sparkline MaterialDark theme Spec', () => { let trigger: MouseEvents = new MouseEvents(); let element: Element; let sparkline: Sparkline; let id: string = 'sparks'; let ele: Element; let rect: Rect; let d: string[]; beforeAll(() => { element = createElement('div', { id: id }); document.body.appendChild(element); sparkline = new Sparkline({ theme:'MaterialDark', width: '400', height: '100', type: 'Column', containerArea: { border: { width: 4 } }, dataSource: [ { id: 10, value: 50 }, { id: 20, value: 30 }, { id: 30, value: -40 }, { id: 40, value: 10 }, { id: 50, value: -60 }, { id: 60, value: 20 }, { id: 70, value: 70 }, { id: 80, value: -55 }, { id: 90, value: 80 }, { id: 100, value: 45 } ], yName: 'value', xName: 'id', axisSettings:{ lineSettings:{ visible: true } }, rangeBandSettings: [ { startRange: 1, endRange: 3, } ], dataLabelSettings:{ visible: ['All'] }, tooltipSettings: { visible: true, trackLineSettings: { visible: true, width: 2 } } }); }); afterAll(() => { sparkline.destroy(); removeElement(id); }); it('Sparkline tracker line checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { args.sparkline.loaded = () => { /* null function */ }; ele = getIdElement(id + '_sparkline_column_1'); trigger.mousemoveEvent(ele, 0, 0, 30, 30); ele = getIdElement(id + '_sparkline_tracker'); expect(ele.getAttribute('fill')).toBe('transparent'); expect(ele.getAttribute('stroke')).toBe('#ffffff'); }; sparkline.appendTo('#' + id); }); it('Sparkline tooltip checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { args.sparkline.loaded = () => { /* null function */ }; ele = getIdElement(id + '_sparkline_column_1'); trigger.mousemoveEvent(ele, 0, 0, 30, 30); ele = getIdElement(id + '_sparkline_tooltip_div_text'); expect(ele.firstChild.textContent).toBe('50'); expect(ele.lastChild.textContent).toBe('50'); ele = getIdElement(id + '_sparkline_tracker'); expect(ele.getAttribute('fill')).toBe('transparent'); expect(ele.getAttribute('stroke')).toBe('#ffffff'); }; sparkline.appendTo('#' + id); }); it('Sparkline tooltip fill checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { args.sparkline.loaded = () => { /* null function */ }; ele = getIdElement(id + '_sparkline_column_1'); trigger.mousemoveEvent(ele, 0, 0, 30, 30); ele = getIdElement(id + '_sparkline_tooltip_div_path'); expect(ele.getAttribute('fill')).toBe('#ffffff'); }; sparkline.appendTo('#' + id); }); it('checking the axisLineColor',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_Sparkline_XAxis'); expect(ele.getAttribute('stroke')).toBe('#ffffff'); } sparkline.appendTo('#' + id); }) it('checking the dataLabelColor',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_sparkline_label_text_0'); expect(ele.getAttribute('fill')).toBe('#ffffff'); } sparkline.appendTo('#' + id); }) it('checking the rangeBandColor',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_rangeBand_0'); expect(ele.getAttribute('fill')).toBe('#ffffff'); } sparkline.appendTo('#' + id); }) it('checking the background',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_SparklineBorder'); expect(ele.getAttribute('fill')).toBe('#000000'); } sparkline.appendTo('#' + id); }) }); describe('Sparkline bootstrap4 theme Spec', () => { let trigger: MouseEvents = new MouseEvents(); let element: Element; let sparkline: Sparkline; let id: string = 'sparks'; let ele: Element; let rect: Rect; let d: string[]; beforeAll(() => { element = createElement('div', { id: id }); document.body.appendChild(element); sparkline = new Sparkline({ theme:'Bootstrap4', width: '400', height: '100', type: 'Column', containerArea: { border: { width: 4 } }, dataSource: [ { id: 10, value: 50 }, { id: 20, value: 30 }, { id: 30, value: -40 }, { id: 40, value: 10 }, { id: 50, value: -60 }, { id: 60, value: 20 }, { id: 70, value: 70 }, { id: 80, value: -55 }, { id: 90, value: 80 }, { id: 100, value: 45 } ], yName: 'value', xName: 'id', axisSettings:{ lineSettings:{ visible: true } }, rangeBandSettings: [ { startRange: 1, endRange: 3, } ], dataLabelSettings:{ visible: ['All'] }, tooltipSettings: { visible: true, trackLineSettings: { visible: true, width: 2 } } }); }); afterAll(() => { sparkline.destroy(); removeElement(id); }); it('Sparkline tracker line checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { args.sparkline.loaded = () => { /* null function */ }; ele = getIdElement(id + '_sparkline_column_1'); trigger.mousemoveEvent(ele, 0, 0, 30, 30); ele = getIdElement(id + '_sparkline_tracker'); expect(ele.getAttribute('fill')).toBe('transparent'); expect(ele.getAttribute('stroke')).toBe('#212529'); }; sparkline.appendTo('#' + id); }); it('Sparkline tooltip checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { args.sparkline.loaded = () => { /* null function */ }; ele = getIdElement(id + '_sparkline_column_1'); trigger.mousemoveEvent(ele, 0, 0, 30, 30); ele = getIdElement(id + '_sparkline_tooltip_div_text'); expect(ele.firstChild.textContent).toBe('50'); expect(ele.lastChild.textContent).toBe('50'); ele = getIdElement(id + '_sparkline_tracker'); expect(ele.getAttribute('fill')).toBe('transparent'); expect(ele.getAttribute('stroke')).toBe('#212529'); expect(ele.getAttribute('opacity')).toBe('1'); }; sparkline.appendTo('#' + id); }); it('Sparkline tooltip fill checking', () => { sparkline.loaded = (args: ISparklineLoadedEventArgs) => { args.sparkline.loaded = () => { /* null function */ }; ele = getIdElement(id + '_sparkline_column_1'); trigger.mousemoveEvent(ele, 0, 0, 30, 30); ele = getIdElement(id + '_sparkline_tooltip_div_path'); expect(ele.getAttribute('fill')).toBe('#000000'); }; sparkline.appendTo('#' + id); }); it('checking the axisLineColor',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_Sparkline_XAxis'); expect(ele.getAttribute('stroke')).toBe('#6C757D'); } sparkline.appendTo('#' + id); }) it('checking the dataLabelColor',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_sparkline_label_text_0'); expect(ele.getAttribute('fill')).toBe('#212529'); expect(ele.getAttribute('font-family')).toBe('HelveticaNeue') } sparkline.appendTo('#' + id); }) it('checking the rangeBandColor',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_rangeBand_0'); expect(ele.getAttribute('fill')).toBe('#212529'); } sparkline.appendTo('#' + id); }) it('checking the background',() =>{ sparkline.loaded = (args: ISparklineLoadedEventArgs) => { ele = getIdElement(id + '_SparklineBorder'); expect(ele.getAttribute('fill')).toBe('#FFFFFF'); } sparkline.appendTo('#' + id); }) }); });
the_stack
import type { DictionaryFileTypes } from '@cspell/cspell-types'; import { promises as fs, statSync } from 'fs'; import { genSequence } from 'gensequence'; import * as path from 'path'; import { format } from 'util'; import { DictionaryDefinitionInternal } from '../Models/CSpellSettingsInternalDef'; import { isErrnoException } from '../util/errors'; import { readLines, readLinesSync } from '../util/fileReader'; import { createFailedToLoadDictionary, createSpellingDictionary } from './createSpellingDictionary'; import { SpellingDictionary } from './SpellingDictionary'; import { SpellingDictionaryLoadError } from './SpellingDictionaryError'; import { createSpellingDictionaryTrie } from './SpellingDictionaryFromTrie'; const MAX_AGE = 10000; const loaders: Loaders = { S: loadSimpleWordList, C: legacyWordList, W: wordsPerLineWordList, T: loadTrie, default: loadSimpleWordList, }; const loadersSync: SyncLoaders = { S: loadSimpleWordListSync, C: legacyWordListSync, W: wordsPerLineWordListSync, T: loadTrieSync, default: loadSimpleWordListSync, }; export type LoadOptions = DictionaryDefinitionInternal; enum LoadingState { Loaded = 0, Loading = 1, } interface CacheEntry { uri: string; options: LoadOptions; ts: number; stat: Stats | Error | undefined; dictionary: SpellingDictionary | undefined; pending: Promise<readonly [SpellingDictionary, Stats | Error]>; loadingState: LoadingState; sig: number; } interface CacheEntrySync extends CacheEntry { dictionary: SpellingDictionary; } const debugLog: string[] = []; const debugMode = false; function __log(msg: string): void { debugMode && debugLog.push(msg); } export type LoaderType = keyof Loaders; export type Loader = (filename: string, options: LoadOptions) => Promise<SpellingDictionary>; export type LoaderSync = (filename: string, options: LoadOptions) => SpellingDictionary; export interface Loaders { S: Loader; C: Loader; T: Loader; W: Loader; default: Loader; } export interface SyncLoaders { S: LoaderSync; C: LoaderSync; T: LoaderSync; W: LoaderSync; default: LoaderSync; } const dictionaryCache = new Map<string, CacheEntry>(); const dictionaryCacheByDef = new Map<DictionaryDefinitionInternal, { key: string; entry: CacheEntry }>(); function getCacheEntry(def: DictionaryDefinitionInternal): { key: string; entry: CacheEntry | undefined } { const defEntry = dictionaryCacheByDef.get(def); if (defEntry) { return defEntry; } const key = calcKey(def); const entry = dictionaryCache.get(key); if (entry) { // replace old entry so it can be released. entry.options = def; } return { key, entry }; } function setCacheEntry(key: string, entry: CacheEntry, def: DictionaryDefinitionInternal) { dictionaryCache.set(key, entry); dictionaryCacheByDef.set(def, { key, entry }); } export function loadDictionary(def: DictionaryDefinitionInternal): Promise<SpellingDictionary> { const { key, entry } = getCacheEntry(def); if (entry) { return entry.pending.then(([dictionary]) => dictionary); } const loadedEntry = loadEntry(def.path, def); setCacheEntry(key, loadedEntry, def); return loadedEntry.pending.then(([dictionary]) => dictionary); } export function loadDictionarySync(def: DictionaryDefinitionInternal): SpellingDictionary { const { key, entry } = getCacheEntry(def); if (entry?.dictionary && entry.loadingState === LoadingState.Loaded) { return entry.dictionary; } const loadedEntry = loadEntrySync(def.path, def); setCacheEntry(key, loadedEntry, def); return loadedEntry.dictionary; } const importantOptionKeys: (keyof DictionaryDefinitionInternal)[] = ['name', 'noSuggest', 'useCompounds', 'type']; function calcKey(def: DictionaryDefinitionInternal) { const path = def.path; const loaderType = determineType(path, def); const optValues = importantOptionKeys.map((k) => def[k]?.toString() || ''); const parts = [path, loaderType].concat(optValues); return parts.join('|'); } /** * Check to see if any of the cached dictionaries have changed. If one has changed, reload it. * @param maxAge - Only check the dictionary if it has been at least `maxAge` ms since the last check. * @param now - optional timestamp representing now. (Mostly used in testing) */ export async function refreshCacheEntries(maxAge = MAX_AGE, now = Date.now()): Promise<void> { await Promise.all([...dictionaryCache.values()].map((entry) => refreshEntry(entry, maxAge, now))); } async function refreshEntry(entry: CacheEntry, maxAge: number, now: number): Promise<void> { if (now - entry.ts >= maxAge) { const sig = now + Math.random(); // Write to the ts, so the next one will not do it. entry.sig = sig; entry.ts = now; const pStat = getStat(entry.uri); const [newStat] = await Promise.all([pStat, entry.pending]); const hasChanged = !isEqual(newStat, entry.stat); const sigMatches = entry.sig === sig; // if (entry.options.name === 'temp') { // const processedAt = Date.now(); // __log( // `Refresh ${entry.options.name}; sig: ${sig.toFixed( // 2 // )} at ${processedAt}; Sig Matches: ${sigMatches.toString()}; changed: ${hasChanged.toString()}; file: ${path.relative( // process.cwd(), // entry.uri // )}` // ); // } if (sigMatches && hasChanged) { entry.loadingState = LoadingState.Loading; const key = calcKey(entry.options); const newEntry = loadEntry(entry.uri, entry.options); dictionaryCache.set(key, newEntry); dictionaryCacheByDef.set(entry.options, { key, entry: newEntry }); } } } type StatsOrError = Stats | Error; function isEqual(a: StatsOrError, b: StatsOrError | undefined): boolean { if (!b) return false; if (isError(a)) { return isError(b) && a.message === b.message && a.name === b.name; } return !isError(b) && (a.mtimeMs === b.mtimeMs || a.size === b.size); } function isError(e: StatsOrError): e is Error { const err = e as Partial<Error>; return !!err.message; } function loadEntry(uri: string, options: LoadOptions, now = Date.now()): CacheEntry { const pDictionary = load(uri, options).catch((e) => createFailedToLoadDictionary(new SpellingDictionaryLoadError(uri, options, e, 'failed to load')) ); const pStat = getStat(uri); const pending = Promise.all([pDictionary, pStat]); const sig = now + Math.random(); const entry: CacheEntry = { uri, options, ts: now, stat: undefined, dictionary: undefined, pending, loadingState: LoadingState.Loading, sig, }; // eslint-disable-next-line promise/catch-or-return pending.then(([dictionary, stat]) => { entry.stat = stat; entry.dictionary = dictionary; entry.loadingState = LoadingState.Loaded; return; }); return entry; } function loadEntrySync(uri: string, options: LoadOptions, now = Date.now()): CacheEntrySync { const stat = getStatSync(uri); const sig = now + Math.random(); try { const dictionary = loadSync(uri, options); const pending = Promise.resolve([dictionary, stat] as const); return { uri, options, ts: now, stat, dictionary, pending, loadingState: LoadingState.Loaded, sig, }; } catch (e) { const error = e instanceof Error ? e : new Error(format(e)); const dictionary = createFailedToLoadDictionary( new SpellingDictionaryLoadError(uri, options, error, 'failed to load') ); const pending = Promise.resolve([dictionary, stat] as const); return { uri, options, ts: now, stat, dictionary, pending, loadingState: LoadingState.Loaded, sig, }; } } function determineType(uri: string, opts: Pick<LoadOptions, 'type'>): LoaderType { const t: DictionaryFileTypes = (opts.type && opts.type in loaders && opts.type) || 'S'; const defLoaderType: LoaderType = t; const defType = uri.endsWith('.trie.gz') ? 'T' : defLoaderType; const regTrieTest = /\.trie\b/i; return regTrieTest.test(uri) ? 'T' : defType; } function load(uri: string, options: LoadOptions): Promise<SpellingDictionary> { const type = determineType(uri, options); const loader = loaders[type] || loaders.default; return loader(uri, options); } function loadSync(uri: string, options: LoadOptions): SpellingDictionary { const type = determineType(uri, options); const loader = loadersSync[type] || loaders.default; return loader(uri, options); } async function legacyWordList(filename: string, options: LoadOptions) { const lines = await readLines(filename); return _legacyWordListSync(lines, filename, options); } function legacyWordListSync(filename: string, options: LoadOptions) { const lines = readLinesSync(filename); return _legacyWordListSync(lines, filename, options); } function _legacyWordListSync(lines: Iterable<string>, filename: string, options: LoadOptions) { const words = genSequence(lines) // Remove comments .map((line) => line.replace(/#.*/g, '')) // Split on everything else .concatMap((line) => line.split(/[^\w\p{L}\p{M}'’]+/gu)) .filter((word) => !!word); return createSpellingDictionary(words, determineName(filename, options), filename, options); } async function wordsPerLineWordList(filename: string, options: LoadOptions) { const lines = await readLines(filename); return _wordsPerLineWordList(lines, filename, options); } function wordsPerLineWordListSync(filename: string, options: LoadOptions) { const lines = readLinesSync(filename); return _wordsPerLineWordList(lines, filename, options); } function _wordsPerLineWordList(lines: Iterable<string>, filename: string, options: LoadOptions) { const words = genSequence(lines) // Remove comments .map((line) => line.replace(/#.*/g, '')) // Split on everything else .concatMap((line) => line.split(/\s+/gu)) .filter((word) => !!word); return createSpellingDictionary(words, determineName(filename, options), filename, options); } async function loadSimpleWordList(filename: string, options: LoadOptions) { const lines = await readLines(filename); return createSpellingDictionary(lines, determineName(filename, options), filename, options); } function loadSimpleWordListSync(filename: string, options: LoadOptions) { const lines = readLinesSync(filename); return createSpellingDictionary(lines, determineName(filename, options), filename, options); } async function loadTrie(filename: string, options: LoadOptions) { const lines = await readLines(filename); return createSpellingDictionaryTrie(lines, determineName(filename, options), filename, options); } function loadTrieSync(filename: string, options: LoadOptions) { const lines = readLinesSync(filename); return createSpellingDictionaryTrie(lines, determineName(filename, options), filename, options); } function determineName(filename: string, options: LoadOptions): string { return options.name || path.basename(filename); } export const testing = { dictionaryCache, refreshEntry, loadEntry, load, }; function toError(e: unknown): Error { if (isErrnoException(e)) return e; if (e instanceof Error) return e; return new Error(format(e)); } /** * Copied from the Node definition to avoid a dependency upon a specific version of Node */ interface StatsBase<T> { isFile(): boolean; isDirectory(): boolean; isBlockDevice(): boolean; isCharacterDevice(): boolean; isSymbolicLink(): boolean; isFIFO(): boolean; isSocket(): boolean; dev: T; ino: T; mode: T; nlink: T; uid: T; gid: T; rdev: T; size: T; blksize: T; blocks: T; atimeMs: T; mtimeMs: T; ctimeMs: T; birthtimeMs: T; atime: Date; mtime: Date; ctime: Date; birthtime: Date; } function getStat(uri: string): Promise<Stats | Error> { return fs.stat(uri).catch((e) => toError(e)); } function getStatSync(uri: string): Stats | Error { try { return statSync(uri); } catch (e) { return toError(e); } } export type Stats = StatsBase<number>; export const __testing__ = { debugLog, };
the_stack
/// <reference types="jquery" /> interface ColorboxResizeSettings { height?: number | string | undefined; innerHeight?: number | string | undefined; width?: number | string | undefined; innerWidth?: number | string | undefined; } interface ColorboxSettings { /** * The transition type. Can be set to "elastic", "fade", or "none". */ transition?: string | undefined; /** * Sets the speed of the fade and elastic transitions, in milliseconds. */ speed?: number | undefined; /** * This can be used as an alternative anchor URL or to associate a URL for non-anchor elements such as images or form buttons. */ href?: any; /** * This can be used as an anchor title alternative for Colorbox. */ title?: any; /** * This can be used as an anchor rel alternative for Colorbox. */ rel?: any; /** * If true, and if maxWidth, maxHeight, innerWidth, innerHeight, width, or height have been defined, Colorbox will scale photos to fit within the those values. */ scalePhotos?: boolean | undefined; /** * If false, Colorbox will hide scrollbars for overflowing content. */ scrolling?: boolean | undefined; /** * The overlay opacity level. Range: 0 to 1. */ opacity?: number | undefined; /** * If true, Colorbox will immediately open. */ open?: boolean | undefined; /** * If true, focus will be returned when Colorbox exits to the element it was launched from. */ returnFocus?: boolean | undefined; /** * If false, the loading graphic removal and onComplete event will be delayed until iframe's content has completely loaded. */ fastIframe?: boolean | undefined; /** * Allows for preloading of 'Next' and 'Previous' content in a group, after the current content has finished loading. Set to false to disable. */ preloading?: boolean | undefined; /** * If false, disables closing Colorbox by clicking on the background overlay. */ overlayClose?: boolean | undefined; /** * If false, will disable closing colorbox on 'esc' key press. */ escKey?: boolean | undefined; /** * If false, will disable the left and right arrow keys from navigating between the items in a group. */ arrowKey?: boolean | undefined; /** * If false, will disable the ability to loop back to the beginning of the group when on the last element. */ loop?: boolean | undefined; /** * For submitting GET or POST values through an ajax request. The data property will act exactly like jQuery's .load() data argument, as Colorbox uses .load() for ajax handling. */ data?: any; /** * Adds a given class to colorbox and the overlay. */ className?: any; /** * Sets the fadeOut speed, in milliseconds, when closing Colorbox. */ fadeOut?: number | undefined; /** * Text or HTML for the group counter while viewing a group. {current} and {total} are detected and replaced with actual numbers while Colorbox runs. */ current?: string | undefined; /** * Text or HTML for the previous button while viewing a group. */ previous?: string | undefined; /** * Text or HTML for the next button while viewing a group. */ next?: string | undefined; /** * Text or HTML for the close button. The 'esc' key will also close Colorbox. */ close?: string | undefined; /** * Set to false to remove the close button. */ closeButton?: boolean | undefined; /** * Error message given when ajax content for a given URL cannot be loaded. */ xhrError?: string | undefined; /** * Error message given when a link to an image fails to load. */ imgError?: string | undefined; /** * If true, specifies that content should be displayed in an iFrame. */ iframe?: boolean | undefined; /** * If true, content from the current document can be displayed by passing the href property a jQuery selector, or jQuery object. */ inline?: boolean | undefined; /** * For displaying a string of HTML or text: $.colorbox({html:"<p>Hello</p>"}); */ html?: any; /** * If true, this setting forces Colorbox to display a link as a photo. Use this when automatic photo detection fails (such as using a url like 'photo.php' instead of 'photo.jpg') */ photo?: boolean | undefined; /** * This property isn't actually used as Colorbox assumes all hrefs should be treated as either ajax or photos, unless one of the other content types were specified. */ ajax?: any; /** * Set a fixed total width. This includes borders and buttons. Example: "100%", "500px", or 500 */ width?: number | string | undefined; /** * Set a fixed total height. This includes borders and buttons. Example: "100%", "500px", or 500 */ height?: number | string | undefined; /** * This is an alternative to 'width' used to set a fixed inner width. This excludes borders and buttons. Example: "50%", "500px", or 500 */ innerWidth?: number | string | undefined; /** * This is an alternative to 'height' used to set a fixed inner height. This excludes borders and buttons. Example: "50%", "500px", or 500 */ innerHeight?: number | string | undefined; /** * Set the initial width, prior to any content being loaded. */ initialWidth?: number | string | undefined; /** * Set the initial height, prior to any content being loaded. */ initialHeight?: number | string | undefined; /** * Set a maximum width for loaded content. Example: "100%", 500, "500px" */ maxWidth?: number | string | undefined; /** * Set a maximum height for loaded content. Example: "100%", 500, "500px" */ maxHeight?: number | string | undefined; /** * If true, adds an automatic slideshow to a content group / gallery. */ slideshow?: boolean | undefined; /** * Sets the speed of the slideshow, in milliseconds. */ slideshowSpeed?: number | undefined; /** * If true, the slideshow will automatically start to play. */ slideshowAuto?: boolean | undefined; /** * Text for the slideshow start button. */ slideshowStart?: string | undefined; /** * Text for the slideshow stop button */ slideshowStop?: string | undefined; /** * If true, Colorbox will be displayed in a fixed position within the visitor's viewport. This is unlike the default absolute positioning relative to the document. */ fixed?: boolean | undefined; /** * Accepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's vertical positioning instead of using the default position of being centered in the viewport. */ top?: any; /** * Accepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's vertical positioning instead of using the default position of being centered in the viewport. */ bottom?: any; /** * Accepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's horizontal positioning instead of using the default position of being centered in the viewport. */ left?: any; /** * Accepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's horizontal positioning instead of using the default position of being centered in the viewport. */ right?: any; /** * Repositions Colorbox if the window's resize event is fired. */ reposition?: boolean | undefined; /** * If true, Colorbox will scale down the current photo to match the screen's pixel ratio */ retinaImage?: boolean | undefined; /** * If true and the device has a high resolution display, Colorbox will replace the current photo's file extention with the retinaSuffix+extension */ retinaUrl?: boolean | undefined; /** * If retinaUrl is true and the device has a high resolution display, the href value will have it's extention extended with this suffix. For example, the default value would change `my-photo.jpg` to `my-photo@2x.jpg` */ retinaSuffix?: string | undefined; /** * Callback that fires right before Colorbox begins to open. */ onOpen?: any; /** * Callback that fires right before attempting to load the target content. */ onLoad?: any; /** * Callback that fires right after loaded content is displayed. */ onComplete?: any; /** * Callback that fires at the start of the close process. */ onCleanup?: any; /** * Callback that fires once Colorbox is closed. */ onClosed?: any; } interface ColorboxStatic { /** * This method allows you to call Colorbox without having to assign it to an element. */ (settings: ColorboxSettings): any; /** * This method moves to the next item in a group and are the same as pressing the 'next' or 'previous' buttons. */ next(): void; /** * This method moves to the previous item in a group and are the same as pressing the 'next' or 'previous' buttons. */ prev(): void; /** * This method initiates the close sequence, which does not immediately complete. The lightbox will be completely closed only when the cbox_closed event / onClosed callback is fired. */ close(): void; /** * This method is used to fetch the current HTML element that Colorbox is associated with. */ element(): JQuery; /** * This allows Colorbox to be resized based on it's own auto-calculations, or to a specific size. This must be called manually after Colorbox's content has loaded. */ resize(): void; /** * This allows Colorbox to be resized based on it's own auto-calculations, or to a specific size. This must be called manually after Colorbox's content has loaded. */ resize(settings: ColorboxResizeSettings): void; /** * Removes all traces of Colorbox from the document. */ remove(): void; /** * Default settings used for Colorbox calls */ settings: ColorboxSettings; } interface Colorbox { (): JQuery; (settings: ColorboxSettings): JQuery; } interface JQueryStatic { colorbox: ColorboxStatic; } interface JQuery { colorbox: Colorbox; }
the_stack
const fs = require('fs'); import { DSVModel } from '../src'; function readCSV(path: string): any { path = require.resolve(path); return fs.readFileSync(path, 'utf8'); } /* tslint:disable:no-var-requires */ const CSV_TEST_FILES = [ [ 'comma_in_quotes', readCSV('csv-spectrum/csvs/comma_in_quotes.csv'), require('csv-spectrum/json/comma_in_quotes.json') ], [ 'empty_values', readCSV('csv-spectrum/csvs/empty.csv'), require('csv-spectrum/json/empty.json') ], [ 'empty_crlf', readCSV('csv-spectrum/csvs/empty_crlf.csv'), require('csv-spectrum/json/empty_crlf.json') ], ['empty_file', '', []], [ 'escaped_quotes', readCSV('csv-spectrum/csvs/escaped_quotes.csv'), require('csv-spectrum/json/escaped_quotes.json') ], [ 'json', readCSV('csv-spectrum/csvs/json.csv'), require('csv-spectrum/json/json.json') ], [ 'newlines', readCSV('csv-spectrum/csvs/newlines.csv'), require('csv-spectrum/json/newlines.json') ], [ 'newlines_crlf', readCSV('csv-spectrum/csvs/newlines_crlf.csv'), require('csv-spectrum/json/newlines_crlf.json') ], [ 'quotes_and_newlines', readCSV('csv-spectrum/csvs/quotes_and_newlines.csv'), require('csv-spectrum/json/quotes_and_newlines.json') ], [ 'simple', readCSV('csv-spectrum/csvs/simple.csv'), require('csv-spectrum/json/simple.json') ], [ 'simple_crlf', readCSV('csv-spectrum/csvs/simple_crlf.csv'), require('csv-spectrum/json/simple_crlf.json') ], [ 'utf8', readCSV('csv-spectrum/csvs/utf8.csv'), require('csv-spectrum/json/utf8.json') ] ]; /* tslint:enable:no-var-requires */ describe('csvviewer/model', () => { describe('DSVModel', () => { describe('#constructor()', () => { it('should instantiate a `DSVModel`', () => { const d = new DSVModel({ data: 'a,b,c\nd,e,f\n', delimiter: ',' }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(1); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual([ 'd', 'e', 'f' ]); }); }); it('parses a number of test files correctly', () => { for (const [, csv, answer] of CSV_TEST_FILES) { const d = new DSVModel({ data: csv, delimiter: ',' }); const labels = []; for (let i = 0; i < d.columnCount('body'); i++) { labels.push(d.data('column-header', 0, i)); } const values = []; for (let r = 0; r < d.rowCount('body'); r++) { const row: { [key: string]: string } = {}; for (let c = 0; c < d.columnCount('body'); c++) { row[labels[c]] = d.data('body', r, c); } values.push(row); } expect(values).toEqual(answer); } }); it('handles tab-separated data', () => { const d = new DSVModel({ data: 'a\tb\tc\nd\te\tf\n', delimiter: '\t' }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(1); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual(['d', 'e', 'f']); }); it('handles not having a header', () => { const d = new DSVModel({ data: 'a,b,c\nd,e,f\n', delimiter: ',', header: false }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(2); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ '1', '2', '3' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual(['a', 'b', 'c']); expect([0, 1, 2].map(i => d.data('body', 1, i))).toEqual(['d', 'e', 'f']); }); it('handles having only a header', () => { const d = new DSVModel({ data: 'a,b,c\n', delimiter: ',', header: true }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(0); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); }); it('handles single non-header line', () => { const d = new DSVModel({ data: 'a,b,c\n', delimiter: ',', header: false }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(1); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ '1', '2', '3' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual(['a', 'b', 'c']); }); it('handles CRLF row delimiter', () => { const d = new DSVModel({ data: 'a,b,c\r\nd,e,f\r\n', delimiter: ',', rowDelimiter: '\r\n' }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(1); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual(['d', 'e', 'f']); }); it('handles CR row delimiter', () => { const d = new DSVModel({ data: 'a,b,c\rd,e,f\r', delimiter: ',', rowDelimiter: '\r' }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(1); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual(['d', 'e', 'f']); }); it('can guess the row delimiter', () => { const d = new DSVModel({ data: 'a,b,c\rd,e,f\r', delimiter: ',' }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(1); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual(['d', 'e', 'f']); }); it('handles a given quote character', () => { const d = new DSVModel({ data: `a,'b','c'\r'd',e,'f'\r`, delimiter: ',', quote: `'` }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(1); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual(['d', 'e', 'f']); }); it('handles delimiters and quotes inside quotes', () => { const d = new DSVModel({ data: `'a\rx',b,'c''x'\r'd,x',e,'f'\r`, delimiter: ',', quote: `'`, rowDelimiter: '\r' }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(1); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a\rx', 'b', `c'x` ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual([ 'd,x', 'e', 'f' ]); }); it('handles rows that are too short or too long', () => { const d = new DSVModel({ data: `a,b,c\n,c,d,e,f\ng,h`, delimiter: ',' }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(2); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual([ '', 'c', 'd,e,f' ]); expect([0, 1, 2].map(i => d.data('body', 1, i))).toEqual(['g', 'h', '']); }); it('handles delayed parsing of rows past the initial rows', async () => { const d = new DSVModel({ data: `a,b,c\nc,d,e\nf,g,h\ni,j,k`, delimiter: ',', initialRows: 2 }); expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(1); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); // Expected behavior is that all unparsed data is lumped into the final field. expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual([ 'c', 'd', 'e\nf,g,h\ni,j,k' ]); // Check everything is in order after all the data has been parsed asynchronously. await d.ready; expect(d.rowCount('column-header')).toBe(1); expect(d.rowCount('body')).toBe(3); expect(d.columnCount('row-header')).toBe(1); expect(d.columnCount('body')).toBe(3); expect([0, 1, 2].map(i => d.data('column-header', 0, i))).toEqual([ 'a', 'b', 'c' ]); expect([0, 1, 2].map(i => d.data('body', 0, i))).toEqual(['c', 'd', 'e']); expect([0, 1, 2].map(i => d.data('body', 1, i))).toEqual(['f', 'g', 'h']); expect([0, 1, 2].map(i => d.data('body', 2, i))).toEqual(['i', 'j', 'k']); }); }); });
the_stack
import React from 'react'; import ReactDOM from 'react-dom'; import isEqual from 'lodash/isEqual'; import Quill, { QuillOptionsStatic, DeltaStatic, RangeStatic, BoundsStatic, StringMap, Sources, } from 'quill'; // Merged namespace hack to export types along with default object // See: https://github.com/Microsoft/TypeScript/issues/2719 namespace ReactQuill { export type Value = string | DeltaStatic; export type Range = RangeStatic | null; export interface QuillOptions extends QuillOptionsStatic { tabIndex?: number, } export interface ReactQuillProps { bounds?: string | HTMLElement, children?: React.ReactElement<any>, className?: string, defaultValue?: Value, formats?: string[], id?: string, modules?: StringMap, onChange?( value: string, delta: DeltaStatic, source: Sources, editor: UnprivilegedEditor, ): void, onChangeSelection?( selection: Range, source: Sources, editor: UnprivilegedEditor, ): void, onFocus?( selection: Range, source: Sources, editor: UnprivilegedEditor, ): void, onBlur?( previousSelection: Range, source: Sources, editor: UnprivilegedEditor, ): void, onKeyDown?: React.EventHandler<any>, onKeyPress?: React.EventHandler<any>, onKeyUp?: React.EventHandler<any>, placeholder?: string, preserveWhitespace?: boolean, readOnly?: boolean, scrollingContainer?: string | HTMLElement, style?: React.CSSProperties, tabIndex?: number, theme?: string, value?: Value, } export interface UnprivilegedEditor { getLength(): number; getText(index?: number, length?: number): string; getHTML(): string; getBounds(index: number, length?: number): BoundsStatic; getSelection(focus?: boolean): RangeStatic; getContents(index?: number, length?: number): DeltaStatic; } } // Re-import everything from namespace into scope for comfort import Value = ReactQuill.Value; import Range = ReactQuill.Range; import QuillOptions = ReactQuill.QuillOptions; import ReactQuillProps = ReactQuill.ReactQuillProps; import UnprivilegedEditor = ReactQuill.UnprivilegedEditor; interface ReactQuillState { generation: number, } class ReactQuill extends React.Component<ReactQuillProps, ReactQuillState> { static displayName = 'React Quill' /* Export Quill to be able to call `register` */ static Quill = Quill; /* Changing one of these props should cause a full re-render and a re-instantiation of the Quill editor. */ dirtyProps: (keyof ReactQuillProps)[] = [ 'modules', 'formats', 'bounds', 'theme', 'children', ] /* Changing one of these props should cause a regular update. These are mostly props that act on the container, rather than the quillized editing area. */ cleanProps: (keyof ReactQuillProps)[] = [ 'id', 'className', 'style', 'placeholder', 'tabIndex', 'onChange', 'onChangeSelection', 'onFocus', 'onBlur', 'onKeyPress', 'onKeyDown', 'onKeyUp', ] static defaultProps = { theme: 'snow', modules: {}, readOnly: false, } state: ReactQuillState = { generation: 0, } /* The Quill Editor instance. */ editor?: Quill /* Reference to the element holding the Quill editing area. */ editingArea?: React.ReactInstance | null /* Tracks the internal value of the Quill editor */ value: Value /* Tracks the internal selection of the Quill editor */ selection: Range = null /* Used to compare whether deltas from `onChange` are being used as `value`. */ lastDeltaChangeSet?: DeltaStatic /* Stores the contents of the editor to be restored after regeneration. */ regenerationSnapshot?: { delta: DeltaStatic, selection: Range, } /* A weaker, unprivileged proxy for the editor that does not allow accidentally modifying editor state. */ unprivilegedEditor?: UnprivilegedEditor constructor(props: ReactQuillProps) { super(props); const value = this.isControlled()? props.value : props.defaultValue; this.value = value ?? ''; } validateProps(props: ReactQuillProps): void { if (React.Children.count(props.children) > 1) throw new Error( 'The Quill editing area can only be composed of a single React element.' ); if (React.Children.count(props.children)) { const child = React.Children.only(props.children); if (child?.type === 'textarea') throw new Error( 'Quill does not support editing on a <textarea>. Use a <div> instead.' ); } if ( this.lastDeltaChangeSet && props.value === this.lastDeltaChangeSet ) throw new Error( 'You are passing the `delta` object from the `onChange` event back ' + 'as `value`. You most probably want `editor.getContents()` instead. ' + 'See: https://github.com/zenoamaro/react-quill#using-deltas' ); } shouldComponentUpdate(nextProps: ReactQuillProps, nextState: ReactQuillState) { this.validateProps(nextProps); // If the editor hasn't been instantiated yet, or the component has been // regenerated, we already know we should update. if (!this.editor || this.state.generation !== nextState.generation) { return true; } // Handle value changes in-place if ('value' in nextProps) { const prevContents = this.getEditorContents(); const nextContents = nextProps.value ?? ''; // NOTE: Seeing that Quill is missing a way to prevent edits, we have to // settle for a hybrid between controlled and uncontrolled mode. We // can't prevent the change, but we'll still override content // whenever `value` differs from current state. // NOTE: Comparing an HTML string and a Quill Delta will always trigger a // change, regardless of whether they represent the same document. if (!this.isEqualValue(nextContents, prevContents)) { this.setEditorContents(this.editor, nextContents); } } // Handle read-only changes in-place if (nextProps.readOnly !== this.props.readOnly) { this.setEditorReadOnly(this.editor, nextProps.readOnly!); } // Clean and Dirty props require a render return [...this.cleanProps, ...this.dirtyProps].some((prop) => { return !isEqual(nextProps[prop], this.props[prop]); }); } shouldComponentRegenerate(nextProps: ReactQuillProps): boolean { // Whenever a `dirtyProp` changes, the editor needs reinstantiation. return this.dirtyProps.some((prop) => { return !isEqual(nextProps[prop], this.props[prop]); }); } componentDidMount() { this.instantiateEditor(); this.setEditorContents(this.editor!, this.getEditorContents()); } componentWillUnmount() { this.destroyEditor(); } componentDidUpdate(prevProps: ReactQuillProps, prevState: ReactQuillState) { // If we're changing one of the `dirtyProps`, the entire Quill Editor needs // to be re-instantiated. Regenerating the editor will cause the whole tree, // including the container, to be cleaned up and re-rendered from scratch. // Store the contents so they can be restored later. if (this.editor && this.shouldComponentRegenerate(prevProps)) { const delta = this.editor.getContents(); const selection = this.editor.getSelection(); this.regenerationSnapshot = {delta, selection}; this.setState({generation: this.state.generation + 1}); this.destroyEditor(); } // The component has been regenerated, so it must be re-instantiated, and // its content must be restored to the previous values from the snapshot. if (this.state.generation !== prevState.generation) { const {delta, selection} = this.regenerationSnapshot!; delete this.regenerationSnapshot; this.instantiateEditor(); const editor = this.editor!; editor.setContents(delta); postpone(() => this.setEditorSelection(editor, selection)); } } instantiateEditor(): void { if (this.editor) return; this.editor = this.createEditor( this.getEditingArea(), this.getEditorConfig() ); } destroyEditor(): void { if (!this.editor) return; this.unhookEditor(this.editor); delete this.editor; } /* We consider the component to be controlled if `value` is being sent in props. */ isControlled(): boolean { return 'value' in this.props; } getEditorConfig(): QuillOptions { return { bounds: this.props.bounds, formats: this.props.formats, modules: this.props.modules, placeholder: this.props.placeholder, readOnly: this.props.readOnly, scrollingContainer: this.props.scrollingContainer, tabIndex: this.props.tabIndex, theme: this.props.theme, }; } getEditor(): Quill { if (!this.editor) throw new Error('Accessing non-instantiated editor'); return this.editor; } /** Creates an editor on the given element. The editor will be passed the configuration, have its events bound, */ createEditor(element: Element, config: QuillOptions) { const editor = new Quill(element, config); if (config.tabIndex != null) { this.setEditorTabIndex(editor, config.tabIndex); } this.hookEditor(editor); return editor; } hookEditor(editor: Quill) { // Expose the editor on change events via a weaker, unprivileged proxy // object that does not allow accidentally modifying editor state. this.unprivilegedEditor = this.makeUnprivilegedEditor(editor); // Using `editor-change` allows picking up silent updates, like selection // changes on typing. editor.on('editor-change', this.onEditorChange); } unhookEditor(editor: Quill) { editor.off('editor-change', this.onEditorChange); } getEditorContents(): Value { return this.value; } getEditorSelection(): Range { return this.selection; } /* True if the value is a Delta instance or a Delta look-alike. */ isDelta(value: any): boolean { return value && value.ops; } /* Special comparison function that knows how to compare Deltas. */ isEqualValue(value: any, nextValue: any): boolean { if (this.isDelta(value) && this.isDelta(nextValue)) { return isEqual(value.ops, nextValue.ops); } else { return isEqual(value, nextValue); } } /* Replace the contents of the editor, but keep the previous selection hanging around so that the cursor won't move. */ setEditorContents(editor: Quill, value: Value) { this.value = value; const sel = this.getEditorSelection(); if (typeof value === 'string') { editor.setContents(editor.clipboard.convert(value)); } else { editor.setContents(value); } postpone(() => this.setEditorSelection(editor, sel)); } setEditorSelection(editor: Quill, range: Range) { this.selection = range; if (range) { // Validate bounds before applying. const length = editor.getLength(); range.index = Math.max(0, Math.min(range.index, length-1)); range.length = Math.max(0, Math.min(range.length, (length-1) - range.index)); editor.setSelection(range); } } setEditorTabIndex(editor: Quill, tabIndex: number) { if (editor?.scroll?.domNode) { (editor.scroll.domNode as HTMLElement).tabIndex = tabIndex; } } setEditorReadOnly(editor: Quill, value: boolean) { if (value) { editor.disable(); } else { editor.enable(); } } /* Returns a weaker, unprivileged proxy object that only exposes read-only accessors found on the editor instance, without any state-modifying methods. */ makeUnprivilegedEditor(editor: Quill) { const e = editor; return { getHTML: () => e.root.innerHTML, getLength: e.getLength.bind(e), getText: e.getText.bind(e), getContents: e.getContents.bind(e), getSelection: e.getSelection.bind(e), getBounds: e.getBounds.bind(e), }; } getEditingArea(): Element { if (!this.editingArea) { throw new Error('Instantiating on missing editing area'); } const element = ReactDOM.findDOMNode(this.editingArea); if (!element) { throw new Error('Cannot find element for editing area'); } if (element.nodeType === 3) { throw new Error('Editing area cannot be a text node'); } return element as Element; } /* Renders an editor area, unless it has been provided one to clone. */ renderEditingArea(): JSX.Element { const {children, preserveWhitespace} = this.props; const {generation} = this.state; const properties = { key: generation, ref: (instance: React.ReactInstance | null) => { this.editingArea = instance }, }; if (React.Children.count(children)) { return React.cloneElement( React.Children.only(children)!, properties ); } return preserveWhitespace ? <pre {...properties}/> : <div {...properties}/>; } render() { return ( <div id={this.props.id} style={this.props.style} key={this.state.generation} className={`quill ${this.props.className ?? ''}`} onKeyPress={this.props.onKeyPress} onKeyDown={this.props.onKeyDown} onKeyUp={this.props.onKeyUp} > {this.renderEditingArea()} </div> ); } onEditorChange = ( eventName: 'text-change' | 'selection-change', rangeOrDelta: Range | DeltaStatic, oldRangeOrDelta: Range | DeltaStatic, source: Sources, ) => { if (eventName === 'text-change') { this.onEditorChangeText?.( this.editor!.root.innerHTML, rangeOrDelta as DeltaStatic, source, this.unprivilegedEditor! ); } else if (eventName === 'selection-change') { this.onEditorChangeSelection?.( rangeOrDelta as RangeStatic, source, this.unprivilegedEditor! ); } }; onEditorChangeText( value: string, delta: DeltaStatic, source: Sources, editor: UnprivilegedEditor, ): void { if (!this.editor) return; // We keep storing the same type of value as what the user gives us, // so that value comparisons will be more stable and predictable. const nextContents = this.isDelta(this.value) ? editor.getContents() : editor.getHTML(); if (nextContents !== this.getEditorContents()) { // Taint this `delta` object, so we can recognize whether the user // is trying to send it back as `value`, preventing a likely loop. this.lastDeltaChangeSet = delta; this.value = nextContents; this.props.onChange?.(value, delta, source, editor); } } onEditorChangeSelection( nextSelection: RangeStatic, source: Sources, editor: UnprivilegedEditor, ): void { if (!this.editor) return; const currentSelection = this.getEditorSelection(); const hasGainedFocus = !currentSelection && nextSelection; const hasLostFocus = currentSelection && !nextSelection; if (isEqual(nextSelection, currentSelection)) return; this.selection = nextSelection; this.props.onChangeSelection?.(nextSelection, source, editor); if (hasGainedFocus) { this.props.onFocus?.(nextSelection, source, editor); } else if (hasLostFocus) { this.props.onBlur?.(currentSelection, source, editor); } } focus(): void { if (!this.editor) return; this.editor.focus(); } blur(): void { if (!this.editor) return; this.selection = null; this.editor.blur(); } } /* Small helper to execute a function in the next micro-tick. */ function postpone(fn: (value: void) => void) { Promise.resolve().then(fn); } // Compatibility Export to avoid `require(...).default` on CommonJS. // See: https://github.com/Microsoft/TypeScript/issues/2719 export = ReactQuill;
the_stack
import { WebGLRenderingContext } from '../../../node_modules/aswebglue/src/WebGL' import { Scene } from '../scenes/Scene' import { Camera } from '../cameras/Camera' // import { WebGLExtensions } from './webgl/WebGLExtensions'; // import { WebGLInfo } from './webgl/WebGLInfo'; // import { WebGLShadowMap } from './webgl/WebGLShadowMap'; import { WebGLCapabilities } from './webgl/WebGLCapabilities' import { WebGLProperties } from './webgl/WebGLProperties' import { RenderTarget, WebGLRenderLists } from './webgl/WebGLRenderLists' import { WebGLState } from './webgl/WebGLState' // import { Vector2 } from '../math/Vector2'; import { Vector4 } from '../math/Vector4' import { Color } from '../math/Color' // import { WebGLRenderTarget } from './WebGLRenderTarget'; import { Object3D } from '../core/Object3D' import { Material } from '../materials/Material' import { Fog } from '../scenes/Fog' import { BufferGeometry } from '../core/BufferGeometry' import { PowerPreference, Precision, ToneMapping } from '../constants' // import { WebVRManager } from './webvr/WebVRManager'; import { WebGLUtils } from './webgl/WebGLUtils' import { WebGLTextures } from './webgl/WebGLTextures' import { WebGLAttributes } from './webgl/WebGLAttributes' import { WebGLBindingStates } from './webgl/WebGLBindingStates' import { WebGLGeometries } from './webgl/WebGLGeometries' import { WebGLObjects } from './webgl/WebGLObjects' import { WebGLClipping } from './webgl/WebGLClipping' import { WebGLPrograms } from './webgl/WebGLPrograms' import { WebGLRenderStates } from './webgl/WebGLRenderStates' import { WebGLBackground } from './webgl/WebGLBackground' import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer' import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer' import { WebGLExtensions } from './webgl/WebGLExtensions' import { WebGLInfo } from './webgl/WebGLInfo' import { WebGLShadowMap } from './webgl/WebGLShadowMap' import { WebGLCubeMaps } from './webgl/WebGLCubeMaps' // export interface Renderer { // domElement: HTMLCanvasElement; // render( scene: Scene, camera: Camera ): void; // setSize( width: f32, height: f32, updateStyle?: boolean ): void; // } /** These are options for passing into WebGLRenderer constructor. */ export class WebGLRendererParameters { /** * A Canvas where the renderer draws its output. */ // TODO support this once we have a DOM interface in AssemblyScript // canvas?: HTMLCanvasElement // For now just pass a context instead. /** * A WebGL Rendering Context. * (https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext) * Default is null */ context: WebGLRenderingContext | null = null /** * shader precision. Can be Precision.Highp, Precision.Mediump or Precision.Mediump. Defaults to Precision.Highp. */ precision: Precision = Precision.Highp /** * default is true. */ alpha: boolean = true /** * default is true. */ premultipliedAlpha: boolean = true /** * default is false. */ antialias: boolean = false /** * default is true. */ stencil: boolean = true /** * default is false. */ preserveDrawingBuffer: boolean = false /** * Can be "high-performance", "low-power" or "default". Defaults to "default". */ powerPreference: PowerPreference = PowerPreference.Default /** * default is true. */ depth: boolean = true /** * default is false. */ logarithmicDepthBuffer: boolean = false /** * default is false. */ failIfMajorPerformanceCaveat: boolean = false } export class WebGLDebug { /** * Enables error checking and reporting when shader programs are being compiled. Default is true. */ checkShaderErrors: boolean = true } /** * The WebGL renderer displays your beautifully crafted scenes using WebGL, if your device supports it. * This renderer has way better performance than CanvasRenderer. * * @see <a href="https://github.com/mrdoob/three.js/blob/master/src/renderers/WebGLRenderer.js">src/renderers/WebGLRenderer.js</a> */ export class WebGLRenderer /*implements Renderer*/ { // private _canvas: HTMLCanvasElement // private _context: WebGLRenderingContext | null = null private _gl: WebGLRenderingContext private _alpha: boolean private _depth: boolean private _stencil: boolean private _antialias: boolean private _premultipliedAlpha: boolean private _preserveDrawingBuffer: boolean private _powerPreference: PowerPreference private _failIfMajorPerformanceCaveat: boolean /** * parameters is an optional object with properties defining the renderer's behaviour. The constructor also accepts no parameters at all. In all cases, it will assume sane defaults when parameters are missing. */ constructor(private parameters: WebGLRendererParameters | null = null) { this.parameters = this.parameters || new WebGLRendererParameters() // this._canvas = this.parameters.canvas != null ? this.parameters.canvas : createCanvasElement() // this._context = this.parameters.context // custom this._gl = this.parameters.context || new WebGLRenderingContext('#glas-canvas', 'webgl') this._alpha = this.parameters.alpha this._depth = this.parameters.depth this._stencil = this.parameters.stencil this._antialias = this.parameters.antialias this._premultipliedAlpha = this.parameters.premultipliedAlpha this._preserveDrawingBuffer = this.parameters.preserveDrawingBuffer this._powerPreference = this.parameters.powerPreference this._failIfMajorPerformanceCaveat = this.parameters.failIfMajorPerformanceCaveat this.initGLContext() } // /** // * A Canvas where the renderer draws its output. // * This is automatically created by the renderer in the constructor (if not provided already); you just need to add it to your page. // */ // domElement: HTMLCanvasElement /** * The HTML5 Canvas's 'webgl' context obtained from the canvas where the renderer will draw. */ context: WebGLRenderingContext /** * Defines whether the renderer should automatically clear its output before rendering. Default is true. */ autoClear: boolean = true /** * If autoClear is true, defines whether the renderer should clear the color buffer. Default is true. */ autoClearColor: boolean = true /** * If autoClear is true, defines whether the renderer should clear the depth buffer. Default is true. */ autoClearDepth: boolean = true /** * If autoClear is true, defines whether the renderer should clear the stencil buffer. Default is true. */ autoClearStencil: boolean = true /** * Debug configurations. */ debug: WebGLDebug = new WebGLDebug() /** * Defines whether the renderer should sort objects. Default is true. */ sortObjects: boolean = true // clippingPlanes: any[] // localClippingEnabled: boolean extensions: WebGLExtensions physicallyCorrectLights: boolean = false toneMapping: ToneMapping = ToneMapping.NoToneMapping toneMappingExposure: f32 = 1.0 /** * Default is 8. */ maxMorphTargets: i32 = 8 /** * Default is 4. */ maxMorphNormals: i32 = 4 info: WebGLInfo shadowMap: WebGLShadowMap private pixelRatio: f32 = 1.0 capabilities: WebGLCapabilities | null = null // TODO, a bit of work is needed in ASWebGLue for this. // xr: WebXRManager renderLists: WebGLRenderLists state: WebGLState | null = null private utils: WebGLUtils private properties: WebGLProperties private textures: WebGLTextures private cubemaps: WebGLCubeMaps private attributes: WebGLAttributes private bindingStates: WebGLBindingStates private geometries: WebGLGeometries private objects: WebGLObjects private morphtargets: WebGLMorphtargets private clipping: WebGLClipping private programCache: WebGLPrograms private materials: WebGLMaterials private renderStates: WebGLRenderStates private background: WebGLBackground private bufferRenderer: WebGLBufferRenderer private indexedBufferRenderer: WebGLIndexedBufferRenderer private initGLContext() { this.extensions = new WebGLExtensions(this._gl!) this.capabilities = new WebGLCapabilities(this._gl!, this.extensions, this.parameters) // this.extensions.init(this.capabilities) // this.utils = new WebGLUtils(this._gl, this.extensions, this.capabilities) this.state = new WebGLState(this._gl, this.extensions, this.capabilities) // state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); // state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); // this.info = new WebGLInfo( this._gl ); this.properties = new WebGLProperties() this.textures = new WebGLTextures( this._gl, this.extensions, this.state, this.properties, this.capabilities, this.utils, this.info ) this.cubemaps = new WebGLCubeMaps(this) this.attributes = new WebGLAttributes(this._gl, this.capabilities) // CONTINUE (note to self for @trusktr): continue updating the webgl/* classes to r125, and adding all the types to WebGLProperties as needed. this.bindingStates = new WebGLBindingStates(this._gl, this.extensions, attributes, this.capabilities) this.geometries = new WebGLGeometries(this._gl, this.attributes, this.info, this.bindingStates) this.objects = new WebGLObjects(this._gl, this.geometries, this.attributes, this.info) // this.morphtargets = new WebGLMorphtargets( this._gl ); this.clipping = new WebGLClipping(this.properties) this.programCache = new WebGLPrograms( this, this.cubemaps, this.extensions, this.capabilities, this.bindingStates, this.clipping ) this.materials = new WebGLMaterials(this.properties) this.renderLists = new WebGLRenderLists(this.properties) this.renderStates = new WebGLRenderStates(this.extensions, this.capabilities) this.background = new WebGLBackground(this, this.cubemaps, this.state, this.objects, this._premultipliedAlpha) this.bufferRenderer = new WebGLBufferRenderer(this._gl, this.extensions, info, this.capabilities) this.indexedBufferRenderer = new WebGLIndexedBufferRenderer(this._gl, this.extensions, info, this.capabilities) this.info.programs = programCache.programs } // /** // * Return the WebGL context. // */ // getContext(): WebGLRenderingContext // getContextAttributes(): any // forceContextLoss(): void // /** // * @deprecated Use {@link WebGLCapabilities#getMaxAnisotropy .capabilities.getMaxAnisotropy()} instead. // */ // getMaxAnisotropy(): f32 // /** // * @deprecated Use {@link WebGLCapabilities#precision .capabilities.precision} instead. // */ // getPrecision(): string // getPixelRatio(): f32 setPixelRatio(value: f32): void {} // getDrawingBufferSize(target: Vector2): Vector2 // setDrawingBufferSize(width: f32, height: f32, pixelRatio: f32): void // getSize(target: Vector2): Vector2 /** * Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0). */ setSize(width: f32, height: f32, updateStyle?: boolean): void {} // getCurrentViewport(target: Vector4): Vector4 // /** // * Copies the viewport into target. // */ // getViewport(target: Vector4): Vector4 /** * Sets the viewport to render from (x, y) to (x + width, y + height). * (x, y) is the lower-left corner of the region. */ setViewport(x: Vector4 | f32, y?: f32, width?: f32, height?: f32): void {} // /** // * Copies the scissor area into target. // */ // getScissor(target: Vector4): Vector4 // /** // * Sets the scissor area from (x, y) to (x + width, y + height). // */ // setScissor(x: Vector4 | f32, y?: f32, width?: f32, height?: f32): void // /** // * Returns true if scissor test is enabled; returns false otherwise. // */ // getScissorTest(): boolean // /** // * Enable the scissor test. When this is enabled, only the pixels within the defined scissor area will be affected by further renderer actions. // */ // setScissorTest(enable: boolean): void // /** // * Returns a THREE.Color instance with the current clear color. // */ // getClearColor(): Color /** * Sets the clear color, using color for the color and alpha for the opacity. */ setClearColor(color: Color, alpha?: f32): void {} // setClearColor(color: string, alpha?: f32): void // setClearColor(color: f32, alpha?: f32): void // /** // * Returns a float with the current clear alpha. Ranges from 0 to 1. // */ // getClearAlpha(): f32 // setClearAlpha(alpha: f32): void /** * Tells the renderer to clear its color, depth or stencil drawing buffer(s). * Arguments default to true */ clear(color?: boolean, depth?: boolean, stencil?: boolean): void {} // clearColor(): void // clearDepth(): void // clearStencil(): void // clearTarget(renderTarget: WebGLRenderTarget, color: boolean, depth: boolean, stencil: boolean): void // /** // * @deprecated Use {@link WebGLState#reset .state.reset()} instead. // */ // resetGLState(): void dispose(): void {} // /** // * Tells the shadow map plugin to update using the passed scene and camera parameters. // * // * @param scene an instance of Scene // * @param camera — an instance of Camera // */ // renderBufferImmediate(object: Object3D, program: Object, material: Material): void private _emptyScene = {} // TODO private renderBufferDirect( camera: Camera, scene: Object | null, geometry: BufferGeometry, material: Material, object: Object3D, group: TODO_what_is_it ): void { if (!scene) scene = this._emptyScene } // /** // * A build in function that can be used instead of requestAnimationFrame. For WebVR projects this function must be used. // * @param callback The function will be called every available frame. If `null` is passed it will stop any already ongoing animation. // */ // setAnimationLoop(callback: Function): void // /** // * @deprecated Use {@link WebGLRenderer#setAnimationLoop .setAnimationLoop()} instead. // */ // animate(callback: Function): void // /** // * Compiles all materials in the scene with the camera. This is useful to precompile shaders before the first rendering. // */ // compile(scene: Scene, camera: Camera): void /** * Render a scene using a camera. * The render is done to a previously specified {@link WebGLRenderTarget#renderTarget .renderTarget} set by calling * {@link WebGLRenderer#setRenderTarget .setRenderTarget} or to the canvas as usual. * * By default render buffers are cleared before rendering but you can prevent this by setting the property * {@link WebGLRenderer#autoClear autoClear} to false. If you want to prevent only certain buffers being cleared * you can set either the {@link WebGLRenderer#autoClearColor autoClearColor}, * {@link WebGLRenderer#autoClearStencil autoClearStencil} or {@link WebGLRenderer#autoClearDepth autoClearDepth} * properties to false. To forcibly clear one ore more buffers call {@link WebGLRenderer#clear .clear}. */ render(scene: Scene, camera: Camera): void { // TODO remove // let forceClear // TODO, we asume it won't be lost for now. // if (_isContextLost === true) { // throw new Error('Context is lost, unable to render.') // } // reset caching for this frame bindingStates.resetDefaultState() _currentMaterialId = -1 _currentCamera = null // update scene graph if (scene.autoUpdate === true) scene.updateMatrixWorld() // update camera matrices and frustum if (camera.parent === null) camera.updateMatrixWorld() // if (this.xr.enabled === true && this.xr.isPresenting === true) { // camera = this.xr.getCamera(camera) // } // if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget) currentRenderState = this.renderStates.get(scene, renderStateStack.length) currentRenderState.init() renderStateStack.push(currentRenderState) _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse) _frustum.setFromProjectionMatrix(_projScreenMatrix) _localClippingEnabled = this.localClippingEnabled _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera) currentRenderList = renderLists.get(scene, camera) currentRenderList.init() projectObject(scene, camera, 0, _this.sortObjects) currentRenderList.finish() if (_this.sortObjects === true) { currentRenderList.sort(_opaqueSort, _transparentSort) } // if (_clippingEnabled === true) clipping.beginShadows() const shadowsArray = currentRenderState.state.shadowsArray shadowMap.render(shadowsArray, scene, camera) currentRenderState.setupLights() currentRenderState.setupLightsView(camera) if (_clippingEnabled === true) clipping.endShadows() // if (this.info.autoReset === true) this.info.reset() // background.render(currentRenderList, scene, camera /*TODO REMOVE , forceClear*/) // render scene const opaqueObjects = currentRenderList.opaque const transparentObjects = currentRenderList.transparent if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera) if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera) // if (scene.isScene === true) scene.onAfterRender(_this, scene, camera) // if (_currentRenderTarget !== null) { // Generate mipmap if we're using any kind of mipmap filtering textures.updateRenderTargetMipmap(_currentRenderTarget) // resolve multisample renderbuffers to a single-sample texture if necessary textures.updateMultisampleRenderTarget(_currentRenderTarget) } // Ensure depth buffer writing is enabled so it can be cleared on next render state.buffers.depth.setTest(true) state.buffers.depth.setMask(true) state.buffers.color.setMask(true) state.setPolygonOffset(false) // this._gl.finish(); // This was already commented out in Three.js renderStateStack.pop() if (renderStateStack.length > 0) { currentRenderState = renderStateStack[renderStateStack.length - 1] } else { currentRenderState = null } currentRenderList = null } // /** // * Returns the current active cube face. // */ // getActiveCubeFace(): f32 // /** // * Returns the current active mipmap level. // */ // getActiveMipMapLevel(): f32 /** * Returns the current render target. If no render target is set, null is returned. */ getRenderTarget(): RenderTarget | null { // TODO return null } // /** // * @deprecated Use {@link WebGLRenderer#getRenderTarget .getRenderTarget()} instead. // */ // getCurrentRenderTarget(): RenderTarget | null // /** // * Sets the active render target. // * // * @param renderTarget The {@link WebGLRenderTarget renderTarget} that needs to be activated. When `null` is given, the canvas is set as the active render target instead. // * @param activeCubeFace Specifies the active cube side (PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5) of {@link WebGLRenderTargetCube}. // * @param activeMipMapLevel Specifies the active mipmap level. // */ // setRenderTarget(renderTarget: RenderTarget | null, activeCubeFace?: f32, activeMipMapLevel?: f32): void // readRenderTargetPixels( // renderTarget: RenderTarget, // x: f32, // y: f32, // width: f32, // height: f32, // buffer: any, // activeCubeFaceIndex?: f32 // ): void // /** // * @deprecated // */ // gammaFactor: f32 // /** // * @deprecated Use {@link WebGLShadowMap#enabled .shadowMap.enabled} instead. // */ // shadowMapEnabled: boolean // /** // * @deprecated Use {@link WebGLShadowMap#type .shadowMap.type} instead. // */ // shadowMapType: ShadowMapType // /** // * @deprecated Use {@link WebGLShadowMap#cullFace .shadowMap.cullFace} instead. // */ // shadowMapCullFace: CullFace // /** // * @deprecated Use {@link WebGLExtensions#get .extensions.get( 'OES_texture_float' )} instead. // */ // supportsFloatTextures(): any // /** // * @deprecated Use {@link WebGLExtensions#get .extensions.get( 'OES_texture_half_float' )} instead. // */ // supportsHalfFloatTextures(): any // /** // * @deprecated Use {@link WebGLExtensions#get .extensions.get( 'OES_standard_derivatives' )} instead. // */ // supportsStandardDerivatives(): any // /** // * @deprecated Use {@link WebGLExtensions#get .extensions.get( 'WEBGL_compressed_texture_s3tc' )} instead. // */ // supportsCompressedTextureS3TC(): any // /** // * @deprecated Use {@link WebGLExtensions#get .extensions.get( 'WEBGL_compressed_texture_pvrtc' )} instead. // */ // supportsCompressedTexturePVRTC(): any // /** // * @deprecated Use {@link WebGLExtensions#get .extensions.get( 'EXT_blend_minmax' )} instead. // */ // supportsBlendMinMax(): any // /** // * @deprecated Use {@link WebGLCapabilities#vertexTextures .capabilities.vertexTextures} instead. // */ // supportsVertexTextures(): any // /** // * @deprecated Use {@link WebGLExtensions#get .extensions.get( 'ANGLE_instanced_arrays' )} instead. // */ // supportsInstancedArrays(): any // /** // * @deprecated Use {@link WebGLRenderer#setScissorTest .setScissorTest()} instead. // */ // enableScissorTest(boolean: any): any }
the_stack
import _ from 'lodash' import capitalize from 'underscore.string/capitalize' import minimatch from 'minimatch' import $errUtils from './error_utils' import $XHR from './xml_http_request' import { makeContentWindowListener } from './events' const regularResourcesRe = /\.(jsx?|coffee|html|less|s?css|svg)(\?.*)?$/ const needsDashRe = /([a-z][A-Z])/g const props = 'onreadystatechange onload onerror'.split(' ') let restoreFn = null const setHeader = (xhr, key, val, transformer) => { if (val != null) { if (transformer) { val = transformer(val) } key = `X-Cypress-${capitalize(key)}` return xhr.setRequestHeader(key, encodeURI(val)) } } const normalize = (val) => { val = val.replace(needsDashRe, (match) => { return `${match[0]}-${match[1]}` }) return val.toLowerCase() } const nope = () => { return null } const responseTypeIsTextOrEmptyString = (responseType) => { return responseType === '' || responseType === 'text' } // when the browser naturally cancels/aborts // an XHR because the window is unloading // on chrome < 71 const isAbortedThroughUnload = (xhr) => { return xhr.canceled !== true && xhr.readyState === 4 && xhr.status === 0 && // responseText may be undefined on some responseTypes // https://github.com/cypress-io/cypress/issues/3008 // TODO: How do we want to handle other responseTypes? responseTypeIsTextOrEmptyString(xhr.responseType) && xhr.responseText === '' } const warnOnWhitelistRenamed = (obj, type) => { if (obj.whitelist) { return $errUtils.throwErrByPath('server.whitelist_renamed', { args: { type } }) } } const ignore = (xhr) => { const url = new URL(xhr.url) // https://github.com/cypress-io/cypress/issues/7280 // we want to strip the xhr's URL of any hash and query params before // checking the REGEX for matching file extensions url.search = '' url.hash = '' // allow if we're GET + looks like we're fetching regular resources return xhr.method === 'GET' && regularResourcesRe.test(url.href) } const serverDefaults = { xhrUrl: '', method: 'GET', delay: 0, status: 200, headers: null, response: null, enable: true, autoRespond: true, waitOnResponses: Infinity, force404: false, // to force 404's for non-stubbed routes onAnyAbort: undefined, onAnyRequest: undefined, onAnyResponse: undefined, urlMatchingOptions: { matchBase: true }, stripOrigin: _.identity, getUrlOptions: _.identity, ignore, // function whether to allow a request to go out (css/js/html/templates) etc onOpen () {}, onSend () {}, onXhrAbort () {}, onXhrCancel () {}, onError () {}, onLoad () {}, onFixtureError () {}, onNetworkError () {}, } const restore = () => { if (restoreFn) { restoreFn() restoreFn = null } } const getStack = () => { const err = new Error return err.stack.split('\n').slice(3).join('\n') } const get404Route = () => { return { status: 404, response: '', delay: 0, headers: null, is404: true, } } const transformHeaders = (headers) => { // normalize camel-cased headers key headers = _.reduce(headers, (memo, value, key) => { memo[normalize(key)] = value return memo }, {}) return JSON.stringify(headers) } const normalizeStubUrl = (xhrUrl, url) => { if (!xhrUrl) { $errUtils.warnByPath('server.xhrurl_not_set') } // always ensure this is an absolute-relative url // and remove any double slashes xhrUrl = _.compact(xhrUrl.split('/')).join('/') url = _.trimStart(url, '/') return [`/${xhrUrl}`, url].join('/') } const getFullyQualifiedUrl = (contentWindow, url) => { // the href getter will always resolve a full path const a = contentWindow.document.createElement('a') a.href = url return a.href } // override the defaults for all servers const defaults = (obj = {}) => { // merge obj into defaults return _.extend(serverDefaults, obj) } // TODO: Convert it to a class. // It's written in this way to bypass type failures. export type Server = { restore: () => void cancelPendingXhrs: () => any[] bindTo: (win: Window) => void } const create = (options = {}): Server => { options = _.defaults(options, serverDefaults) const xhrs = {} const proxies = {} const routes = [] // always start disabled // so we dont handle stubs let hasEnabledStubs = false const enableStubs = (bool = true) => { return hasEnabledStubs = bool } const server = { options, restore, getStack, get404Route, transformHeaders, normalizeStubUrl, getFullyQualifiedUrl, getOptions () { // clone the options to prevent // accidental mutations return _.clone(options) }, getRoutes () { return routes }, isIgnored (xhr) { return options.ignore(xhr) }, shouldApplyStub (route) { return hasEnabledStubs && route && (route.response != null) }, applyStubProperties (xhr, route) { const responser = _.isObject(route.response) ? JSON.stringify : null // add header properties for the xhr's id // and the testId setHeader(xhr, 'id', xhr.id) // setHeader(xhr, "testId", options.testId) setHeader(xhr, 'status', route.status) setHeader(xhr, 'response', route.response, responser) setHeader(xhr, 'matched', `${route.url}`) setHeader(xhr, 'delay', route.delay) return setHeader(xhr, 'headers', route.headers, transformHeaders) }, route (attrs = {}) { // merge attrs with the server's defaults // so we preserve the state of the attrs // at the time they're created since we // can create another server later // dont mutate the original attrs const route = _.defaults( {}, attrs, _.pick(options, 'delay', 'method', 'status', 'autoRespond', 'waitOnResponses', 'onRequest', 'onResponse'), ) routes.push(route) return route }, getRouteForXhr (xhr) { // return the 404 stub if we dont have any stubs // but we are stubbed - meaning we havent added any routes // but have started the server // and this request shouldnt be allowed if (!routes.length && hasEnabledStubs && options.force404 !== false && !server.isIgnored(xhr)) { return get404Route() } // bail if we've attached no stubs if (!routes.length) { return nope() } // bail if this xhr matches our ignore list if (server.isIgnored(xhr)) { return nope() } // loop in reverse to get // the first matching stub // thats been most recently added for (let i = routes.length - 1; i >= 0; i--) { const route = routes[i] if (server.xhrMatchesRoute(xhr, route)) { return route } } // else if no stub matched // send 404 if we're allowed to if (options.force404) { return get404Route() } // else return null return nope() }, methodsMatch (routeMethod, xhrMethod) { // normalize both methods by uppercasing them return routeMethod.toUpperCase() === xhrMethod.toUpperCase() }, urlsMatch (routePattern, fullyQualifiedUrl) { const match = (str, pattern) => { // be nice to our users and prepend // pattern with "/" if it doesnt have one // and str does if (pattern[0] !== '/' && str[0] === '/') { pattern = `/${pattern}` } return minimatch(str, pattern, options.urlMatchingOptions) } const testRe = (url1, url2) => { return routePattern.test(url1) || routePattern.test(url2) } const testStr = (url1, url2) => { return (routePattern === url1) || (routePattern === url2) || match(url1, routePattern) || match(url2, routePattern) } if (_.isRegExp(routePattern)) { return testRe(fullyQualifiedUrl, options.stripOrigin(fullyQualifiedUrl)) } return testStr(fullyQualifiedUrl, options.stripOrigin(fullyQualifiedUrl)) }, xhrMatchesRoute (xhr, route) { return server.methodsMatch(route.method, xhr.method) && server.urlsMatch(route.url, xhr.url) }, add (xhr, attrs = {}) { const id = _.uniqueId('xhr') _.extend(xhr, attrs) xhr.id = id xhrs[id] = xhr proxies[id] = $XHR.create(xhr) return proxies[id] }, getProxyFor (xhr) { return proxies[xhr.id] }, abortXhr (xhr) { const proxy = server.getProxyFor(xhr) // if the XHR leaks into the next test // after we've reset our internal server // then this may be undefined if (!proxy) { return } // return if we're already aborted which // can happen if the browser already canceled // this xhr but we called abort later if (xhr.aborted) { return } xhr.aborted = true const abortStack = server.getStack() proxy.aborted = true options.onXhrAbort(proxy, abortStack) if (_.isFunction(options.onAnyAbort)) { const route = server.getRouteForXhr(xhr) // call the onAnyAbort function // after we've called options.onSend return options.onAnyAbort(route, proxy) } }, cancelXhr (xhr) { const proxy = server.getProxyFor(xhr) // if the XHR leaks into the next test // after we've reset our internal server // then this may be undefined if (!proxy) { return } xhr.canceled = true proxy.canceled = true options.onXhrCancel(proxy) return xhr }, cancelPendingXhrs () { // cancel any outstanding xhr's // which aren't already complete // or already canceled return _ .chain(xhrs) .reject({ readyState: 4 }) .reject({ canceled: true }) .map(server.cancelXhr) .value() }, set (obj) { warnOnWhitelistRenamed(obj, 'server') // handle enable=true|false if (obj.enable != null) { enableStubs(obj.enable) } return _.extend(options, obj) }, bindTo (contentWindow) { restore() const XHR = contentWindow.XMLHttpRequest const { send, open, abort } = XHR.prototype const srh = XHR.prototype.setRequestHeader const bridgeContentWindowListener = makeContentWindowListener('cypressXhrBridge', contentWindow) restoreFn = () => { // restore the property back on the window return _.each( { send, open, abort, setRequestHeader: srh }, (value, key) => { return XHR.prototype[key] = value }, ) } XHR.prototype.setRequestHeader = function (...args) { // if the XHR leaks into the next test // after we've reset our internal server // then this may be undefined const proxy = server.getProxyFor(this) if (proxy) { proxy._setRequestHeader.apply(proxy, args) } return srh.apply(this, args) } XHR.prototype.abort = function (...args) { // if we already have a readyState of 4 // then do not get the abort stack or // set the aborted property or call onXhrAbort // to test this just use a regular XHR if (this.readyState !== 4) { server.abortXhr(this) } return abort.apply(this, args) } XHR.prototype.open = function (method, url, async = true, username, password) { // get the fully qualified url that normally the browser // would be sending this request to // FQDN: http://www.google.com/responses/users.json // relative: partials/phones-list.html // absolute-relative: /app/partials/phones-list.html const fullyQualifiedUrl = getFullyQualifiedUrl(contentWindow, url) // decode the entire url.display to make // it easier to do assertions const proxy = server.add(this, { method, url: decodeURIComponent(fullyQualifiedUrl), }) // if this XHR matches a stubbed route then shift // its url to the stubbed url and set the request // headers for the response const route = server.getRouteForXhr(this) if (server.shouldApplyStub(route)) { url = server.normalizeStubUrl(options.xhrUrl, fullyQualifiedUrl) } const timeStart = new Date const xhr = this const fns = {} const overrides = {} const bailIfRecursive = (fn) => { let isCalled = false return (...args) => { if (isCalled) { return } isCalled = true try { return fn.apply(contentWindow, args) } finally { isCalled = false } } } const onLoadFn = function (...args) { proxy._setDuration(timeStart) proxy._setStatus() proxy._setResponseHeaders() proxy._setResponseBody() let err = proxy._getFixtureError() if (err) { return options.onFixtureError(proxy, err) } // catch synchronous errors caused // by the onload function try { const ol = fns.onload if (_.isFunction(ol)) { ol.apply(xhr, args) } options.onLoad(proxy, route) } catch (error) { err = error options.onError(proxy, err) } if (_.isFunction(options.onAnyResponse)) { return options.onAnyResponse(route, proxy) } } const onErrorFn = function (...args) { // its possible our real onerror handler // throws so we need to catch those errors too try { const oe = fns.onerror if (_.isFunction(oe)) { oe.apply(xhr, args) } return options.onNetworkError(proxy) } catch (err) { return options.onError(proxy, err) } } const onReadyStateFn = function (...args) { // catch synchronous errors caused // by the onreadystatechange function try { const orst = fns.onreadystatechange if (isAbortedThroughUnload(xhr)) { server.abortXhr(xhr) } if (_.isFunction(orst)) { return orst.apply(xhr, args) } } catch (err) { // its failed stop sending the callack xhr.onreadystatechange = null return options.onError(proxy, err) } } // bail if eventhandlers have already been called to prevent // infinite recursion overrides.onload = bridgeContentWindowListener(bailIfRecursive(onLoadFn)) overrides.onerror = bridgeContentWindowListener(bailIfRecursive(onErrorFn)) overrides.onreadystatechange = bridgeContentWindowListener(bailIfRecursive(onReadyStateFn)) props.forEach((prop) => { // if we currently have one of these properties then // back them up! const fn = xhr[prop] if (fn) { fns[prop] = fn } // set the override now xhr[prop] = overrides[prop] // and in the future if this is redefined // then just back it up return Object.defineProperty(xhr, prop, { get () { const bak = fns[prop] if (_.isFunction(bak)) { return (...args) => { return bak.apply(xhr, args) } } return overrides[prop] }, set (fn) { fns[prop] = fn }, configurable: true, }) }) options.onOpen(method, url, async, username, password) // change absolute url's to relative ones // if they match our baseUrl / visited URL return open.call(this, method, url, async, username, password) } XHR.prototype.send = function (requestBody) { // if there is an existing route for this // XHR then add those properties into it // only if route isnt explicitly false // and the server is enabled const route = server.getRouteForXhr(this) if (server.shouldApplyStub(route)) { server.applyStubProperties(this, route) } // capture where this xhr came from const sendStack = server.getStack() // get the proxy xhr const proxy = server.getProxyFor(this) proxy._setRequestBody(requestBody) // log this out now since it's being sent officially // unless its not been ignored if (!server.isIgnored(this)) { options.onSend(proxy, sendStack, route) } if (_.isFunction(options.onAnyRequest)) { // call the onAnyRequest function // after we've called options.onSend options.onAnyRequest(route, proxy) } // eslint-disable-next-line prefer-rest-params return send.apply(this, arguments) } }, } return server } export default { create, defaults, }
the_stack
'use strict'; import * as solparse from 'solparse-exp-jb'; import { CompletionItem, CompletionItemKind } from 'vscode-languageserver'; import * as vscode from 'vscode-languageserver'; import {Contract2, DeclarationType, DocumentContract, Function, SolidityCodeWalker, Variable, Struct} from './codeWalkerService'; import * as glob from 'glob'; import { relative } from 'path'; import { fileURLToPath } from 'url'; import * as path from 'path'; import { Project } from '../common/model/project'; export class CompletionService { public rootPath: string; constructor(rootPath: string) { this.rootPath = rootPath; } public getTypeString(literal: any) { const isArray = literal.array_parts.length > 0; let isMapping = false; const literalType = literal.literal; let suffixType = ''; if (typeof literalType.type !== 'undefined') { isMapping = literalType.type === 'MappingExpression'; if (isMapping) { suffixType = '(' + this.getTypeString(literalType.from) + ' => ' + this.getTypeString(literalType.to) + ')'; } } if (isArray) { suffixType = suffixType + '[]'; } if (isMapping) { return 'mapping' + suffixType; } return literalType + suffixType; } public createFunctionParamsSnippet(params: any, skipFirst: boolean = false): string { let paramsSnippet = ''; let counter = 0; if (typeof params !== 'undefined' && params !== null) { params.forEach( parameterElement => { if(skipFirst && counter === 0) { skipFirst = false; } else { const typeString = this.getTypeString(parameterElement.literal); counter = counter + 1; const currentParamSnippet = '${' + counter + ':' + parameterElement.id + '}'; if (paramsSnippet === '') { paramsSnippet = currentParamSnippet; } else { paramsSnippet = paramsSnippet + ', ' + currentParamSnippet; } } }); } return paramsSnippet; } public createParamsInfo(params: any): string { let paramsInfo = ''; if (typeof params !== 'undefined' && params !== null) { if (params.hasOwnProperty('params')) { params = params.params; } params.forEach( parameterElement => { const typeString = this.getTypeString(parameterElement.literal); let currentParamInfo = ''; if (typeof parameterElement.id !== 'undefined' && parameterElement.id !== null ) { // no name on return parameters currentParamInfo = typeString + ' ' + parameterElement.id; } else { currentParamInfo = typeString; } if (paramsInfo === '') { paramsInfo = currentParamInfo; } else { paramsInfo = paramsInfo + ', ' + currentParamInfo; } }); } return paramsInfo; } public createFunctionEventCompletionItem(contractElement: any, type: string, contractName: string, skipFirstParamSnipppet: boolean = false): CompletionItem { const completionItem = CompletionItem.create(contractElement.name); completionItem.kind = CompletionItemKind.Function; const paramsInfo = this.createParamsInfo(contractElement.params); const paramsSnippet = this.createFunctionParamsSnippet(contractElement.params, skipFirstParamSnipppet); let returnParamsInfo = this.createParamsInfo(contractElement.returnParams); if (returnParamsInfo !== '') { returnParamsInfo = ' returns (' + returnParamsInfo + ')'; } completionItem.insertTextFormat = 2; completionItem.insertText = contractElement.name + '(' + paramsSnippet + ');'; const info = '(' + type + ' in ' + contractName + ') ' + contractElement.name + '(' + paramsInfo + ')' + returnParamsInfo; completionItem.documentation = info; completionItem.detail = info; return completionItem; } public createParameterCompletionItem(contractElement: any, type: string, contractName: string): CompletionItem { const completionItem = CompletionItem.create(contractElement.id); completionItem.kind = CompletionItemKind.Variable; const typeString = this.getTypeString(contractElement.literal); completionItem.detail = '(' + type + ' in ' + contractName + ') ' + typeString + ' ' + contractElement.id; return completionItem; } public createVariableCompletionItem(contractElement: any, type: string, contractName: string): CompletionItem { const completionItem = CompletionItem.create(contractElement.name); completionItem.kind = CompletionItemKind.Field; const typeString = this.getTypeString(contractElement.literal); completionItem.detail = '(' + type + ' in ' + contractName + ') ' + typeString + ' ' + contractElement.name; return completionItem; } public createStructCompletionItem(contractElement: any, contractName: string): CompletionItem { const completionItem = CompletionItem.create(contractElement.name); completionItem.kind = CompletionItemKind.Struct; //completionItem.insertText = contractName + '.' + contractElement.name; completionItem.insertText = contractElement.name; completionItem.detail = '(Struct in ' + contractName + ') ' + contractElement.name; return completionItem; } public createEnumCompletionItem(contractElement: any, contractName: string): CompletionItem { const completionItem = CompletionItem.create(contractElement.name); completionItem.kind = CompletionItemKind.Enum; //completionItem.insertText = contractName + '.' + contractElement.name; completionItem.insertText = contractElement.name; completionItem.detail = '(Enum in ' + contractName + ') ' + contractElement.name; return completionItem; } // type "Contract, Libray, Abstract contract" public createContractCompletionItem(contractName: string, type: string): CompletionItem { const completionItem = CompletionItem.create(contractName); completionItem.kind = CompletionItemKind.Class; completionItem.insertText = contractName; completionItem.detail = '(' + type + ' : ' + contractName + ') ' return completionItem; } public createInterfaceCompletionItem(contractName: string): CompletionItem { const completionItem = CompletionItem.create(contractName); completionItem.kind = CompletionItemKind.Interface; completionItem.insertText = contractName; completionItem.detail = '( Interface : ' + contractName + ') ' return completionItem; } public getDocumentCompletionItems(documentText: string): CompletionItem[] { const completionItems = []; try { const result = solparse.parse(documentText); // console.log(JSON.stringify(result)); // TODO struct, modifier result.body.forEach(element => { if (element.type === 'ContractStatement' || element.type === 'LibraryStatement' || element.type == 'InterfaceStatement') { const contractName = element.name; if (typeof element.body !== 'undefined' && element.body !== null) { element.body.forEach(contractElement => { if (contractElement.type === 'FunctionDeclaration') { // ignore the constructor TODO add to contract initialiasation if (contractElement.name !== contractName) { completionItems.push( this.createFunctionEventCompletionItem(contractElement, 'function', contractName )); } } if (contractElement.type === 'EventDeclaration') { completionItems.push(this.createFunctionEventCompletionItem(contractElement, 'event', contractName )); } if (contractElement.type === 'StateVariableDeclaration') { completionItems.push(this.createVariableCompletionItem(contractElement, 'state variable', contractName)); } if (contractElement.type === 'EnumDeclaration') { completionItems.push(this.createEnumCompletionItem(contractElement, contractName)); } if (contractElement.type === 'StructDeclaration') { completionItems.push(this.createStructCompletionItem(contractElement, contractName)); } }); } } }); } catch (error) { // gracefule catch // console.log(error.message); } // console.log('file completion items' + completionItems.length); return completionItems; } public getAllCompletionItems(packageDefaultDependenciesDirectory: string, packageDefaultDependenciesContractsDirectory: string, remappings: string[], document: vscode.TextDocument, position: vscode.Position, ): CompletionItem[] { let completionItems = []; let triggeredByEmit = false; let triggeredByImport = false; let triggeredByDotStart = 0; try { var walker = new SolidityCodeWalker(this.rootPath, packageDefaultDependenciesDirectory, packageDefaultDependenciesContractsDirectory, remappings ); const offset = document.offsetAt(position); var documentContractSelected = walker.getAllContracts(document, position); const lines = document.getText().split(/\r?\n/g); triggeredByDotStart = this.getTriggeredByDotStart(lines, position); //triggered by emit is only possible with ctrl space triggeredByEmit = getAutocompleteVariableNameTrimmingSpaces(lines[position.line], position.character - 1) === 'emit'; triggeredByImport = getAutocompleteVariableNameTrimmingSpaces(lines[position.line], position.character - 1) === 'import' // TODO: this does not work due to the trigger. // || (lines[position.line].trimLeft().startsWith('import "') && lines[position.line].trimLeft().lastIndexOf('"') === 7); if(triggeredByDotStart > 0) { const globalVariableContext = GetContextualAutoCompleteByGlobalVariable(lines[position.line], triggeredByDotStart); if (globalVariableContext != null) { completionItems = completionItems.concat(globalVariableContext); } else { let autocompleteByDot = getAutocompleteTriggerByDotVariableName(lines[position.line], triggeredByDotStart - 1); // if triggered by variable //done // todo triggered by method (get return type) // done // todo triggered by property // done // todo variable // method return is an array (push, length etc) // variable / method / property is an address or other specific type functionality (balance, etc) // variable / method / property type is extended by a library if(autocompleteByDot.name !== '') { // have we got a selected contract (assuming not type.something) if(documentContractSelected.selectedContract !== undefined && documentContractSelected.selectedContract !== null ) { let selectedContract = documentContractSelected.selectedContract; //this contract if(autocompleteByDot.name === 'this' && autocompleteByDot.isVariable && autocompleteByDot.parentAutocomplete === null) { //add selectd contract completion items this.addContractCompletionItems(selectedContract, completionItems); } else { /// the types let topParent = autocompleteByDot.getTopParent(); if (topParent.name === "this") { topParent = topParent.childAutocomplete; } this.findDotCompletionItemsForSelectedContract(topParent, completionItems, documentContractSelected, documentContractSelected.selectedContract, offset); } } } } return completionItems; } if(triggeredByImport) { let files = glob.sync(this.rootPath + '/**/*.sol'); files.forEach(item => { let dependenciesDir = path.join(this.rootPath, packageDefaultDependenciesDirectory); item = path.join(item); if(item.startsWith(dependenciesDir)) { let pathLibrary = item.substr(dependenciesDir.length + 1); pathLibrary = pathLibrary.split('\\').join('/'); let completionItem = CompletionItem.create(pathLibrary); completionItem.kind = CompletionItemKind.Reference; completionItem.insertText = '"' + pathLibrary + '";'; completionItems.push(completionItem); } else { let remapping = walker.project.findRemappingForFile(item); if (remapping != null) { let pathLibrary = remapping.createImportFromFile(item); pathLibrary = pathLibrary.split('\\').join('/'); let completionItem = CompletionItem.create(pathLibrary); completionItem.kind = CompletionItemKind.Reference; completionItem.insertText = '"' + pathLibrary + '";'; completionItems.push(completionItem); } else { let rel = relative(fileURLToPath(document.uri), item); rel = rel.split('\\').join('/'); if(rel.startsWith('../')) { rel = rel.substr(1); } let completionItem = CompletionItem.create(rel); completionItem.kind = CompletionItemKind.Reference; completionItem.insertText = '"' + rel + '";'; completionItems.push(completionItem); } } }); return completionItems; } if(triggeredByEmit) { if(documentContractSelected.selectedContract !== undefined && documentContractSelected.selectedContract !== null ) { this.addAllEventsAsCompletionItems(documentContractSelected.selectedContract, completionItems); } } else { if(documentContractSelected.selectedContract !== undefined && documentContractSelected.selectedContract !== null ) { let selectedContract = documentContractSelected.selectedContract; this.addSelectedContractCompletionItems(selectedContract, completionItems, offset); } documentContractSelected.allContracts.forEach(x => { if(x.contractType === "ContractStatement") { completionItems.push(this.createContractCompletionItem(x.name, "Contract")); } if(x.contractType === "LibraryStatement") { completionItems.push(this.createContractCompletionItem(x.name, "Library")); } if(x.contractType === "InterfaceStatement") { completionItems.push(this.createInterfaceCompletionItem(x.name)); } }) } } catch (error) { // graceful catch console.log(error); } finally { completionItems = completionItems.concat(GetCompletionTypes()); completionItems = completionItems.concat(GetCompletionKeywords()); completionItems = completionItems.concat(GeCompletionUnits()); completionItems = completionItems.concat(GetGlobalFunctions()); completionItems = completionItems.concat(GetGlobalVariables()); } return completionItems; } private findDotCompletionItemsForSelectedContract(autocompleteByDot:AutocompleteByDot, completionItems: any[], documentContractSelected: DocumentContract, currentContract: Contract2, offset:number) { if(currentContract === documentContractSelected.selectedContract) { let selectedFunction = documentContractSelected.selectedContract.getSelectedFunction(offset); this.findDotCompletionItemsForContract(autocompleteByDot, completionItems, documentContractSelected.allContracts, documentContractSelected.selectedContract, selectedFunction, offset); } else { this.findDotCompletionItemsForContract(autocompleteByDot, completionItems, documentContractSelected.allContracts, documentContractSelected.selectedContract); } } private findDotCompletionItemsForContract(autocompleteByDot:AutocompleteByDot, completionItems: any[], allContracts: Contract2[], currentContract: Contract2, selectedFunction: Function = null, offset:number = null) { let allStructs = currentContract.getAllStructs(); let allEnums = currentContract.getAllEnums(); let allVariables: Variable[] = currentContract.getAllStateVariables(); let allfunctions: Function[] = currentContract.getAllFunctions(); if(selectedFunction !== undefined && selectedFunction !== null) { selectedFunction.findVariableDeclarationsInScope(offset, null); //adding input parameters allVariables = allVariables.concat(selectedFunction.input); //ading all variables allVariables = allVariables.concat(selectedFunction.variablesInScope); } let found = false; if (autocompleteByDot.isVariable) { allVariables.forEach(item => { if (item.name === autocompleteByDot.name && !found) { found = true; if(autocompleteByDot.childAutocomplete !== undefined && autocompleteByDot.childAutocomplete !== null) { this.findDotType(allStructs, item.type, autocompleteByDot.childAutocomplete, completionItems, allContracts, currentContract); } else { this.findDotTypeCompletion(allStructs, item.type, completionItems, allContracts, currentContract); } } }); if (!found && (autocompleteByDot.childAutocomplete === undefined || autocompleteByDot.childAutocomplete === null)) { allEnums.forEach(item => { if (item.name === autocompleteByDot.name) { found = true; item.items.forEach(property => { let completitionItem = CompletionItem.create(property); completionItems.push(completitionItem); }); } }); } if (!found && (autocompleteByDot.childAutocomplete === undefined || autocompleteByDot.childAutocomplete === null) ) { allContracts.forEach(item => { if (item.name === autocompleteByDot.name) { found = true; this.addContractCompletionItems(item, completionItems); } }); } } if (autocompleteByDot.isMethod) { allfunctions.forEach(item => { if (item.name === autocompleteByDot.name) { found = true; if (item.output.length === 1) { //todo return array let type = item.output[0].type; if(autocompleteByDot.childAutocomplete !== undefined && autocompleteByDot.childAutocomplete !== null) { this.findDotType(allStructs, type, autocompleteByDot.childAutocomplete, completionItems, allContracts, currentContract); } else { this.findDotTypeCompletion(allStructs, type, completionItems, allContracts, currentContract); } } } }); //contract declaration as IMyContract(address) if (!found && (autocompleteByDot.childAutocomplete === undefined || autocompleteByDot.childAutocomplete === null) ) { allContracts.forEach(item => { if (item.name === autocompleteByDot.name) { found = true; this.addContractCompletionItems(item, completionItems); } }); } } } private findDotTypeCompletion(allStructs: Struct[], type: DeclarationType, completionItems: any[], allContracts: Contract2[], currentContract: Contract2) { let foundStruct = allStructs.find(x => x.name === type.name); if (foundStruct !== undefined) { foundStruct.variables.forEach(property => { //own method refactor let completitionItem = CompletionItem.create(property.name); const typeString = this.getTypeString(property.element.literal); completitionItem.detail = '(' + property.name + ' in ' + foundStruct.name + ') ' + typeString + ' ' + foundStruct.name; completionItems.push(completitionItem); }); } else { let foundContract = allContracts.find(x => x.name === type.name); if (foundContract !== undefined) { foundContract.initialiseExtendContracts(allContracts); this.addContractCompletionItems(foundContract, completionItems); } } let allUsing = currentContract.getAllUsing(type); allUsing.forEach(usingItem => { let foundLibrary = allContracts.find(x => x.name === usingItem.name); if (foundLibrary !== undefined) { this.addAllLibraryExtensionsAsCompletionItems(foundLibrary, completionItems, type); } }); } private findDotType(allStructs: Struct[], type: DeclarationType, autocompleteByDot: AutocompleteByDot, completionItems: any[], allContracts: Contract2[], currentContract: Contract2) { let foundStruct = allStructs.find(x => x.name === type.name); if (foundStruct !== undefined) { foundStruct.variables.forEach(property => { //own method refactor if(autocompleteByDot.name === property.name) { if(autocompleteByDot.childAutocomplete !== undefined && autocompleteByDot.childAutocomplete !== null) { this.findDotType(allStructs, property.type, autocompleteByDot.childAutocomplete, completionItems, allContracts, currentContract); } else { this.findDotTypeCompletion(allStructs, property.type, completionItems, allContracts, currentContract); } } }); } else { let foundContract = allContracts.find(x => x.name === type.name); if (foundContract !== undefined) { foundContract.initialiseExtendContracts(allContracts); this.findDotCompletionItemsForContract(autocompleteByDot, completionItems, allContracts, foundContract); } } /* let allUsing = currentContract.getAllUsing(type); allUsing.forEach(usingItem => { let foundLibrary = allContracts.find(x => x.name === usingItem.name); if (foundLibrary !== undefined) { this.addAllLibraryExtensionsAsCompletionItems(foundLibrary, completionItems, type); } }); */ } private addContractCompletionItems(selectedContract: Contract2, completionItems: any[]) { this.addAllFunctionsAsCompletionItems(selectedContract, completionItems); this.addAllStateVariablesAsCompletionItems(selectedContract, completionItems); } private addSelectedContractCompletionItems(selectedContract: Contract2, completionItems: any[], offset: number) { this.addAllFunctionsAsCompletionItems(selectedContract, completionItems); this.addAllEventsAsCompletionItems(selectedContract, completionItems); this.addAllStateVariablesAsCompletionItems(selectedContract, completionItems); this.addAllStructsAsCompletionItems(selectedContract, completionItems); this.addAllEnumsAsCompletionItems(selectedContract, completionItems); let selectedFunction = selectedContract.getSelectedFunction(offset); if (selectedFunction !== undefined) { selectedFunction.findVariableDeclarationsInScope(offset, null); selectedFunction.input.forEach(parameter => { completionItems.push(this.createParameterCompletionItem(parameter.element, "function parameter", selectedFunction.contract.name)); }); selectedFunction.output.forEach(parameter => { completionItems.push(this.createParameterCompletionItem(parameter.element, "return parameter", selectedFunction.contract.name)); }); selectedFunction.variablesInScope.forEach(variable => { completionItems.push(this.createVariableCompletionItem(variable.element, "function variable", selectedFunction.contract.name)); }); } } private addAllEnumsAsCompletionItems(documentContractSelected: Contract2, completionItems: any[]) { let allEnums = documentContractSelected.getAllEnums(); allEnums.forEach(item => { completionItems.push( this.createEnumCompletionItem(item.element, item.contract.name)); }); } private addAllStructsAsCompletionItems(documentContractSelected: Contract2, completionItems: any[]) { let allStructs = documentContractSelected.getAllStructs(); allStructs.forEach(item => { completionItems.push( this.createStructCompletionItem(item.element, item.contract.name)); }); } private addAllEventsAsCompletionItems(documentContractSelected: Contract2, completionItems: any[]) { let allevents = documentContractSelected.getAllEvents(); allevents.forEach(item => { completionItems.push( this.createFunctionEventCompletionItem(item.element, 'event', item.contract.name)); }); } private addAllStateVariablesAsCompletionItems(documentContractSelected: Contract2, completionItems: any[]) { let allStateVariables = documentContractSelected.getAllStateVariables(); allStateVariables.forEach(item => { completionItems.push( this.createVariableCompletionItem(item.element, 'state variable', item.contract.name)); }); } private addAllFunctionsAsCompletionItems(documentContractSelected: Contract2, completionItems: any[]) { let allfunctions = documentContractSelected.getAllFunctions(); allfunctions.forEach(item => { completionItems.push( this.createFunctionEventCompletionItem(item.element, 'function', item.contract.name)); }); } private addAllLibraryExtensionsAsCompletionItems(documentContractSelected: Contract2, completionItems: any[], type: DeclarationType) { let allfunctions = documentContractSelected.getAllFunctions(); let filteredFunctions = allfunctions.filter( x => { if(x.input.length > 0 ) { let typex = x.input[0].type; let validTypeName = false; if(typex.name === type.name || (type.name === "address_payable" && typex.name === "address")) { validTypeName = true; } return typex.isArray === type.isArray && validTypeName && typex.isMapping === type.isMapping; } return false; }); filteredFunctions.forEach(item => { completionItems.push( this.createFunctionEventCompletionItem(item.element, 'function', item.contract.name, true)); }); } public getTriggeredByDotStart(lines:string[], position: vscode.Position):number { let start = 0; let triggeredByDot = false; for (let i = position.character; i >= 0; i--) { if (lines[position.line[i]] === ' ') { triggeredByDot = false; i = 0; start = 0; } if (lines[position.line][i] === '.') { start = i; i = 0; triggeredByDot = true; } } return start; } /* public getAllCompletionItems(documentText: string, documentPath: string, packageDefaultDependenciesDirectory: string, packageDefaultDependenciesContractsDirectory: string, remappings: string[]): CompletionItem[] { if (this.rootPath !== 'undefined' && this.rootPath !== null) { const contracts = new ContractCollection(); contracts.addContractAndResolveImports( documentPath, documentText, initialiseProject(this.rootPath, packageDefaultDependenciesDirectory, packageDefaultDependenciesContractsDirectory, remappings)); let completionItems = []; contracts.contracts.forEach(contract => { completionItems = completionItems.concat(this.getDocumentCompletionItems(contract.code)); }); // console.log('total completion items' + completionItems.length); return completionItems; } else { return this.getDocumentCompletionItems(documentText); } }*/ } export function GetCompletionTypes(): CompletionItem[] { const completionItems = []; const types = ['address', 'string', 'bytes', 'byte', 'int', 'uint', 'bool', 'hash']; for (let index = 8; index <= 256; index += 8) { types.push('int' + index); types.push('uint' + index); types.push('bytes' + index / 8); } types.forEach(type => { const completionItem = CompletionItem.create(type); completionItem.kind = CompletionItemKind.Keyword; completionItem.detail = type + ' type'; completionItems.push(completionItem); }); // add mapping return completionItems; } function CreateCompletionItem(label: string, kind: CompletionItemKind, detail: string) { const completionItem = CompletionItem.create(label); completionItem.kind = kind; completionItem.detail = detail; return completionItem; } export function GetCompletionKeywords(): CompletionItem[] { const completionItems = []; const keywords = [ 'modifier', 'mapping', 'break', 'continue', 'delete', 'else', 'for', 'if', 'new', 'return', 'returns', 'while', 'using', 'private', 'public', 'external', 'internal', 'payable', 'nonpayable', 'view', 'pure', 'case', 'do', 'else', 'finally', 'in', 'instanceof', 'return', 'throw', 'try', 'catch', 'typeof', 'yield', 'void', 'virtual', 'override'] ; keywords.forEach(unit => { const completionItem = CompletionItem.create(unit); completionItem.kind = CompletionItemKind.Keyword; completionItems.push(completionItem); }); completionItems.push(CreateCompletionItem('contract', CompletionItemKind.Class, null)); completionItems.push(CreateCompletionItem('library', CompletionItemKind.Class, null)); completionItems.push(CreateCompletionItem('storage', CompletionItemKind.Field, null)); completionItems.push(CreateCompletionItem('memory', CompletionItemKind.Field, null)); completionItems.push(CreateCompletionItem('var', CompletionItemKind.Field, null)); completionItems.push(CreateCompletionItem('constant', CompletionItemKind.Constant, null)); completionItems.push(CreateCompletionItem('immutable', CompletionItemKind.Keyword, null)); completionItems.push(CreateCompletionItem('constructor', CompletionItemKind.Constructor, null)); completionItems.push(CreateCompletionItem('event', CompletionItemKind.Event, null)); completionItems.push(CreateCompletionItem('import', CompletionItemKind.Module, null)); completionItems.push(CreateCompletionItem('enum', CompletionItemKind.Enum, null)); completionItems.push(CreateCompletionItem('struct', CompletionItemKind.Struct, null)); completionItems.push(CreateCompletionItem('function', CompletionItemKind.Function, null)); return completionItems; } export function GeCompletionUnits(): CompletionItem[] { const completionItems = []; const etherUnits = ['wei', 'finney', 'szabo', 'ether'] ; etherUnits.forEach(unit => { const completionItem = CompletionItem.create(unit); completionItem.kind = CompletionItemKind.Unit; completionItem.detail = unit + ': ether unit'; completionItems.push(completionItem); }); const timeUnits = ['seconds', 'minutes', 'hours', 'days', 'weeks', 'years']; timeUnits.forEach(unit => { const completionItem = CompletionItem.create(unit); completionItem.kind = CompletionItemKind.Unit; if (unit !== 'years') { completionItem.detail = unit + ': time unit'; } else { completionItem.detail = 'DEPRECATED: ' + unit + ': time unit'; } completionItems.push(completionItem); }); return completionItems; } export function GetGlobalVariables(): CompletionItem[] { return [ { detail: 'Current block', kind: CompletionItemKind.Variable, label: 'block', }, { detail: 'Current Message', kind: CompletionItemKind.Variable, label: 'msg', }, { detail: '(uint): current block timestamp (alias for block.timestamp)', kind: CompletionItemKind.Variable, label: 'now', }, { detail: 'Current transaction', kind: CompletionItemKind.Variable, label: 'tx', }, { detail: 'ABI encoding / decoding', kind: CompletionItemKind.Variable, label: 'abi', }, ]; } export function GetGlobalFunctions(): CompletionItem[] { return [ { detail: 'assert(bool condition): throws if the condition is not met - to be used for internal errors.', insertText: 'assert(${1:condition});', insertTextFormat: 2, kind: CompletionItemKind.Function, label: 'assert', }, { detail: 'gasleft(): returns the remaining gas', insertText: 'gasleft();', insertTextFormat: 2, kind: CompletionItemKind.Function, label: 'gasleft', }, { detail: 'unicode: converts string into unicode', insertText: 'unicode"${1:text}"', insertTextFormat: 2, kind: CompletionItemKind.Function, label: 'unicode', }, { detail: 'blockhash(uint blockNumber): hash of the given block - only works for 256 most recent, excluding current, blocks', insertText: 'blockhash(${1:blockNumber});', insertTextFormat: 2, kind: CompletionItemKind.Function, label: 'blockhash', }, { detail: 'require(bool condition): reverts if the condition is not met - to be used for errors in inputs or external components.', insertText: 'require(${1:condition});', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'require', }, { // tslint:disable-next-line:max-line-length detail: 'require(bool condition, string message): reverts if the condition is not met - to be used for errors in inputs or external components. Also provides an error message.', insertText: 'require(${1:condition}, ${2:message});', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'require', }, { detail: 'revert(): abort execution and revert state changes', insertText: 'revert();', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'revert', }, { detail: 'addmod(uint x, uint y, uint k) returns (uint):' + 'compute (x + y) % k where the addition is performed with arbitrary precision and does not wrap around at 2**256', insertText: 'addmod(${1:x}, ${2:y}, ${3:k})', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'addmod', }, { detail: 'mulmod(uint x, uint y, uint k) returns (uint):' + 'compute (x * y) % k where the multiplication is performed with arbitrary precision and does not wrap around at 2**256', insertText: 'mulmod(${1:x}, ${2:y}, ${3:k})', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'mulmod', }, { detail: 'keccak256(...) returns (bytes32):' + 'compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments', insertText: 'keccak256(${1:x})', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'keccak256', }, { detail: 'sha256(...) returns (bytes32):' + 'compute the SHA-256 hash of the (tightly packed) arguments', insertText: 'sha256(${1:x})', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'sha256', }, { detail: 'sha3(...) returns (bytes32):' + 'alias to keccak256', insertText: 'sha3(${1:x})', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'sha3', }, { detail: 'ripemd160(...) returns (bytes20):' + 'compute RIPEMD-160 hash of the (tightly packed) arguments', insertText: 'ripemd160(${1:x})', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'ripemd160', }, { detail: 'ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address):' + 'recover the address associated with the public key from elliptic curve signature or return zero on error', insertText: 'ecrecover(${1:hash}, ${2:v}, ${3:r}, ${4:s})', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'ecrecover', }, ]; } export function GetContextualAutoCompleteByGlobalVariable(lineText: string, wordEndPosition: number): CompletionItem[] { if (isAutocompleteTrigeredByVariableName('block', lineText, wordEndPosition)) { return getBlockCompletionItems(); } if (isAutocompleteTrigeredByVariableName('msg', lineText, wordEndPosition)) { return getMsgCompletionItems(); } if (isAutocompleteTrigeredByVariableName('tx', lineText, wordEndPosition)) { return getTxCompletionItems(); } if (isAutocompleteTrigeredByVariableName('abi', lineText, wordEndPosition)) { return getAbiCompletionItems(); } return null; } function isAutocompleteTrigeredByVariableName(variableName: string, lineText: string, wordEndPosition: number): Boolean { const nameLength = variableName.length; if (wordEndPosition >= nameLength // does it equal our name? && lineText.substr(wordEndPosition - nameLength, nameLength) === variableName) { return true; } return false; } export class AutocompleteByDot { public isVariable: boolean = false; public isMethod: boolean = false; public isArray: boolean = false; public isProperty: boolean = false; public parentAutocomplete: AutocompleteByDot = null;// could be a property or a method public childAutocomplete: AutocompleteByDot = null; public name: string = ''; getTopParent(): AutocompleteByDot { if(this.parentAutocomplete != null) { return this.parentAutocomplete.getTopParent(); } return this; } } function getAutocompleteTriggerByDotVariableName(lineText: string, wordEndPosition:number): AutocompleteByDot { let searching = true; let result: AutocompleteByDot = new AutocompleteByDot(); //simpler way might be to find the first space or beginning of line //and from there split / match (but for now kiss or slowly) wordEndPosition = getArrayStart(lineText, wordEndPosition, result); if(lineText[wordEndPosition] == ')' ) { result.isMethod = true; let methodParamBeginFound = false; while(!methodParamBeginFound && wordEndPosition >= 0 ) { if(lineText[wordEndPosition] === '(') { methodParamBeginFound = true; } wordEndPosition = wordEndPosition - 1; } } if(!result.isMethod && !result.isArray) { result.isVariable = true; } while(searching && wordEndPosition >= 0) { let currentChar = lineText[wordEndPosition]; if(isAlphaNumeric(currentChar) || currentChar === '_' || currentChar === '$') { result.name = currentChar + result.name; wordEndPosition = wordEndPosition - 1; } else { if(currentChar === ' ') { // we only want a full word for a variable / method // this cannot be parsed due incomplete statements searching = false; return result; } else { if(currentChar === '.') { result.parentAutocomplete = getAutocompleteTriggerByDotVariableName(lineText, wordEndPosition - 1); result.parentAutocomplete.childAutocomplete = result; } } searching = false; return result; } } return result; } function getArrayStart(lineText: string, wordEndPosition: number, result: AutocompleteByDot) { if (lineText[wordEndPosition] == ']') { result.isArray = true; let arrayBeginFound = false; while (!arrayBeginFound && wordEndPosition >= 0) { if (lineText[wordEndPosition] === '[') { arrayBeginFound = true; } wordEndPosition = wordEndPosition - 1; } } if(lineText[wordEndPosition] == ']') { wordEndPosition = getArrayStart(lineText, wordEndPosition, result); } return wordEndPosition; } function getAutocompleteVariableNameTrimmingSpaces(lineText: string, wordEndPosition:number): string { let searching = true; let result: string = ''; if(lineText[wordEndPosition] === ' ' ) { let spaceFound = true; while(spaceFound && wordEndPosition >= 0 ) { wordEndPosition = wordEndPosition - 1; if(lineText[wordEndPosition] !== ' ') { spaceFound = false; } } } while(searching && wordEndPosition >= 0) { let currentChar = lineText[wordEndPosition]; if(isAlphaNumeric(currentChar) || currentChar === '_' || currentChar === '$') { result = currentChar + result; wordEndPosition = wordEndPosition - 1; } else { if(currentChar === ' ') { // we only want a full word for a variable // this cannot be parsed due incomplete statements searching = false; return result; } searching = false; return ''; } } return result; } function isAlphaNumeric(str) { var code, i, len; for (i = 0, len = str.length; i < len; i++) { code = str.charCodeAt(i); if (!(code > 47 && code < 58) && // numeric (0-9) !(code > 64 && code < 91) && // upper alpha (A-Z) !(code > 96 && code < 123)) { // lower alpha (a-z) return false; } } return true; }; function getBlockCompletionItems(): CompletionItem[] { return [ { detail: '(address): Current block miner’s address', kind: CompletionItemKind.Property, label: 'coinbase', }, { detail: '(bytes32): DEPRICATED In 0.4.22 use blockhash(uint) instead. Hash of the given block - only works for 256 most recent blocks excluding current', insertText: 'blockhash(${1:blockNumber});', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'blockhash', }, { detail: '(uint): current block difficulty', kind: CompletionItemKind.Property, label: 'difficulty', }, { detail: '(uint): current block gaslimit', kind: CompletionItemKind.Property, label: 'gaslimit', }, { detail: '(uint): current block number', kind: CompletionItemKind.Property, label: 'number', }, { detail: '(uint): current block timestamp as seconds since unix epoch', kind: CompletionItemKind.Property, label: 'timestamp', }, ]; } function getTxCompletionItems(): CompletionItem[] { return [ { detail: '(uint): gas price of the transaction', kind: CompletionItemKind.Property, label: 'gas', }, { detail: '(address): sender of the transaction (full call chain)', kind: CompletionItemKind.Property, label: 'origin', }, ]; } function getMsgCompletionItems(): CompletionItem[] { return [ { detail: '(bytes): complete calldata', kind: CompletionItemKind.Property, label: 'data', }, { detail: '(uint): remaining gas DEPRICATED in 0.4.21 use gasleft()', kind: CompletionItemKind.Property, label: 'gas', }, { detail: '(address): sender of the message (current call)', kind: CompletionItemKind.Property, label: 'sender', }, { detail: '(bytes4): first four bytes of the calldata (i.e. function identifier)', kind: CompletionItemKind.Property, label: 'sig', }, { detail: '(uint): number of wei sent with the message', kind: CompletionItemKind.Property, label: 'value', }, ]; } function getAbiCompletionItems(): CompletionItem[] { return [ { detail: 'encode(..) returs (bytes): ABI-encodes the given arguments', insertText: 'encode(${1:arg});', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'encode', }, { detail: 'encodePacked(..) returns (bytes): Performes packed encoding of the given arguments', insertText: 'encodePacked(${1:arg});', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'encodePacked', }, { detail: 'encodeWithSelector(bytes4,...) returns (bytes): ABI-encodes the given arguments starting from the second and prepends the given four-byte selector', insertText: 'encodeWithSelector(${1:bytes4}, ${2:arg});', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'encodeWithSelector', }, { detail: 'encodeWithSignature(string,...) returns (bytes): Equivalent to abi.encodeWithSelector(bytes4(keccak256(signature), ...)`', insertText: 'encodeWithSignature(${1:signatureString}, ${2:arg});', insertTextFormat: 2, kind: CompletionItemKind.Method, label: 'encodeWithSignature', }, ]; }
the_stack
import { Component, ElementRef, EventEmitter, forwardRef, Input, NgZone, OnDestroy, OnInit, Output, Renderer2 } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { DomHandler } from './slider.handler'; import { ValueAccessorBaseComponent } from '../../base/value-accessor'; @Component({ selector: 'amexio-slider', templateUrl: 'slider.component.html', providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => AmexioSliderComponent), multi: true, }], }) export class AmexioSliderComponent extends ValueAccessorBaseComponent<number> implements OnInit, OnDestroy, ControlValueAccessor { /* Properties name : animate datatype : boolean version : 4.0 onwards default : false description : Sets if animate flag is set */ @Input() animate: boolean; /* Properties name : disabled datatype : boolean version : 4.0 onwards default : false description : Sets if slider is disabled */ @Input() disabled: boolean; /* Properties name : min-value datatype : number version : 4.0 onwards default : description : Min slider value */ @Input('min-value') min = 0; /* Properties name : max-value datatype : number version : 4.0 onwards default : description : Max slider value */ @Input('max-value') max = 100; /* Properties name : orientation datatype : string version : 4.0 onwards default : horizontal description : Vertical or Horizontal Orientation of slider */ @Input() orientation = 'horizontal'; /* Properties name : step-value datatype : number version : 4.0 onwards default : description : Step value in slider */ @Input('step-value') step: number; /* Properties name : range datatype : boolean version : 4.0 onwards default : false description : Range set to the slider */ @Input() range: boolean; @Input() style: any; /* Properties name : style-class datatype : string version : 4.0 onwards default : description : Styling class applied slider */ @Input('style-class') styleClass: string; /* Properties name : input datatype : number version : 5.11.2 onwards default : description : Type applied to slider */ @Input('type') type = 1; /* Properties name :shape datatype : string version : 4.0 onwards default : round description : Round or Square Shape for toggle switch ,example shape=round,square . */ @Input() shape: string; /* /* Events name : onChange datatype : any version : 4.0 onwards default : description : Triggers when slider is moved */ @Output() onChange: EventEmitter<any> = new EventEmitter(); /* Events name : onSlideEnd datatype : any version : 4.0 onwards default : description : Triggers when slider reaches the end */ @Output() onSlideEnd: EventEmitter<any> = new EventEmitter(); // For input use only @Input('darkmode-slider') darkmodeSlider = false; public dragging: boolean; public dragListener: any; public mouseupListener: any; public initX: number; public initY: number; public barWidth: number; public barHeight: number; public sliderHandleClick: boolean; public handleIndex = 0; public startHandleValue: any; public startx: number; public starty: number; public value: number; public values: number; public handleValue: number; public handleValues: number[] = []; public slidevar: any; componentId: string; sliderFocus = false; public onModelChange: any = () => { }; public onModelTouched: any = () => { }; constructor(public el: ElementRef, public domHandler: DomHandler, public renderer: Renderer2, private ngZone: NgZone) { super(); this.componentId = 'slider' + '_' + Math.floor(window.crypto.getRandomValues(new Uint32Array(1))[0]); } ngOnInit() { if (this.shape === '' || this.shape == null) { this.shape = 'round'; } } onMouseDown(event: Event, index?: number) { if (this.disabled) { return; } this.dragging = true; this.updateDomData(); this.sliderHandleClick = true; this.handleIndex = index; this.bindDragListeners(); event.preventDefault(); } onTouchStart(event: any, index?: number) { const touchobj = event.changedTouches[0]; this.startHandleValue = (this.range) ? this.handleValues[index] : this.handleValue; this.dragging = true; this.handleIndex = index; if (this.orientation === 'horizontal') { this.startx = parseInt(touchobj.clientX, 10); this.barWidth = this.el.nativeElement.children[0].offsetWidth; } else { this.starty = parseInt(touchobj.clientY, 10); this.barHeight = this.el.nativeElement.children[0].offsetHeight; } event.preventDefault(); } onTouchMove(event: any, index?: number) { const touchobj = event.changedTouches[0]; let handleValue = 0; if (this.orientation === 'horizontal') { handleValue = Math.floor(((parseInt(touchobj.clientX, 10) - this.startx) * 100) / (this.barWidth)) + this.startHandleValue; } else { handleValue = Math.floor(((this.starty - parseInt(touchobj.clientY, 10)) * 100) / (this.barHeight)) + this.startHandleValue; } this.setValueFromHandle(event, handleValue); event.preventDefault(); } onBarClick(event: any) { if (this.disabled) { return; } if (!this.sliderHandleClick) { this.updateDomData(); this.handleChange(event); } this.sliderHandleClick = false; } handleChange(event: Event) { let handleValue = this.calculateHandleValue(event); const stepvalue = parseInt(this.step + '', 10); if ((handleValue + stepvalue) > 99) { handleValue = 100; } else if ((handleValue - stepvalue) < 1) { handleValue = 0; } this.setValueFromHandle(event, handleValue); } bindDragListeners() { this.ngZone.runOutsideAngular(() => { if (!this.dragListener) { this.dragListener = this.renderer.listen('document', 'mousemove', (event: any) => { if (this.dragging) { this.ngZone.run(() => { this.handleChange(event); }); } }); } if (!this.mouseupListener) { this.mouseupListener = this.renderer.listen('document', 'mouseup', (event: any) => { this.mouseUpListMethod(); }); } }); } mouseUpListMethod() { if (this.dragging) { this.dragging = false; this.ngZone.run(() => { if (this.range) { this.onSlideEnd.emit({ originalEvent: event, values: this.values }); } else { this.onSlideEnd.emit({ originalEvent: event, value: this.value }); } }); } } unbindDragListeners() { if (this.dragListener) { this.dragListener(); } if (this.mouseupListener) { this.mouseupListener(); } } setValueFromHandle(event: Event, handleValue: any) { const newValue = this.getValueFromHandle(handleValue); if (this.range) { if (this.step) { this.handleStepChange(newValue, this.values[this.handleIndex]); } else { this.handleValues[this.handleIndex] = handleValue; this.updateValue(newValue, event); } } else { if (this.step) { this.handleStepChange(newValue, this.value); } else { this.handleValue = handleValue; this.updateValue(newValue, event); } } } handleStepChange(newValue: number, oldValue: number) { const diff = (newValue - oldValue); let val = oldValue; if (diff < 0) { val = oldValue + Math.ceil((newValue - oldValue) / this.step) * this.step; } else if (diff > 0) { val = oldValue + Math.floor((newValue - oldValue) / this.step) * this.step; } this.updateValue(val); this.updateHandleValue(); } setDisabledState(val: boolean): void { this.disabled = val; } get rangeStartLeft() { return this.isVertical() ? 'auto' : this.handleValues[0] + '%'; } get rangeStartBottom() { return this.isVertical() ? this.handleValues[0] + '%' : 'auto'; } get rangeEndLeft() { return this.isVertical() ? 'auto' : this.handleValues[1] + '%'; } get rangeEndBottom() { return this.isVertical() ? this.handleValues[1] + '%' : 'auto'; } isVertical(): boolean { return this.orientation === 'vertical'; } updateDomData(): void { const rect = this.el.nativeElement.children[0].getBoundingClientRect(); this.initX = rect.left + this.domHandler.getWindowScrollLeft(); this.initY = rect.top + this.domHandler.getWindowScrollTop(); this.barWidth = this.el.nativeElement.children[0].offsetWidth; this.barHeight = this.el.nativeElement.children[0].offsetHeight; } calculateHandleValue(event: any): number { if (this.orientation === 'horizontal') { return ((event.pageX - this.initX) * 100) / (this.barWidth); } else { return (((this.initY + this.barHeight) - event.pageY) * 100) / (this.barHeight); } } updateHandleValue(): void { if (this.range) { this.handleValues[0] = (this.values[0] < this.min ? 0 : this.values[0] - this.min) * 100 / (this.max - this.min); this.handleValues[1] = (this.values[1] > this.max ? 100 : this.values[1] - this.min) * 100 / (this.max - this.min); } else { if (this.value < this.min) { this.handleValue = 0; } else if (this.value > this.max) { this.handleValue = 100; } else { this.handleValue = (this.value - this.min) * 100 / (this.max - this.min); } } } updateValue(val: number, valueEvent?: Event): void { if (this.range) { let value = val; if (this.handleIndex === 0) { if (value < this.min) { value = this.min; this.handleValues[0] = 0; } else if (value > this.values[1]) { value = this.values[1]; this.handleValues[0] = this.handleValues[1]; } } else { if (value > this.max) { value = this.max; this.handleValues[1] = 100; } else if (value < this.values[0]) { value = this.values[0]; this.handleValues[1] = this.handleValues[0]; } } this.values[this.handleIndex] = Math.floor(value); this.onModelChange(this.values); this.onChange.emit({ event: valueEvent, values: this.values }); } else { this.updateValueNoRange(val, valueEvent); } } updateValueNoRange(val: number, valueEvent?: Event) { if (val < this.min) { val = this.min; this.handleValue = 0; } else if (val > this.max) { val = this.max; this.handleValue = 100; } this.value = Math.floor(val); this.onModelChange(this.value); this.onChange.emit({ event: valueEvent, value: this.value }); } getValueFromHandle(handleValue: number): number { return (this.max - this.min) * (handleValue / 100) + this.min; } ngOnDestroy() { this.unbindDragListeners(); } onKeyLeftDown(event: Event) { if (!this.step) { this.step = 10; this.step = this.max / this.step; } else if (!this.max && !this.step && !this.min) { this.step = this.max / this.step; } this.handleValue = this.handleValue - this.step; this.setValueFromHandle(event, this.handleValue); } onKeyRightUp(event: Event) { if (!this.step) { this.step = 10; this.step = this.max / this.step; } else if (!this.max && !this.step && !this.min) { this.step = this.max / this.step; } this.handleValue = this.handleValue + this.step; this.setValueFromHandle(event, this.handleValue); } onKeyHome(event: Event) { if (!this.step) { this.step = 10; this.step = this.max / this.step; } else if (!this.max && !this.step && !this.min) { this.step = this.max / this.step; } this.handleValue = this.min; this.setValueFromHandle(event, this.handleValue); } onKeyEnd(event: Event) { if (!this.step) { this.step = 10; this.step = this.max / this.step; } else if (!this.max && !this.step && !this.min) { this.step = this.max / this.step; } this.handleValue = this.max; this.setValueFromHandle(event, this.handleValue); } onKeyPageUp(event: Event) { this.handleValue = this.handleValue + 10; this.setValueFromHandle(event, this.handleValue); } onKeyPageDown(event: Event) { this.handleValue = this.handleValue - 10; this.setValueFromHandle(event, this.handleValue); } onFocus(event: Event) { this.sliderFocus = true; } onBlur(event: Event) { this.sliderFocus = false; } }
the_stack
import { Balance } from './balance'; import { Hlr, HLRParameter } from './hlr'; import { Message, MessageParameters, FilterParameters } from './messages'; import { VoiceMessage, VoiceParameters, VoiceParametersWithRecipients } from './voice_messages'; import { msisdn } from './general'; import { Verify, VerifyParameter, VerifyMessage } from './verify'; import { Lookup } from './lookup'; import { Contact, ContactParameter } from './contact'; import { GroupParameter } from './group'; import { Recording } from './recordings'; import { Call, CallParameter, CallFlowParameter } from './calls'; import { CallFlow } from './callflows'; import { ConversationParameter, SendResponse, UpdateConversationParameters, ReplyConversationParameters, Webhooks, StartConversationParameter, StartConversationResponse } from './conversations'; import { Webhooks as VoiceWebhooks } from './voice'; import { MmsObject, MmsParameter } from './mms'; import { Features } from './feature'; import { TranscriptionData } from './transcriptions'; type CallbackFn<T = unknown> = (err: Error | null, res: T | null) => void; export interface MessageBird { balance: { /** Get account balance */ read(callback: CallbackFn<Balance>): void; }; hlr: { read(id: string, callback: CallbackFn<Hlr>): void; create(msisdn: msisdn, callback?: CallbackFn<Hlr>): void; create(msisdn: msisdn, ref: string, callback: CallbackFn<Hlr>): void; }; messages: { read(id: string, callback: CallbackFn<Message>): void; create(params: MessageParameters, callback: CallbackFn<Message>): void; list(filter: FilterParameters, callback: CallbackFn<Message[]>): void; delete(id: string, callback: CallbackFn): void; }; callflows: { read(id: string, callback: CallbackFn<CallFlow>): void; list(page: number, perPage: number, callback: CallbackFn<CallFlow[]>): void; list(callback: CallbackFn<CallFlow[]>): void; delete(id: string, callback: CallbackFn): void; update(id: string, params: CallFlowParameter, callback: CallbackFn): void; create(params: CallFlowParameter, callback: CallbackFn<CallFlow>): void; }; voice_messages: { list(limit: number, offset: number, callback: CallbackFn<VoiceMessage[]>): void; read(id: string, callback: CallbackFn<VoiceMessage>): void; create( recipients: msisdn[], params: VoiceParameters, callback: CallbackFn<VoiceMessage> ): void; create( params: VoiceParametersWithRecipients, callback: CallbackFn<VoiceMessage> ): void; delete(id: string, callback: CallbackFn): void; }; verify: { read(id: string, callback: CallbackFn<Verify>): void; create( recipient: string | [string], params: VerifyParameter, callback: CallbackFn<Verify> ): void; create(recipient: string | [string], callback: CallbackFn<Verify>): void; createWithEmail(from: string, to: string | [string], params: VerifyParameter, callback: CallbackFn<Verify>): void; createWithEmail(from: string, to: string | [string], callback: CallbackFn<Verify>): void; delete(id: string, callback: CallbackFn<void>): void; verify( /** A unique random ID which is created on the MessageBird platform and is returned upon creation of the object. */ id: string, /** An unique token which was sent to the recipient upon creation of the object. */ token: string, callback: CallbackFn<Verify> ): void; getVerifyEmailMessage(id: string, callback: CallbackFn<VerifyMessage>): void; }; lookup: { read( phoneNumber: msisdn, countryCode: string, callback: CallbackFn<Lookup> ): void; read(phoneNumber: msisdn, callback: CallbackFn<Lookup>): void; hlr: { read( phoneNumber: msisdn, countryCode: string, callback: CallbackFn<Hlr> ): void; read(phoneNumber: msisdn, callback: CallbackFn<Hlr>): void; create( phoneNumber: msisdn, params: HLRParameter, callback: CallbackFn<Hlr> ): void; create(phoneNumber: msisdn, callback: CallbackFn<Hlr>): void; }; }; contacts: { create( phoneNumber: string, params: ContactParameter, callback: CallbackFn<Contact> ): void; create(phoneNumber: string, callback: CallbackFn<Contact>): void; delete(id: string, callback: CallbackFn<void>): void; list(limit: number, offset: number, callback: CallbackFn<Contact[]>): void; list(callback: CallbackFn<Contact[]>): void; read(id: string, callback: CallbackFn<Contact>): void; update( id: string, params: ContactParameter, callback: CallbackFn<Contact> ): void; listGroups( contactId: string, limit: number, offset: number, callback: CallbackFn ): void; listGroups(contactId: string, callback: CallbackFn): void; listMessages(contactId: string, callback: CallbackFn): void; listMessages( contactId: string, limit: number, offset: number, callback: CallbackFn ): void; }; groups: { create(name: string, params: GroupParameter, callback: CallbackFn): void; create(name: string, callback: CallbackFn): void; delete(id: string, callback: CallbackFn): void; list(limit: number, offset: number, callback: CallbackFn): void; list(callback: CallbackFn): void; read(id: string, callback: CallbackFn): void; update(id: string, params: GroupParameter, callback: CallbackFn): void; addContacts( groupId: string, contactIds: string[], callback: CallbackFn ): void; listContacts( groupId: string, limit: number, offset: number, callback: CallbackFn ): void; listContacts(groupId: string, callback: CallbackFn): void; removeContact( groupId: string, contactId: string, callback: CallbackFn ): void; }; conversations: { /** * Sends a new message to a channel-specific user identifier (e.g. phone * number). If an active conversation already exists for the recipient, * this conversation will be resumed. If an active conversation does not * exist, a new one will be created. */ send( params: ConversationParameter, callback: CallbackFn<SendResponse> ): void; /** * Starts a new conversation from a channel-specific user identifier, * such as a phone number, and sends a first message. If an active * conversation already exists for the recipient, this conversation will * be resumed. */ start(params: StartConversationParameter, callback: CallbackFn<StartConversationResponse>): void; /** * Retrieves all conversations for this account. By default, * conversations are sorted by their lastReceivedDatetime field so that * conversations with new messages appear first. */ list(limit: number, offset: number, callback: CallbackFn): void; /** * Retrieves a single conversation. */ read(id: string, callback: CallbackFn): void; /** * Update Conversation Status. */ update( id: string, params: UpdateConversationParameters, callback: CallbackFn ): void; /** * Adds a new message to an existing conversation and sends it to the * contact that you're in conversation with. */ reply( id: string, params: ReplyConversationParameters, callback: CallbackFn ): void; /** * Lists the messages for a contact. */ listMessages( contactId: string, limit: number, offset: number, callback: CallbackFn ): void; /** * View a message */ readMessage(id: string, callback: CallbackFn): void; webhooks: { /** * Creates a new webhook. */ create(params: Webhooks.CreateParameters, callback: CallbackFn): void; /** * Retrieves an existing webhook by id. */ read(id: string, callback: CallbackFn): void; /** * Updates a webhook. */ update( id: string, params: Webhooks.UpdateParameters, callback: CallbackFn ): void; /** * Retrieves a list of webhooks. */ list(limit: number, offset: number, callback: CallbackFn): void; /** * Deletes webhook */ delete(id: string, callback: CallbackFn): void; }; /** * MessageBird's MMS Messaging API enables you to send and receive MMS messages to and from a selected group of countries. Currently you can only send MMS within the US and Canada. * * Messages are identified by a unique ID. And with this ID you can always check the status of the MMS message through the provided endpoint. */ mms: { /** * Retrieves the information of an existing sent MMS message. You only need to supply the unique message id that was returned upon creation. */ read(id: string, callback: CallbackFn<MmsObject>): void; /** * * Creates a new MMS message object. MessageBird returns the created message object with each request. Per request, a max of 50 recipients can be entered. */ create(params: MmsParameter, callback: CallbackFn<MmsObject>): void; list(limit: number, offset: number, callback: CallbackFn): void; delete(id: string, callback: CallbackFn): void; }; }; /** * A recording describes a voice recording of a leg. You can initiate a recording of a leg by having a step in your callflow with the record action set. */ calls: { /** * This request initiates an outbound call. */ create(params: CallParameter, callback: CallbackFn<Call>): void; /** * This request retrieves a listing of all calls. */ list(callback: CallbackFn<Call[]>): void; /** * This request retrieves a call resource. The single parameter is the unique ID that was returned upon creation. */ read(callId: string, callback: CallbackFn<Call>): void; /** * This request will hang up all the legs of the call. */ delete(callId: string, callback: CallbackFn): void; }; /** * A recording describes a voice recording of a leg. You can initiate a recording of a leg by having a step in your callflow with the record action set. */ recordings: { /** * Lists all recordings */ list(callId: string, legId: string, limit: number, offset: number, callback: CallbackFn<Recording[]>): void; /** * This request retrieves a recording resource. The parameters are the unique ID of the recording, the leg and the call with which the recording is associated. */ read(callId: string, legId: string, recordingId: string, callback: CallbackFn<Recording>): void; /** * Deletes a recording */ delete(callId: string, legId: string, recordingId: string, callback: CallbackFn): void; /** * Downloads a recording */ download(callId: string, legId: string, recordingId: string, callback: CallbackFn): void; }; /** * A transcription is a textual representation of a recording as text. */ transcriptions: { /** * Creates a new transcription */ create(callId: string, legId: string, recordingId: string, language: string, callback: CallbackFn<TranscriptionData>): void; /** * Lists all transcriptions */ list(callId: string, legId: string, recordingId: string, callback: CallbackFn<TranscriptionData>): void; /** * Retrieves a transcription */ read(callId: string, legId: string, recordingId: string, transcriptionId: string, callback: CallbackFn<TranscriptionData>): void; /** * Downloads a transcription */ download(callId: string, legId: string, recordingId: string, transcriptionId: string, callback: CallbackFn<boolean|string>): void; }; voice: { webhooks: { /** * Creates a new webhook. */ create(params: VoiceWebhooks.CreateParameters, callback: CallbackFn): void; /** * Retrieves an existing webhook by id. */ read(id: string, callback: CallbackFn): void; /** * Updates a webhook. */ update( id: string, params: VoiceWebhooks.UpdateParameters, callback: CallbackFn ): void; /** * Retrieves a list of webhooks. */ list(limit: number, offset: number, callback: CallbackFn): void; /** * Deletes webhook */ delete(id: string, callback: CallbackFn): void; } }; } export * from './balance'; export * from './callflows'; export * from './calls'; export * from './contact'; export * from './conversations'; export * from './feature'; export * from './hlr'; export * from './lookup'; export * from './messages'; export * from './mms'; export * from './recordings'; export * from './transcriptions'; export default function messagebird(accessKey: string, timeout?: number, features?: ReadonlyArray<Features>): MessageBird;
the_stack
import { each, get, isEmpty } from 'lodash'; import { BrickAction, ChildNodesType, PageConfigType, ComponentSchemaType, PropsNodeType, SelectedInfoType, StateType, BrickDesignStateType, ConfigType, STATE_PROPS, } from '../types'; import { ReducerType } from '../reducers'; import { BrickdStoreType } from '../store'; import { legoState } from '../reducers/handlePageBrickdState'; /** * 根节点key */ export const ROOT = '0'; /** * 复制组件 * @param pageConfig * @param selectedKey * @param newKey */ export const copyConfig = ( pageConfig: PageConfigType, selectedKey: string, newKey: number, ) => { const vDom = pageConfig[selectedKey]; const childNodes = vDom.childNodes; if (!childNodes) { pageConfig[newKey] = vDom; } else { const newVDom = { ...vDom }; pageConfig[newKey] = newVDom; if (Array.isArray(childNodes)) { newVDom.childNodes = copyChildNodes(pageConfig, childNodes); } else { const newChildNodes: PropsNodeType = {}; each(childNodes, (nodes, propName) => { newChildNodes[propName] = copyChildNodes(pageConfig, nodes!); }); newVDom.childNodes = newChildNodes; } } }; function copyChildNodes(pageConfig: PageConfigType, childNodes: string[]) { const newChildKeys: string[] = []; for (const oldKey of childNodes) { const newChildKey = getNewKey(pageConfig); newChildKeys.push(`${newChildKey}`); copyConfig(pageConfig, oldKey, newChildKey); } return newChildKeys; } export function deleteChildNodes( pageConfig: PageConfigType, childNodes: ChildNodesType, propName?: string, ) { if (Array.isArray(childNodes)) { deleteArrChild(pageConfig, childNodes); } else { each(childNodes, (propChildNodes, key) => { if (propName) { if (key === propName) { deleteArrChild(pageConfig, propChildNodes!); } } else { deleteArrChild(pageConfig, propChildNodes!); } }); } } function deleteArrChild(pageConfig: PageConfigType, childNodes: string[]) { for (const key of childNodes) { const childNodesInfo = pageConfig[key].childNodes; if (childNodesInfo) { deleteChildNodes(pageConfig, childNodesInfo); } delete pageConfig[key]; } } /** * 获取路径 * */ export function getLocation(key: string, propName?: string): string[] { const basePath = [key, 'childNodes']; return propName ? [...basePath, propName] : basePath; } /** * 生成新的Key * @param dragVDOMAndPropsConfig * @param rootKey */ export const generateNewKey = ( vDOMCollection: PageConfigType, rootKey: number, ) => { const keyMap: { [key: string]: string } = {}; const newVDOMCollection: PageConfigType = {}; let newKey = rootKey; each(vDOMCollection, (vDom, key) => { ++newKey; if (key === ROOT) { newKey = rootKey; } keyMap[key] = `${newKey}`; newVDOMCollection[newKey] = vDom; }); each(newVDOMCollection, (vDom) => { const childNodes = vDom.childNodes; if (!childNodes) return; if (Array.isArray(childNodes)) { vDom.childNodes = childNodes.map((key) => keyMap[key]); } else { const newChildNodes: PropsNodeType = {}; each(childNodes, (nodes, propName) => { newChildNodes[propName] = nodes!.map((key) => keyMap[key]); }); vDom.childNodes = newChildNodes; } }); return newVDOMCollection; }; /** * 获取字段在props中的位置 * @param fieldConfigLocation * @returns {string} */ export const getFieldInPropsLocation = (fieldConfigLocation: string) => { return fieldConfigLocation .split('.') .filter((location) => location !== 'childPropsConfig'); }; /** * 处理子节点非空 * @param selectedInfo * @param pageConfig * @param payload */ export const handleRequiredHasChild = ( selectedInfo: SelectedInfoType, pageConfig: PageConfigType, ) => { const { selectedKey, propName: selectedPropName } = selectedInfo; const { componentName, childNodes } = pageConfig[selectedKey]; const { nodePropsConfig, isRequired } = getComponentConfig(componentName); return ( (get(nodePropsConfig, [selectedPropName, 'isRequired']) && !get(childNodes, selectedPropName)) || (isRequired && !childNodes) ); }; export function shallowEqual(objA: any, objB: any) { for (const k of Object.keys(objA)) { if (objA[k] !== objB[k]) return false; } return true; } export function deleteChildNodesKey( childNodes: ChildNodesType, deleteKey: string, parentPropName?: string, ) { if (Array.isArray(childNodes)) { const resultChildNodes = childNodes.filter( (nodeKey: string) => nodeKey !== deleteKey, ); return restObject(resultChildNodes); } else { const resultChildNodes = childNodes[parentPropName!]!.filter( (nodeKey: string) => nodeKey !== deleteKey, ); if (resultChildNodes.length === 0) { delete childNodes[parentPropName!]; } else { childNodes[parentPropName!] = resultChildNodes; } return restObject(childNodes); } } export function getComponentConfig(componentName?: string): ComponentSchemaType { if(!componentName) return; const componentSchemasMap = get(getBrickdConfig(), ['componentSchemasMap']); if (!componentSchemasMap) { error('Component configuration information set not found!! !'); } const componentSchema = componentSchemasMap[componentName]; if (componentName && !componentSchema) { warn(`${componentName} configuration information not found!! !`); } return componentSchema; } export function isContainer(componentName: string) { return !get(getBrickdConfig(), [ 'componentSchemasMap', componentName, 'isNonContainer', ]); } export function error(msg: string) { console.error(msg); throw new Error(msg); } export function warn(msg: string) { const warn = getWarn(); if (warn) { warn(msg); } else { console.warn(msg); } return true; } export function getNewKey(pageConfig: PageConfigType) { const lastKey = Object.keys(pageConfig).pop(); return Number(lastKey) + 1; } export function restObject(obj: any, field?: string) { if (field) { delete obj[field]; } if (Object.keys(obj).length === 0) return undefined; return obj; } export function handleRules( pageConfig: PageConfigType, dragKey: string, selectedKey: string, propName?: string, isForbid?: boolean, ) { /** * 获取当前拖拽组件的父组件约束,以及属性节点配置信息 */ const dragComponentName = pageConfig[dragKey!].componentName; const dropComponentName = pageConfig[selectedKey!].componentName; const { fatherNodesRule } = getComponentConfig(dragComponentName); const { nodePropsConfig, childNodesRule } = getComponentConfig( dropComponentName, ); /** * 子组件约束限制,减少不必要的组件错误嵌套 */ const childRules = propName ? get(nodePropsConfig, [propName, 'childNodesRule']) : childNodesRule; if (childRules && !childRules.includes(dragComponentName)) { !isForbid && warn( `${ propName || dropComponentName }:only allow drag and drop to add${childRules.toString()}`, ); return true; } /** * 父组件约束限制,减少不必要的组件错误嵌套 */ if ( fatherNodesRule && !fatherNodesRule.includes( propName ? `${dropComponentName}.${propName}` : `${dropComponentName}`, ) ) { !isForbid && warn( `${dragComponentName}:Only allowed as a child node or attribute node of${fatherNodesRule.toString()}`, ); return true; } return false; } export function combineReducers( brickReducer: ReducerType, customReducer?: ReducerType, ): ReducerType { return ( state: BrickDesignStateType | undefined, action: BrickAction, ): BrickDesignStateType => { const newState = brickReducer(state, action); if (customReducer) { return customReducer(newState, action); } else { return newState; } }; } export function createTemplateConfigs( templateConfigs: PageConfigType, pageConfig: PageConfigType, childNodes: ChildNodesType, ) { if (Array.isArray(childNodes)) { for (const key of childNodes) { templateConfigs[key] = pageConfig[key]; const { childNodes } = templateConfigs[key]; if (childNodes) createTemplateConfigs(templateConfigs, pageConfig, childNodes); } } else { each(childNodes, (childKeys) => { if (!isEmpty(childKeys)) createTemplateConfigs(templateConfigs, pageConfig, childKeys); }); } } export function createTemplate(state: StateType) { const { selectedInfo, pageConfig } = state; const { selectedKey } = selectedInfo; const templateConfigs = { [ROOT]: pageConfig[selectedKey] }; const { childNodes } = pageConfig[selectedKey]; if (!isEmpty(childNodes)) { createTemplateConfigs(templateConfigs, pageConfig, childNodes); } return templateConfigs; } export function createActions(action: BrickAction) { return getStore().dispatch(action); } let CURRENT_PAGE_NAME: null | string = null; export const setPageName = (pageName: null | string) => (CURRENT_PAGE_NAME = pageName); export const getPageName = () => CURRENT_PAGE_NAME; let STORE: BrickdStoreType<BrickDesignStateType, BrickAction> | null = null; export const setStore = ( store: BrickdStoreType<BrickDesignStateType, BrickAction> | null, ) => (STORE = store); export const getStore = () => STORE; let BRICKD_CONFIG: ConfigType | null = null; export const getBrickdConfig = () => BRICKD_CONFIG; export const setBrickdConfig = (config: ConfigType | null) => (BRICKD_CONFIG = config); export type WarnType = (msg: string) => void; let WARN: WarnType | null = null; export const getWarn = () => WARN; export const setWarn = (warn: WarnType | null) => (WARN = warn); export function getPageState() { const pageName = getPageName(); return get(getStore().getState(), pageName, legoState); } export function getSelector(selector: STATE_PROPS[]) { const states = getPageState(); const resultState = {}; each(selector, (stateName) => (resultState[stateName] = states[stateName])); return resultState; } export const cleanStateCache = () => { setBrickdConfig(null); setWarn(null); setStore(null); setPageName(null); };
the_stack
import { vec2, vec3, mat4, vec4, quat } from "../math"; export class Mesh { attributes: Accessor[]; // AKA Vertexes indices: Accessor; // AKA Triangles // Render mode mode: number; data = {}; // Raw data constructor(attributes: Accessor[], indices?: Accessor, mode = WebGL2RenderingContext.TRIANGLES) { this.attributes = attributes; if(indices) { this.indices = indices; // Ensure current buffer type is exist, considering the target value is not required at glTF this.indices.bufferView.target = WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER; } this.mode = mode; // reference mesh data for(let attr of attributes) { const name = attr.attribute; this.data[name] = attr.data; } } static bindAccessorsVBO(target: Mesh, gl: WebGL2RenderingContext, locationList) { for(let acc of target.attributes) { // Ignore indeces let loc = locationList[acc.attribute]; if(acc.attribute && loc!=undefined) { bufferView.bindBuffer(acc.bufferView, gl); gl.enableVertexAttribArray(loc); let offset = acc.byteOffset; gl.vertexAttribPointer(loc, acc.size, acc.componentType, acc.normalized, acc.bufferView.byteStride, offset); } else { // console.warn(`Attribute '${acc.attribute}' doesn't support in this material!`); } } } static drawElements(target: Mesh, gl: WebGL2RenderingContext) { let acc = target.indices; gl.drawElements(target.mode, acc.count, acc.componentType, acc.byteOffset); } static drawArrays(target: Mesh, gl: WebGL2RenderingContext) { gl.drawArrays(target.mode, 0, target.attributes[0].count); } static drawcall(target: Mesh, gl: WebGL2RenderingContext) { if(target.indices) { bufferView.bindBuffer(target.indices.bufferView, gl); this.drawElements(target, gl); } else { this.drawArrays(target, gl); } } static preComputeNormal(mesh: Mesh) { let {indices} = mesh // Collect required data chunks let atts = {}; for(let acc of mesh.attributes) { if(acc.attribute != 'POSITION') continue; let data = Accessor.newFloat32Array(acc); let chunks = Accessor.getSubChunks(acc, data); atts['_'+acc.attribute] = data; atts[acc.attribute] = chunks; // normal data is vec3, same as position if(acc.attribute == 'POSITION') { // malloc space for normal buffer atts['_NORMAL'] = new Float32Array(data.length); atts['NORMAL'] = Accessor.getSubChunks(acc, atts['_NORMAL']); } } if(indices) { // element atts['i'] = Accessor.newTypedArray(indices); } else { // array atts['i'] = atts['POSITION'].map((e,i) => i); } let pos: Float32Array[] = atts['POSITION']; let ind = atts['i']; let normal = atts['NORMAL']; // Temp let edge1 = vec3.create(); let edge2 = vec3.create(); for(let i = 0, l = ind.length; i < l; i+=3) { let i0 = ind[i]; let i1 = ind[i+1]; let i2 = ind[i+2]; let p1 = pos[i0]; let p2 = pos[i1]; let p3 = pos[i2]; vec3.sub(edge1, p2, p1); vec3.sub(edge2, p3, p1); let nor = normal[i0]; // let f = 1.0 / (duv1[0] * duv2[1] - duv2[0] * duv1[1]); // nor[0] = f * (duv2[1] * edge1[0] - duv1[1] * edge2[0]); // nor[1] = f * (duv2[1] * edge1[1] - duv1[1] * edge2[1]); // nor[2] = f * (duv2[1] * edge1[2] - duv1[1] * edge2[2]); vec3.cross(nor, edge1, edge2); vec3.normalize(nor, nor); // Sharing the same normal vector vec3.copy(normal[i1], nor); vec3.copy(normal[i2], nor); } let normalBuffer = new bufferView(); normalBuffer.dataView = atts['_NORMAL']; mesh.attributes.push(new Accessor( { bufferView: normalBuffer, byteOffset: 0, componentType: 5126, count: normal.length, type: 'VEC3', }, 'NORMAL' )) } static preComputeTangent(mesh: Mesh) { // http://www.opengl-tutorial.org/cn/intermediate-tutorials/tutorial-13-normal-mapping/ // https://learnopengl-cn.readthedocs.io/zh/latest/05%20Advanced%20Lighting/04%20Normal%20Mapping/ let indices = mesh.indices; let atts = {}; for(let acc of mesh.attributes) { if(acc.attribute != 'POSITION' && acc.attribute != 'TEXCOORD_0') continue; let data = Accessor.newFloat32Array(acc); let chunks = Accessor.getSubChunks(acc, data); atts['_'+acc.attribute] = data; atts[acc.attribute] = chunks; // tagent data is vec3, same as position if(acc.attribute == 'POSITION') { // malloc space for tangent buffer atts['_TANGENT'] = new Float32Array(data.length); atts['TANGENT'] = Accessor.getSubChunks(acc, atts['_TANGENT']); } } if(indices) { // element atts['i'] = Accessor.newTypedArray(indices); } else { // array atts['i'] = atts['POSITION'].map((e,i) => i); } let pos: Float32Array[] = atts['POSITION']; let uv = atts['TEXCOORD_0']; let ind = atts['i']; let tangent = atts['TANGENT']; // Temp let edge1 = vec3.create(); let edge2 = vec3.create(); let duv1 = vec2.create(); let duv2 = vec2.create(); for(let i = 0, l = ind.length; i < l; i+=3) { let i0 = ind[i]; let i1 = ind[i+1]; let i2 = ind[i+2]; let p1 = pos[i0]; let p2 = pos[i1]; let p3 = pos[i2]; let uv1 = uv[i0]; let uv2 = uv[i1]; let uv3 = uv[i2]; vec3.sub(edge1, p2, p1); vec3.sub(edge2, p3, p1); vec3.sub(duv1, uv2, uv1); vec3.sub(duv2, uv3, uv1); let tan = tangent[i0]; let f = 1.0 / (duv1[0] * duv2[1] - duv2[0] * duv1[1]); tan[0] = f * (duv2[1] * edge1[0] - duv1[1] * edge2[0]); tan[1] = f * (duv2[1] * edge1[1] - duv1[1] * edge2[1]); tan[2] = f * (duv2[1] * edge1[2] - duv1[1] * edge2[2]); vec3.normalize(tan, tan); vec3.copy(tangent[i1], tan); vec3.copy(tangent[i2], tan); } let tangentBuffer = new bufferView(); tangentBuffer.dataView = atts['_TANGENT']; mesh.attributes.push(new Accessor( { bufferView: tangentBuffer, byteOffset: 0, componentType: 5126, count: tangent.length, type: 'VEC3', }, 'TANGENT' )) // return atts; } } export class Accessor { static types = { "SCALAR": 1, 'VEC1': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4, "MAT2": 4, "MAT3": 9, "MAT4": 16, }; attribute: string; bufferView: bufferView; byteOffset: number; componentType: number; normalized: boolean; count: number; max: number[]; min: number[]; size: number; private _data: any; constructor({bufferView, byteOffset = 0, componentType, normalized = false, count, type, max = [], min = []}, name = '') { this.attribute = name; this.bufferView = bufferView; this.byteOffset = byteOffset; this.componentType = componentType; this.normalized = normalized; this.count = count; this.max = max; this.min = min; this.size = Accessor.types[type]; } get data() { if(!this._data) this._data = Accessor.getData(this); return this._data; } static newFloat32Array(acc: Accessor) { return new Float32Array(acc.bufferView.rawBuffer, acc.byteOffset + acc.bufferView.byteOffset, acc.size * acc.count); } static getSubChunks(acc, data) { let blocks = []; for (let i = 0; i < acc.count; i++) { let offset = i * acc.size; blocks.push(data.subarray(offset, offset + acc.size)); } return blocks; } static getFloat32Blocks(acc: Accessor) { return this.getSubChunks(acc, Accessor.newTypedArray(acc)); } static getUint16Blocks(acc: Accessor) { return this.getSubChunks(acc, Accessor.newTypedArray(acc)); } static newTypedArray(acc: Accessor) { switch(acc.componentType) { case 5120: return new Int8Array(acc.bufferView.rawBuffer, acc.byteOffset + acc.bufferView.byteOffset, acc.size * acc.count); case 5121: return new Uint8Array(acc.bufferView.rawBuffer, acc.byteOffset + acc.bufferView.byteOffset, acc.size * acc.count); case 5122: return new Int16Array(acc.bufferView.rawBuffer, acc.byteOffset + acc.bufferView.byteOffset, acc.size * acc.count); case 5123: return new Uint16Array(acc.bufferView.rawBuffer, acc.byteOffset + acc.bufferView.byteOffset, acc.size * acc.count); case 5125: return new Uint32Array(acc.bufferView.rawBuffer, acc.byteOffset + acc.bufferView.byteOffset, acc.size * acc.count); case 5126: return new Float32Array(acc.bufferView.rawBuffer, acc.byteOffset + acc.bufferView.byteOffset, acc.size * acc.count); } } static getData(acc: Accessor) { if(acc.size > 1) { return this.getFloat32Blocks(acc); } return this.newTypedArray(acc); } } export class bufferView { rawBuffer: ArrayBuffer; dataView: DataView; byteLength: number; byteOffset: number; byteStride: number; target: number; buffer: WebGLBuffer = null; constructor(rawData?: ArrayBuffer, {byteOffset = 0, byteLength = 0, byteStride = 0, target = 34962} = {}) { this.rawBuffer = rawData; this.byteOffset = byteOffset; this.byteLength = byteLength; this.byteStride = byteStride; if(rawData) this.dataView = new DataView(rawData, this.byteOffset, this.byteLength); this.target = target; } static updateBuffer(bView: bufferView, gl: WebGL2RenderingContext, usage = WebGL2RenderingContext.STATIC_DRAW) { if(bView.buffer) { gl.deleteBuffer(bView.buffer); } bView.buffer = gl.createBuffer(); gl.bindBuffer(bView.target, bView.buffer); gl.bufferData(bView.target, bView.dataView, usage); } static bindBuffer(bView: bufferView, gl: WebGL2RenderingContext) { if(!bView.buffer) { this.updateBuffer(bView, gl); } gl.bindBuffer(bView.target, bView.buffer); } }
the_stack
declare module 'stripe' { namespace Stripe { namespace Identity { /** * The VerificationSession object. */ interface VerificationSession { /** * Unique identifier for the object. */ id: string; /** * String representing the object's type. Objects of the same type share the same value. */ object: 'identity.verification_session'; /** * The short-lived client secret used by Stripe.js to [show a verification modal](https://stripe.com/docs/js/identity/modal) inside your app. This client secret expires after 24 hours and can only be used once. Don't store it, log it, embed it in a URL, or expose it to anyone other than the user. Make sure that you have TLS enabled on any page that includes the client secret. Refer to our docs on [passing the client secret to the frontend](https://stripe.com/docs/identity/verification-sessions#client-secret) to learn more. */ client_secret: string | null; /** * Time at which the object was created. Measured in seconds since the Unix epoch. */ created: number; /** * If present, this property tells you the last error encountered when processing the verification. */ last_error: VerificationSession.LastError | null; /** * ID of the most recent VerificationReport. [Learn more about accessing detailed verification results.](https://stripe.com/docs/identity/verification-sessions#results) */ last_verification_report: | string | Stripe.Identity.VerificationReport | null; /** * Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. */ livemode: boolean; /** * Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. */ metadata: Stripe.Metadata; options: VerificationSession.Options; /** * Redaction status of this VerificationSession. If the VerificationSession is not redacted, this field will be null. */ redaction: VerificationSession.Redaction | null; /** * Status of this VerificationSession. [Learn more about the lifecycle of sessions](https://stripe.com/docs/identity/how-sessions-work). */ status: VerificationSession.Status; /** * The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. */ type: VerificationSession.Type; /** * The short-lived URL that you use to redirect a user to Stripe to submit their identity information. This URL expires after 48 hours and can only be used once. Don't store it, log it, send it in emails or expose it to anyone other than the user. Refer to our docs on [verifying identity documents](https://stripe.com/docs/identity/verify-identity-documents?platform=web&type=redirect) to learn how to redirect users to Stripe. */ url: string | null; /** * The user's verified data. */ verified_outputs: VerificationSession.VerifiedOutputs | null; } namespace VerificationSession { interface LastError { /** * A short machine-readable string giving the reason for the verification or user-session failure. */ code: LastError.Code | null; /** * A message that explains the reason for verification or user-session failure. */ reason: string | null; } namespace LastError { type Code = | 'abandoned' | 'consent_declined' | 'country_not_supported' | 'device_not_supported' | 'document_expired' | 'document_type_not_supported' | 'document_unverified_other' | 'id_number_insufficient_document_data' | 'id_number_mismatch' | 'id_number_unverified_other' | 'selfie_document_missing_photo' | 'selfie_face_mismatch' | 'selfie_manipulated' | 'selfie_unverified_other' | 'under_supported_age'; } interface Options { document?: Options.Document; id_number?: Options.IdNumber; } namespace Options { interface Document { /** * Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. */ allowed_types?: Array<Document.AllowedType>; /** * Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. */ require_id_number?: boolean; /** * Disable image uploads, identity document images have to be captured using the device's camera. */ require_live_capture?: boolean; /** * Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). */ require_matching_selfie?: boolean; } namespace Document { type AllowedType = 'driving_license' | 'id_card' | 'passport'; } interface IdNumber {} } interface Redaction { /** * Indicates whether this object and its related objects have been redacted or not. */ status: Redaction.Status; } namespace Redaction { type Status = 'processing' | 'redacted'; } type Status = 'canceled' | 'processing' | 'requires_input' | 'verified'; type Type = 'document' | 'id_number'; interface VerifiedOutputs { /** * The user's verified address. */ address: Stripe.Address | null; /** * The user's verified date of birth. */ dob: VerifiedOutputs.Dob | null; /** * The user's verified first name. */ first_name: string | null; /** * The user's verified id number. */ id_number: string | null; /** * The user's verified id number type. */ id_number_type: VerifiedOutputs.IdNumberType | null; /** * The user's verified last name. */ last_name: string | null; } namespace VerifiedOutputs { interface Dob { /** * Numerical day between 1 and 31. */ day: number | null; /** * Numerical month between 1 and 12. */ month: number | null; /** * The four-digit year. */ year: number | null; } type IdNumberType = 'br_cpf' | 'sg_nric' | 'us_ssn'; } } interface VerificationSessionCreateParams { /** * The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. */ type: VerificationSessionCreateParams.Type; /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; /** * Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. */ metadata?: Stripe.MetadataParam; /** * A set of options for the session's verification checks. */ options?: VerificationSessionCreateParams.Options; /** * The URL that the user will be redirected to upon completing the verification flow. */ return_url?: string; } namespace VerificationSessionCreateParams { interface Options { /** * Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). */ document?: Stripe.Emptyable<Options.Document>; } namespace Options { interface Document { /** * Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. */ allowed_types?: Array<Document.AllowedType>; /** * Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. */ require_id_number?: boolean; /** * Disable image uploads, identity document images have to be captured using the device's camera. */ require_live_capture?: boolean; /** * Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). */ require_matching_selfie?: boolean; } namespace Document { type AllowedType = 'driving_license' | 'id_card' | 'passport'; } } type Type = 'document' | 'id_number'; } interface VerificationSessionRetrieveParams { /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; } interface VerificationSessionUpdateParams { /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; /** * Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`. */ metadata?: Stripe.MetadataParam; /** * A set of options for the session's verification checks. */ options?: VerificationSessionUpdateParams.Options; /** * The type of [verification check](https://stripe.com/docs/identity/verification-checks) to be performed. */ type?: VerificationSessionUpdateParams.Type; } namespace VerificationSessionUpdateParams { interface Options { /** * Options that apply to the [document check](https://stripe.com/docs/identity/verification-checks?type=document). */ document?: Stripe.Emptyable<Options.Document>; } namespace Options { interface Document { /** * Array of strings of allowed identity document types. If the provided identity document isn't one of the allowed types, the verification check will fail with a document_type_not_allowed error code. */ allowed_types?: Array<Document.AllowedType>; /** * Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) with the document's extracted name and date of birth. */ require_id_number?: boolean; /** * Disable image uploads, identity document images have to be captured using the device's camera. */ require_live_capture?: boolean; /** * Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) comparing a photo ID and a picture of your user's face. [Learn more](https://stripe.com/docs/identity/selfie). */ require_matching_selfie?: boolean; } namespace Document { type AllowedType = 'driving_license' | 'id_card' | 'passport'; } } type Type = 'document' | 'id_number'; } interface VerificationSessionListParams extends PaginationParams { created?: Stripe.RangeQueryParam | number; /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; /** * Only return VerificationSessions with this status. [Learn more about the lifecycle of sessions](https://stripe.com/docs/identity/how-sessions-work). */ status?: VerificationSessionListParams.Status; } namespace VerificationSessionListParams { type Status = 'canceled' | 'processing' | 'requires_input' | 'verified'; } interface VerificationSessionCancelParams { /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; } interface VerificationSessionRedactParams { /** * Specifies which fields in the response should be expanded. */ expand?: Array<string>; } class VerificationSessionsResource { /** * Creates a VerificationSession object. * * After the VerificationSession is created, display a verification modal using the session client_secret or send your users to the session's url. * * If your API key is in test mode, verification checks won't actually process, though everything else will occur as if in live mode. * * Related guide: [Verify your users' identity documents](https://stripe.com/docs/identity/verify-identity-documents). */ create( params: VerificationSessionCreateParams, options?: RequestOptions ): Promise<Stripe.Response<Stripe.Identity.VerificationSession>>; /** * Retrieves the details of a VerificationSession that was previously created. * * When the session status is requires_input, you can use this method to retrieve a valid * client_secret or url to allow re-submission. */ retrieve( id: string, params?: VerificationSessionRetrieveParams, options?: RequestOptions ): Promise<Stripe.Response<Stripe.Identity.VerificationSession>>; retrieve( id: string, options?: RequestOptions ): Promise<Stripe.Response<Stripe.Identity.VerificationSession>>; /** * Updates a VerificationSession object. * * When the session status is requires_input, you can use this method to update the * verification check and options. */ update( id: string, params?: VerificationSessionUpdateParams, options?: RequestOptions ): Promise<Stripe.Response<Stripe.Identity.VerificationSession>>; /** * Returns a list of VerificationSessions */ list( params?: VerificationSessionListParams, options?: RequestOptions ): ApiListPromise<Stripe.Identity.VerificationSession>; list( options?: RequestOptions ): ApiListPromise<Stripe.Identity.VerificationSession>; /** * A VerificationSession object can be canceled when it is in requires_input [status](https://stripe.com/docs/identity/how-sessions-work). * * Once canceled, future submission attempts are disabled. This cannot be undone. [Learn more](https://stripe.com/docs/identity/verification-sessions#cancel). */ cancel( id: string, params?: VerificationSessionCancelParams, options?: RequestOptions ): Promise<Stripe.Response<Stripe.Identity.VerificationSession>>; cancel( id: string, options?: RequestOptions ): Promise<Stripe.Response<Stripe.Identity.VerificationSession>>; /** * Redact a VerificationSession to remove all collected information from Stripe. This will redact * the VerificationSession and all objects related to it, including VerificationReports, Events, * request logs, etc. * * A VerificationSession object can be redacted when it is in requires_input or verified * [status](https://stripe.com/docs/identity/how-sessions-work). Redacting a VerificationSession in requires_action * state will automatically cancel it. * * The redaction process may take up to four days. When the redaction process is in progress, the * VerificationSession's redaction.status field will be set to processing; when the process is * finished, it will change to redacted and an identity.verification_session.redacted event * will be emitted. * * Redaction is irreversible. Redacted objects are still accessible in the Stripe API, but all the * fields that contain personal data will be replaced by the string [redacted] or a similar * placeholder. The metadata field will also be erased. Redacted objects cannot be updated or * used for any purpose. * * [Learn more](https://stripe.com/docs/identity/verification-sessions#redact). */ redact( id: string, params?: VerificationSessionRedactParams, options?: RequestOptions ): Promise<Stripe.Response<Stripe.Identity.VerificationSession>>; redact( id: string, options?: RequestOptions ): Promise<Stripe.Response<Stripe.Identity.VerificationSession>>; } } } }
the_stack
const Me = imports.misc.extensionUtils.getCurrentExtension(); /** Gnome libs imports */ import { Rectangular } from 'src/types/mod'; const Signals = imports.signals; const MIN_BASIS_RATIO = 0.1; export type PortionState = { basis: number; vertical: boolean; children: PortionState[]; }; export class Portion { vertical: boolean; children: Portion[]; borders: PortionBorder[]; private _basis: number; constructor(basis = 100, vertical = false) { this._basis = basis; this.vertical = vertical; this.children = []; this.borders = []; } get state(): PortionState { return { basis: this.basis, vertical: this.vertical, children: this.children.map((child) => child.state), }; } set state(state) { this.basis = state.basis; this.vertical = state.vertical; this.children = state.children.map((childState) => { const child = new Portion(); child.state = childState; return child; }); this.updateBorders(); } get portionLength(): number { return this.children.length ? this.children.reduce( (sum, portion) => sum + portion.portionLength, 0 ) : 1; } get concatBorders() { return this.borders.concat( ...this.children.map((portion) => { return portion.borders; }) ); } get basis() { return this._basis; } set basis(value: number) { if (value < 0) { value = 0; } this._basis = value; } updateBorders() { this.borders = []; if (this.children.length < 2) { return; } for (let i = 0; i < this.children.length - 1; i++) { const [firstPortion, secondPortion] = this.children.slice(i, i + 2); this.borders.push( new PortionBorder(firstPortion, secondPortion, this) ); } } hasPortion(portion: Portion) { for (let i = 0; i < this.children.length; i++) { const possiblePortion = this.children[i]; if ( possiblePortion === portion || (possiblePortion.children.length > 0 && possiblePortion.hasPortion(portion)) ) { return true; } } return false; } insert(basis = 100, vertical: boolean | undefined) { if (vertical === undefined) { vertical = !this.vertical; } if (this.children.length === 0) { this.children.splice(0, 0, new Portion(basis, vertical)); } this.children.splice(0, 0, new Portion(basis, vertical)); this.updateBorders(); } insertVertical(basis = 100) { this.insert(basis, true); } insertHorizontal(basis = 100) { this.insert(basis, false); } push(basis = 100, vertical?: boolean) { if (vertical === undefined) { vertical = !this.vertical; } if (this.children.length === 0) { this.children.push(new Portion(basis, vertical)); } this.children.push(new Portion(basis, vertical)); this.updateBorders(); } pushVertical(basis = 100) { this.push(basis, true); } pushHorizontal(basis = 100) { this.push(basis, false); } shift() { // If this portion has less than 3 portions, it means that when // want to delete one, this portion describes the space. if (this.portionLength <= 2) { this.children = []; this.borders = []; return; } const child = this.children[0]; if (child) { if (child.children.length) { child.shift(); } else { this.children.shift(); } } this.updateBorders(); } pop() { // If this portion has less than 3 portions, it means that when // want to delete one, this portion describes the space. if (this.portionLength <= 2) { this.children = []; this.borders = []; return; } const child = this.children[this.children.length - 1]; if (child) { if (child.children.length) { child.pop(); } else { this.children.pop(); } } this.updateBorders(); } isBorderInSubPortion(index: number, after = false): boolean { let portionIndex = 0; const afterOffset = after ? 1 : 0; for (let i = 0; i < this.children.length; i++) { const portion = this.children[i]; if (portionIndex === index) { if ( after || i - afterOffset < 0 || portion.children.length === 0 ) { return false; } } if (portion.portionLength + portionIndex > index) { if (portion.children.length === 0) { return false; } if (after) { if (portionIndex === index) { if (portion.children[0].portionLength > 1) { return portion.children[0].isBorderInSubPortion( 0, after ); } else { return false; } } return true; } const lastPortion = portion.children[portion.children.length - 1]; const portionIndexUntilLast = portion.portionLength + portionIndex - lastPortion.portionLength; if (index > portionIndexUntilLast) { if (lastPortion.portionLength > 1) { return lastPortion.isBorderInSubPortion( index - portionIndexUntilLast, after ); } else { return false; } } return true; } portionIndex += portion.portionLength; } return false; } getBorderForIndex( index: number, vertical = false, after = false ): PortionBorder | undefined { let portionIndex = 0; const afterOffset = after ? 1 : 0; if (index >= this.portionLength) { return; } for (let i = 0; i < this.children.length; i++) { const portion = this.children[i]; if (portionIndex === index) { if (i - afterOffset < 0) { return; } } if (portion.portionLength + portionIndex > index) { if ( this.vertical === vertical && !portion.isBorderInSubPortion(index - portionIndex, after) ) { return this.borders[i - afterOffset]; } return portion.getBorderForIndex( index - portionIndex, vertical, after ); } portionIndex += portion.portionLength; } } getRatioForIndex( index: number, ratio: Rectangular = { x: 0, y: 0, width: 1, height: 1 } ): Rectangular | undefined { let portionIndex = 0; if (index >= this.portionLength) { return; } for (let i = 0; i < this.children.length; i++) { const portion = this.children[i]; if (portionIndex === index && portion.children.length === 0) { return this.getRatioForPortion(portion, ratio); } if (portion.portionLength + portionIndex > index) { return portion.getRatioForIndex( index - portionIndex, this.getRatioForPortion(portion, ratio) ); } portionIndex += portion.portionLength; } return ratio; } getRatioForPortion( portion: Portion, ratio: Rectangular = { x: 0, y: 0, width: 1, height: 1 } ): Rectangular { const basisTotal = this.children.reduce( (sum, child) => sum + child.basis, 0 ); let basisSum = 0; for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; const hasPortion = child.hasPortion(portion); if (child !== portion && !hasPortion) { basisSum += child.basis; continue; } const [position, size] = this.vertical ? (['y', 'height'] as const) : (['x', 'width'] as const); ratio[position] += ratio[size] * (basisSum / basisTotal); ratio[size] *= child.basis / basisTotal; if (hasPortion) { return child.getRatioForPortion(portion, ratio); } break; } return ratio; } convert() { this.vertical = !this.vertical; this.children.forEach((portion) => portion.convert()); } } export class PortionBorder { firstPortion: Portion; secondPortion: Portion; parentPortion: Portion; constructor( firstPortion: Portion, secondPortion: Portion, parentPortion: Portion ) { this.firstPortion = firstPortion; this.secondPortion = secondPortion; this.parentPortion = parentPortion; } get vertical() { return !this.parentPortion.vertical; } updateBasis(basisRatio: number) { if (basisRatio < 0) { basisRatio = 0; } const basisSum = this.firstPortion.basis + this.secondPortion.basis; this.firstPortion.basis *= basisRatio; if (this.firstPortion.basis / basisSum < MIN_BASIS_RATIO) { this.firstPortion.basis = MIN_BASIS_RATIO * basisSum; } else if (this.firstPortion.basis / basisSum > 1 - MIN_BASIS_RATIO) { this.firstPortion.basis = (1 - MIN_BASIS_RATIO) * basisSum; } else if ( this.firstPortion.basis / basisSum > 0.24 && this.firstPortion.basis / basisSum < 0.26 ) { this.firstPortion.basis = basisSum * 0.25; } else if ( this.firstPortion.basis / basisSum > 0.49 && this.firstPortion.basis / basisSum < 0.51 ) { this.firstPortion.basis = basisSum * 0.5; } else if ( this.firstPortion.basis / basisSum > 0.74 && this.firstPortion.basis / basisSum < 0.76 ) { this.firstPortion.basis = basisSum * 0.75; } this.secondPortion.basis = basisSum - this.firstPortion.basis; } }
the_stack
import { dirname, join } from 'path' import { fileURLToPath } from 'url' import fs from 'fs' // eslint-disable-next-line import/no-named-as-default import glob from 'glob' import { watch } from 'chokidar' import markdownToAst from 'markdown-to-ast' import { format } from 'prettier' import { SRC_DIR, getVantConfig } from '../common/constant.js' import { ora, consola } from '../common/logger.js' const __dirname = dirname(fileURLToPath(import.meta.url)) const pages: Record<string, { title: string; path: string }> = {} let DEFAULT_PAGE_PATH = join(__dirname, `../../site/simulator/src/pages`) let simulatorConfig: any = {} const fromTaroComps = ['View', 'Text', 'Input', 'Block'] let CACHE: Record<string, any> = {} const CACHE_URL = join(__dirname, '../../.cache/mdcode.json') type IMdCodeParams = { mode: 'create' | 'watch' } export async function mdCode(params: IMdCodeParams) { const { mode } = params const spinner = ora(`Compile md-code and sync to simulator...`).start() const res = await getVantConfig() simulatorConfig = res.site?.simulator if (res.site?.simulator?.pagePath) { DEFAULT_PAGE_PATH = res.site.simulator.pagePath } await initCache() createBaseFiles(res) glob(`${SRC_DIR}/**/README.md`, async function (err, path: string[]) { if (err) { spinner.stop() consola.error(err) process.exit(1) } for (let i = 0; i < path.length; i++) { // @ts-ignore const pat: string = path[i] const { codeArr, commonUtils } = getCode(pat) const pArr = pat.split('/') const name = pArr[pArr.length - 2] if (commonUtils && commonUtils.length) { await createPageCommonUtils( commonUtils, `${DEFAULT_PAGE_PATH}/${name}/common.js`, ) } await createPageComponent(codeArr, name) } spinner.stop() spinner.succeed('Compile success') await saveCache() if (mode === 'watch') { consola.info(` 🐒 Watching for md file changes... `) watchMd() consola.info(CACHE) } }) } process.on('SIGINT', () => { saveCache() }) function watchMd() { let readyOk = false const watcher = watch(`${SRC_DIR}/**/README.md`, { persistent: true, }) watcher.on('ready', function () { readyOk = true }) watcher.on('add', function (path: string) { if (readyOk) { const { codeArr, commonUtils } = getCode(path) const pArr = path.split('/') const name = pArr[pArr.length - 2] createPageCommonUtils( commonUtils, `${DEFAULT_PAGE_PATH}/${name}/common.js`, ) createPageComponent(codeArr, name) } }) watcher.on('change', function (path: string) { if (readyOk) { const { codeArr, commonUtils } = getCode(path) const pArr = path.split('/') const name = pArr[pArr.length - 2] createPageCommonUtils( commonUtils, `${DEFAULT_PAGE_PATH}/${name}/common.js`, ) createPageComponent(codeArr, name) } }) } type IcodeItem = { importFromJsx: any value: string demoTitle: string } async function createPageCommonUtils( utilsArr: { value: string; import?: string[] }[], targetPath: string, ) { let preImportStr = '' let utilsStr = '' utilsArr.forEach((item) => { utilsStr += `${item.value}\n` // @ts-ignore .replace('function', 'export function') .replace('const', 'export const') if (item.import && item.import.length) { preImportStr = createImportStr(item.import) } }) if (preImportStr) preImportStr = `import react from "react"\n` + preImportStr if (utilsStr) { await fs.writeFileSync( targetPath, formatCode( `/* eslint-disable */ ` + preImportStr + utilsStr, ), ) } } async function createPageComponent(codeRes: IcodeItem[], name?: string) { if (!name) return const spinner = ora(`update...`).start() let pageIndexImport = '' let pageIndexJsxInsert = '' let updateCount = 0 for (let i = 0; i < codeRes.length; i++) { const item = codeRes[i] as IcodeItem const index = i const compName = toFirstBigStr(`demo${index + 1}`) pageIndexImport += `import ${compName} from './demo${index + 1}'\n` let padding = 'padding' if (['goods-action', 'tab'].includes(name || '')) padding = '' if ( simulatorConfig.withTabPages && simulatorConfig.withTabPages.includes(name) ) { pageIndexJsxInsert += ` <Tab title="${item.demoTitle}"> <${compName} /> </Tab> ` } else { pageIndexJsxInsert += ` <DemoBlock title="${item.demoTitle}" ${padding}> <${compName} /> </DemoBlock> ` } const commonUtilsImport = item.value.includes('COMMON') ? 'import * as COMMON from "./common.js" ' : '' const demoPath = `/${name}/demo${index + 1}.js` const demoCode = formatCode( ` /* eslint-disable */ import react from 'react'; ${createImportStr(item.importFromJsx)} ${commonUtilsImport} ${item.value} `.replace(`function Demo`, 'export default function Demo'), ) if (!CACHE[name] || CACHE[name][demoPath] !== demoCode) { await fs.writeFileSync(join(DEFAULT_PAGE_PATH, demoPath), demoCode) updateCount++ if (!CACHE[name]) CACHE[name] = {} CACHE[name][demoPath] = demoCode } } if ( pageIndexJsxInsert && name && (CACHE[name] || []).length === codeRes.length ) { await createPageIndex({ targetPath: name, pageTile: pages[name]?.title, importStr: pageIndexImport, jsxStr: pageIndexJsxInsert, }) } spinner.succeed(`mdcode sync ${name} success ${updateCount}`) } type Iresult = { codeArr: IcodeItem[] commonUtils: { value: string }[] } function getCode(targetPath: string): Iresult { const res = fs.readFileSync(targetPath, 'utf-8') const children = markdownToAst.parse(res).children const commonUtils: { value: string; import?: string[] }[] = [] const codeArr = children .map((item: any, index: number) => { if ( item.type === 'CodeBlock' && (item.lang === 'js common' || item.lang === 'jsx common') ) { // 收集公共方法变量 commonUtils.push({ value: item.value, import: item.lang === 'jsx common' ? findImportFromJsx(item.value) : undefined, }) } if ( item.type === 'CodeBlock' && item.lang === 'jsx' && item.value.includes('function Demo()') ) { // 查询demo标题 let demoTitle = '' for (let i = index; i > 0; i--) { if (children[i].type === 'Header') { demoTitle = children[i].raw.replace('### ', '') break } } return { ...item, demoTitle: demoTitle, } } return item }) .filter((item: any) => { return ( item.type === 'CodeBlock' && item.lang === 'jsx' && item.value.includes('function Demo()') ) }) .map((item: any) => { return { value: item.value, importFromJsx: findImportFromJsx(item.value), demoTitle: item.demoTitle, } }) return { codeArr, commonUtils, } } type InavItem = { title: string path: string } type Inav = { title: string items: InavItem[] } // 创建路由菜单文件 async function createBaseFiles(res: any) { const nav = res.site.nav let routers: InavItem[] = [] const simulatorDefaultMenuConfigPath = join( __dirname, '../../site/simulator/src/config.json', ) const simulatorDefaultRouterConfigPath = join( __dirname, '../../site/simulator/src/app.config.js', ) const menuConfigPath = res.site.simulator?.configPath || simulatorDefaultMenuConfigPath const routerConfigPath = res.site.simulator?.appConfigPath || simulatorDefaultRouterConfigPath const navFilter = nav.filter((item: Inav) => { let flag = true item.items.forEach((item: any) => { if (item.hideSimulator !== undefined) { flag = false } }) return flag }) fs.writeFileSync(menuConfigPath, JSON.stringify(navFilter)) navFilter.map((item: Inav) => { routers = routers.concat(item.items) }) const routerTemplateStr = `export default { pages: [ 'pages/dashboard/index',ROUTER_PLACEHOLDER ], window: { navigationBarBackgroundColor: '#f8f8f8', navigationBarTitleText: 'antmjs-vantui', navigationBarTextStyle: 'black', backgroundTextStyle: 'dark', backgroundColor: '#f8f8f8', titleBarColor: 'black', }, sitemapLocation: 'sitemap.json', animation: false, } ` let insertStr = '' routers.forEach((rou) => { pages[rou.path] = rou insertStr += `\n'pages/${rou.path}/index',` createPageIndex({ targetPath: rou.path, pageTile: rou.title, }) }) await fs.writeFileSync( routerConfigPath, formatCode(routerTemplateStr.replace('ROUTER_PLACEHOLDER', insertStr)), ) } function formatCode(codes: string) { let res = codes try { res = format(codes, { singleQuote: true, trailingComma: 'all', semi: false, parser: 'babel', }) return res } catch (err) { if (err) consola.error(`formatCode err: ${err}`) return res } } type IpageParams = { importStr?: string jsxStr?: string pageTile?: string targetPath?: string } // 创建组件入口文件 async function createPageIndex(props: IpageParams) { const { pageTile = '', jsxStr = '等待同步...', importStr = '', targetPath = '', } = props const target = join(DEFAULT_PAGE_PATH, `/${targetPath}`) let lastJsx = ` <DemoPage title="${pageTile}" className="pages-${targetPath}-index"> ${jsxStr} </DemoPage> ` let importStrAdd = '' if ( simulatorConfig.withTabPages && simulatorConfig.withTabPages.includes(targetPath) ) { lastJsx = ` <DemoPage title="${pageTile}" className="pages-${targetPath}-index"> <Tabs active={0} animated> ${jsxStr} </Tabs> </DemoPage> ` importStrAdd += `import { Tab, Tabs } from '@antmjs/vantui'` } const page = ` /* eslint-disable */ ${importStrAdd} import { Component } from 'react' import DemoPage from '../../components/demo-page/index' import DemoBlock from '../../components/demo-block/index' ${importStr} export default class Index extends Component { constructor() { super() } state = {} render() { return ( ${lastJsx} ) } } ` const config = `export default { navigationBarTitleText: '${pageTile}', enableShareAppMessage: true, } ` if (!fs.existsSync(target)) { fs.mkdirSync(target) } await fs.writeFileSync(`${target}/index.js`, formatCode(page)) await fs.writeFileSync(`${target}/index.config.js`, formatCode(config)) } function createImportStr(arr: string[]) { let str = '' let taroComps = '' let selfComps = '' arr.forEach((item: string) => { if (fromTaroComps.includes(item)) { taroComps += `${item},` } else { selfComps += `${item},` } }) if (!!taroComps) str += `import { ${taroComps} } from '@tarojs/components'\n` if (!!selfComps) str += `import { ${selfComps} } from '@antmjs/vantui'` return str } function toFirstBigStr(str: string) { return str.substring(0, 1).toLocaleUpperCase() + str.substring(1) } function findImportFromJsx(ss: string): string[] { const res: string[] = (ss.match(/<[A-Za-z]{3,20}/g) || []).map( (item: string) => item.replace('<', ''), ) // 过滤重复且自定义组件 如: DatetimePickerBox_ return res.filter( (a: string, index: number) => res.indexOf(a) === index && !a.includes('_'), ) } async function saveCache() { const _cacheDir = join(__dirname, '../../.cache') if (!fs.existsSync(_cacheDir)) { await fs.mkdirSync(_cacheDir) } await fs.writeFileSync(CACHE_URL, JSON.stringify(CACHE)) } async function initCache() { if (fs.existsSync(CACHE_URL)) { const res = await fs.readFileSync(CACHE_URL, 'utf-8') CACHE = JSON.parse(res) } }
the_stack
import * as Fluent from '@fluentui/react' import { B, Dict, Id, S, U } from 'h2o-wave' import React from 'react' import { stylesheet } from 'typestyle' import { IconTableCellType, XIconTableCellType } from "./icon_table_cell_type" import { ProgressTableCellType, XProgressTableCellType } from "./progress_table_cell_type" import { cssVar, rem } from './theme' import { wave } from './ui' /** Defines cell content to be rendered instead of a simple text. */ interface TableCellType { /** Renders a progress arc with a percentage value in the middle. */ progress?: ProgressTableCellType /** Renders an icon. */ icon?: IconTableCellType } /** Create a table column. */ interface TableColumn { /** An identifying name for this column. */ name: Id /** The text displayed on the column header. */ label: S /** The minimum width of this column, e.g. '50px'. Only `px` units are supported at this time. */ min_width?: S /** The maximum width of this column, e.g. '100px'. Only `px` units are supported at this time. */ max_width?: S /** Indicates whether the column is sortable. */ sortable?: B /** Indicates whether the contents of this column can be searched through. Enables a search box for the table if true. */ searchable?: B /** Indicates whether the contents of this column are displayed as filters in a dropdown. */ filterable?: B /** Indicates whether each cell in this column should be displayed as a clickable link. Applies to exactly one text column in the table. */ link?: B /** Defines the data type of this column. Defaults to `string`. */ data_type?: 'string' | 'number' | 'time' /** Defines how to render each cell in this column. Defaults to plain text. */ cell_type?: TableCellType } /** Create a table row. */ interface TableRow { /** An identifying name for this row. */ name: Id /** The cells in this row (displayed left to right). */ cells: S[] } /** * Create an interactive table. * * This table differs from a markdown table in that it supports clicking or selecting rows. If you simply want to * display a non-interactive table of information, use a markdown table. * * If `multiple` is set to False (default), each row in the table is clickable. When a row is clicked, the form is * submitted automatically, and `q.args.table_name` is set to `[row_name]`, where `table_name` is the `name` of * the table, and `row_name` is the `name` of the row that was clicked on. * * If `multiple` is set to True, each row in the table is selectable. A row can be selected by clicking on it. * Multiple rows can be selected either by shift+clicking or using marquee selection. When the form is submitted, * `q.args.table_name` is set to `[row1_name, row2_name, ...]` where `table_name` is the `name` of the table, * and `row1_name`, `row2_name` are the `name` of the rows that were selected. Note that if `multiple` is * set to True, the form is not submitted automatically, and one or more buttons are required in the form to trigger * submission. */ export interface Table { /** An identifying name for this component. */ name: Id /** The columns in this table. */ columns: TableColumn[] /** The rows in this table. */ rows: TableRow[] /** True to allow multiple rows to be selected. */ multiple?: B /** True to allow group by feature. */ groupable?: B /** Indicates whether the contents of this table can be downloaded and saved as a CSV file. Defaults to False. */ downloadable?: B /** Indicates whether a Reset button should be displayed to reset search / filter / group-by values to their defaults. Defaults to False. */ resettable?: B /** The height of the table, e.g. '400px', '50%', etc. */ height?: S /** The width of the table, e.g. '100px'. Defaults to '100%'. */ width?: S /** The names of the selected rows. If this parameter is set, multiple selections will be allowed (`multiple` is assumed to be `True`). */ values?: S[] /** Controls visibility of table rows when `multiple` is set to `True`. Defaults to 'on-hover'. */ checkbox_visibility?: 'always' | 'on-hover' | 'hidden' /** True if the component should be visible. Defaults to true. */ visible?: B /** An optional tooltip message displayed when a user clicks the help icon to the right of the component. */ tooltip?: S } type QColumn = Fluent.IColumn & { dataType?: S cellType?: TableCellType isSortable?: B } type DataTable = { model: Table onFilterChange: (filterKey: S, filterVal: S) => (e?: React.FormEvent<HTMLInputElement | HTMLElement>, checked?: B) => void sort: (col: QColumn) => void, reset: () => void filteredItems: any[] selectedFilters: Dict<S[]> | null items: any[] selection: Fluent.Selection isMultiple: B isSearchable: B groups?: Fluent.IGroup[] } const css = stylesheet({ // HACK: Put sorting icon on right (same as filter). sortableHeader: { $nest: { '.ms-DetailsHeader-cellName': { position: 'relative', paddingRight: 15 } } }, sortingIcon: { marginLeft: 10, fontSize: rem(1.1), position: 'absolute', top: -2, right: -5 }, // HACK: incorrect width recalculated after changing to "group by mode" - collapse icon in header // causes horizontal overflow for whole table. hideCellGroupCollapse: { $nest: { 'div[class*="cellIsGroupExpander"]': { display: 'none' } } } }), checkboxVisibilityMap = { 'always': Fluent.CheckboxVisibility.always, 'on-hover': Fluent.CheckboxVisibility.onHover, 'hidden': Fluent.CheckboxVisibility.hidden, }, groupByF = function <T extends Dict<any>>(arr: T[], key: S): Dict<any> { return arr.reduce((rv, x: T) => { (rv[x[key]] = rv[x[key]] || []).push(x) return rv }, {} as Dict<any>) }, sortingF = (column: QColumn, sortAsc: B) => (rowA: any, rowB: any) => { let a = rowA[column.key], b = rowB[column.key] switch (column.dataType) { case 'number': a = +a b = +b return sortAsc ? a - b : b - a case 'time': a = Date.parse(a) b = Date.parse(b) break default: a = a.toLowerCase() b = b.toLowerCase() break } return sortAsc ? b > a ? -1 : 1 : b > a ? 1 : -1 }, formatNum = (num: U) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","), toCSV = (data: unknown[][]): S => data.map(row => { const line = JSON.stringify(row) return line.substr(1, line.length - 2) }).join('\n'), DataTable = ({ model: m, onFilterChange, items, filteredItems, selection, selectedFilters, isMultiple, isSearchable, groups, sort, reset }: DataTable) => { const [colContextMenuList, setColContextMenuList] = React.useState<Fluent.IContextualMenuProps | null>(null), selectedFiltersRef = React.useRef(selectedFilters), onColumnClick = (e: React.MouseEvent<HTMLElement>, column: QColumn) => { const isMenuClicked = (e.target as HTMLElement).getAttribute('data-icon-name') === 'ChevronDown' if (isMenuClicked) onColumnContextMenu(column, e) else if (column.isSortable) { sort(column) setColumns(columns.map(col => column.key === col.key ? column : col)) } }, [columns, setColumns] = React.useState(m.columns.map((c): QColumn => { const minWidth = c.min_width ? c.min_width.endsWith('px') ? +c.min_width.substring(0, c.min_width.length - 2) : +c.min_width : 150, maxWidth = c.max_width ? c.max_width.endsWith('px') ? +c.max_width.substring(0, c.max_width.length - 2) : +c.max_width : undefined return { key: c.name, name: c.label, fieldName: c.name, minWidth, maxWidth, headerClassName: c.sortable ? css.sortableHeader : undefined, iconClassName: c.sortable ? css.sortingIcon : undefined, iconName: c.sortable ? 'SortDown' : undefined, onColumnClick, columnActionsMode: c.filterable ? Fluent.ColumnActionsMode.hasDropdown : Fluent.ColumnActionsMode.clickable, cellType: c.cell_type, dataType: c.data_type, isSortable: c.sortable, isResizable: true, } })), primaryColumnKey = m.columns.find(c => c.link)?.name || (m.columns[0].link === false ? undefined : m.columns[0].name), onRenderMenuList = React.useCallback((listProps?: Fluent.IContextualMenuListProps) => { if (!listProps) return null return ( <div style={{ padding: 10 }}> <Fluent.Text variant='mediumPlus' styles={{ root: { paddingTop: 10, paddingBottom: 10, fontWeight: 'bold' } }} block>Show only</Fluent.Text> { listProps.items.map(({ key, name, data }) => ( <Fluent.Checkbox key={key} label={name} defaultChecked={!!name && !!selectedFiltersRef.current && selectedFiltersRef.current[data]?.includes(name)} onChange={onFilterChange(data || '', name || '')} styles={{ root: { marginBottom: 5 } }} /> ) ) } </div> ) }, [onFilterChange]), onColumnContextMenu = React.useCallback((col: Fluent.IColumn, e: React.MouseEvent<HTMLElement>) => { setColContextMenuList({ items: Array.from(new Set(items.map(i => i[col.fieldName || col.key]))).map(option => ({ key: option, name: option, data: col.fieldName || col.key })), target: e.target as HTMLElement, directionalHint: Fluent.DirectionalHint.bottomLeftEdge, gapSpace: 10, isBeakVisible: true, onRenderMenuList, onDismiss: () => setColContextMenuList(null), }) }, [items, onRenderMenuList]), onRenderDetailsHeader = React.useCallback((props?: Fluent.IDetailsHeaderProps) => { if (!props) return <span /> return ( <Fluent.Sticky stickyPosition={Fluent.StickyPositionType.Header} isScrollSynced> <Fluent.DetailsHeader {...props} onColumnContextMenu={onColumnContextMenu} className={groups ? css.hideCellGroupCollapse : ''} /> </Fluent.Sticky> ) }, [groups, onColumnContextMenu]), onRenderDetailsFooter = (props?: Fluent.IDetailsFooterProps) => { const isFilterable = m.columns.some(c => c.filterable) if (!props || (!m.downloadable && !m.resettable && !isSearchable && !isFilterable)) return null const footerItems: Fluent.ICommandBarItemProps[] = [], buttonStyles = { root: { background: cssVar('$card') } } if (m.downloadable) footerItems.push({ key: 'download', text: 'Download data', iconProps: { iconName: 'Download' }, onClick: download, buttonStyles }) if (m.resettable) footerItems.push({ key: 'reset', text: 'Reset table', iconProps: { iconName: 'Refresh' }, onClick: reset, buttonStyles }) return ( <Fluent.Sticky stickyPosition={Fluent.StickyPositionType.Footer} isScrollSynced> <Fluent.Stack horizontal horizontalAlign={isFilterable ? 'space-between' : 'end'} verticalAlign='center'> { isFilterable && ( <Fluent.Text variant='smallPlus' block styles={{ root: { whiteSpace: 'nowrap' } }}>Rows: <b style={{ paddingLeft: 5 }}>{formatNum(filteredItems.length)} of {formatNum(items.length)}</b> </Fluent.Text> ) } <div style={{ width: '80%' }}> <Fluent.CommandBar items={footerItems} styles={{ root: { background: cssVar('$card') }, primarySet: { justifyContent: 'flex-end' } }} /> </div> </Fluent.Stack> </Fluent.Sticky> ) }, onRenderRow = (props?: Fluent.IDetailsRowProps) => props ? <Fluent.DetailsRow {...props} styles={{ cell: { alignSelf: 'center' }, checkCell: { display: 'flex', alignItems: 'center' }, root: { width: '100%' } }} /> : null, onItemInvoked = (item: Fluent.IObjectWithKey & Dict<any>) => { wave.args[m.name] = [item.key as S] wave.push() }, download = () => { // TODO: Prompt a dialog for name, encoding, etc. const data = toCSV([m.columns.map(({ label, name }) => label || name), ...m.rows.map(({ cells }) => cells)]), a = document.createElement('a'), blob = new Blob([data], { type: "octet/stream" }), url = window.URL.createObjectURL(blob) a.href = url a.download = 'exported_data.csv' a.click() window.URL.revokeObjectURL(url) }, onRenderItemColumn = (item?: Fluent.IObjectWithKey & Dict<any>, _index?: number, col?: QColumn) => { if (!item || !col) return <span /> let v = item[col.fieldName as S] if (col.cellType?.progress) return <XProgressTableCellType model={col.cellType.progress} progress={item[col.key]} /> if (col.cellType?.icon) return <XIconTableCellType model={col.cellType.icon} icon={item[col.key]} /> if (col.dataType === 'time') v = new Date(v).toLocaleString() if (col.key === primaryColumnKey && !isMultiple) { const onClick = () => { wave.args[m.name] = [item.key as S] wave.push() } return <Fluent.Link onClick={onClick}>{v}</Fluent.Link> } return v } // HACK: React stale closures - https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function // TODO: Find a reasonable way of doing this. React.useEffect(() => { { selectedFiltersRef.current = selectedFilters } }, [selectedFilters]) return ( <> <Fluent.DetailsList items={filteredItems} columns={columns} constrainMode={Fluent.ConstrainMode.unconstrained} layoutMode={Fluent.DetailsListLayoutMode.fixedColumns} groups={groups} selection={selection} selectionMode={isMultiple ? Fluent.SelectionMode.multiple : Fluent.SelectionMode.none} selectionPreservedOnEmptyClick onItemInvoked={isMultiple ? undefined : onItemInvoked} onRenderRow={onRenderRow} onRenderItemColumn={onRenderItemColumn} onRenderDetailsHeader={onRenderDetailsHeader} onRenderDetailsFooter={onRenderDetailsFooter} checkboxVisibility={checkboxVisibilityMap[m.checkbox_visibility || 'on-hover']} /> {colContextMenuList && <Fluent.ContextualMenu {...colContextMenuList} />} </> ) } export const XTable = ({ model: m }: { model: Table }) => { const items = React.useMemo(() => m.rows.map(r => { const item: Fluent.IObjectWithKey & Dict<any> = { key: r.name } for (let i = 0, n = r.cells.length; i < n; i++) { const col = m.columns[i] item[col.name] = r.cells[i] } return item }), [m.rows, m.columns]), isMultiple = Boolean(m.values?.length || m.multiple), [filteredItems, setFilteredItems] = React.useState(items), searchableKeys = React.useMemo(() => m.columns.filter(({ searchable }) => searchable).map(({ name }) => name), [m.columns]), [searchStr, setSearchStr] = React.useState(''), [selectedFilters, setSelectedFilters] = React.useState<Dict<S[]> | null>(null), [groups, setGroups] = React.useState<Fluent.IGroup[] | undefined>(), [groupByKey, setGroupByKey] = React.useState('*'), groupByOptions: Fluent.IDropdownOption[] = React.useMemo(() => m.groupable ? [{ key: '*', text: '(No Grouping)' }, ...m.columns.map(col => ({ key: col.name, text: col.label }))] : [], [m.columns, m.groupable] ), filter = React.useCallback((selectedFilters: Dict<S[]> | null) => { // If we have filters, check if any of the data-item's props (filter's keys) equals to any of its filter values. setFilteredItems( selectedFilters ? items.filter(i => Object.keys(selectedFilters) .every(filterKey => !selectedFilters[filterKey].length || selectedFilters[filterKey] .some(filterVal => i[filterKey] === filterVal) ) ) : items ) }, [items]), makeGroups = React.useCallback((groupByKey: S, filteredItems: (Fluent.IObjectWithKey & Dict<any>)[]) => { let prevSum = 0 const groupedBy = groupByF(filteredItems, groupByKey), groupedByKeys = Object.keys(groupedBy), groups: Fluent.IGroup[] = groupedByKeys.map((key, i) => { if (i !== 0) { const prevKey = groupedByKeys[i - 1] prevSum += groupedBy[prevKey].length } let name = key if (isNaN(Number(key)) && !isNaN(Date.parse(key))) name = new Date(key).toLocaleString() return { key, name, startIndex: prevSum, count: groupedBy[key].length, isCollapsed: true } }) groups.sort(({ name: name1 }, { name: name2 }) => { const numName1 = Number(name1), numName2 = Number(name2) if (!isNaN(numName1) && !isNaN(numName2)) return numName1 - numName2 const dateName1 = Date.parse(name1), dateName2 = Date.parse(name2) if (!isNaN(dateName1) && !isNaN(dateName2)) return dateName1 - dateName2 return name2 < name1 ? 1 : -1 }) return { groupedBy, groups } }, []), initGroups = React.useCallback(() => { setGroupByKey(groupByKey => { setFilteredItems(filteredItems => { const { groupedBy, groups } = makeGroups(groupByKey, filteredItems) setGroups(groups) return Object.values(groupedBy).flatMap(arr => arr) }) return groupByKey }) }, [makeGroups]), search = React.useCallback(() => { setSearchStr(searchString => { const _searchStr = searchString.toLowerCase() if (!_searchStr || !searchableKeys.length) return searchString || '' setFilteredItems(filteredItems => filteredItems.filter(i => searchableKeys.some(key => (i[key] as S).toLowerCase().includes(_searchStr)))) return searchString || '' }) }, [searchableKeys]), onSearchChange = React.useCallback((_e: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, searchStr = '') => { setSearchStr(searchStr) if (!searchStr && !selectedFilters) { setFilteredItems(items) setGroups(groups => { if (groups) initGroups() return groups }) return } filter(selectedFilters) search() setGroups(groups => { if (groups) initGroups() return groups }) }, [selectedFilters, filter, search, initGroups, items]), onGroupByChange = (_e: React.FormEvent<HTMLDivElement>, option?: Fluent.IDropdownOption) => { if (!option) return reset() if (option.key === '*') return setGroupByKey(option.key as S) initGroups() }, onFilterChange = React.useCallback((filterKey: S, filterVal: S) => (_e?: React.FormEvent<HTMLInputElement | HTMLElement>, checked?: B) => { setSelectedFilters(selectedFilters => { const filters = selectedFilters || {} if (checked) { if (filters[filterKey]) filters[filterKey].push(filterVal) else filters[filterKey] = [filterVal] } else filters[filterKey] = filters[filterKey].filter(f => f !== filterVal) const newFilters = Object.values(filters).every(v => !v.length) ? null : { ...filters } filter(newFilters) search() setGroups(groups => { if (groups) initGroups() return groups }) return newFilters }) }, [filter, initGroups, search]), // TODO: Make filter options in dropdowns dynamic. reset = React.useCallback(() => { setSelectedFilters(null) setSearchStr('') setGroups(undefined) setGroupByKey('*') filter(null) search() }, [filter, search]), selection = React.useMemo(() => new Fluent.Selection({ onSelectionChanged: () => { wave.args[m.name] = selection.getSelection().map(item => item.key as S) } }), [m.name]), computeHeight = () => { if (m.height) return m.height if (items.length > 10) return 500 const topToolbarHeight = searchableKeys.length || m.groupable ? 60 : 0, headerHeight = 60, rowHeight = m.columns.some(c => c.cell_type) ? m.columns.some(c => c.cell_type?.progress) ? 68 : 50 : 43, footerHeight = m.downloadable || m.resettable || searchableKeys.length ? 44 : 0 return topToolbarHeight + headerHeight + (items.length * rowHeight) + footerHeight }, sort = React.useCallback((column: QColumn) => { const sortAsc = column.iconName === 'SortDown' column.iconName = sortAsc ? 'SortUp' : 'SortDown' setGroups(groups => { if (groups) { setFilteredItems(filteredItems => groups?.reduce((acc, group) => [...acc, ...filteredItems.slice(group.startIndex, acc.length + group.count).sort(sortingF(column, sortAsc))], [] as any[]) || []) } else setFilteredItems(filteredItems => [...filteredItems].sort(sortingF(column, sortAsc))) return groups }) }, []) React.useEffect(() => { wave.args[m.name] = [] if (isMultiple && m.values) { m.values.forEach(v => selection.setKeySelected(v, true, false)) wave.args[m.name] = m.values } // eslint-disable-next-line react-hooks/exhaustive-deps }, []) React.useEffect(() => setFilteredItems(items), [items]) const dataTableProps: DataTable = React.useMemo(() => ({ model: m, onFilterChange, items, filteredItems, selectedFilters, groups, selection, sort, isMultiple, reset, isSearchable: !!searchableKeys.length }), [filteredItems, groups, isMultiple, items, m, onFilterChange, reset, searchableKeys.length, selectedFilters, selection, sort]) return ( <div data-test={m.name} style={{ position: 'relative', height: computeHeight() }}> <Fluent.Stack horizontal horizontalAlign='space-between' > {m.groupable && <Fluent.Dropdown data-test='groupby' label='Group by' selectedKey={groupByKey} onChange={onGroupByChange} options={groupByOptions} styles={{ root: { width: 300 } }} />} {!!searchableKeys.length && <Fluent.TextField data-test='search' label='Search' onChange={onSearchChange} value={searchStr} styles={{ root: { width: '50%' } }} />} </Fluent.Stack> <Fluent.ScrollablePane scrollbarVisibility={Fluent.ScrollbarVisibility.auto} styles={{ root: { top: m.groupable || searchableKeys.length ? 80 : 0 } }}> { isMultiple ? <Fluent.MarqueeSelection selection={selection}><DataTable {...dataTableProps} /></Fluent.MarqueeSelection> : <DataTable {...dataTableProps} /> } </Fluent.ScrollablePane> </div> ) }
the_stack
import * as fs from "fs" /** * Comparison options. */ export interface Options { /** * Properties to be used in various extension points ie. result builder. */ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ [key: string]: any /** * Compares files by size. Defaults to 'false'. * * Usually one of `compareSize` or `compareContent` options has to be activated. Otherwise files are compared by name disregarding size or content. */ compareSize?: boolean /** * Compares files by content. Defaults to 'false'. * * Usually one of `compareSize` or `compareContent` options has to be activated. Otherwise files are compared by name disregarding size or content. */ compareContent?: boolean /** * Compares files by date of modification (stat.mtime). Defaults to 'false'. * * Also see [[Options.dateTolerance]]. */ compareDate?: boolean /** * Two files are considered to have the same date if the difference between their modification dates fits within date tolerance. Defaults to 1000 ms. */ dateTolerance?: number /** * Compares entries by symlink. Defaults to 'false'. * If this option is enabled two entries must have the same type in order to be considered equal. * They have to be either two fies, two directories or two symlinks. * * If left entry is a file and right entry is a symlink, they are considered distinct disregarding the content of the file. * * Further if both entries are symlinks they need to have the same link value. For example if one symlink points to '/x/b.txt' and the other to '/x/../x/b.txt' the symlinks are considered distinct even if they point to the same file. */ compareSymlink?: boolean /** * Skips sub directories. Defaults to 'false'. */ skipSubdirs?: boolean /** * Ignore empty directories. Defaults to 'false'. */ skipEmptyDirs?: boolean /** * Ignore symbolic links. Defaults to 'false'. */ skipSymlinks?: boolean /** * Ignores case when comparing names. Defaults to 'false'. */ ignoreCase?: boolean /** * Toggles presence of diffSet in output. If true, only statistics are provided. Use this when comparing large number of files to avoid out of memory situations. Defaults to 'false'. */ noDiffSet?: boolean /** * File name filter. Comma separated minimatch patterns. See [Glob patterns](https://github.com/gliviu/dir-compare#glob-patterns). */ includeFilter?: string /** * File/directory name exclude filter. Comma separated minimatch patterns. See [Glob patterns](https://github.com/gliviu/dir-compare#glob-patterns) */ excludeFilter?: string /** * Handle permission denied errors. Defaults to 'false'. * * By default when some entry cannot be read due to `EACCES` error the comparison will * stop immediately with an exception. * * If `handlePermissionDenied` is set to true the comparison will continue when unreadable entries are encountered. * * Offending entries will be reported within [[Difference.permissionDeniedState]], [[Difference.reason]] and [[Result.permissionDenied]]. * * Lets consider we want to compare two identical folders `A` and `B` with `B/dir2` being unreadable for the current user. * ``` * A B * ├── dir1 ├── dir1 * ├──── file1 ├──── file1 * ├── dir2 ├── dir2 (permission denied) * └─────file2 └─────file2 * ``` * * [[Result.diffSet]] will look like: * * |relativePath |path1 |path2 | state |reason |permissionDeniedState| * |--------------|---------|---------|------------|------------------------|---------------------| * |[/] |dir1 |dir1 |`equal` | | | * |[/dir1] |file1 |file1 |`equal` | | | * |[/] |dir2 |dir2 |`distinct` | `permission-denied` |`access-error-right` | * |[/dir2] |file2 |missing |`left` | | | * * And [[Result.permissionDenied]] statistics look like - left: 0, right: 1, distinct: 0, total: 1 * */ handlePermissionDenied?: boolean /** * Callback for constructing result. Called for each compared entry pair. * * Updates 'statistics' and 'diffSet'. * * See [Custom result builder](https://github.com/gliviu/dir-compare#custom-result-builder). */ resultBuilder?: ResultBuilder /** * File comparison handler. See [Custom file comparators](https://github.com/gliviu/dir-compare#custom-file-content-comparators). */ compareFileSync?: CompareFileSync /** * File comparison handler. See [Custom file comparators](https://github.com/gliviu/dir-compare#custom-file-content-comparators). */ compareFileAsync?: CompareFileAsync /** * Entry name comparison handler. See [Custom name comparators](https://github.com/gliviu/dir-compare#custom-name-comparators). */ compareNameHandler?: CompareNameHandler } /** * Callback for constructing result. Called for each compared entry pair. * * Updates 'statistics' and 'diffSet'. */ export type ResultBuilder = /** * @param entry1 Left entry. * @param entry2 Right entry. * @param state See [[DifferenceState]]. * @param level Depth level relative to root dir. * @param relativePath Path relative to root dir. * @param statistics Statistics to be updated. * @param diffSet Status per each entry to be appended. * Do not append if [[Options.noDiffSet]] is false. * @param reason See [[Reason]]. Not available if entries are equal. */ ( entry1: Entry | undefined, entry2: Entry | undefined, state: DifferenceState, level: number, relativePath: string, options: Options, statistics: Statistics, diffSet: Array<Difference> | undefined, reason: Reason | undefined ) => void export interface Entry { name: string absolutePath: string path: string stat: fs.Stats lstat: fs.Stats symlink: boolean /** * True when this entry is not readable. * This value is set only when [[Options.handlePermissionDenied]] is enabled. */ isPermissionDenied: boolean } /** * Comparison result. */ export interface Result extends Statistics { /** * List of changes (present if [[Options.noDiffSet]] is false). */ diffSet?: Array<Difference> } export interface Statistics { /** * Any property is allowed if default result builder is not used. */ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ [key: string]: any /** * True if directories are identical. */ same: boolean /** * Number of distinct entries. */ distinct: number /** * Number of equal entries. */ equal: number /** * Number of entries only in path1. */ left: number /** * Number of entries only in path2. */ right: number /** * Total number of differences (distinct+left+right). */ differences: number /** * Total number of entries (differences+equal). */ total: number /** * Number of distinct files. */ distinctFiles: number /** * Number of equal files. */ equalFiles: number /** * Number of files only in path1. */ leftFiles: number /** * Number of files only in path2 */ rightFiles: number /** * Total number of different files (distinctFiles+leftFiles+rightFiles). */ differencesFiles: number /** * Total number of files (differencesFiles+equalFiles). */ totalFiles: number /** * Number of distinct directories. */ distinctDirs: number /** * Number of equal directories. */ equalDirs: number /** * Number of directories only in path1. */ leftDirs: number /** * Number of directories only in path2. */ rightDirs: number /** * Total number of different directories (distinctDirs+leftDirs+rightDirs). */ differencesDirs: number /** * Total number of directories (differencesDirs+equalDirs). */ totalDirs: number /** * Stats about broken links. */ brokenLinks: BrokenLinksStatistics /** * Statistics available if 'compareSymlink' options is used. */ symlinks?: SymlinkStatistics /** * Stats about entries that could not be accessed. */ permissionDenied: PermissionDeniedStatistics } export interface BrokenLinksStatistics { /** * Number of broken links only in path1 */ leftBrokenLinks: number /** * Number of broken links only in path2 */ rightBrokenLinks: number /** * Number of broken links with same name appearing in both path1 and path2 (leftBrokenLinks + rightBrokenLinks + distinctBrokenLinks) */ distinctBrokenLinks: number /** * Total number of broken links */ totalBrokenLinks: number } export interface PermissionDeniedStatistics { /** * Number of forbidden entries found only in path1 */ leftPermissionDenied: number /** * Number of forbidden entries found only in path2 */ rightPermissionDenied: number /** * Number of forbidden entries with same name appearing in both path1 and path2 (leftPermissionDenied + rightPermissionDenied + distinctPermissionDenied) */ distinctPermissionDenied: number /** * Total number of forbidden entries */ totalPermissionDenied: number } export interface SymlinkStatistics { /** * Number of distinct links. */ distinctSymlinks: number /** * Number of equal links. */ equalSymlinks: number /** * Number of links only in path1. */ leftSymlinks: number /** * Number of links only in path2 */ rightSymlinks: number /** * Total number of different links (distinctSymlinks+leftSymlinks+rightSymlinks). */ differencesSymlinks: number /** * Total number of links (differencesSymlinks+equalSymlinks). */ totalSymlinks: number } /** * State of left/right entries relative to each other. * * `equal` - Identical entries are found in both left/right dirs. * * `left` - Entry is found only in left dir. * * `right` - Entry is found only in right dir. * * `distinct` - Entries exist in both left/right dir but have different content. See [[Difference.reason]] to understan why entries are considered distinct. */ export type DifferenceState = "equal" | "left" | "right" | "distinct" /** * Permission related state of left/right entries. Available only when [[Options.handlePermissionDenied]] is enabled. * * `access-ok` - Both entries are accessible. * * `access-error-both` - Neither entry can be accessed. * * `access-error-left` - Left entry cannot be accessed. * * `access-error-right` - Right entry cannot be accessed. */ export type PermissionDeniedState = "access-ok" | "access-error-both" | "access-error-left" | "access-error-right" /** * Type of entry. */ export type DifferenceType = "missing" | "file" | "directory" | "broken-link" /** * Provides reason when two identically named entries are distinct. * * Not available if entries are equal. * * * `different-size` - Files differ in size. * * `different-date - Entry dates are different. Used when [[Options.compareDate]] is `true`. * * `different-content` - File contents are different. Used when [[Options.compareContent]] is `true`. * * `broken-link` - Both left/right entries are broken links. * * `different-symlink` - Symlinks are different. See [[Options.compareSymlink]] for details. * * `permission-denied` - One or both left/right entries are not accessible. See [[Options.handlePermissionDenied]] for details. */ export type Reason = undefined | "different-size" | "different-date" | "different-content" | "broken-link" | 'different-symlink' | 'permission-denied' export interface Difference { /** * Any property is allowed if default result builder is not used. */ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ [key: string]: any /** * Path not including file/directory name; can be relative or absolute depending on call to compare(). * Is undefined if missing on the left side. */ path1?: string /** * Path not including file/directory name; can be relative or absolute depending on call to compare(). * Is undefined if missing on the right side. */ path2?: string /** * Path relative to root dir. */ relativePath: string /** * Left file/directory name. * Is undefined if missing on the left side. */ name1?: string /** * Right file/directory name. * Is undefined if missing on the right side. */ name2?: string /** * See [[DifferenceState]] */ state: DifferenceState /** * Permission related state of left/right entries. */ permissionDeniedState: PermissionDeniedState /** * Type of left entry. * Is undefined if missing on the left side. */ type1: DifferenceType /** * Type of right entry. * Is undefined if missing on the right side. */ type2: DifferenceType /** * Left file size. * Is undefined if missing on the left side. */ size1?: number /** * Right file size. * Is undefined if missing on the right side. */ size2?: number /** * Left entry modification date (stat.mtime). * Is undefined if missing on the left side. */ date1?: number /** * Right entry modification date (stat.mtime). * Is undefined if missing on the right side. */ date2?: number /** * Depth level relative to root dir. */ level: number /** * Provides reason when two identically named entries are distinct. */ reason: Reason } /** * Synchronous file content comparison handler. */ export type CompareFileSync = ( path1: string, stat1: fs.Stats, path2: string, stat2: fs.Stats, options: Options ) => boolean /** * Asynchronous file content comparison handler. */ export type CompareFileAsync = ( path1: string, stat1: fs.Stats, path2: string, stat2: fs.Stats, options: Options ) => Promise<boolean> export interface CompareFileHandler { compareSync: CompareFileSync, compareAsync: CompareFileAsync } /** * Compares the names of two entries. * The comparison should be dependent on received options (ie. case sensitive, ...). * Returns 0 if names are identical, -1 if name1<name2, 1 if name1>name2. */ export type CompareNameHandler = ( name1: string, name2: string, options: Options ) => 0 | 1 | -1
the_stack
import { act, fireEvent, screen } from '@testing-library/react' import React, { useState, StrictMode } from 'react' import useSWR, { useSWRConfig, SWRConfig, mutate as globalMutate } from 'swr' import { sleep, createKey, createResponse, nextTick, focusOn, renderWithConfig, renderWithGlobalCache } from './utils' describe('useSWR - cache provider', () => { let provider beforeEach(() => { provider = new Map() }) it('should be able to update the cache', async () => { const fetcher = _key => 'res:' + _key const keys = [createKey(), createKey()] function Page() { const [index, setIndex] = useState(0) const { data } = useSWR(keys[index], fetcher) return <div onClick={() => setIndex(1)}>{data}</div> } renderWithConfig(<Page />, { provider: () => provider }) await screen.findByText(fetcher(keys[0])) expect(provider.get(keys[1])?.data).toBe(undefined) fireEvent.click(screen.getByText(fetcher(keys[0]))) await act(() => sleep(10)) expect(provider.get(keys[0])?.data).toBe(fetcher(keys[0])) expect(provider.get(keys[1])?.data).toBe(fetcher(keys[1])) }) it('should be able to read from the initial cache with updates', async () => { const key = createKey() const renderedValues = [] const fetcher = () => createResponse('updated value', { delay: 10 }) function Page() { const { data } = useSWR(key, fetcher) renderedValues.push(data) return <div>{data}</div> } renderWithConfig(<Page />, { provider: () => new Map([[key, { data: 'cached value' }]]) }) screen.getByText('cached value') await screen.findByText('updated value') expect(renderedValues.length).toBe(2) }) it('should correctly mutate the cached value', async () => { const key = createKey() let mutate function Page() { const { mutate: mutateWithCache } = useSWRConfig() mutate = mutateWithCache const { data } = useSWR(key, null) return <div>{data}</div> } renderWithConfig(<Page />, { provider: () => new Map([[key, { data: 'cached value' }]]) }) screen.getByText('cached value') await act(() => mutate(key, 'mutated value', false)) await screen.findByText('mutated value') }) it('should support multi-level cache', async () => { const key = createKey() // Nested components with the same cache key can get different values. function Foo() { const { data } = useSWR(key, null) return <>{data}</> } function Page() { const { data } = useSWR(key, null) return ( <div> {data}: <SWRConfig value={{ provider: () => new Map([[key, { data: '2' }]]) }} > <Foo /> </SWRConfig> </div> ) } renderWithConfig(<Page />, { provider: () => new Map([[key, { data: '1' }]]) }) screen.getByText('1:2') }) it('should support isolated cache', async () => { const key = createKey() // Nested components with the same cache key can get different values. function Foo() { const { data } = useSWR(key, null) return <>{data}</> } function Page() { return ( <div> <SWRConfig value={{ provider: () => new Map([[key, { data: '1' }]]) }} > <Foo /> </SWRConfig> : <SWRConfig value={{ provider: () => new Map([[key, { data: '2' }]]) }} > <Foo /> </SWRConfig> </div> ) } renderWithConfig(<Page />) screen.getByText('1:2') }) it('should respect provider options', async () => { const key = createKey() const focusFn = jest.fn() const unsubscribeFocusFn = jest.fn() const unsubscribeReconnectFn = jest.fn() let value = 1 function Page() { const { data } = useSWR(key, () => value++, { dedupingInterval: 0 }) return <>{String(data)}</> } const { unmount } = renderWithConfig(<Page />, { provider: () => new Map([[key, { data: 0 }]]), initFocus() { focusFn() return unsubscribeFocusFn }, initReconnect() { /* do nothing */ return unsubscribeReconnectFn } }) screen.getByText('0') // mount await screen.findByText('1') await nextTick() // try to trigger revalidation, but shouldn't work await focusOn(window) // revalidateOnFocus won't work screen.getByText('1') unmount() expect(focusFn).toBeCalled() expect(unsubscribeFocusFn).toBeCalledTimes(1) expect(unsubscribeReconnectFn).toBeCalledTimes(1) }) it('should work with revalidateOnFocus', async () => { const key = createKey() let value = 0 function Page() { const { data } = useSWR(key, () => value++, { dedupingInterval: 0 }) return <>{String(data)}</> } renderWithConfig(<Page />, { provider: () => provider }) screen.getByText('undefined') await screen.findByText('0') await nextTick() await focusOn(window) await nextTick() screen.getByText('1') }) it('should support fallback values with custom provider', async () => { const key = createKey() function Page() { const { data, isLoading } = useSWR(key, async () => { await sleep(10) return 'data' }) return ( <> {String(data)},{String(isLoading)} </> ) } renderWithConfig(<Page />, { provider: () => provider, fallback: { [key]: 'fallback' } }) screen.getByText('fallback,true') // no `undefined`, directly fallback await screen.findByText('data,false') }) it('should not return the fallback if cached', async () => { const key = createKey() function Page() { const { data } = useSWR(key, async () => { await sleep(10) return 'data' }) return <>{String(data)}</> } renderWithConfig(<Page />, { provider: () => new Map([[key, { data: 'cache' }]]), fallback: { [key]: 'fallback' } }) screen.getByText('cache') // no `undefined`, directly from cache await screen.findByText('data') }) it.skip('should be able to extend the parent cache', async () => { let parentCache const key = createKey() function Page() { const { data } = useSWR(key, async () => { await sleep(10) return 'data' }) return <>{String(data)}</> } renderWithConfig(<Page />, { provider: parentCache_ => { parentCache = parentCache_ return { set: (k, v) => parentCache_.set(k, v), get: k => { // We append `-extended` to the value returned by the parent cache. const v = parentCache_.get(k) if (v && typeof v.data !== 'undefined') { return { ...v, data: v.data + '-extended' } } return v }, delete: k => parentCache_.delete(k) } } }) expect(parentCache).toBe(SWRConfig.default.cache) screen.getByText('undefined') await screen.findByText('data-extended') }) it('should return the cache instance from the useSWRConfig', async () => { let cache function Page() { cache = useSWRConfig().cache return null } renderWithConfig(<Page />, { provider: () => provider }) expect(provider).toBe(cache) }) it('should retain the correct cache hierarchy', async () => { const key = createKey() const fetcher = async () => { await sleep(10) return 'data' } function Foo() { const { data } = useSWR(key, fetcher) return <>{String(data)}</> } function Bar() { const { data } = useSWR(key, fetcher) return <>{String(data)}</> } function Page() { const { data } = useSWR(key, fetcher) return ( <div> {String(data)}, <SWRConfig value={{ fallback: { [key]: 'fallback' } }}> <Foo /> </SWRConfig> , <Bar /> </div> ) } renderWithConfig(<Page />) screen.getByText('undefined,fallback,undefined') await screen.findByText('data,data,data') }) it('should not recreate the cache if rerendering', async () => { const createCacheProvider = jest.fn() let rerender function Page() { rerender = useState({})[1] return ( <SWRConfig value={{ provider: () => { createCacheProvider() return provider } }} /> ) } renderWithConfig(<Page />) expect(createCacheProvider).toBeCalledTimes(1) act(() => rerender({})) expect(createCacheProvider).toBeCalledTimes(1) }) }) describe('useSWR - global cache', () => { it('should return the global cache and mutate by default', async () => { let localCache, localMutate function Page() { const { cache, mutate } = useSWRConfig() localCache = cache localMutate = mutate return null } renderWithGlobalCache(<Page />) expect(localCache).toBe(SWRConfig.default.cache) expect(localMutate).toBe(globalMutate) }) it('should be able to update the cache', async () => { const fetcher = _key => 'res:' + _key const keys = [createKey(), createKey()] let cache function Page() { const [index, setIndex] = useState(0) cache = useSWRConfig().cache const { data } = useSWR(keys[index], fetcher) return <div onClick={() => setIndex(1)}>{data}</div> } renderWithGlobalCache(<Page />) await screen.findByText(fetcher(keys[0])) expect(cache.get(keys[1])?.data).toBe(undefined) fireEvent.click(screen.getByText(fetcher(keys[0]))) await act(() => sleep(10)) expect(cache.get(keys[0])?.data).toBe(fetcher(keys[0])) expect(cache.get(keys[1])?.data).toBe(fetcher(keys[1])) }) it('should correctly mutate the cached value', async () => { const key = createKey() let mutate function Page() { const { mutate: mutateWithCache } = useSWRConfig() mutate = mutateWithCache const { data } = useSWR(key, null) return <div>data:{data}</div> } renderWithGlobalCache(<Page />) screen.getByText('data:') await act(() => mutate(key, 'mutated value', false)) await screen.findByText('data:mutated value') }) it('should work with revalidateOnFocus', async () => { const key = createKey() let value = 0 function Page() { const { data } = useSWR(key, () => value++, { dedupingInterval: 0 }) return <>{String(data)}</> } renderWithGlobalCache(<Page />) screen.getByText('undefined') await screen.findByText('0') await nextTick() await focusOn(window) await nextTick() screen.getByText('1') }) it('should support fallback values', async () => { const key = createKey() function Page() { const { data } = useSWR(key, async () => { await sleep(10) return 'data' }) return <>{String(data)}</> } renderWithGlobalCache(<Page />, { fallback: { [key]: 'fallback' } }) screen.getByText('fallback') // no `undefined`, directly fallback await screen.findByText('data') }) it('should reusing the same cache instance after unmounting SWRConfig', async () => { let focusEventRegistered = false const cacheSingleton = new Map([['key', { data: 'value' }]]) function Page() { return ( <SWRConfig value={{ provider: () => cacheSingleton, initFocus: () => { focusEventRegistered = true return () => (focusEventRegistered = false) } }} > <Comp /> </SWRConfig> ) } function Comp() { const { cache } = useSWRConfig() return <>{String(cache.get('key')?.data)}</> } function Wrapper() { const [mount, setMountPage] = useState(true) return ( <> <button onClick={() => setMountPage(!mount)}>toggle</button> {mount ? <Page /> : null} </> ) } renderWithGlobalCache(<Wrapper />) await screen.findByText('value') fireEvent.click(screen.getByText('toggle')) fireEvent.click(screen.getByText('toggle')) await screen.findByText('value') expect(focusEventRegistered).toEqual(true) }) it('should correctly return the cache instance under strict mode', async () => { function Page() { // Intentionally do this. const [cache] = useState(new Map([['key', { data: 'value' }]])) return ( <SWRConfig value={{ provider: () => cache }}> <Comp /> </SWRConfig> ) } function Comp() { const { cache } = useSWRConfig() return <>{String(cache.get('key')?.data)}</> } renderWithGlobalCache( <StrictMode> <Page /> </StrictMode> ) await screen.findByText('value') }) })
the_stack
import React, { useLayoutEffect, MouseEvent } from 'react' import clsx from 'clsx' import { makeStyles, createStyles } from '@material-ui/core/styles' import List from '@material-ui/core/List' import ListItemIcon from '@material-ui/core/ListItemIcon' import ListItemText from '@material-ui/core/ListItemText' import Tooltip from '@material-ui/core/Tooltip' import Popover from '@material-ui/core/Popover' import Collapse from '@material-ui/core/Collapse' import IconExpandLess from '@material-ui/icons/ExpandLess' import IconExpandMore from '@material-ui/icons/ExpandMore' import IconSpacer from '@material-ui/icons/FiberManualRecord' import { ISidebarNavItem } from './SidebarNav' import NavItemComponent from './NavItemComponent' // ---------------------------------------------------------------------- export interface INavItemCollapsedProps { name: string link?: string Icon?: any IconStyles?: object IconClassName?: string isCollapsed?: boolean className?: string nestingLevel?: number nestingOffset?: number isNested?: boolean items?: ISidebarNavItem[] isOpen?: boolean style?: any onClick?: () => void } const NavItemCollapsed: React.FC<INavItemCollapsedProps> = (props) => { const { name, link, Icon, IconStyles = {}, IconClassName = '', isCollapsed, className, items = [], } = props const classes = useStyles() const hasChildren = items && items.length > 0 const itemsAll = getItemsAll(items) const hasChildrenAndIsActive = hasChildren && itemsAll.filter((item: ISidebarNavItem) => `#${item.link}` === window.location.hash) .length > 0 const [anchorEl, setAnchorEl] = React.useState<HTMLAnchorElement>() const handlePopoverOpen = (event: MouseEvent<HTMLAnchorElement>) => { if (!hasChildren) { return false } setAnchorEl(event.currentTarget) } const handlePopoverClose = () => { setAnchorEl(undefined) } const open = Boolean(anchorEl) const id = open ? 'sidebar-nav-item-popper' : undefined const ListItemIconInner = (!!Icon && <Icon />) || (isCollapsed && <IconSpacer className={classes.iconSpacer} />) || '' const ListItemRoot = ( <Tooltip disableFocusListener={true} disableHoverListener={false} disableTouchListener={true} title={name} placement="right" > <NavItemComponent link={link} className={clsx( classes.navItem, classes.navItemCollapsed, hasChildrenAndIsActive && 'active', open && 'open', className, )} isCollapsed={true} aria-describedby={id} onClick={handlePopoverOpen} > {!!ListItemIconInner && ( <ListItemIcon style={IconStyles} className={clsx(classes.navItemIcon, IconClassName)} > {ListItemIconInner} </ListItemIcon> )} <ListItemText primary={name} disableTypography={true} style={{ visibility: 'hidden' }} /> {hasChildren && ( <IconExpandLess className={clsx(classes.iconToggle, !open && classes.iconToggleInactive)} /> )} </NavItemComponent> </Tooltip> ) const ListItemChildren = hasChildren ? ( <Popover id={id} open={open} anchorEl={anchorEl} anchorOrigin={{ vertical: 'top', horizontal: 'right', }} transformOrigin={{ vertical: 'top', horizontal: 'left', }} onClose={handlePopoverClose} classes={{ paper: classes.navItemPoper, }} > <div className={clsx(classes.navItemChildren)}> <List component="div" disablePadding> {items.map((item) => ( <NavItem {...item} isNested={true} nestingLevel={0} isCollapsed={false} key={item.name || item.link} isOpen={open} onClick={!item.items || !item.items.length ? handlePopoverClose : undefined} /> ))} </List> </div> </Popover> ) : null return ( <div className={clsx( hasChildrenAndIsActive && classes.navItemWrapperActive, hasChildrenAndIsActive && isCollapsed && classes.navItemWrapperActiveCollapsed, )} > {ListItemRoot} {ListItemChildren} </div> ) } export interface INavItemDefaultProps { name: string link?: string Icon?: any IconStyles?: object IconClassName?: string isCollapsed?: boolean className?: string nestingLevel?: number nestingOffset?: number style?: any items?: ISidebarNavItem[] isOpen?: boolean onClick?: () => void } const NavItemDefault: React.FC<INavItemDefaultProps> = (props) => { const { name, link, Icon, IconStyles = {}, IconClassName = '', isCollapsed, nestingLevel = 0, nestingOffset = 16, className, items = [], onClick = () => {}, } = props const classes = useStyles() const hasChildren = items && items.length > 0 const itemsAll = getItemsAll(items) const hasChildrenAndIsActive = hasChildren && itemsAll.filter((item) => `#${item.link}` === window.location.hash).length > 0 const isOpen = hasChildrenAndIsActive || false const [open, setOpen] = React.useState(isOpen) // This is a work around for fixing the collapsed item poper overflow bug useLayoutEffect(() => { window.dispatchEvent(new CustomEvent('resize')) }) function handleClick() { setOpen(!open) } const ListItemIconInner = (!!Icon && <Icon />) || (isCollapsed && <IconSpacer className={classes.iconSpacer} />) || '' const nestingOffsetChildren = !isCollapsed ? nestingOffset + 16 : 16 const ListItemRoot = ( <NavItemComponent link={link} className={clsx( classes.navItem, isCollapsed && classes.navItemCollapsed, hasChildrenAndIsActive && 'active', className, )} style={{ fontSize: `${1 - 0.07 * nestingLevel}em`, paddingLeft: `${!ListItemIconInner ? nestingOffset + 40 : nestingOffset}px`, }} isCollapsed={isCollapsed} onClick={handleClick} > {!!ListItemIconInner && ( <ListItemIcon style={IconStyles} className={clsx(classes.navItemIcon, IconClassName)} > {ListItemIconInner} </ListItemIcon> )} <ListItemText primary={name} disableTypography={true} /> {hasChildren && !open && <IconExpandMore className={classes.iconToggle} />} {hasChildren && open && <IconExpandLess className={classes.iconToggle} />} </NavItemComponent> ) const ListItemChildren = hasChildren ? ( <div className={clsx(classes.navItemChildren)}> <Collapse in={open} timeout="auto" unmountOnExit> {/* <Divider /> */} <List component="div" disablePadding> {items.map((item) => ( <NavItem {...item} isNested={true} nestingLevel={nestingLevel + 1} isCollapsed={isCollapsed} key={item.name || item.link} isOpen={open} nestingOffset={nestingOffsetChildren} /> ))} </List> </Collapse> </div> ) : null return ( <div className={clsx( hasChildrenAndIsActive && classes.navItemWrapperActive, hasChildrenAndIsActive && isCollapsed && classes.navItemWrapperActiveCollapsed, )} onClick={onClick} > {ListItemRoot} {ListItemChildren} </div> ) } const NavItem: React.FC<INavItemCollapsedProps | INavItemDefaultProps> = (props) => { if (props.isCollapsed) { return <NavItemCollapsed {...props} /> } else { return <NavItemDefault {...props} /> } } const useStyles = makeStyles((theme) => createStyles({ // nested: { // paddingLeft: theme.spacing(10), // }, navItemWrapper: { position: 'relative', }, navItemWrapperActive: { // background: 'rgba(0, 0, 0, 0.08)', }, navItemWrapperActiveCollapsed: { background: 'rgba(0, 0, 0, 0.08)', }, navItem: { color: '#fff', position: 'relative', transition: 'background .23s ease', '& a': { color: 'inherit', }, '&.active:not(.open)': { color: theme.palette.primary.main, // background: 'rgba(0, 0, 0, 0.08)', '& .MuiListItemIcon-root': { // color: '#fff', color: theme.palette.primary.main, }, }, '&.open': { color: '#fff', '& .MuiListItemIcon-root': { color: '#fff', }, }, }, navItemPoper: { width: theme.sidebar.width, color: theme.sidebar.color, background: theme.sidebar.background, }, navItemChildren: { transition: 'background .23s ease', // position: 'absolute', }, navItemChildrenActive: { // background: 'rgba(0, 0, 0, 0.1)', }, navItemCollapsed: { whiteSpace: 'nowrap', flexWrap: 'nowrap', width: theme.sidebar.widthCollapsed, '& $iconToggle': { position: 'absolute', // bottom: -1, fontSize: 14, top: '50%', marginTop: '-0.5em', transform: 'rotate(90deg)', right: '3px', }, '&.active': { background: 'rgba(0, 0, 0, 0.08)', }, }, navItemIcon: { minWidth: 40, }, iconToggle: {}, iconToggleInactive: { opacity: 0.35, }, iconSpacer: { fontSize: 13, marginLeft: 6, }, }), ) // ---------------------- // Flattened array of all children function getItemsAll(items: ISidebarNavItem[]): ISidebarNavItem[] { return items.reduce((allItems: ISidebarNavItem[], item: ISidebarNavItem) => { // let res = allItems.concat([item]) if (item.items && item.items.length) { return allItems.concat([item], getItemsAll(item.items)) } else { return allItems.concat([item]) } }, []) } export default NavItem
the_stack
import * as assert from 'assert'; import { values } from 'bitcode-builder'; import { Abbr, BitStream, BlockInfoMap } from '../bitstream'; import { BLOCK_ID, FIXED, FUNCTION_CODE, VALUE_SYMTAB_CODE, VBR, } from '../constants'; import { encodeBinopType, encodeCallFlags, encodeCastType, encodeICmpPredicate, encodeSigned, } from '../encoding'; import { Enumerator } from '../enumerator'; import { Block } from './base'; import { ConstantBlock } from './constant'; import { MetadataBlock } from './metadata'; import { MetadataAttachmentBlock } from './metadata-attachment'; import { TypeBlock } from './type'; import constants = values.constants; import instructions = values.instructions; import BasicBlock = values.BasicBlock; const FUNCTION_ABBR_ID_WIDTH = 6; const VALUE_SYMTAB_ABBR_ID_WIDTH = 3; export class FunctionBlock extends Block { public static buildInfo(info: BlockInfoMap): void { info.set(BLOCK_ID.FUNCTION, [ new Abbr('declareblocks', [ Abbr.literal(FUNCTION_CODE.DECLAREBLOCKS), Abbr.vbr(VBR.BLOCK_COUNT), ]), // Terminators new Abbr('ret_void', [ Abbr.literal(FUNCTION_CODE.INST_RET), ]), new Abbr('ret', [ Abbr.literal(FUNCTION_CODE.INST_RET), Abbr.vbr(VBR.VALUE_INDEX), ]), new Abbr('jump', [ Abbr.literal(FUNCTION_CODE.INST_BR), Abbr.vbr(VBR.BLOCK_INDEX), // target ]), new Abbr('branch', [ Abbr.literal(FUNCTION_CODE.INST_BR), Abbr.vbr(VBR.BLOCK_INDEX), // onTrue Abbr.vbr(VBR.BLOCK_INDEX), // onFalse Abbr.vbr(VBR.VALUE_INDEX), // condition ]), new Abbr('unreachable', [ Abbr.literal(FUNCTION_CODE.INST_UNREACHABLE), ]), // Regular instructions new Abbr('cast', [ Abbr.literal(FUNCTION_CODE.INST_CAST), Abbr.vbr(VBR.VALUE_INDEX), // value Abbr.vbr(VBR.TYPE_INDEX), // to type Abbr.fixed(FIXED.CAST_TYPE), ]), new Abbr('binop', [ Abbr.literal(FUNCTION_CODE.INST_BINOP), Abbr.vbr(VBR.VALUE_INDEX), // left Abbr.vbr(VBR.VALUE_INDEX), // right Abbr.fixed(FIXED.BINOP_TYPE), ]), new Abbr('icmp', [ Abbr.literal(FUNCTION_CODE.INST_CMP), Abbr.vbr(VBR.VALUE_INDEX), // left Abbr.vbr(VBR.VALUE_INDEX), // right Abbr.fixed(FIXED.PREDICATE), // predicate ]), new Abbr('load', [ Abbr.literal(FUNCTION_CODE.INST_LOAD), Abbr.vbr(VBR.TYPE_INDEX), // resultTy Abbr.vbr(VBR.VALUE_INDEX), // ptr Abbr.vbr(VBR.ALIGNMENT), // alignment Abbr.fixed(FIXED.BOOL), // isVolatile ]), new Abbr('store', [ Abbr.literal(FUNCTION_CODE.INST_STORE), Abbr.vbr(VBR.VALUE_INDEX), // ptr Abbr.vbr(VBR.VALUE_INDEX), // value Abbr.vbr(VBR.ALIGNMENT), // alignment Abbr.fixed(FIXED.BOOL), // isVolatile ]), new Abbr('getelementptr', [ Abbr.literal(FUNCTION_CODE.INST_GEP), Abbr.fixed(FIXED.BOOL), // inbounds Abbr.vbr(VBR.TYPE_INDEX), // sourceElementType Abbr.array(Abbr.vbr(VBR.VALUE_INDEX)), // operands ]), new Abbr('extractvalue', [ Abbr.literal(FUNCTION_CODE.INST_EXTRACTVAL), Abbr.vbr(VBR.VALUE_INDEX), // aggr Abbr.vbr(VBR.INTEGER), // index ]), new Abbr('insertvalue', [ Abbr.literal(FUNCTION_CODE.INST_INSERTVAL), Abbr.vbr(VBR.VALUE_INDEX), // aggr Abbr.vbr(VBR.VALUE_INDEX), // element Abbr.vbr(VBR.INTEGER), // index ]), ]); info.set(BLOCK_ID.VALUE_SYMTAB, [ new Abbr('bbentry', [ Abbr.literal(VALUE_SYMTAB_CODE.BBENTRY), Abbr.vbr(VBR.BLOCK_INDEX), Abbr.array(Abbr.char6()), ]), new Abbr('entry', [ Abbr.literal(VALUE_SYMTAB_CODE.ENTRY), Abbr.vbr(VBR.VALUE_INDEX), Abbr.array(Abbr.char6()), ]), ]); } constructor(private readonly enumerator: Enumerator, private readonly typeBlock: TypeBlock, private readonly fn: constants.Func) { super(); } // TODO(indutny): metadata public build(writer: BitStream): void { super.build(writer); writer.enterBlock(BLOCK_ID.FUNCTION, FUNCTION_ABBR_ID_WIDTH); const fn = this.fn; const fnConstants = new ConstantBlock(this.enumerator, this.typeBlock, this.enumerator.getFunctionConstants(fn)); fnConstants.build(writer); const fnMetadata = new MetadataBlock(this.enumerator, this.typeBlock, this.enumerator.getFunctionMetadata(fn)); fnMetadata.build(writer); const blocks: ReadonlyArray<BasicBlock> = Array.from(fn); const blockIds: Map<BasicBlock, number> = new Map(); blocks.forEach((bb, index) => blockIds.set(bb, index)); writer.writeRecord('declareblocks', [ blocks.length ]); for (const bb of blocks) { for (const instr of bb) { this.buildInstruction(writer, instr, blockIds); } } this.buildSymtab(writer, blocks); const attachment = new MetadataAttachmentBlock(fnMetadata, fn, this.enumerator.getMetadataKinds()); attachment.build(writer); writer.endBlock(BLOCK_ID.FUNCTION); // Reset last emitted id this.enumerator.leaveFunction(); } // TODO(indutny): metadata private buildInstruction(writer: BitStream, instr: instructions.Instruction, blockIds: Map<BasicBlock, number>): void { this.enumerator.checkValueOrder(instr); const instrId = this.enumerator.get(instr); const relativeId = (operand: values.Value): number => { return instrId - this.enumerator.get(operand); }; // TODO(indutny): support forward references in non-Phi instructions // Terminators if (instr instanceof instructions.Ret) { if (instr.operand === undefined) { writer.writeRecord('ret_void', []); } else { writer.writeRecord('ret', [ relativeId(instr.operand) ]); } } else if (instr instanceof instructions.Jump) { assert(blockIds.has(instr.target), 'Unknown block'); writer.writeRecord('jump', [ blockIds.get(instr.target)!, ]); } else if (instr instanceof instructions.Branch) { assert(blockIds.has(instr.onTrue), 'Unknown block'); assert(blockIds.has(instr.onFalse), 'Unknown block'); writer.writeRecord('branch', [ blockIds.get(instr.onTrue)!, blockIds.get(instr.onFalse)!, relativeId(instr.condition), ]); } else if (instr instanceof instructions.Switch) { assert(blockIds.has(instr.otherwise), 'Unknown block'); assert(instr.cases.every((c) => blockIds.has(c.block)), 'Unknown block'); const operands = [ this.typeBlock.get(instr.condition.ty), relativeId(instr.condition), blockIds.get(instr.otherwise)!, ]; for (const c of instr.cases) { operands.push(this.enumerator.get(c.value), blockIds.get(c.block)!); } writer.writeUnabbrRecord(FUNCTION_CODE.INST_SWITCH, operands); } else if (instr instanceof instructions.Unreachable) { writer.writeRecord('unreachable', []); // Phi } else if (instr instanceof instructions.Phi) { const operands = [ this.typeBlock.get(instr.ty) ]; const edges = instr.edges; for (const edge of edges) { assert(blockIds.has(edge.fromBlock), `Unknown PHI fromBlock: "${edge.fromBlock}" in ` + `"${edge.fromBlock.parent}"`); operands.push(encodeSigned(relativeId(edge.value))); operands.push(blockIds.get(edge.fromBlock)!); } writer.writeUnabbrRecord(FUNCTION_CODE.INST_PHI, operands); // Regular instructions } else if (instr instanceof instructions.Cast) { writer.writeRecord('cast', [ relativeId(instr.operand), this.typeBlock.get(instr.targetType), encodeCastType(instr.castType), ]); } else if (instr instanceof instructions.Binop) { writer.writeRecord('binop', [ relativeId(instr.left), relativeId(instr.right), encodeBinopType(instr.binopType), ]); } else if (instr instanceof instructions.ICmp) { writer.writeRecord('icmp', [ relativeId(instr.left), relativeId(instr.right), encodeICmpPredicate(instr.predicate), ]); } else if (instr instanceof instructions.Load) { writer.writeRecord('load', [ relativeId(instr.ptr), this.typeBlock.get(instr.ty), instr.alignment === undefined ? 0 : 1 + Math.log2(instr.alignment), instr.isVolatile ? 1 : 0, ]); } else if (instr instanceof instructions.Store) { writer.writeRecord('store', [ relativeId(instr.ptr), relativeId(instr.value), instr.alignment === undefined ? 0 : 1 + Math.log2(instr.alignment), instr.isVolatile ? 1 : 0, ]); } else if (instr instanceof instructions.GetElementPtr) { const operands = Array.from(instr).map(relativeId); writer.writeRecord('getelementptr', [ instr.inbounds ? 1 : 0, this.typeBlock.get(instr.ptr.ty.toPointer().to), operands, ]); } else if (instr instanceof instructions.InsertValue) { writer.writeRecord('insertvalue', [ relativeId(instr.aggr), relativeId(instr.element), instr.index, ]); } else if (instr instanceof instructions.ExtractValue) { writer.writeRecord('extractvalue', [ relativeId(instr.aggr), instr.index, ]); } else if (instr instanceof instructions.Call) { const operands = []; // TODO(indutny): return attributes operands.push(0); // attributes operands.push(encodeCallFlags(instr)); // TODO(indutny): optimization flags operands.push(this.typeBlock.get(instr.calleeSignature)); operands.push(relativeId(instr.callee)); for (const arg of instr.args) { operands.push(relativeId(arg)); } writer.writeUnabbrRecord(FUNCTION_CODE.INST_CALL, operands); } else { throw new Error(`Unsupported instruction: "${instr.opcode}"`); } } private buildSymtab(writer: BitStream, blocks: ReadonlyArray<BasicBlock>) { // Write block/param names writer.enterBlock(BLOCK_ID.VALUE_SYMTAB, VALUE_SYMTAB_ABBR_ID_WIDTH); blocks.forEach((bb, index) => { if (bb.name === undefined) { return; } writer.writeRecord('bbentry', [ index, bb.name ]); }); this.fn.args.forEach((arg, index) => { writer.writeRecord('entry', [ this.enumerator.get(arg), arg.name ]); }); writer.endBlock(BLOCK_ID.VALUE_SYMTAB); } }
the_stack
import { Rhum } from "../../deps.ts"; import * as Drash from "../../../mod.ts"; Rhum.testPlan("http/request_test.ts", () => { Rhum.testSuite("accepts()", () => { acceptsTests(); }); Rhum.testSuite("getCookie()", () => { getCookieTests(); }); Rhum.testSuite("bodyParam()", () => { bodyTests(); }); Rhum.testSuite("pathParam()", () => { paramTests(); }); Rhum.testSuite("queryParam()", () => { queryTests(); }); }); Rhum.run(); //////////////////////////////////////////////////////////////////////////////// // FILE MARKER - TEST CASES //////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function acceptsTests() { Rhum.testCase( "accepts the single type if it is present in the header", () => { const req = new Request("https://drash.land", { headers: { Accept: "application/json;text/html", }, }); const request = new Drash.Request( req, new Map(), ); let actual; actual = request.accepts("application/json"); Rhum.asserts.assertEquals(actual, true); actual = request.accepts("text/html"); Rhum.asserts.assertEquals(actual, true); }, ); Rhum.testCase( "rejects the single type if it is not present in the header", () => { const req = new Request("https://drash.land", { headers: { Accept: "application/json;text/html", }, }); const request = new Drash.Request( req, new Map(), ); const actual = request.accepts("text/xml"); Rhum.asserts.assertEquals(actual, false); }, ); } function getCookieTests() { Rhum.testCase("Returns the cookie value if it exists", () => { const req = new Request("https://drash.land", { headers: { Accept: "application/json;text/html", Cookie: "test_cookie=test_cookie_value", credentials: "include", }, }); const request = new Drash.Request( req, new Map(), ); const cookieValue = request.getCookie("test_cookie"); Rhum.asserts.assertEquals(cookieValue, "test_cookie_value"); }); Rhum.testCase("Returns undefined if the cookie does not exist", () => { const req = new Request("https://drash.land", { headers: { Accept: "application/json;text/html", Cookie: "test_cookie=test_cookie_value", credentials: "include", }, }); const request = new Drash.Request( req, new Map(), ); const cookieValue = request.getCookie("cookie_doesnt_exist"); Rhum.asserts.assertEquals(cookieValue, undefined); }); } function bodyTests() { Rhum.testCase("Can return multiple files", async () => { const formData = new FormData(); const file1 = new Blob([JSON.stringify({ hello: "world" }, null, 2)], { type: "application/json", }); const file2 = new Blob([JSON.stringify({ hello: "world" }, null, 2)], { type: "application/json", }); formData.append("foo[]", file1, "hello.json"); formData.append("foo[]", file2, "world.json"); const serverRequest = new Request("https://drash.land", { body: formData, method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), ); Rhum.asserts.assertEquals(request.bodyParam("foo"), [ { content: '{\n "hello": "world"\n}', size: 22, type: "application/json", filename: "hello.json", }, { content: '{\n "hello": "world"\n}', size: 22, type: "application/json", filename: "world.json", }, ]); // make sure that if a requets has multiple files, we can get each one eh <input type=file name=uploads[] /> }); // Reason: `this.request.getBodyParam()` didn't work for multipart/form-data requests Rhum.testCase("Returns the file object if the file exists", async () => { const formData = new FormData(); const file = new Blob([JSON.stringify({ hello: "world" }, null, 2)], { type: "application/json", }); formData.append("foo", file, "hello.json"); const serverRequest = new Request("https://drash.land", { body: formData, method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), ); Rhum.asserts.assertEquals(request.bodyParam("foo"), { content: '{\n "hello": "world"\n}', size: 22, type: "application/json", filename: "hello.json", }); }); Rhum.testCase( "Returns the value of a normal field for formdata requests", async () => { const formData = new FormData(); formData.append("user", "Drash"); const req = new Request("https://drash.land", { body: formData, method: "POST", }); const request = await Drash.Request.create( req, new Map(), ); Rhum.asserts.assertEquals(request.bodyParam("user"), "Drash"); }, ); Rhum.testCase("Returns undefined if the file does not exist", async () => { const formData = new FormData(); const file = new Blob([JSON.stringify({ hello: "world" }, null, 2)], { type: "application/json", }); formData.append("foo[]", file, "hello.json"); const serverRequest = new Request("https://drash.land", { body: formData, method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), ); Rhum.asserts.assertEquals(request.bodyParam("dontexist"), undefined); }); Rhum.testCase( "Returns the value for the parameter when the data exists for application/json", async () => { const req = new Request("https://drash.land", { headers: { "Content-Type": "application/json", }, body: JSON.stringify({ hello: "world", }), method: "POST", }); const request = await Drash.Request.create( req, new Map(), ); const actual = request.bodyParam("hello"); Rhum.asserts.assertEquals("world", actual); }, ); Rhum.testCase( "Returns null when the data doesn't exist for application/json", async () => { const serverRequest = new Request("https://drash.land", { headers: { "Content-Type": "application/json", }, body: JSON.stringify({ hello: "world", }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), ); const actual = request.bodyParam("dont_exist"); Rhum.asserts.assertEquals(undefined, actual); }, ); Rhum.testCase( "Returns the value for the parameter when it exists and request is multipart/form-data when using generics", async () => { const formData = new FormData(); const file = new Blob([JSON.stringify({ hello: "world" }, null, 2)], { type: "application/json", }); formData.append("foo", file, "hello.json"); formData.append("user", "drash"); const serverRequest = new Request("https://drash.land", { body: formData, method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), ); const param = request.bodyParam<{ content: string; filename: string; size: string; type: string; }>("foo"); Rhum.asserts.assertEquals(param!.content, '{\n "hello": "world"\n}'); Rhum.asserts.assertEquals(request.bodyParam("user"), "drash"); }, ); // Before the date of 5th, Oct 2020, type errors were thrown for objects because the return value of `getBodyParam` was either a string or null Rhum.testCase("Can handle when a body param is an object", async () => { const serverRequest = new Request("https://drash.land", { headers: { "Content-Type": "application/json", }, body: JSON.stringify({ user: { name: "Edward", location: "UK", }, }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), ); const actual = request.bodyParam<{ name: string; location: string; }>("user")!; Rhum.asserts.assertEquals({ name: "Edward", location: "UK", }, actual); const name = actual.name; // Ensuring we can access it and TS doesn't throw errors Rhum.asserts.assertEquals(name, "Edward"); }); Rhum.testCase("Can handle when a body param is an array", async () => { const serverRequest = new Request("https://drash.land", { headers: { "Content-Type": "application/json", }, body: JSON.stringify({ usernames: ["Edward", "John Smith", "Lord Voldemort", "Count Dankula"], }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), ); const actual = request.bodyParam("usernames"); Rhum.asserts.assertEquals( ["Edward", "John Smith", "Lord Voldemort", "Count Dankula"], actual, ); const firstName = (actual as Array<string>)[0]; Rhum.asserts.assertEquals(firstName, "Edward"); }); Rhum.testCase("Can handle when a body param is a boolean", async () => { const serverRequest = new Request("https://drash.land", { headers: { "Content-Type": "application/json", }, body: JSON.stringify({ authenticated: false, }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), ); const actual = request.bodyParam("authenticated"); Rhum.asserts.assertEquals(actual, false); const authenticated = (actual as boolean); Rhum.asserts.assertEquals(authenticated, false); }); } function paramTests() { Rhum.testCase( "Returns the value for the header param when it exists", () => { const serverRequest = new Request("https://drash.land"); const request = new Drash.Request( serverRequest, new Map().set("hello", "world"), ); const actual = request.pathParam("hello"); Rhum.asserts.assertEquals("world", actual); }, ); Rhum.testCase( "Returns null when the path param doesn't exist", () => { const serverRequest = new Request("https://drash.land"); const request = new Drash.Request( serverRequest, new Map().set("hello", "world"), ); const actual = request.pathParam("dont-exist"); Rhum.asserts.assertEquals(actual, undefined); }, ); } function queryTests() { Rhum.testCase( "Returns the value for the query param when it exists", () => { const serverRequest = new Request("https://drash.land/?hello=world"); const request = new Drash.Request( serverRequest, new Map(), ); const actual = request.queryParam("hello"); Rhum.asserts.assertEquals(actual, "world"); }, ); Rhum.testCase( "Returns null when the query data doesn't exist", () => { const serverRequest = new Request("https://drash.land/?hello=world"); const request = new Drash.Request( serverRequest, new Map(), ); const actual = request.queryParam("dont_exist"); Rhum.asserts.assertEquals(undefined, actual); }, ); }
the_stack
import * as coreClient from "@azure/core-client"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; import * as Parameters from "./models/parameters"; import * as Mappers from "./models/mappers"; import { GeneratedClientContext } from "./generatedClientContext"; import { GeneratedClientOptionalParams, OperationInfo, GeneratedClientGetOperationsNextOptionalParams, GeneratedClientGetOperationsOptionalParams, ModelSummary, GeneratedClientGetModelsNextOptionalParams, GeneratedClientGetModelsOptionalParams, ContentType, GeneratedClientAnalyzeDocument$binaryOptionalParams, GeneratedClientAnalyzeDocument$jsonOptionalParams, GeneratedClientAnalyzeDocumentResponse, GeneratedClientGetAnalyzeDocumentResultOptionalParams, GeneratedClientGetAnalyzeDocumentResultResponse, BuildDocumentModelRequest, GeneratedClientBuildDocumentModelOptionalParams, GeneratedClientBuildDocumentModelResponse, ComposeDocumentModelRequest, GeneratedClientComposeDocumentModelOptionalParams, GeneratedClientComposeDocumentModelResponse, AuthorizeCopyRequest, GeneratedClientAuthorizeCopyDocumentModelOptionalParams, GeneratedClientAuthorizeCopyDocumentModelResponse, CopyAuthorization, GeneratedClientCopyDocumentModelToOptionalParams, GeneratedClientCopyDocumentModelToResponse, GeneratedClientGetOperationsResponse, GeneratedClientGetOperationOptionalParams, GeneratedClientGetOperationResponse, GeneratedClientGetModelsResponse, GeneratedClientGetModelOptionalParams, GeneratedClientGetModelResponse, GeneratedClientDeleteModelOptionalParams, GeneratedClientGetInfoOptionalParams, GeneratedClientGetInfoResponse, GeneratedClientGetOperationsNextResponse, GeneratedClientGetModelsNextResponse } from "./models"; /// <reference lib="esnext.asynciterable" /> export class GeneratedClient extends GeneratedClientContext { /** * Initializes a new instance of the GeneratedClient class. * @param endpoint Supported Cognitive Services endpoints (protocol and hostname, for example: * https://westus2.api.cognitive.microsoft.com). * @param options The parameter options */ constructor(endpoint: string, options?: GeneratedClientOptionalParams) { super(endpoint, options); } /** * Lists all operations. * @param options The options parameters. */ public listOperations( options?: GeneratedClientGetOperationsOptionalParams ): PagedAsyncIterableIterator<OperationInfo> { const iter = this.getOperationsPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getOperationsPagingPage(options); } }; } private async *getOperationsPagingPage( options?: GeneratedClientGetOperationsOptionalParams ): AsyncIterableIterator<OperationInfo[]> { let result = await this._getOperations(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getOperationsNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *getOperationsPagingAll( options?: GeneratedClientGetOperationsOptionalParams ): AsyncIterableIterator<OperationInfo> { for await (const page of this.getOperationsPagingPage(options)) { yield* page; } } /** * List all models * @param options The options parameters. */ public listModels( options?: GeneratedClientGetModelsOptionalParams ): PagedAsyncIterableIterator<ModelSummary> { const iter = this.getModelsPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getModelsPagingPage(options); } }; } private async *getModelsPagingPage( options?: GeneratedClientGetModelsOptionalParams ): AsyncIterableIterator<ModelSummary[]> { let result = await this._getModels(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getModelsNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *getModelsPagingAll( options?: GeneratedClientGetModelsOptionalParams ): AsyncIterableIterator<ModelSummary> { for await (const page of this.getModelsPagingPage(options)) { yield* page; } } /** * Analyzes document with model. * @param modelId Unique model name. * @param contentType Upload file type * @param options The options parameters. */ analyzeDocument( modelId: string, contentType: ContentType, options?: GeneratedClientAnalyzeDocument$binaryOptionalParams ): Promise<GeneratedClientAnalyzeDocumentResponse>; /** * Analyzes document with model. * @param modelId Unique model name. * @param contentType Body Parameter content-type * @param options The options parameters. */ analyzeDocument( modelId: string, contentType: "application/json", options?: GeneratedClientAnalyzeDocument$jsonOptionalParams ): Promise<GeneratedClientAnalyzeDocumentResponse>; /** * Analyzes document with model. * @param args Includes all the parameters for this operation. */ analyzeDocument( ...args: | [ string, ContentType, GeneratedClientAnalyzeDocument$binaryOptionalParams? ] | [ string, "application/json", GeneratedClientAnalyzeDocument$jsonOptionalParams? ] ): Promise<GeneratedClientAnalyzeDocumentResponse> { let operationSpec: coreClient.OperationSpec; let operationArguments: coreClient.OperationArguments; let options; if ( args[1] === "application/octet-stream" || args[1] === "application/pdf" || args[1] === "image/bmp" || args[1] === "image/jpeg" || args[1] === "image/png" || args[1] === "image/tiff" ) { operationSpec = analyzeDocument$binaryOperationSpec; operationArguments = { modelId: args[0], contentType: args[1], options: args[2] }; options = args[2]; } else if (args[1] === "application/json") { operationSpec = analyzeDocument$jsonOperationSpec; operationArguments = { modelId: args[0], contentType: args[1], options: args[2] }; options = args[2]; } else { throw new TypeError( `"contentType" must be a valid value but instead was "${args[1]}".` ); } operationArguments.options = options || {}; return this.sendOperationRequest(operationArguments, operationSpec); } /** * Gets the result of document analysis. * @param modelId Unique model name. * @param resultId Analyze operation result ID. * @param options The options parameters. */ getAnalyzeDocumentResult( modelId: string, resultId: string, options?: GeneratedClientGetAnalyzeDocumentResultOptionalParams ): Promise<GeneratedClientGetAnalyzeDocumentResultResponse> { return this.sendOperationRequest( { modelId, resultId, options }, getAnalyzeDocumentResultOperationSpec ); } /** * Builds a custom document analysis model. * @param buildRequest Building request parameters. * @param options The options parameters. */ buildDocumentModel( buildRequest: BuildDocumentModelRequest, options?: GeneratedClientBuildDocumentModelOptionalParams ): Promise<GeneratedClientBuildDocumentModelResponse> { return this.sendOperationRequest( { buildRequest, options }, buildDocumentModelOperationSpec ); } /** * Creates a new model from document types of existing models. * @param composeRequest Compose request parameters. * @param options The options parameters. */ composeDocumentModel( composeRequest: ComposeDocumentModelRequest, options?: GeneratedClientComposeDocumentModelOptionalParams ): Promise<GeneratedClientComposeDocumentModelResponse> { return this.sendOperationRequest( { composeRequest, options }, composeDocumentModelOperationSpec ); } /** * Generates authorization to copy a model to this location with specified modelId and optional * description. * @param authorizeCopyRequest Authorize copy request parameters. * @param options The options parameters. */ authorizeCopyDocumentModel( authorizeCopyRequest: AuthorizeCopyRequest, options?: GeneratedClientAuthorizeCopyDocumentModelOptionalParams ): Promise<GeneratedClientAuthorizeCopyDocumentModelResponse> { return this.sendOperationRequest( { authorizeCopyRequest, options }, authorizeCopyDocumentModelOperationSpec ); } /** * Copies model to the target resource, region, and modelId. * @param modelId Unique model name. * @param copyToRequest Copy to request parameters. * @param options The options parameters. */ copyDocumentModelTo( modelId: string, copyToRequest: CopyAuthorization, options?: GeneratedClientCopyDocumentModelToOptionalParams ): Promise<GeneratedClientCopyDocumentModelToResponse> { return this.sendOperationRequest( { modelId, copyToRequest, options }, copyDocumentModelToOperationSpec ); } /** * Lists all operations. * @param options The options parameters. */ private _getOperations( options?: GeneratedClientGetOperationsOptionalParams ): Promise<GeneratedClientGetOperationsResponse> { return this.sendOperationRequest({ options }, getOperationsOperationSpec); } /** * Gets operation info. * @param operationId Unique operation ID. * @param options The options parameters. */ getOperation( operationId: string, options?: GeneratedClientGetOperationOptionalParams ): Promise<GeneratedClientGetOperationResponse> { return this.sendOperationRequest( { operationId, options }, getOperationOperationSpec ); } /** * List all models * @param options The options parameters. */ private _getModels( options?: GeneratedClientGetModelsOptionalParams ): Promise<GeneratedClientGetModelsResponse> { return this.sendOperationRequest({ options }, getModelsOperationSpec); } /** * Gets detailed model information. * @param modelId Unique model name. * @param options The options parameters. */ getModel( modelId: string, options?: GeneratedClientGetModelOptionalParams ): Promise<GeneratedClientGetModelResponse> { return this.sendOperationRequest( { modelId, options }, getModelOperationSpec ); } /** * Deletes model. * @param modelId Unique model name. * @param options The options parameters. */ deleteModel( modelId: string, options?: GeneratedClientDeleteModelOptionalParams ): Promise<void> { return this.sendOperationRequest( { modelId, options }, deleteModelOperationSpec ); } /** * Return basic info about the current resource. * @param options The options parameters. */ getInfo( options?: GeneratedClientGetInfoOptionalParams ): Promise<GeneratedClientGetInfoResponse> { return this.sendOperationRequest({ options }, getInfoOperationSpec); } /** * GetOperationsNext * @param nextLink The nextLink from the previous successful call to the GetOperations method. * @param options The options parameters. */ private _getOperationsNext( nextLink: string, options?: GeneratedClientGetOperationsNextOptionalParams ): Promise<GeneratedClientGetOperationsNextResponse> { return this.sendOperationRequest( { nextLink, options }, getOperationsNextOperationSpec ); } /** * GetModelsNext * @param nextLink The nextLink from the previous successful call to the GetModels method. * @param options The options parameters. */ private _getModelsNext( nextLink: string, options?: GeneratedClientGetModelsNextOptionalParams ): Promise<GeneratedClientGetModelsNextResponse> { return this.sendOperationRequest( { nextLink, options }, getModelsNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const analyzeDocument$binaryOperationSpec: coreClient.OperationSpec = { path: "/documentModels/{modelId}:analyze", httpMethod: "POST", responses: { 202: { headersMapper: Mappers.GeneratedClientAnalyzeDocumentHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.analyzeRequest, queryParameters: [ Parameters.pages, Parameters.locale, Parameters.stringIndexType, Parameters.apiVersion ], urlParameters: [Parameters.endpoint, Parameters.modelId], headerParameters: [Parameters.contentType, Parameters.accept], mediaType: "binary", serializer }; const analyzeDocument$jsonOperationSpec: coreClient.OperationSpec = { path: "/documentModels/{modelId}:analyze", httpMethod: "POST", responses: { 202: { headersMapper: Mappers.GeneratedClientAnalyzeDocumentHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.analyzeRequest1, queryParameters: [ Parameters.pages, Parameters.locale, Parameters.stringIndexType, Parameters.apiVersion ], urlParameters: [Parameters.endpoint, Parameters.modelId], headerParameters: [Parameters.contentType1, Parameters.accept1], mediaType: "json", serializer }; const getAnalyzeDocumentResultOperationSpec: coreClient.OperationSpec = { path: "/documentModels/{modelId}/analyzeResults/{resultId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AnalyzeResultOperation }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.modelId, Parameters.resultId], headerParameters: [Parameters.accept1], serializer }; const buildDocumentModelOperationSpec: coreClient.OperationSpec = { path: "/documentModels:build", httpMethod: "POST", responses: { 202: { headersMapper: Mappers.GeneratedClientBuildDocumentModelHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.buildRequest, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.accept1, Parameters.contentType2], mediaType: "json", serializer }; const composeDocumentModelOperationSpec: coreClient.OperationSpec = { path: "/documentModels:compose", httpMethod: "POST", responses: { 202: { headersMapper: Mappers.GeneratedClientComposeDocumentModelHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.composeRequest, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.accept1, Parameters.contentType2], mediaType: "json", serializer }; const authorizeCopyDocumentModelOperationSpec: coreClient.OperationSpec = { path: "/documentModels:authorizeCopy", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.CopyAuthorization }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.authorizeCopyRequest, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.accept1, Parameters.contentType2], mediaType: "json", serializer }; const copyDocumentModelToOperationSpec: coreClient.OperationSpec = { path: "/documentModels/{modelId}:copyTo", httpMethod: "POST", responses: { 202: { headersMapper: Mappers.GeneratedClientCopyDocumentModelToHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.copyToRequest, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.modelId], headerParameters: [Parameters.accept1, Parameters.contentType2], mediaType: "json", serializer }; const getOperationsOperationSpec: coreClient.OperationSpec = { path: "/operations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GetOperationsResponse }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.accept1], serializer }; const getOperationOperationSpec: coreClient.OperationSpec = { path: "/operations/{operationId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GetOperationResponse }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.operationId], headerParameters: [Parameters.accept1], serializer }; const getModelsOperationSpec: coreClient.OperationSpec = { path: "/documentModels", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GetModelsResponse }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.accept1], serializer }; const getModelOperationSpec: coreClient.OperationSpec = { path: "/documentModels/{modelId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ModelInfo }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.modelId], headerParameters: [Parameters.accept1], serializer }; const deleteModelOperationSpec: coreClient.OperationSpec = { path: "/documentModels/{modelId}", httpMethod: "DELETE", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.modelId], headerParameters: [Parameters.accept1], serializer }; const getInfoOperationSpec: coreClient.OperationSpec = { path: "/info", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GetInfoResponse }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.accept1], serializer }; const getOperationsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GetOperationsResponse }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.nextLink], headerParameters: [Parameters.accept1], serializer }; const getModelsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GetModelsResponse }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.nextLink], headerParameters: [Parameters.accept1], serializer };
the_stack
import React, { Component } from 'react' import { StyleSheet, View, Image, Dimensions, TouchableNativeFeedback, KeyboardAvoidingView, InteractionManager, Keyboard, TextInput, Animated, StatusBar, Picker } from 'react-native' import Ionicons from 'react-native-vector-icons/Ionicons' import { standardColor, accentColor } from '../../constant/colorConfig' import { getNewQaAPI, getQaEditAPI } from '../../dao' import { postCreateTopic } from '../../dao/post' import Emotion from '../../component/Emotion' let toolbarActions = [ ] declare var global let AnimatedKeyboardAvoidingView = Animated.createAnimatedComponent(KeyboardAvoidingView) let screen = Dimensions.get('window') let { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = screen SCREEN_HEIGHT = SCREEN_HEIGHT - (StatusBar.currentHeight || 0) + 1 let CIRCLE_SIZE = 56 const emotionToolbarHeight = 190 let config = { tension: 30, friction: 7 } export default class NewTopic extends Component<any, any> { constructor(props) { super(props) const { params = {} } = this.props.navigation.state // console.log(params) this.state = { icon: false, title: '', hb: '10', psngameid: '', node: '', content: '', type: 'game', data: { hb: [], game: [], node: [] }, id: '', key: 'addqa', isLoading: true, openVal: new Animated.Value(1), marginTop: new Animated.Value(0), toolbarOpenVal: new Animated.Value(0), modalVisible: false, selection: { start: 0, end: 0 } } } componentDidMount() { const { modeInfo } = this.props.screenProps // Animated.spring(this.state.openVal, { toValue: 1, ...config }).start(() => { if (modeInfo.settingInfo.psnid === '') { global.toast('请首先登录') this.props.navigation.goBack() return } // }); } _pressButton = (callback) => { const { marginTop } = this.state let value = marginTop._value if (Math.abs(value) >= 50) { Animated.spring(marginTop, { toValue: 0, ...config }).start() return true } this.content.clear() Keyboard.dismiss() // Animated.spring(openVal, { toValue: 0, ...config }).start(() => { typeof callback === 'function' && callback() this.props.navigation.goBack() // }); } content: any = false shouldShowEmotion: any = false keyboardDidHideListener: any = false keyboardDidShowListener: any = false removeListener: any = false isToolbarShowing: any = false isKeyboardShowing = false _pressEmotion = () => { let config = { tension: 30, friction: 7 } const target = this.state.toolbarOpenVal._value === 1 ? 0 : 1 if (target === 1 && this.isKeyboardShowing === true) { this.shouldShowEmotion = true Keyboard.dismiss() return } Animated.spring(this.state.toolbarOpenVal, { toValue: target, ...config }).start() } componentWillUnmount() { this.keyboardDidHideListener.remove() this.keyboardDidShowListener.remove() this.removeListener && this.removeListener.remove() } async componentWillMount() { const { params } = this.props.navigation.state InteractionManager.runAfterInteractions(() => { getNewQaAPI().then(data => { // console.log(data) if ((params.URL || '').includes('?psngameid=')) { data.game = data.game.concat({ text: params.URL.split('=').pop(), value: params.URL.split('=').pop() }) } this.setState({ data, isLoading: false }, () => { // console.log(params) if (params.URL) { getQaEditAPI(params.URL).then(data => { if (params.URL.includes('?psngameid=')) { global.toast('已设置对应游戏ID' + data.psngameid) } this.setState(data) }) } }) }) }) this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => { this.isKeyboardShowing = true this.state.toolbarOpenVal.setValue(0) }) this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => { this.isKeyboardShowing = false this.shouldShowEmotion === true && Animated.spring(this.state.toolbarOpenVal, { toValue: 1, friction: 10 }).start(() => { this.shouldShowEmotion = false }) }) this.isToolbarShowing = false const icon = await Promise.all([ Ionicons.getImageSource('md-arrow-back', 20, '#fff'), Ionicons.getImageSource('md-happy', 50, '#fff'), Ionicons.getImageSource('md-photos', 50, '#fff'), Ionicons.getImageSource('md-send', 50, '#fff'), Ionicons.getImageSource('md-color-wand', 50, '#fff') ]) this.setState({ icon: { backIcon: icon[0], emotionIcon: icon[1], photoIcon: icon[2], sendIcon: icon[3], previewIcon: icon[4] } }) } sendReply = () => { const { title, hb, psngameid, node, content } = this.state const result: any = { title, hb, psngameid, node, content } result[this.state.key] = '' if (this.state.id !== '') { result.qaid = this.state.id } postCreateTopic(result, 'qa').then(res => { // console.log(res) return res }).then(res => res.text()).then(text => { // console.log(text, text.length) if (text.includes('玩脱了')) { const arr = text.match(/\<title\>(.*?)\<\/title\>/) if (arr && arr[1]) { const msg = `发布失败: ${arr[1]}` global.toast(msg) return } } InteractionManager.runAfterInteractions(() => { this._pressButton() global.toast('发布成功') }) }).catch(err => { const msg = `发布失败: ${err}` global.toast(msg) }) } onValueChange = (key: string, value: string) => { const newState = {} newState[key] = value this.setState(newState, () => { // this._onRefresh() }) } render() { let { openVal, marginTop } = this.state const { icon, toolbarOpenVal } = this.state const { modeInfo } = this.props.screenProps const statusHeight = global.isIOS ? 0 : (StatusBar.currentHeight || 0) let outerStyle = { marginTop: marginTop.interpolate({ inputRange: [0, SCREEN_HEIGHT], outputRange: [0, SCREEN_HEIGHT] }) } let animatedStyle = { // left: openVal.interpolate({ inputRange: [0, 1], outputRange: [SCREEN_WIDTH - 56 - 16, 0] }), // top: openVal.interpolate({ inputRange: [0, 1], outputRange: [SCREEN_HEIGHT - 16 - 56, 0] }), width: openVal.interpolate({ inputRange: [0, 1], outputRange: [CIRCLE_SIZE, SCREEN_WIDTH] }), height: openVal.interpolate({ inputRange: [0, 1], outputRange: [CIRCLE_SIZE, SCREEN_HEIGHT + 100 + statusHeight] }), borderWidth: openVal.interpolate({ inputRange: [0, 0.5, 1], outputRange: [2, 2, 0] }), borderRadius: openVal.interpolate({ inputRange: [-0.15, 0, 0.5, 1], outputRange: [0, CIRCLE_SIZE / 2, CIRCLE_SIZE * 1.3, 0] }), opacity: openVal.interpolate({ inputRange: [0, 0.1, 1], outputRange: [0, 1, 1] }), zIndex: openVal.interpolate({ inputRange: [0, 1], outputRange: [0, 3] }), backgroundColor: openVal.interpolate({ inputRange: [0, 1], outputRange: [accentColor, modeInfo.backgroundColor] }) // elevation : openVal.interpolate({inputRange: [0 ,1], outputRange: [0, 8]}) } let animatedToolbarStyle = { height: openVal.interpolate({ inputRange: [0, 0.9, 1], outputRange: [0, 0, 56] }), backgroundColor: modeInfo.standardColor } const { params } = this.props.navigation.state return ( <Animated.View ref={ref => this.ref = ref} style={[ styles.circle, styles.open, animatedStyle, outerStyle ]} > <Animated.View style={[styles.toolbar, animatedToolbarStyle, { height: 56 + statusHeight }]}> <Ionicons.ToolbarAndroid navIconName='md-arrow-back' overflowIconName='md-more' iconColor={modeInfo.isNightMode ? '#000' : '#fff'} title={params.URL ? '编辑问答' : '创建问答'} style={[styles.toolbar, { backgroundColor: modeInfo.standardColor }]} titleColor={modeInfo.isNightMode ? '#000' : '#fff'} subtitleColor={modeInfo.isNightMode ? '#000' : '#fff'} actions={toolbarActions} onIconClicked={this._pressButton} /> </Animated.View > <Animated.View style={[styles.KeyboardAvoidingView, { flex: openVal.interpolate({ inputRange: [0, 1], outputRange: [0, 10] }) }]} > <TextInput placeholder='标题' autoCorrect={false} multiline={false} keyboardType='default' returnKeyType='next' returnKeyLabel='next' blurOnSubmit={false} numberOfLines={100} ref={ref => this.title = ref} onChange={({ nativeEvent }) => { this.setState({ title: nativeEvent.text }) }} value={this.state.title} style={[styles.textInput, { color: modeInfo.titleTextColor, textAlign: 'left', height: 56, borderBottomColor: modeInfo.brighterLevelOne, borderBottomWidth: StyleSheet.hairlineWidth }]} placeholderTextColor={modeInfo.standardTextColor} // underlineColorAndroid={accentColor} underlineColorAndroid='rgba(0,0,0,0)' /> <Picker style={{ flex: 1, borderWidth: 1, borderBottomColor: modeInfo.standardTextColor, color: modeInfo.standardTextColor }} prompt='悬赏' selectedValue={this.state.open} onValueChange={this.onValueChange.bind(this, 'open')}> { this.state.isLoading && <Picker.Item label={'加载中'} value={''}/> || this.state.data.hb.map((item, index) => <Picker.Item key={index} label={'悬赏: ' + item.text} value={item.value}/>) } </Picker> <View style={{ flex: 1, flexDirection: 'row' }}> <Picker style={{ flex: 1, color: modeInfo.standardTextColor }} prompt='类型' selectedValue={this.state.type} onValueChange={this.onValueChange.bind(this, 'type')}> <Picker.Item label={'游戏'} value={'game'}/> <Picker.Item label={'节点'} value={'node'}/> </Picker> { this.state.type === 'game' && ( <Picker style={{ flex: 2, color: modeInfo.standardTextColor }} prompt='选择游戏' selectedValue={this.state.psngameid} onValueChange={this.onValueChange.bind(this, 'psngameid')}> { this.state.data.game.map((item, index) => <Picker.Item key={index} label={item.text} value={item.value}/>) } </Picker> ) || ( <Picker style={{ flex: 2, color: modeInfo.standardTextColor }} prompt='选择节点' selectedValue={this.state.node} onValueChange={this.onValueChange.bind(this, 'node')}> { this.state.data.node.map((item, index) => <Picker.Item key={index} label={item.text} value={item.value}/>) } </Picker> ) } </View> <AnimatedKeyboardAvoidingView behavior={'padding'} style={[styles.contentView, { flex: openVal.interpolate({ inputRange: [0, 1], outputRange: [0, 12] }) }]} keyboardVerticalOffset={global.isIOS ? -44 : 0}> <TextInput placeholder='内容' autoCorrect={false} multiline={true} keyboardType='default' returnKeyType={global.isIOS ? 'default' : 'go'} blurOnSubmit={global.isIOS ? false : true} returnKeyLabel='go' onSelectionChange={this.onSelectionChange} numberOfLines={100} ref={ref => this.content = ref} onChange={({ nativeEvent }) => { this.setState({ content: nativeEvent.text }) }} value={this.state.content} style={[styles.textInput, { color: modeInfo.titleTextColor, textAlign: 'left', textAlignVertical: 'top', flex: 1 }]} placeholderTextColor={modeInfo.standardTextColor} // underlineColorAndroid={accentColor} underlineColorAndroid='rgba(0,0,0,0)' /> <Animated.View style={[{ elevation: 4, bottom: 0 // toolbarOpenVal.interpolate({ inputRange: [0, 1], outputRange: [0, 1] }) }, animatedToolbarStyle]}> <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}> <View style={{ flexDirection: 'row' }}> <TouchableNativeFeedback onPress={this._pressEmotion} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} style={{ borderRadius: 25 }} > <View style={{ width: 50, height: 50, marginLeft: 0, borderRadius: 25, justifyContent: 'center', alignItems: 'center' }}> {icon && <Image source={icon.emotionIcon} style={{ width: 22, height: 22 }} />} </View> </TouchableNativeFeedback> <TouchableNativeFeedback onPress={this._pressImageButton} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} style={{ borderRadius: 25 }} > <View style={{ width: 50, height: 50, marginLeft: 0, borderRadius: 25, justifyContent: 'center', alignItems: 'center' }}> {icon && <Image source={icon.photoIcon} style={{ width: 22, height: 22 }} />} </View> </TouchableNativeFeedback> </View> <TouchableNativeFeedback onPress={this.toolbar} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} style={{ borderRadius: 25 }} > <View style={{ width: 50, height: 50, marginLeft: 0, borderRadius: 25, justifyContent: 'center', alignItems: 'center' }}> {icon && <Image source={icon.previewIcon} style={{ width: 22, height: 22 }} />} </View> </TouchableNativeFeedback> <TouchableNativeFeedback onPress={this.sendReply} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} style={{ borderRadius: 25 }} > <View style={{ width: 50, height: 50, marginLeft: 0, borderRadius: 25, justifyContent: 'center', alignItems: 'center' }}> {icon && <Image source={icon.sendIcon} style={{ width: 22, height: 22 }} />} </View> </TouchableNativeFeedback> </View> </Animated.View> {/* 表情 */} <Animated.View style={{ elevation: 4, bottom: 0, // toolbarOpenVal.interpolate({ inputRange: [0, 1], outputRange: [0, 100] }), backgroundColor: modeInfo.standardColor, height: toolbarOpenVal.interpolate({ inputRange: [-1, 0, 1], outputRange: [0, 0, emotionToolbarHeight] }), opacity: openVal.interpolate({ inputRange: [0, 0.9, 1], outputRange: [0, 0, 1] }) }} > <Emotion modeInfo={modeInfo} onPress={this.onPressEmotion} /> </Animated.View> <Animated.View style={{ elevation: 4, bottom: 0, backgroundColor: modeInfo.standardColor, height: 100, opacity: openVal.interpolate({ inputRange: [0, 0.9, 1], outputRange: [0, 0, 1] }) }} /> </AnimatedKeyboardAvoidingView> </Animated.View> </Animated.View> ) } onPressEmotion = ({ text }) => { this.addText( text ) } toolbar = () => { Keyboard.dismiss() this.props.navigation.navigate('Toolbar', { callback: ({ text }) => { this.addText(text) } }) } addText = (text) => { const origin = this.state.content let { start = 0, end = 0 } = this.state.selection if (start !== end) { const exist = origin.slice(start, end) text = text.slice(0, start) + exist + text.slice(end) end = start + exist.length } let input = origin.slice(0, start) + text + origin.slice(end) this.setState({ content: input, selection: { start, end } }, () => { this.content && this.content.focus() }) } onSelectionChange = ({ nativeEvent }) => { // console.log(nativeEvent.selection) this.setState({ selection: nativeEvent.selection }) } _pressImageButton = () => { Keyboard.dismiss() this.props.navigation.navigate('UserPhoto', { URL: 'https://psnine.com/my/photo?page=1', callback: ({ url }) => { this.addText(`[img]${url}[/img]`) } }) } } const styles = StyleSheet.create({ circle: { flex: 1, position: 'absolute', backgroundColor: 'white', width: CIRCLE_SIZE, height: CIRCLE_SIZE, borderRadius: CIRCLE_SIZE / 2, borderWidth: 2, borderColor: accentColor, elevation: 12 }, open: { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, width: undefined, // unset value from styles.circle height: undefined, // unset value from styles.circle borderRadius: CIRCLE_SIZE / 2 // unset value from styles.circle }, toolbar: { backgroundColor: standardColor, height: 56, elevation: 4, flex: -1 }, mainFont: { fontSize: 15, color: accentColor }, textInput: { fontSize: 15 }, KeyboardAvoidingView: { flex: 10, // width: width, // alignSelf:'center', // justifyContent: 'space-between', flexDirection: 'column' }, titleView: { flex: 1, // marginTop: -10, justifyContent: 'center' // flexDirection: 'column', // justifyContent: 'space-between', }, isPublicView: { flex: 1, flexDirection: 'row', // flexDirection: 'column', alignItems: 'center' }, contentView: { flex: 12 // flexDirection: 'column', }, submit: { // flex: -1, // height: 20, // //margin: 10, // marginTop: 30, // marginBottom: 20, }, submitButton: { // backgroundColor: accentColor, // height: 40, // alignItems: 'center', // justifyContent: 'center', }, regist: { flex: 1, flexDirection: 'row', marginTop: 20, margin: 10 }, openURL: { color: accentColor, textDecorationLine: 'underline' } })
the_stack
import * as loginPage from '../../Base/pages/Login.po'; import { LoginPageData } from '../../Base/pagedata/LoginPageData'; import * as customersPage from '../../Base/pages/Customers.po'; import * as faker from 'faker'; import { CustomersPageData } from '../../Base/pagedata/CustomersPageData'; import * as dashboardPage from '../../Base/pages/Dashboard.po'; import * as organizationProjectsPage from '../../Base/pages/OrganizationProjects.po'; import { OrganizationProjectsPageData } from '../../Base/pagedata/OrganizationProjectsPageData'; import * as organizationTagsUserPage from '../../Base/pages/OrganizationTags.po'; import { OrganizationTagsPageData } from '../../Base/pagedata/OrganizationTagsPageData'; import { CustomCommands } from '../../commands'; import * as logoutPage from '../../Base/pages/Logout.po'; import * as manageEmployeesPage from '../../Base/pages/ManageEmployees.po'; import { Given, Then, When, And } from 'cypress-cucumber-preprocessor/steps'; const pageLoadTimeout = Cypress.config('pageLoadTimeout'); let email = faker.internet.email(); let fullName = faker.name.firstName() + ' ' + faker.name.lastName(); let deleteName = faker.name.firstName() + ' ' + faker.name.lastName(); let city = faker.address.city(); let postcode = faker.address.zipCode(); let street = faker.address.streetAddress(); let website = faker.internet.url(); let firstName = faker.name.firstName(); let lastName = faker.name.lastName(); let username = faker.internet.userName(); let password = faker.internet.password(); let employeeEmail = faker.internet.email(); let imgUrl = faker.image.avatar(); // Login with email Given('Login with default credentials', () => { CustomCommands.login(loginPage, LoginPageData, dashboardPage); }); // Add new tag Then('User can add new tag', () => { dashboardPage.verifyAccountingDashboardIfVisible(); CustomCommands.addTag(organizationTagsUserPage, OrganizationTagsPageData); }); // Add employee And('User can add new employee', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); CustomCommands.addEmployee( manageEmployeesPage, firstName, lastName, username, employeeEmail, password, imgUrl ); }); // Add project And('User can add new project', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); CustomCommands.addProject( organizationProjectsPage, OrganizationProjectsPageData ); }); // Add new customer And('User can visit Contacts customers page', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); cy.intercept('GET', ' /api/organization-projects*').as('waitToLoad'); cy.visit('/#/pages/contacts/customers', { timeout: pageLoadTimeout }); cy.wait('@waitToLoad'); }); Then('User can see grid button', () => { customersPage.gridBtnExists(); }); And('User can see grid second grid button to change view', () => { customersPage.gridBtnClick(1); }); And('User can see Add button', () => { customersPage.addButtonVisible(); }); When('User click Add button', () => { customersPage.clickAddButton(); }); Then('User can see name input field', () => { customersPage.nameInputVisible(); }); And('User can enter new value for name', () => { customersPage.enterNameInputData(fullName); }); And('User can see email input field', () => { customersPage.emailInputVisible(); }); And('User can enter new value for email', () => { customersPage.enterEmailInputData(email); }); And('User can see phone input field', () => { customersPage.phoneInputVisible(); }); And('User can enter new value for phone', () => { customersPage.enterPhoneInputData(CustomersPageData.defaultPhone); }); And('User can see project dropdown', () => { customersPage.projectDropdownVisible(); }); When('User click on project dropdown', () => { customersPage.clickProjectDropdown(); }); Then('User can select project from dropdown options', () => { customersPage.selectProjectFromDropdown(CustomersPageData.defaultProject); }); And('User can see tags multi-select', () => { customersPage.tagsMultiSelectVisible(); }); When('User click on tags multi-select', () => { customersPage.clickTagsMultiSelect(); }); Then('User can select tags from dropdown options', () => { customersPage.selectTagsFromDropdown(0); customersPage.clickCardBody(); }); And('User can see website input field', () => { customersPage.websiteInputVisible(); }); And('User can enter value for website', () => { customersPage.enterWebsiteInputData(website); }); And('User can see save button', () => { customersPage.saveButtonVisible(); }); When('User click on save button', () => { customersPage.clickSaveButton(); }); Then('User can see country dropdown', () => { customersPage.countryDropdownVisible(); }); When('User click on country dropdown', () => { customersPage.clickCountryDropdown(); }); Then('User can select country from dropdown options', () => { customersPage.selectCountryFromDropdown(CustomersPageData.country); }); And('User can see city input field', () => { customersPage.cityInputVisible(); }); And('User can enter value for city', () => { customersPage.enterCityInputData(city); }); And('User can see post code input field', () => { customersPage.postcodeInputVisible(); }); And('User can enter value for postcode', () => { customersPage.enterPostcodeInputData(postcode); }); And('User can see street input field', () => { customersPage.streetInputVisible(); }); And('User can enter value for street', () => { customersPage.enterStreetInputData(street); }); And('User can see next button', () => { customersPage.verifyNextButtonVisible(); }); When('User click on next button', () => { customersPage.clickNextButton(); }); Then('User can see hours input field', () => { customersPage.budgetInputVisible(); }); And('User can enter value for hours', () => { customersPage.enterBudgetData(CustomersPageData.hours); }); And('User can see last step button', () => { customersPage.lastStepBtnVisible(); }); When('User click on last step button', () => { customersPage.clickLastStepBtn(); }); And('User can see employee dropdown', () => { customersPage.selectEmployeeDropdownVisible(); }); When('User click on employee dropdown', () => { customersPage.clickSelectEmployeeDropdown(); }); Then('User can select employee from dropdown options', () => { customersPage.selectEmployeeDropdownOption(0); customersPage.clickKeyboardButtonByKeyCode(9); }); Then('User can see finish button', () => { customersPage.verifyFinishButtonVisible(); }); When('User click on finish button', () => { customersPage.clickFinishButton(); }); Then('Notification message will appear', () => { customersPage.waitMessageToHide(); }); And('User can verify customer was edited', () => { customersPage.verifyCustomerExists(fullName); }); // Invite customer And('User can see invite button', () => { customersPage.inviteButtonVisible(); }); When('User click on invite button', () => { customersPage.clickInviteButton(); }); Then('User can see customer name input field', () => { customersPage.customerNameInputVisible(); }); And('User can enter value for customer name', () => { customersPage.enterCustomerNameData(fullName); }); And('User can see customer phone input field', () => { customersPage.customerPhoneInputVisible(); }); And('User can enter value for customer phone', () => { customersPage.enterCustomerPhoneData(CustomersPageData.defaultPhone); }); And('User can see customer email input field', () => { customersPage.customerEmailInputVisible(); }); And('User can enter value for customer email', () => { customersPage.enterCustomerEmailData(email); }); And('User can see save invite button', () => { customersPage.saveInvitebuttonVisible(); }); When('User click on save invite button', () => { customersPage.clickSaveInviteButton(); }); Then('Notification message will appear', () => { customersPage.waitMessageToHide(); }); And('User can verify customer was created', () => { customersPage.verifyCustomerExists(fullName); }); // Edit customer And('User can see customers table', () => { customersPage.tableRowVisible(); }); When('User select first table row', () => { customersPage.selectTableRow(0); }); Then('Edit button will become active', () => { customersPage.editButtonVisible(); }); When('User click on edit button', () => { customersPage.clickEditButton(); }); Then('User can see name input field', () => { customersPage.nameInputVisible(); }); And('User can enter new value for name', () => { customersPage.enterNameInputData(deleteName); }); And('User can see email input field', () => { customersPage.emailInputVisible(); }); And('User can enter new value for email', () => { customersPage.enterEmailInputData(email); }); And('User can see phone input field', () => { customersPage.phoneInputVisible(); }); And('User can enter new value for phone', () => { customersPage.enterPhoneInputData(CustomersPageData.defaultPhone); }); And('User can see website input field', () => { customersPage.websiteInputVisible(); }); And('User can enter value for website', () => { customersPage.enterWebsiteInputData(website); }); And('User can see save button', () => { customersPage.saveButtonVisible(); }); When('User click on save button', () => { cy.on('uncaught:exception', (err, runnable) => { return false; }); customersPage.clickSaveButton(); }); Then('User can see country dropdown', () => { customersPage.countryDropdownVisible(); }); When('User click on country dropdown', () => { customersPage.clickCountryDropdown(); }); Then('User can select country from dropdown options', () => { customersPage.selectCountryFromDropdown(CustomersPageData.country); }); And('User can see city input field', () => { customersPage.cityInputVisible(); }); And('User can enter value for city', () => { customersPage.enterCityInputData(city); }); And('User can see post code input field', () => { customersPage.postcodeInputVisible(); }); And('User can enter value for postcode', () => { customersPage.enterPostcodeInputData(postcode); }); And('User can see street input field', () => { customersPage.streetInputVisible(); }); And('User can enter value for street', () => { customersPage.enterStreetInputData(street); }); And('User can see next button', () => { customersPage.verifyNextButtonVisible(); }); When('User click on next button', () => { customersPage.clickNextButton(); }); Then('User can see hours input field', () => { customersPage.budgetInputVisible(); }); And('User can enter value for hours', () => { customersPage.enterBudgetData(CustomersPageData.hours); }); And('User can see last step button', () => { customersPage.lastStepBtnVisible(); }); When('User click on last step button', () => { customersPage.clickLastStepBtn(); }); Then('User can see finish button', () => { customersPage.verifyFinishButtonVisible(); }); When('User click on finish button', () => { customersPage.clickFinishButton(); }); Then('Notification message will appear', () => { customersPage.waitMessageToHide(); }); And('User can verify customer was edited', () => { customersPage.verifyCustomerExists(deleteName); }); // Delete customer Then('User can see contacts table', () => { customersPage.tableRowVisible(); }); When('User select first table row', () => { customersPage.selectTableRow(0); }); Then('Delete button will become active', () => { customersPage.deleteButtonVisible(); }); When('User click on delete button', () => { customersPage.clickDeleteButton(); }); Then('User can see confirm delete button', () => { customersPage.confirmDeleteButtonVisible(); }); When('User click on confirm delete button', () => { customersPage.clickConfirmDeleteButton(); }); Then('Notification message will appear', () => { customersPage.waitMessageToHide(); }); And('User can verify customer was deleted', () => { customersPage.verifyElementIsDeleted(deleteName); });
the_stack
import { Workbook } from '@syncfusion/ej2-excel-export'; import { ExcelRow, ExcelCell, ExcelColumn, BeforeExportEventArgs } from '../../common/base/interface'; import * as events from '../../common/base/constant'; import { PivotView } from '../base/pivotview'; import { IAxisSet, IPivotValues, PivotEngine } from '../../base/engine'; import { IPageSettings } from '../../base/engine'; import { OlapEngine } from '../../base/olap/engine'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; import { PivotExportUtil } from '../../base/export-util'; import { ExcelExportProperties, ExcelFooter, ExcelHeader, ExcelHeaderQueryCellInfoEventArgs, ExcelQueryCellInfoEventArgs, ExcelStyle } from '@syncfusion/ej2-grids'; /** * @hidden * `ExcelExport` module is used to handle the Excel export action. */ export class ExcelExport { private parent: PivotView; private engine: PivotEngine | OlapEngine; private rows: ExcelRow[]; private actualrCnt: number = 0; /** * Constructor for the PivotGrid Excel Export module. * @param {PivotView} parent - Instance of pivot table. * @hidden */ constructor(parent?: PivotView) { /* eslint-disable-line */ this.parent = parent; } /** * For internal use only - Get the module name. * @returns {string} - string. * @private */ protected getModuleName(): string { return 'excelExport'; } private addHeaderAndFooter(excelExportProperties?: ExcelHeader | ExcelFooter, stringValue?: string, type?: string, rowCount?: number): void { let cells: ExcelCell[] = []; if (!isNullOrUndefined(excelExportProperties.rows)) { this.actualrCnt = (type === 'footer') ? this.actualrCnt + rowCount - (excelExportProperties.rows[0].cells.length) : this.actualrCnt; let row: ExcelRow[] = excelExportProperties.rows; for (let i: number = 0; i < row.length; i++) { for (let j: number = 0; j < row[i].cells.length; j++) { cells = []; cells.push({ index: i + 1, value: row[i].cells[j].value, colSpan: row[i].cells[j].colSpan, rowSpan: row[i].cells[j].rowSpan, style: row[i].cells[j].style }); this.actualrCnt++; this.rows.push({ index: this.actualrCnt, cells: cells }); } } this.actualrCnt = (type === 'header') ? rowCount : this.actualrCnt; } else { if (stringValue !== '') { if (type === 'footer') { this.actualrCnt++; } cells.push({ index: 1, value: stringValue, }); this.rows.push({ index: this.actualrCnt + 1, cells: cells }); this.actualrCnt = (type === 'header') ? this.actualrCnt + 2 : this.actualrCnt; } } } /* eslint-disable */ /** * Method to perform excel export. * @hidden */ public exportToExcel(type: string, exportProperties?: ExcelExportProperties): void { this.rows = []; this.actualrCnt = 0; let isHeaderSet: boolean = !isNullOrUndefined(exportProperties) && !isNullOrUndefined(exportProperties.header); let isFooterSet: boolean = !isNullOrUndefined(exportProperties) && !isNullOrUndefined(exportProperties.footer); let isFileNameSet: boolean = !isNullOrUndefined(exportProperties) && !isNullOrUndefined(exportProperties.fileName); this.engine = this.parent.dataType === 'olap' ? this.parent.olapEngineModule : this.parent.engineModule; /** Event trigerring */ let clonedValues: IPivotValues; let currentPivotValues: IPivotValues = PivotExportUtil.getClonedPivotValues(this.engine.pivotValues); let customFileName: string = isFileNameSet ? exportProperties.fileName : 'default.xlsx'; if (this.parent.exportAllPages && this.parent.enableVirtualization && this.parent.dataType !== 'olap') { let pageSettings: IPageSettings = this.engine.pageSettings; this.engine.pageSettings = null; (this.engine as PivotEngine).generateGridData(this.parent.dataSourceSettings, true); this.parent.applyFormatting(this.engine.pivotValues); clonedValues = PivotExportUtil.getClonedPivotValues(this.engine.pivotValues); this.engine.pivotValues = currentPivotValues; this.engine.pageSettings = pageSettings; } else { clonedValues = currentPivotValues; } let args: BeforeExportEventArgs = { fileName: customFileName, header: '', footer: '', dataCollections: [clonedValues], excelExportProperties: exportProperties }; let fileName: string; let header: string; let footer: string; let dataCollections: IPivotValues[]; this.parent.trigger(events.beforeExport, args, (observedArgs: BeforeExportEventArgs) => { fileName = observedArgs.fileName; header = observedArgs.header; footer = observedArgs.footer; dataCollections = observedArgs.dataCollections; }); if (!isHeaderSet && isNullOrUndefined(args.excelExportProperties) && header !== '') { this.addHeaderAndFooter({}, header, 'header', undefined); } else if (!isNullOrUndefined(args.excelExportProperties) && !isNullOrUndefined(args.excelExportProperties.header)) { this.addHeaderAndFooter(args.excelExportProperties.header, '', 'header', args.excelExportProperties.header.headerRows) } /** Fill data and export */ let workSheets: any = []; for (let dataColl: number = 0; dataColl < dataCollections.length; dataColl++) { let pivotValues: IPivotValues = dataCollections[dataColl]; let colLen: number = 0; let rowLen: number = pivotValues.length; let formatList: { [key: string]: string } = this.parent.renderModule.getFormatList(); let maxLevel: number = 0; for (let rCnt: number = 0; rCnt < rowLen; rCnt++) { if (pivotValues[rCnt]) { this.actualrCnt++; colLen = pivotValues[rCnt].length; let cells: ExcelCell[] = []; for (let cCnt: number = 0; cCnt < colLen; cCnt++) { if (pivotValues[rCnt][cCnt]) { let pivotCell: IAxisSet = (pivotValues[rCnt][cCnt] as IAxisSet); if(pivotCell && pivotCell.axis === 'value' && pivotCell.formattedText === ""){ pivotCell.value = pivotCell.formattedText as any; } let field: string = (this.parent.dataSourceSettings.valueAxis === 'row' && this.parent.dataType === 'olap' && pivotCell.rowOrdinal && (this.engine as OlapEngine).tupRowInfo[pivotCell.rowOrdinal]) ? (this.engine as OlapEngine).tupRowInfo[pivotCell.rowOrdinal].measureName : pivotCell.actualText as string; let styles: ExcelStyle = (pivotCell.axis == 'row') ? { hAlign: 'Left', bold: true, wrapText: true } : { numberFormat: formatList[field], bold: false, wrapText: true }; let headerStyle: ExcelStyle = { bold: true, vAlign: 'Center', wrapText: true, indent: cCnt === 0 ? pivotCell.level * 10 : 0 }; if (!(pivotCell.level === -1 && !pivotCell.rowSpan)) { let cellValue: string | number = pivotCell.axis === 'value' ? pivotCell.value : pivotCell.formattedText; let isgetValuesHeader: boolean = ((this.parent.dataSourceSettings.rows.length === 0 && this.parent.dataSourceSettings.valueAxis === 'row') || (this.parent.dataSourceSettings.columns.length === 0 && this.parent.dataSourceSettings.valueAxis === 'column')); if (pivotCell.type === 'grand sum' && !(this.parent.dataSourceSettings.values.length === 1 && this.parent.dataSourceSettings.valueAxis === 'row' && pivotCell.axis === 'column')) { cellValue = isgetValuesHeader ? this.parent.getValuesHeader(pivotCell, 'grandTotal') : this.parent.localeObj.getConstant('grandTotal'); } else if (pivotCell.type === 'sum') { cellValue = cellValue.toString().replace('Total', this.parent.localeObj.getConstant('total')); } else { cellValue = (!isNullOrUndefined(pivotCell.valueSort) && (this.parent.localeObj.getConstant('grandTotal') + this.parent.dataSourceSettings.valueSortSettings.headerDelimiter + pivotCell.formattedText === pivotCell.valueSort.levelName) && isgetValuesHeader) ? this.parent.getValuesHeader(pivotCell, 'value') : cellValue; } if (!(pivotCell.level === -1 && !pivotCell.rowSpan)) { cells.push({ index: cCnt + 1, value: cellValue, colSpan: pivotCell.colSpan, rowSpan: (pivotCell.rowSpan === -1 ? 1 : pivotCell.rowSpan), }); let lastCell: any = cells[cells.length - 1]; if (pivotCell.axis === 'value') { if (isNaN(pivotCell.value) || pivotCell.formattedText === '' || pivotCell.formattedText === undefined || isNullOrUndefined(pivotCell.value)) { lastCell.value = type === 'Excel' ? null : ''; } styles.numberFormat = typeof cellValue === 'string' ? undefined : styles.numberFormat; lastCell.style = !isNullOrUndefined(lastCell.value) ? styles : { bold: false, wrapText: true }; } else { lastCell.style = headerStyle; if (pivotCell.axis === 'row' && cCnt === 0) { lastCell.style = styles; if (this.parent.dataType === 'olap') { let indent: number = this.parent.renderModule.indentCollection[rCnt]; lastCell.style.indent = indent * 2; maxLevel = maxLevel > indent ? maxLevel : indent; } else { let levelName: string = pivotCell.valueSort ? pivotCell.valueSort.levelName.toString() : ''; let memberPos: number = pivotCell.actualText ? pivotCell.actualText.toString().split(this.parent.dataSourceSettings.valueSortSettings.headerDelimiter).length : 0; let levelPosition: number = levelName.split(this.parent.dataSourceSettings.valueSortSettings.headerDelimiter).length - (memberPos ? memberPos - 1 : memberPos); let level: number = levelPosition ? (levelPosition - 1) : 0; lastCell.style.indent = level * 2; maxLevel = level > maxLevel ? level : maxLevel; } } } if (pivotCell.style || lastCell.style.backColor || lastCell.style.backgroundColor || lastCell.style.fontColor || lastCell.style.fontName || lastCell.style.fontSize) { lastCell.style.backColor = lastCell.style.backgroundColor ? lastCell.style.backgroundColor : pivotCell.style.backgroundColor; lastCell.style.fontColor = lastCell.style.fontColor ? lastCell.style.fontColor : pivotCell.style.color; lastCell.style.fontName = lastCell.style.fontName ? lastCell.style.fontName : pivotCell.style.fontFamily; lastCell.style.fontSize = lastCell.style.fontSize ? Number(lastCell.style.fontSize) : Number(pivotCell.style.fontSize.split('px')[0]); } lastCell.style.borders = { color: '#000000', lineStyle: 'Thin' }; let excelHeaderQueryCellInfoArgs: ExcelHeaderQueryCellInfoEventArgs; let excelQueryCellInfoArgs: ExcelQueryCellInfoEventArgs; if (pivotCell.axis === 'column') { excelHeaderQueryCellInfoArgs = { style: headerStyle, cell: pivotCell, }; this.parent.trigger(events.excelHeaderQueryCellInfo, excelHeaderQueryCellInfoArgs); } else { excelQueryCellInfoArgs = { style: styles, cell: pivotCell, column: undefined, data: pivotValues, value: cellValue }; this.parent.trigger(events.excelQueryCellInfo, excelQueryCellInfoArgs); } lastCell.value = (pivotCell.axis == 'column') ? (excelHeaderQueryCellInfoArgs.cell as any).formattedText : excelQueryCellInfoArgs.value; lastCell.style = (pivotCell.axis == 'column') ? excelHeaderQueryCellInfoArgs.style : excelQueryCellInfoArgs.style; } } cCnt = cCnt + (pivotCell.colSpan ? (pivotCell.colSpan - 1) : 0); } else { let pivotCell: IAxisSet = { formattedText: "" }; let excelHeaderQueryCellInfoArgs: ExcelHeaderQueryCellInfoEventArgs; if (pivotCell) { excelHeaderQueryCellInfoArgs = { style: undefined, cell: pivotCell, }; this.parent.trigger(events.excelHeaderQueryCellInfo, excelHeaderQueryCellInfoArgs); } cells.push({ index: cCnt + 1, colSpan: 1, rowSpan: 1, value: pivotCell.formattedText, style: excelHeaderQueryCellInfoArgs.style }); } } this.rows.push({ index: this.actualrCnt, cells: cells }); } } if (isFooterSet) { this.addHeaderAndFooter(exportProperties.footer, '', 'footer', exportProperties.footer.footerRows); } else if (!isFooterSet && footer !== '' && isNullOrUndefined(args.excelExportProperties)) { this.addHeaderAndFooter({}, footer, 'footer', undefined); } else if (!isNullOrUndefined(args.excelExportProperties) && !isNullOrUndefined(args.excelExportProperties.footer)) { this.addHeaderAndFooter(args.excelExportProperties.footer, '', 'footer', args.excelExportProperties.footer.footerRows) } let columns: ExcelColumn[] = []; for (let cCnt: number = 0; cCnt < colLen; cCnt++) { columns.push({ index: cCnt + 1, width: 100 }); } if (maxLevel > 0) { columns[0].width = 100 + (maxLevel * 20); } workSheets.push({ columns: columns, rows: this.rows }); } let book: Workbook = new Workbook({ worksheets: workSheets }, type === 'Excel' ? 'xlsx' : 'csv', undefined, (this.parent as any).currencyCode); if ('.xlsx' === fileName.substring(fileName.length - 5, fileName.length) || '.csv' === fileName.substring(fileName.length - 4, fileName.length)) { book.save(fileName); } else { book.save(fileName + (type === 'Excel' ? '.xlsx' : '.csv')); } } /** * To destroy the excel export module * @returns {void} * @hidden */ public destroy(): void { } }
the_stack
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base"; import { IPropertyPaneConfiguration, IPropertyPaneDropdownOption, PropertyPaneDropdown, PropertyPaneSlider, PropertyPaneTextField, PropertyPaneToggle } from "@microsoft/sp-property-pane"; import { IODataList } from '@microsoft/sp-odata-types'; import { sp } from '@pnp/sp'; import * as strings from 'TilesWebPartStrings'; import Tiles from './components/Tiles'; import { ITilesProps } from './components/ITilesProps'; import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder"; export interface ITilesWebPartProps { list: string; descriptionField: string; backgroundImageField: string; fallbackImageUrl: string; newTabField: string; orderByField: string; linkField: string; count: number; imageWidth: number; imageHeight: number; textPadding: number; relativeSiteUrl: string; tileType: string; tileTypeField: string; showAdvanced: boolean; } export default class TilesWebPart extends BaseClientSideWebPart<ITilesWebPartProps> { private listOptions: IPropertyPaneDropdownOption[]; private tileTypeFieldOptions: IPropertyPaneDropdownOption[]; private tileTypeOptions: IPropertyPaneDropdownOption[]; private tileTypeFieldDropdownDisabled: boolean; private tileTypeDropdownDisabled: boolean; private listsDropdownDisabled: boolean; public onInit(): Promise<void> { return super.onInit().then(_ => { sp.setup({ spfxContext: this.context }); }); } public render(): void { const element: React.ReactElement<ITilesProps> = React.createElement( Tiles, { list: this.properties.list, title: "Title", descriptionField: this.properties.descriptionField, backgroundImageField: this.properties.backgroundImageField, fallbackImageUrl: this.properties.fallbackImageUrl, newTabField: this.properties.newTabField, linkField: this.properties.linkField, orderByField: this.properties.orderByField, count: this.properties.count, imageWidth: this.properties.imageWidth, imageHeight: this.properties.imageHeight, textPadding: this.properties.textPadding, webServerRelativeUrl: this.context.pageContext.web.serverRelativeUrl, tileType: this.properties.tileType, tileTypeField: this.properties.tileTypeField } ); ReactDom.render((this.properties.list) ? element : <Placeholder iconName='Edit' iconText={strings.View_EmptyPlaceholder_Label} description={strings.View_EmptyPlaceholder_Description} buttonLabel={strings.View_EmptyPlaceholder_Button} onConfigure={this._onConfigure.bind(this)} />, this.domElement); } protected get dataVersion(): Version { return Version.parse('1.0'); } protected async onPropertyPaneConfigurationStart(): Promise<void> { try { await this.loadListDropdown(); await this.loadTileTypeFieldDropdown(); await this.loadTileTypeDropdown(); } catch (error) { throw error; } } private _onConfigure(): void { this.context.propertyPane.open(); } /** * * * @protected * @param {string} propertyPath * @param {*} oldValue * @param {*} newValue * @memberof TilesWebPart */ protected onPropertyPaneFieldChanged(propertyPath: string, oldValue: any, newValue: any): void { if (propertyPath === 'list' && newValue) { super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue); const previousTileTypeFieldValue: string = this.properties.tileTypeField; this.properties.tileTypeField = undefined; this.onPropertyPaneFieldChanged('tileTypeField', previousTileTypeFieldValue, this.properties.tileTypeField); this.tileTypeFieldDropdownDisabled = true; this.context.propertyPane.refresh(); this.context.statusRenderer.displayLoadingIndicator(this.domElement, 'tileTypeField'); this.fetchChoiceFieldTypes() .then((itemOptions: IPropertyPaneDropdownOption[]): void => { this.tileTypeFieldOptions = itemOptions; this.tileTypeFieldDropdownDisabled = false; this.context.statusRenderer.clearLoadingIndicator(this.domElement); this.render(); this.context.propertyPane.refresh(); }); } else if (propertyPath === 'tileTypeField' && newValue) { super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue); const previousItem: string = this.properties.tileType; this.properties.tileType = undefined; this.onPropertyPaneFieldChanged('tileType', previousItem, this.properties.tileType); this.tileTypeDropdownDisabled = true; this.context.propertyPane.refresh(); this.context.statusRenderer.displayLoadingIndicator(this.domElement, 'tileType'); this.fetchFileTypeOptions() .then((itemOptions: IPropertyPaneDropdownOption[]): void => { this.tileTypeOptions = itemOptions; this.tileTypeOptions.push({ text: `${strings.View_NoOptionValue}`, key: "" }); this.tileTypeDropdownDisabled = false; this.context.statusRenderer.clearLoadingIndicator(this.domElement); this.render(); this.context.propertyPane.refresh(); }); } else { super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue); } } private async loadListDropdown() { this.listsDropdownDisabled = !this.listOptions; if (!this.listOptions) { this.context.statusRenderer.displayLoadingIndicator(this.domElement, 'list'); let response = await this.fetchListOptions(); this.listOptions = response; this.listsDropdownDisabled = false; this.context.propertyPane.refresh(); this.context.statusRenderer.clearLoadingIndicator(this.domElement); this.render(); } } private async loadTileTypeFieldDropdown() { this.tileTypeFieldDropdownDisabled = !this.tileTypeFieldOptions; if (!this.tileTypeFieldOptions && this.properties.list) { this.context.statusRenderer.displayLoadingIndicator(this.domElement, 'tileTypeField'); let response = await this.fetchChoiceFieldTypes(); this.tileTypeFieldOptions = response; this.tileTypeFieldDropdownDisabled = false; this.context.propertyPane.refresh(); this.context.statusRenderer.clearLoadingIndicator(this.domElement); this.render(); } } private async loadTileTypeDropdown() { this.tileTypeDropdownDisabled = !this.tileTypeOptions; if (!this.tileTypeOptions && this.properties.list && this.properties.tileTypeField) { this.context.statusRenderer.displayLoadingIndicator(this.domElement, 'tileType'); let response = await this.fetchFileTypeOptions(); this.tileTypeOptions = response; this.tileTypeOptions.push({ text: "<Ingen verdi>", key: "" }); this.tileTypeDropdownDisabled = false; this.context.propertyPane.refresh(); this.context.statusRenderer.clearLoadingIndicator(this.domElement); this.render(); } } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.Property_PropertyPaneDescription }, groups: [ { groupName: strings.Property_BasicGroupName, groupFields: [ PropertyPaneDropdown('list', { label: strings.Property_List_Label, options: this.listOptions, disabled: this.listsDropdownDisabled }), PropertyPaneDropdown('tileTypeField', { label: strings.Property_TileChoiceField_Label, options: this.tileTypeFieldOptions, disabled: this.tileTypeFieldDropdownDisabled }), PropertyPaneDropdown('tileType', { label: strings.Property_TileType_Label, options: this.tileTypeOptions, disabled: this.tileTypeDropdownDisabled }), PropertyPaneToggle('showAdvanced', { label: strings.Property_AdvancedSettings_Label, offText: strings.Property_AdvancedSettings_OffText, onText: strings.Property_AdvancedSettings_OnText }), ] }, { isCollapsed: !this.properties.showAdvanced, groupFields: [ PropertyPaneTextField('descriptionField', { label: strings.Property_Description_Label, description: strings.Property_Description_Description, }), PropertyPaneTextField('backgroundImageField', { label: strings.Property_BackgroundImage_Label, description: strings.Property_BackgroundImage_Description, }), PropertyPaneTextField('fallbackImageUrl', { label: strings.Property_FallbackImageUrl_Label, description: strings.Property_FallbackImageUrl_Description, }), PropertyPaneTextField('newTabField', { label: strings.Property_NewTab_Label, description: strings.Property_NewTab_Description, }), PropertyPaneTextField('linkField', { label: strings.Property_Link_Label, description: strings.Property_Link_Description, }), PropertyPaneTextField('orderByField', { label: strings.Property_OrderBy_Label, description: strings.Property_OrderBy_Description, }), ] }, { isCollapsed: !this.properties.showAdvanced, groupFields: [ PropertyPaneSlider('count', { label: strings.Property_Count_Label, min: 1, max: 20 }), PropertyPaneSlider('imageWidth', { label: strings.Property_ImageWidth_Label, min: 100, max: 500 }), PropertyPaneSlider('imageHeight', { label: strings.Property_ImageHeight_Label, min: 100, max: 500 }), PropertyPaneSlider('textPadding', { label: strings.Property_TextPadding_Label, min: 2, max: 20 }), ] } ] } ] }; } private async fetchListOptions(): Promise<IPropertyPaneDropdownOption[]> { try { const results = await sp.web.lists.filter('BaseTemplate eq 100 and Hidden eq false').get(); return results.map((item: IODataList, index) => { return { text: item.Title, key: item.Title, index: index }; }); } catch (error) { throw error; } } private async fetchChoiceFieldTypes(): Promise<IPropertyPaneDropdownOption[]> { try { let fields = await sp.web.lists.getByTitle(this.properties.list).fields.filter("TypeAsString eq 'Choice'").get(); let options: Array<IPropertyPaneDropdownOption> = fields.map((field) => { return { key: field.InternalName, text: field.Title }; }); return options; } catch (error) { throw error; } } private async fetchFileTypeOptions(): Promise<IPropertyPaneDropdownOption[]> { try { let field = await sp.web.lists.getByTitle(this.properties.list).fields.getByInternalNameOrTitle(this.properties.tileTypeField).get(); let options: Array<IPropertyPaneDropdownOption> = field.Choices.map((choice) => { return { key: choice, text: choice }; }); return options; } catch (error) { throw error; } } private validateFields(value: string): string { return (value) ? "" : "Vennligst fyll inn verdi."; } }
the_stack
import {assert} from '../../../platform/chai-web.js'; import {checkDefined} from '../../../runtime/testing/preconditions.js'; import {ParticleNode, ParticleOutput, ParticleInput} from '../particle-node.js'; import {buildFlowGraph} from '../testing/flow-graph-testing.js'; import {FlowModifier} from '../graph-internals.js'; const entityString = '{"root": {"values": {"ida": {"value": {"id": "ida", "text": "asdf"}, "version": {"u": 1}}}, "version":{"u": 1}}, "locations": {}}'; describe('FlowGraph', () => { it('works with empty recipe', async () => { const graph = await buildFlowGraph(` recipe R `); assert.isEmpty(graph.particleMap); assert.isEmpty(graph.handles); }); it('works with single particle', async () => { const graph = await buildFlowGraph(` particle P recipe R P `); assert.isEmpty(graph.handles); assert.hasAllKeys(graph.particleMap, ['P']); const node = checkDefined(graph.particleMap.get('P')); assert.isEmpty(node.inEdges); assert.isEmpty(node.outEdges); }); it('works with two particles', async () => { const graph = await buildFlowGraph(` particle P1 foo: writes Foo {} particle P2 bar: reads Foo {} recipe R P1 foo: writes h P2 bar: reads h `); assert.lengthOf(graph.particles, 2); assert.lengthOf(graph.handles, 1); assert.hasAllKeys(graph.particleMap, ['P1', 'P2']); const P1 = checkDefined(graph.particleMap.get('P1')); const P2 = checkDefined(graph.particleMap.get('P2')); assert.isEmpty(P1.inEdges); assert.isEmpty(P2.outEdges); assert.strictEqual(P1.outNodes[0], P2.inNodes[0], 'handle node is different'); assert.sameMembers(graph.connectionsAsStrings, ['P1.foo -> P2.bar']); }); it('works with inout handle connections', async () => { const graph = await buildFlowGraph(` particle P foo: reads writes Foo {} check foo is t1 claim foo is t2 recipe R P foo: reads writes h `); assert.lengthOf(graph.particles, 1); const particleNode = graph.particles[0]; assert.lengthOf(graph.handles, 1); const handleNode = graph.handles[0]; assert.lengthOf(graph.edges, 2); const [inEdge, outEdge] = graph.edges; assert.strictEqual(particleNode.nodeId, 'P0'); assert.strictEqual(handleNode.nodeId, 'H0'); assert.strictEqual(inEdge.edgeId, 'E0'); assert.strictEqual(outEdge.edgeId, 'E1'); assert.strictEqual(inEdge.start, handleNode); assert.strictEqual(inEdge.end, particleNode); assert.strictEqual(outEdge.start, particleNode); assert.strictEqual(outEdge.end, handleNode); assert.deepEqual(inEdge.modifier, FlowModifier.parse('+node:H0', '+edge:E0')); assert.deepNestedInclude(inEdge.check, {type: 'tag', value: 't1', negated: false}); assert.deepEqual(outEdge.modifier, FlowModifier.parse('+node:P0', '+edge:E1', '+tag:t2')); assert.isUndefined(outEdge.check); }); it('works with handles with multiple inputs', async () => { const graph = await buildFlowGraph(` particle P1 foo: writes Foo {} particle P2 bar: writes Foo {} particle P3 baz: reads Foo {} recipe R P1 foo: writes h P2 bar: writes h P3 baz: reads h `); assert.hasAllKeys(graph.particleMap, ['P1', 'P2', 'P3']); assert.sameMembers(graph.connectionsAsStrings, ['P1.foo -> P3.baz', 'P2.bar -> P3.baz']); }); it('works with handles with multiple outputs', async () => { const graph = await buildFlowGraph(` particle P1 foo: writes Foo {} particle P2 bar: reads Foo {} particle P3 baz: reads Foo {} recipe R P1 foo: writes h P2 bar: reads h P3 baz: reads h `); assert.hasAllKeys(graph.particleMap, ['P1', 'P2', 'P3']); assert.sameMembers(graph.connectionsAsStrings, ['P1.foo -> P2.bar', 'P1.foo -> P3.baz']); }); it('works with datastores with tag claims', async () => { const graph = await buildFlowGraph(` schema MyEntity text: Text resource MyResource start ${entityString} store MyStore of MyEntity in MyResource claim is trusted particle P input: reads MyEntity recipe R s: use MyStore P input: reads s `); assert.lengthOf(graph.edges, 1); const modifier = graph.edges[0].modifier; assert.strictEqual(modifier.tagOperations.size, 1); assert.strictEqual(modifier.tagOperations.get('trusted'), 'add'); }); it('copies particle claims to particle out-edges as a flow modifier', async () => { const graph = await buildFlowGraph(` particle P foo: writes Foo {} claim foo is trusted recipe R P foo: writes h `); assert.lengthOf(graph.edges, 1); assert.isNotNull(graph.edges[0].modifier); assert.deepEqual(graph.edges[0].modifier, FlowModifier.parse('+node:P0', '+edge:E0', '+tag:trusted')); }); it('copies particle checks to particle nodes and in-edges', async () => { const graph = await buildFlowGraph(` particle P foo: reads Foo {} check foo is trusted recipe R P foo: reads h `); assert.lengthOf(graph.edges, 1); const check = graph.edges[0].check; assert.deepNestedInclude(check, {type: 'tag', value: 'trusted'}); }); it('supports making checks on slots', async () => { const graph = await buildFlowGraph(` particle P1 root: consumes slotToProvide: provides check slotToProvide data is trusted particle P2 slotToConsume: consumes recipe R root: slot 'rootslotid-root' P1 root: consumes root slotToProvide: provides slot0 P2 slotToConsume: consumes slot0 `); assert.lengthOf(graph.slots, 2); const slot1 = checkDefined(graph.slots[0]); assert.isEmpty(slot1.outEdges); assert.lengthOf(slot1.inEdges, 1); assert.strictEqual(slot1.inEdges[0].connectionName, 'root'); assert.strictEqual((slot1.inEdges[0].start as ParticleNode).name, 'P1'); assert.isUndefined(slot1.inEdges[0].check); assert.isUndefined(slot1.check); assert.strictEqual(slot1.inEdges[0].edgeId, 'E0'); assert.strictEqual(slot1.inEdges[0].start.nodeId, 'P0'); assert.deepEqual(slot1.inEdges[0].modifier, FlowModifier.parse('+edge:E0', '+node:P0')); const slot2 = checkDefined(graph.slots[1]); assert.isEmpty(slot2.outEdges); assert.lengthOf(slot2.inEdges, 1); assert.strictEqual(slot2.inEdges[0].connectionName, 'slotToConsume'); assert.strictEqual((slot2.inEdges[0].start as ParticleNode).name, 'P2'); const check = slot2.inEdges[0].check; assert.deepNestedInclude(check, {type: 'tag', value: 'trusted'}); assert.strictEqual(slot2.inEdges[0].edgeId, 'E1'); assert.strictEqual(slot2.inEdges[0].start.nodeId, 'P1'); assert.deepEqual(slot2.inEdges[0].modifier, FlowModifier.parse('+edge:E1', '+node:P1')); }); it('resolves data store names and IDs', async () => { const graph = await buildFlowGraph(` schema MyEntity text: Text resource MyResource start ${entityString} store MyStore of MyEntity 'my-store-id' in MyResource particle P input: reads MyEntity recipe R s: use MyStore P input: reads s `); assert.lengthOf(graph.handles, 1); const storeId = graph.handles[0].storeId; assert.strictEqual(graph.resolveStoreRefToID({type: 'id', store: 'my-store-id'}), 'my-store-id'); assert.strictEqual(graph.resolveStoreRefToID({type: 'name', store: 'MyStore'}), storeId); assert.throws(() => graph.resolveStoreRefToID({type: 'name', store: 'UnknownName'}), 'Store with name UnknownName not found.'); assert.throws(() => graph.resolveStoreRefToID({type: 'id', store: 'unknown-id'}), `Store with id 'unknown-id' not found.`); }); it('all node and edge IDs are unique', async () => { const graph = await buildFlowGraph(` particle P1 root: consumes slotToProvide: provides check slotToProvide data is trusted input: reads Foo {} particle P2 slotToConsume: consumes output: writes Foo {} recipe R root: slot 'rootslotid-root' P1 root: consumes root slotToProvide: provides slot0 input: reads h P2 slotToConsume: consumes slot0 output: writes h `); const allNodeIds = graph.nodes.map(n => n.nodeId); const allEdgeIds = graph.edges.map(e => e.edgeId); assert.lengthOf(allNodeIds, 5); // 2 particles, 2 slots, 1 handle. assert.lengthOf(allEdgeIds, 4); // 2 handle connections, 2 slot connections. // Check all values are unique. assert.strictEqual(new Set(allNodeIds).size, 5); assert.strictEqual(new Set(allEdgeIds).size, 4); assert.sameMembers(allNodeIds, ['P0', 'P1', 'S0', 'S1', 'H0']); assert.sameMembers(allEdgeIds, ['E0', 'E1', 'E2', 'E3']); }); it('handles with the use, map or copy fates are marked as ingress', async () => { const runForHandleWithFate = async (fate: string) => { const graph = await buildFlowGraph(` schema MyEntity text: Text resource MyResource start ${entityString} store MyStore of MyEntity 'my-store-id' in MyResource particle P foo: reads MyEntity recipe R foo: ${fate} P foo: reads foo `); assert.lengthOf(graph.particles, 1); assert.isFalse(graph.particles[0].ingress); assert.lengthOf(graph.handles, 1); return graph.handles[0]; }; assert.isFalse((await runForHandleWithFate('create')).ingress); assert.isTrue((await runForHandleWithFate('use MyStore')).ingress); assert.isTrue((await runForHandleWithFate('map MyStore')).ingress); assert.isTrue((await runForHandleWithFate('copy MyStore')).ingress); }); it('supports circular "derives from" statements', async () => { // Regression test for a race condition bug where the order in which edges // were created was important ('claim foo1 derives from foo2' required that // and edge for foo2 had already been created). const graph = await buildFlowGraph(` particle P foo1: reads writes Foo {} foo2: reads writes Foo {} claim foo1 derives from foo2 claim foo2 derives from foo1 recipe R P foo1: reads writes h1 foo2: reads writes h2 `); assert.lengthOf(graph.edges, 4); const foo1Out = graph.edges.find(e => e instanceof ParticleOutput && e.label === 'P.foo1') as ParticleOutput; const foo2Out = graph.edges.find(e => e instanceof ParticleOutput && e.label === 'P.foo2') as ParticleOutput; const foo1In = graph.edges.find(e => e instanceof ParticleInput && e.label === 'P.foo1') as ParticleInput; const foo2In = graph.edges.find(e => e instanceof ParticleInput && e.label === 'P.foo2') as ParticleInput; assert.lengthOf(foo1Out.derivesFrom, 1); assert.strictEqual(foo1Out.derivesFrom[0], foo2In); assert.lengthOf(foo2Out.derivesFrom, 1); assert.strictEqual(foo2Out.derivesFrom[0], foo1In); }); describe('references', () => { it('derives from input with same type', async () => { const graph = await buildFlowGraph(` particle P foo: reads Foo {} bar: reads Bar {} outRef: writes &Foo {} recipe R P foo: reads h1 bar: reads h2 outRef: writes h3 `); const outEdge = graph.edges.find(e => e instanceof ParticleOutput) as ParticleOutput; assert.lengthOf(outEdge.derivesFrom, 1); assert.strictEqual(outEdge.derivesFrom[0].label, 'P.foo'); }); it('derives from input with same reference type', async () => { const graph = await buildFlowGraph(` particle P fooRef: reads &Foo {} bar: reads Bar {} outRef: writes &Foo {} recipe R P fooRef: reads h1 bar: reads h2 outRef: writes h3 `); const outEdge = graph.edges.find(e => e instanceof ParticleOutput) as ParticleOutput; assert.lengthOf(outEdge.derivesFrom, 1); assert.strictEqual(outEdge.derivesFrom[0].label, 'P.fooRef'); }); it('derives from input collections of same type', async () => { const graph = await buildFlowGraph(` particle P fooCollection: reads [Foo {}] fooBigCollection: reads BigCollection<Foo {}> bar: reads Bar {} outRef: writes &Foo {} recipe R P fooCollection: reads h1 fooBigCollection: reads h2 bar: reads h3 outRef: writes h4 `); const outEdge = graph.edges.find(e => e instanceof ParticleOutput) as ParticleOutput; assert.lengthOf(outEdge.derivesFrom, 2); const labels = outEdge.derivesFrom.map(e => e.label); assert.sameMembers(labels, ['P.fooCollection', 'P.fooBigCollection']); }); it('derives from input entity containing same reference', async () => { const graph = await buildFlowGraph(` schema Baz abc: Text xyz: Number foo: &Foo {} particle P baz: reads Baz bar: reads Bar {} outRef: writes &Foo {} recipe R P baz: reads h1 bar: reads h2 outRef: writes h3 `); const outEdge = graph.edges.find(e => e instanceof ParticleOutput) as ParticleOutput; assert.lengthOf(outEdge.derivesFrom, 1); assert.strictEqual(outEdge.derivesFrom[0].label, 'P.baz'); }); it('derives from output of same type', async () => { const graph = await buildFlowGraph(` particle P outRef: writes &Foo {} outFoo: writes Foo {} recipe R P outRef: writes h2 outFoo: writes h3 `); const outEdge = graph.edges.find(e => e instanceof ParticleOutput && e.label === 'P.outRef') as ParticleOutput; assert.lengthOf(outEdge.derivesFrom, 1); assert.strictEqual(outEdge.derivesFrom[0].label, 'P.outFoo'); }); it('derives from output collection containing same type', async () => { const graph = await buildFlowGraph(` particle P outRef: writes &Foo {} outFoo: writes [Foo {}] recipe R P outRef: writes h1 outFoo: writes h2 `); const outEdge = graph.edges.find(e => e instanceof ParticleOutput && e.label === 'P.outRef') as ParticleOutput; assert.lengthOf(outEdge.derivesFrom, 1); assert.strictEqual(outEdge.derivesFrom[0].label, 'P.outFoo'); }); it('does not derive from output reference of same type', async () => { const graph = await buildFlowGraph(` particle P outRef1: writes &Foo {} outRef2: writes &Foo {} recipe R P outRef1: writes h1 outRef2: writes h2 `); const outEdge = graph.edges.find(e => e instanceof ParticleOutput && e.label === 'P.outRef1') as ParticleOutput; assert.lengthOf(outEdge.derivesFrom, 0); }); it('does not derive from output entity containing same reference', async () => { const graph = await buildFlowGraph(` schema Baz abc: Text xyz: Number foo: &Foo {} particle P outRef: writes &Foo {} outBaz: writes Baz recipe R P outRef: writes h1 outBaz: writes h2 `); const outEdge = graph.edges.find(e => e instanceof ParticleOutput && e.label === 'P.outRef') as ParticleOutput; assert.lengthOf(outEdge.derivesFrom, 0); }); it('"derives from" claims override reference logic', async () => { const graph = await buildFlowGraph(` particle P foo: reads Foo {} bar: reads Bar {} outRef: writes &Foo {} claim outRef derives from bar recipe R P foo: reads h1 bar: reads h2 outRef: writes h3 `); const outEdge = graph.edges.find(e => e instanceof ParticleOutput) as ParticleOutput; assert.lengthOf(outEdge.derivesFrom, 1); assert.strictEqual(outEdge.derivesFrom[0].label, 'P.bar'); }); }); });
the_stack
import { Protocol } from 'devtools-protocol'; import { getResourceTypeForChromeValue } from '@secret-agent/interfaces/ResourceType'; import * as eventUtils from '@secret-agent/commons/eventUtils'; import { TypedEventEmitter } from '@secret-agent/commons/eventUtils'; import { IPuppetNetworkEvents, IPuppetResourceRequest, } from '@secret-agent/interfaces/IPuppetNetworkEvents'; import { CanceledPromiseError } from '@secret-agent/commons/interfaces/IPendingWaitEvent'; import IRegisteredEventListener from '@secret-agent/interfaces/IRegisteredEventListener'; import { IBoundLog } from '@secret-agent/interfaces/ILog'; import { URL } from 'url'; import IProxyConnectionOptions from '@secret-agent/interfaces/IProxyConnectionOptions'; import { DevtoolsSession } from './DevtoolsSession'; import AuthChallengeResponse = Protocol.Fetch.AuthChallengeResponseResponse; import Fetch = Protocol.Fetch; import RequestWillBeSentEvent = Protocol.Network.RequestWillBeSentEvent; import WebSocketFrameSentEvent = Protocol.Network.WebSocketFrameSentEvent; import WebSocketFrameReceivedEvent = Protocol.Network.WebSocketFrameReceivedEvent; import WebSocketWillSendHandshakeRequestEvent = Protocol.Network.WebSocketWillSendHandshakeRequestEvent; import ResponseReceivedEvent = Protocol.Network.ResponseReceivedEvent; import RequestPausedEvent = Protocol.Fetch.RequestPausedEvent; import LoadingFinishedEvent = Protocol.Network.LoadingFinishedEvent; import LoadingFailedEvent = Protocol.Network.LoadingFailedEvent; import RequestServedFromCacheEvent = Protocol.Network.RequestServedFromCacheEvent; import RequestWillBeSentExtraInfoEvent = Protocol.Network.RequestWillBeSentExtraInfoEvent; interface IResourcePublishing { hasRequestWillBeSentEvent: boolean; emitTimeout?: NodeJS.Timeout; isPublished?: boolean; isDetailsEmitted?: boolean; } const mbBytes = 1028 * 1028; export class NetworkManager extends TypedEventEmitter<IPuppetNetworkEvents> { protected readonly logger: IBoundLog; private readonly devtools: DevtoolsSession; private readonly attemptedAuthentications = new Set<string>(); private readonly redirectsById = new Map<string, IPuppetResourceRequest[]>(); private readonly requestsById = new Map<string, IPuppetResourceRequest>(); private readonly requestPublishingById = new Map<string, IResourcePublishing>(); private readonly navigationRequestIdsToLoaderId = new Map<string, string>(); private parentManager?: NetworkManager; private readonly registeredEvents: IRegisteredEventListener[]; private mockNetworkRequests?: ( request: Protocol.Fetch.RequestPausedEvent, ) => Promise<Protocol.Fetch.FulfillRequestRequest>; private readonly proxyConnectionOptions: IProxyConnectionOptions; private isChromeRetainingResources = false; constructor( devtoolsSession: DevtoolsSession, logger: IBoundLog, proxyConnectionOptions?: IProxyConnectionOptions, ) { super(); this.devtools = devtoolsSession; this.logger = logger.createChild(module); this.proxyConnectionOptions = proxyConnectionOptions; this.registeredEvents = eventUtils.addEventListeners(this.devtools, [ ['Fetch.requestPaused', this.onRequestPaused.bind(this)], ['Fetch.authRequired', this.onAuthRequired.bind(this)], ['Network.webSocketWillSendHandshakeRequest', this.onWebsocketHandshake.bind(this)], ['Network.webSocketFrameReceived', this.onWebsocketFrame.bind(this, true)], ['Network.webSocketFrameSent', this.onWebsocketFrame.bind(this, false)], ['Network.requestWillBeSent', this.onNetworkRequestWillBeSent.bind(this)], ['Network.requestWillBeSentExtraInfo', this.onNetworkRequestWillBeSentExtraInfo.bind(this)], ['Network.responseReceived', this.onNetworkResponseReceived.bind(this)], ['Network.loadingFinished', this.onLoadingFinished.bind(this)], ['Network.loadingFailed', this.onLoadingFailed.bind(this)], ['Network.requestServedFromCache', this.onNetworkRequestServedFromCache.bind(this)], ]); } public emit< K extends (keyof IPuppetNetworkEvents & string) | (keyof IPuppetNetworkEvents & symbol) >(eventType: K, event?: IPuppetNetworkEvents[K]): boolean { if (this.parentManager) { this.parentManager.emit(eventType, event); } return super.emit(eventType, event); } public async initialize(): Promise<void> { if (this.mockNetworkRequests) { return this.devtools .send('Fetch.enable', { handleAuthRequests: !!this.proxyConnectionOptions?.password, }) .catch(err => err); } const maxResourceBufferSize = this.proxyConnectionOptions?.address ? mbBytes : 5 * mbBytes; // 5mb max if (maxResourceBufferSize > 0) this.isChromeRetainingResources = true; const errors = await Promise.all([ this.devtools .send('Network.enable', { maxPostDataSize: 0, maxResourceBufferSize, maxTotalBufferSize: maxResourceBufferSize * 5, }) .catch(err => err), this.proxyConnectionOptions?.password ? this.devtools .send('Fetch.enable', { handleAuthRequests: true, }) .catch(err => err) : Promise.resolve(), ]); for (const error of errors) { if (error && error instanceof Error) throw error; } } public async setNetworkInterceptor( mockNetworkRequests: NetworkManager['mockNetworkRequests'], disableSessionLogging: boolean, ): Promise<void> { this.mockNetworkRequests = mockNetworkRequests; const promises: Promise<any>[] = []; if (disableSessionLogging) { promises.push(this.devtools.send('Network.disable')); } promises.push( this.devtools.send('Fetch.enable', { handleAuthRequests: !!this.proxyConnectionOptions?.password, }), ); await Promise.all(promises); } public close(): void { eventUtils.removeEventListeners(this.registeredEvents); this.cancelPendingEvents('NetworkManager closed'); } public initializeFromParent(parentManager: NetworkManager): Promise<void> { this.parentManager = parentManager; return this.initialize(); } private onAuthRequired(event: Protocol.Fetch.AuthRequiredEvent): void { const authChallengeResponse = { response: AuthChallengeResponse.Default, } as Fetch.AuthChallengeResponse; if (this.attemptedAuthentications.has(event.requestId)) { authChallengeResponse.response = AuthChallengeResponse.CancelAuth; } else if (this.proxyConnectionOptions?.password) { this.attemptedAuthentications.add(event.requestId); authChallengeResponse.response = AuthChallengeResponse.ProvideCredentials; authChallengeResponse.username = 'puppet-chrome'; authChallengeResponse.password = this.proxyConnectionOptions.password; } this.devtools .send('Fetch.continueWithAuth', { requestId: event.requestId, authChallengeResponse, }) .catch(error => { if (error instanceof CanceledPromiseError) return; this.logger.info('NetworkManager.continueWithAuthError', { error, requestId: event.requestId, url: event.request.url, }); }); } private async onRequestPaused(networkRequest: RequestPausedEvent): Promise<void> { try { if (this.mockNetworkRequests) { const response = await this.mockNetworkRequests(networkRequest); if (response) { return await this.devtools.send('Fetch.fulfillRequest', response); } } await this.devtools.send('Fetch.continueRequest', { requestId: networkRequest.requestId, }); } catch (error) { if (error instanceof CanceledPromiseError) return; this.logger.info('NetworkManager.continueRequestError', { error, requestId: networkRequest.requestId, url: networkRequest.request.url, }); } let resource: IPuppetResourceRequest; try { // networkId corresponds to onNetworkRequestWillBeSent resource = <IPuppetResourceRequest>{ browserRequestId: networkRequest.networkId ?? networkRequest.requestId, resourceType: getResourceTypeForChromeValue( networkRequest.resourceType, networkRequest.request.method, ), url: new URL(networkRequest.request.url), method: networkRequest.request.method, isSSL: networkRequest.request.url.startsWith('https'), isFromRedirect: false, isUpgrade: false, isHttp2Push: false, isServerHttp2: false, requestTime: new Date(), protocol: null, hasUserGesture: false, documentUrl: networkRequest.request.headers.Referer, frameId: networkRequest.frameId, }; } catch (error) { this.logger.warn('NetworkManager.onRequestPausedError', { error, url: networkRequest.request.url, browserRequestId: networkRequest.requestId, }); return; } const existing = this.requestsById.get(resource.browserRequestId); if (existing) { if (existing.url === resource.url) { resource.requestHeaders = existing.requestHeaders ?? {}; } if (existing.resourceType) resource.resourceType = existing.resourceType; resource.redirectedFromUrl = existing.redirectedFromUrl; } this.mergeRequestHeaders(resource, networkRequest.request.headers); if (networkRequest.networkId && !this.requestsById.has(networkRequest.networkId)) { this.requestsById.set(networkRequest.networkId, resource); } if (networkRequest.requestId !== networkRequest.networkId) { this.requestsById.set(networkRequest.requestId, resource); } // requests from service workers (and others?) will never register with RequestWillBeSentEvent // -- they don't have networkIds this.emitResourceRequested(resource.browserRequestId); } private onNetworkRequestWillBeSent(networkRequest: RequestWillBeSentEvent): void { const redirectedFromUrl = networkRequest.redirectResponse?.url; const isNavigation = networkRequest.requestId === networkRequest.loaderId && networkRequest.type === 'Document'; if (isNavigation) { this.navigationRequestIdsToLoaderId.set(networkRequest.requestId, networkRequest.loaderId); } let resource: IPuppetResourceRequest; try { resource = <IPuppetResourceRequest>{ url: new URL(networkRequest.request.url), isSSL: networkRequest.request.url.startsWith('https'), isFromRedirect: !!redirectedFromUrl, isUpgrade: false, isHttp2Push: false, isServerHttp2: false, requestTime: new Date(networkRequest.wallTime * 1e3), protocol: null, browserRequestId: networkRequest.requestId, resourceType: getResourceTypeForChromeValue( networkRequest.type, networkRequest.request.method, ), method: networkRequest.request.method, hasUserGesture: networkRequest.hasUserGesture, documentUrl: networkRequest.documentURL, redirectedFromUrl, frameId: networkRequest.frameId, }; } catch (error) { this.logger.warn('NetworkManager.onNetworkRequestWillBeSentError', { error, url: networkRequest.request.url, browserRequestId: networkRequest.requestId, }); return; } const publishing = this.getPublishingForRequestId(resource.browserRequestId, true); publishing.hasRequestWillBeSentEvent = true; const existing = this.requestsById.get(resource.browserRequestId); const isNewRedirect = redirectedFromUrl && existing && existing.url !== resource.url; // NOTE: same requestId will be used in devtools for redirected resources if (existing) { if (isNewRedirect) { const existingRedirects = this.redirectsById.get(resource.browserRequestId) ?? []; existing.redirectedToUrl = networkRequest.request.url; existing.responseHeaders = networkRequest.redirectResponse.headers; existing.status = networkRequest.redirectResponse.status; existing.statusMessage = networkRequest.redirectResponse.statusText; this.redirectsById.set(resource.browserRequestId, [...existingRedirects, existing]); publishing.isPublished = false; clearTimeout(publishing.emitTimeout); publishing.emitTimeout = undefined; } else { // preserve headers and frameId from a fetch or networkWillRequestExtraInfo resource.requestHeaders = existing.requestHeaders ?? {}; } } this.requestsById.set(resource.browserRequestId, resource); this.mergeRequestHeaders(resource, networkRequest.request.headers); this.emitResourceRequested(resource.browserRequestId); } private onNetworkRequestWillBeSentExtraInfo( networkRequest: RequestWillBeSentExtraInfoEvent, ): void { const requestId = networkRequest.requestId; let resource = this.requestsById.get(requestId); if (!resource) { resource = {} as any; this.requestsById.set(requestId, resource); } this.mergeRequestHeaders(resource, networkRequest.headers); const hasNetworkRequest = this.requestPublishingById.get(requestId)?.hasRequestWillBeSentEvent === true; if (hasNetworkRequest) { this.doEmitResourceRequested(resource.browserRequestId); } } private mergeRequestHeaders( resource: IPuppetResourceRequest, requestHeaders: RequestWillBeSentEvent['request']['headers'], ): void { resource.requestHeaders ??= {}; for (const [key, value] of Object.entries(requestHeaders)) { const titleKey = `${key .split('-') .map(x => x[0].toUpperCase() + x.slice(1)) .join('-')}`; if (resource.requestHeaders[titleKey] && titleKey !== key) { delete resource.requestHeaders[titleKey]; } resource.requestHeaders[key] = value; } } private emitResourceRequested(browserRequestId: string): void { const resource = this.requestsById.get(browserRequestId); if (!resource) return; const publishing = this.getPublishingForRequestId(browserRequestId, true); // if we're already waiting, go ahead and publish now if (publishing.emitTimeout && !publishing.isPublished) { this.doEmitResourceRequested(browserRequestId); return; } // give it a small period to add extra info. no network id means it's running outside the normal "requestWillBeSent" flow publishing.emitTimeout = setTimeout( this.doEmitResourceRequested.bind(this), 200, browserRequestId, ).unref(); } private doEmitResourceRequested(browserRequestId: string): boolean { const resource = this.requestsById.get(browserRequestId); if (!resource) return false; if (!resource.url) return false; const publishing = this.getPublishingForRequestId(browserRequestId, true); clearTimeout(publishing.emitTimeout); publishing.emitTimeout = undefined; const event = <IPuppetNetworkEvents['resource-will-be-requested']>{ resource, isDocumentNavigation: this.navigationRequestIdsToLoaderId.has(browserRequestId), frameId: resource.frameId, redirectedFromUrl: resource.redirectedFromUrl, loaderId: this.navigationRequestIdsToLoaderId.get(browserRequestId), }; // NOTE: same requestId will be used in devtools for redirected resources if (!publishing.isPublished) { publishing.isPublished = true; this.emit('resource-will-be-requested', event); } else if (!publishing.isDetailsEmitted) { publishing.isDetailsEmitted = true; this.emit('resource-was-requested', event); } } private onNetworkResponseReceived(event: ResponseReceivedEvent): void { const { response, requestId, loaderId, frameId, type } = event; const resource = this.requestsById.get(requestId); if (resource) { resource.responseHeaders = response.headers; resource.status = response.status; resource.statusMessage = response.statusText; resource.remoteAddress = `${response.remoteIPAddress}:${response.remotePort}`; resource.protocol = response.protocol; resource.responseUrl = response.url; resource.responseTime = new Date(); if (response.fromDiskCache) resource.browserServedFromCache = 'disk'; if (response.fromServiceWorker) resource.browserServedFromCache = 'service-worker'; if (response.fromPrefetchCache) resource.browserServedFromCache = 'prefetch'; if (response.requestHeaders) this.mergeRequestHeaders(resource, response.requestHeaders); if (!resource.url) { resource.url = new URL(response.url); resource.frameId = frameId; resource.browserRequestId = requestId; } if (!this.requestPublishingById.get(requestId)?.isPublished && resource.url?.href) { this.doEmitResourceRequested(requestId); } } const isNavigation = requestId === loaderId && type === 'Document'; if (isNavigation) { this.emit('navigation-response', { frameId, browserRequestId: requestId, status: response.status, location: response.headers.location, url: response.url, loaderId: event.loaderId, }); } } private onNetworkRequestServedFromCache(event: RequestServedFromCacheEvent): void { const { requestId } = event; const resource = this.requestsById.get(requestId); if (resource) { resource.browserServedFromCache = 'memory'; setTimeout(() => this.emitLoaded(requestId), 500).unref(); } } private onLoadingFailed(event: LoadingFailedEvent): void { const { requestId, canceled, blockedReason, errorText } = event; const resource = this.requestsById.get(requestId); if (resource) { if (!resource.url || !resource.requestTime) { return; } if (canceled) resource.browserCanceled = true; if (blockedReason) resource.browserBlockedReason = blockedReason; if (errorText) resource.browserLoadFailure = errorText; if (!this.requestPublishingById.get(requestId)?.isPublished) { this.doEmitResourceRequested(requestId); } this.emit('resource-failed', { resource, }); this.redirectsById.delete(requestId); this.requestsById.delete(requestId); this.requestPublishingById.delete(requestId); } } private onLoadingFinished(event: LoadingFinishedEvent): void { const { requestId } = event; this.emitLoaded(requestId); } private emitLoaded(id: string): void { const resource = this.requestsById.get(id); if (resource) { if (!this.requestPublishingById.get(id)?.isPublished) this.emitResourceRequested(id); this.requestsById.delete(id); this.requestPublishingById.delete(id); const loaderId = this.navigationRequestIdsToLoaderId.get(id); if (this.redirectsById.has(id)) { for (const redirect of this.redirectsById.get(id)) { this.emit('resource-loaded', { resource: redirect, frameId: redirect.frameId, loaderId, // eslint-disable-next-line require-await body: async () => Buffer.from(''), }); } this.redirectsById.delete(id); } const body = this.downloadRequestBody.bind(this, id); this.emit('resource-loaded', { resource, frameId: resource.frameId, loaderId, body }); } } private async downloadRequestBody(requestId: string): Promise<Buffer> { if (this.isChromeRetainingResources === false || !this.devtools.isConnected()) { return null; } try { const body = await this.devtools.send('Network.getResponseBody', { requestId, }); return Buffer.from(body.body, body.base64Encoded ? 'base64' : undefined); } catch (e) { return null; } } private getPublishingForRequestId(id: string, createIfNull = false): IResourcePublishing { const publishing = this.requestPublishingById.get(id); if (publishing) return publishing; if (createIfNull) { this.requestPublishingById.set(id, { hasRequestWillBeSentEvent: false }); return this.requestPublishingById.get(id); } } /////// WEBSOCKET EVENT HANDLERS ///////////////////////////////////////////////////////////////// private onWebsocketHandshake(handshake: WebSocketWillSendHandshakeRequestEvent): void { this.emit('websocket-handshake', { browserRequestId: handshake.requestId, headers: handshake.request.headers, }); } private onWebsocketFrame( isFromServer: boolean, event: WebSocketFrameSentEvent | WebSocketFrameReceivedEvent, ): void { const browserRequestId = event.requestId; const { opcode, payloadData } = event.response; const message = opcode === 1 ? payloadData : Buffer.from(payloadData, 'base64'); this.emit('websocket-frame', { message, browserRequestId, isFromServer, }); } }
the_stack
declare function App(param: WeApp.AppParam): void; /**注册一个页面 */ declare function Page(param: WeApp.PageParam): void; /**注册一个组件 */ declare function Component(param: WeApp.ComponentParam): void /**全局函数 可以获取到小程序实例 */ declare function getApp(): WeApp.AppParam; /**获取当前页面栈的实例 以数组形式按栈的顺序给出 第一个元素为首页 最后一个元素为当前页面 */ declare function getCurrentPages(): Array<WeApp.Page>; declare var wx: WeApp.wx; // #endregion declare namespace WeApp { // #region WeApp interfaces /**指定小程序的生命周期函数等 */ interface AppParam { /** * 生命周期函数--监听小程序初始化 * 当小程序初始化完成时 会触发 onLaunch(全局只触发一次) */ onLaunch?: (info: LaunchData) => void; /** * 生命周期函数--监听小程序显示 * 当小程序启动 或从后台进入前台显示 会触发 onShow */ onShow?: (info: LaunchData) => void; /** * 生命周期函数--监听小程序隐藏 * 当小程序从前台进入后台 会触发 onHide */ onHide?: Function; /** * 错误监听函数 * 当小程序发生脚本错误 或者 api 调用失败时 会触发 onError 并带上错误信息 */ onError?: Function; /**开发者可以添加任意的函数或数据到参数中 用 this 可以访问 */ [others: string]: any; } /**指定页面的初始数据 生命周期函数 事件处理函数等 */ interface PageParam { /**页面的初始数据 */ data?: Object; /**生命周期函数--监听页面加载 */ onLoad?: Function; /**生命周期函数--监听页面初次渲染完成 */ onReady?: Function; /**生命周期函数--监听页面显示 */ onShow?: Function /**生命周期函数--监听页面隐藏 */ onHide?: Function; /**生命周期函数--监听页面卸载 */ onUnload?: Function; /**页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh?: Function; /**页面上拉触底事件的处理函数 */ onReachBottom?: Function; /** * 设置该页面的分享信息 * * 只有定义了此事件处理函数 右上角菜单才会显示“分享”按钮 * * 用户点击分享按钮的时候会调用 * * 此事件需要 return 一个 Object 用于自定以分享内容 */ onShareAppMessage?: (options?: { from: string, target: Target }) => PageShareData; /**页面滚动触发事件的处理函数 */ onPageScroll?: Function; /**开发者可以添加任意的函数或数据到参数中 用 this 可以访问 */ [others: string]: any; } /**指定组件的生命周期函数 时间处理函数及方法等 */ interface ComponentParam { /**组件的对外属性 是属性名到属性设置的映射表 * 属性设置中可包含三个字段 * type 表示属性类型 * value 表示属性初始值 * observer 表示属性值被更改时的响应函数 */ properties?: Object /**组件的内部数据 和 properties 一同用于组件的模版渲染 */ data?: Object /**组件的方法 包括事件响应函数和任意的自定义方法 */ methods?: { [others: string]: any } /**类似于mixins和traits的组件间代码复用机制 */ behaviors?: Array<string> /**组件生命周期函数 在组件实例进入页面节点树时执行 注意此时不能调用 setData */ created?: Function /**组件生命周期函数 在组件实例进入页面节点树时执行 */ attached?: Function /**组件生命周期函数 在组件布局完成后执行 此时可以获取节点信息 */ ready?: Function /**组件生命周期函数 在组件实例被移动到节点树另一个位置时执行 */ moved?: Function /**组件生命周期函数 在组件实例被从页面节点树移除时执行 */ detached?: Function /**组件间关系定义 */ relations?: Object /**组件接受的外部样式类 */ externalClasses?: Array<string> /**一些组件选项 请参见文档其他部分的说明 */ options?: Object /**开发者可以添加任意的函数或数据到参数中 用 this 可以访问 */ [others: string]: any } /**页面 */ interface Page { /**用于将数据从逻辑层发送到视图层 */ setData: (data: any, callback?: Function) => void; /**字段可以获取到当前页面的路径*/ route: string; /**页面逻辑层数据 */ data: any; [others: string]: any; } interface wx { // 网络 API 列表 /** * 发起网络请求 * 发起的是https请求 * 一个微信小程序同时只能有5个网络请求连接 */ request(param: RequestParam): RequestTask; /** * 上传文件 * 将本地资源上传到开发者服务器 * 如 页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后 可通过此接口将本地资源上传到指定服务器 客户端发起一个 HTTPS POST 请求 其中 Content-Type 为 multipart/form-data */ uploadFile(param: UploadParam): UploadTask; /** * 下载文件 * 下载文件资源到本地 客户端直接发起一个 HTTP GET 请求 把下载到的资源根据 type 进行处理 并返回文件的本地临时路径 */ downloadFile(param: DownloadParam): DownloadTask; /** * 创建 WebSocket 连接 * 基础库 1.7.0 之前 一个微信小程序同时只能有一个 WebSocket 连接 如果当前已存在一个 WebSocket 连接 会自动关闭该连接 并重新创建一个 WebSocket 连接 基础库版本 1.7.0 及以后 支持存在多个 WebSokcet 连接 每次成功调用 wx.connectSocket 会返回一个新的 SocketTask */ connectSocket(param: ConnectSocketParam): void; /**监听 WebSocket 打开 */ onSocketOpen(callback: (res?: any) => void): void; /**监听 WebSocket 错误 */ onSocketError(callback: (res?: any) => void): void; /** * 发送 WebSocket 消息 * 通过 WebSocket 连接发送数据 需要先 wx.connectSocket 并在 wx.onSocketOpen 回调之后才能发送 */ sendSocketMessage(message: SocketMessage): void; /**接受 WebSocket 消息 */ onSocketMessage(callback: (res?: { data: string | ArrayBuffer }) => void): void; /**关闭 WebSocket 连接 */ closeSocket(param: CloseSocketParam): void; /**监听 WebSocket 关闭 */ onSocketClose(callback: (res?: any) => void): void; // 媒体 API 列表 /**从相册选择图片 或者拍照 */ chooseImage(param: ChooseImageParam): void; /**预览图片 */ previewImage(param: PreviewImageParam): void; /**获取图片信息 */ getImageInfo(param: ImageInfoParam): void; /** * 开始录音 * 当主动调用wx.stopRecord 或者录音超过1分钟时自动结束录音 返回录音文件的临时文件路径 */ startRecord(param: RecordParam): void; /** * 结束录音 * 主动调用停止录音 */ stopRecord(): void; /**获取全局唯一的录音管理器 */ getRecorderManager(): RecorderManager; /** * 播放语音 * 开始播放语音 同时只允许一个语音文件正在播放 如果前一个语音文件还没播放完 将中断前一个语音播放 */ playVoice(param: VoiceParam): void; /** * 暂停播放语音 * 暂停正在播放的语音 再次调用wx.playVoice播放同一个文件时 会从暂停处开始播放 如果想从头开始播放 需要先调用 wx.stopVoice */ pauseVoice(): void; /**结束播放语音 */ stopVoice(): void; /**获取音乐播放状态 */ getBackgroundAudioPlayerState(param: GetBackgroundAudioPlayerStateParam): void; /**播放音乐 */ playBackgroundAudio(param: PlayBackgroundAudioParam): void; /**暂停播放音乐 */ pauseBackgroundAudio(): void; /**控制音乐播放进度 */ seekBackgroundAudio(param: SeekBackgroundAudioParam): void; /**停止播放音乐 */ stopBackgroundAudio(): void; /**监听音乐开始播放 */ onBackgroundAudioPlay(callback: (res?: any) => void): void; /**监听音乐暂停 */ onBackgroundAudioPause(callback: (res?: any) => void): void; /**监听音乐结束 */ onBackgroundAudioStop(callback: (res?: any) => void): void; /**从相册选择视频 或者拍摄 */ chooseVideo(param: ChooseVideoParam): void; /**创建并返回 audio 上下文 audioContext 对象 */ createAudioContext(audioId: string): AudioContext; /** * @since 1.6.0 * @description 创建并返回内部 audio 上下文 innerAudioContext 对象 本接口是 wx.createAudioContext 升级版 */ createInnerAudioContext(): InnerAudioContext; /**创建并返回 video 上下文 videoContext 对象 */ createVideoContext(videoId: string): VideoContext; /**创建并返回 camera 上下文 cameraContext 对象 cameraContext 与页面的 camera 组件绑定 一个页面只能有一个camera 通过它可以操作对应的 <camera/> 组件 */ createCameraContext(): CameraContext; // 文件 /**保存文件 */ saveFile(param: SaveFileParam): void; /**获取本地已保存的文件列表 */ getSavedFileList(param: FileListParam): void; /**获取本地文件的文件信息 */ getSavedFileInfo(param: FileInfoParam): void; /**删除本地存储的文件 */ removeSavedFile(param: RemoveFileParam): void; /** * 新开页面打开文档 * 支持格式 doc/x,xls/x,ppt/x,pdf */ openDocument(param: OpenDocumentParam): void; // 数据 API 列表 /**获取本地数据缓存 */ getStorage(param: GetStorageParam): void; /**从本地缓存中同步获取指定 key 对应的内容 */ getStorageSync(key: string): any; /** * 设置本地数据缓存 * 将数据存储在本地缓存中指定的 key 中会覆盖掉原来该 key 对应的内容 这是一个异步接口 */ setStorage(param: SetStorageParam): void; /**将 data 存储在本地缓存中指定的 key 中 会覆盖掉原来该 key 对应的内容 这是一个同步接口 */ setStorageSync(key: string, data: any): void; /**从本地缓存中异步移除指定key */ removeStorage(param: RemoveStorageParam): void; /**从本地缓存中同步移除指定key */ removeStorageSync(key: string): void; /**清理本地数据缓存 */ clearStorage(): void; /**同步清理本地数据缓存 */ clearStorageSync(): void; /**异步获取当前storage的相关信息 */ getStorageInfo(pram: StorageInfoParam): void; /**同步获取当前storage的相关信息 */ getStorageInfoSync(): StorageInfo; // 位置 API 列表 /**获取当前的地理位置 速度 */ getLocation(param: GetLocationParam): void; /**使用微信内置地图查看位置 */ openLocation(param: OpenLocationParam): void; /**打开地图选择位置 */ chooseLocation(param: ChooseLocationParam): void; /**创建并返回 map 上下文 mapContext 对象 */ createMapContext(mapId: string): void; // 设备 API 列表 /**获取网络类型 */ getNetworkType(param: NetworkTypeParam): void; /**获取系统信息 */ getSystemInfo(param: SystemInfoParam): void; /**同步获取系统信息 */ getSystemInfoSync(): SystemInfo; /** * 获取全局唯一的版本更新管理器,用于管理小程序更新 */ getUpdateManager(): UpdateManager; /** * 监听重力感应数据 * 频率 5次/秒 */ onAccelerometerChange(callback: (res?: AccelerometerInfo) => void): void; /** * 监听罗盘数据 * 频率 5次/秒 */ onCompassChange(callback: (res?: CompassInfo) => void): void; /**打电话 */ makePhoneCall(param: PhoneCallParam): void; //交互反馈 /**显示消息提示框 */ showToast(param: ToastParam): void; /**隐藏消息提示框 */ hideToast(): void; /**显示模态弹窗 */ showModal(param: ModalParam): void; /**显示操作菜单 */ showActionSheet(param: ActionSheetParam): void; // 界面 API 列表 /**设置置顶信息 */ setTopBarText(param: TopBarTextParam): void; /**设置当前页面标题 */ setNavigationBarTitle(param: NavigationBarTitleParam): void; /**在当前页面显示导航条加载动画 */ showNavigationBarLoading(): void; /**隐藏导航条加载动画 */ hideNavigationBarLoading(): void; /**新窗口打开页面 */ navigateTo(param: NavigateToParam): void; /**原窗口打开页面 */ redirectTo(param: NavigateToParam): void; /**关闭当前页面 回退前一页面 */ navigateBack(param?: { /**返回的页面数 如果 delta 大于现有页面数 则返回到首页 默认1 */delta: number }): void; /**动画 */ createAnimation(param: AnimationParam): Animation; /**把当前画布的内容导出生成图片 并返回文件路径 */ canvasToTempFilePath(param: CanvasToTempFilePathParam): void; /** * @deprecated 不推荐使用 * @description 创建绘图上下文 */ createContext(): CanvasContext; /** * @deprecated 不推荐使用 * @description 绘图 */ drawCanvas(param: DrawCanvasParam): void; /**创建 canvas 绘图上下文(指定 canvasId) */ createCanvasContext(canvasId: string): CanvasContext; /**隐藏键盘 */ hideKeyboard(): void; /**停止下拉刷新动画 */ stopPullDownRefresh(): void; /** * @since 1.5.0 * @description 开始下拉刷新 调用后触发下拉刷新动画 效果与用户手动下拉刷新一致 */ startPullDownRefresh(param: CallbackWithErrMsgParam): never; // 开放接口 /**登录 */ login(param: LoginParam): void; /**获取用户信息 */ getUserInfo(param: UserInfoParam): void; /**发起微信支付 */ requestPayment(param: RequestPaymentParam): void; /**检查登陆态是否过期 */ checkSession(param: CallbackParam): void; /**跳转到 tabBar 页面 并关闭其他所有非 tabBar 页面 */ switchTab(param: SwitchTabParam): void; /**调起客户端扫码界面 扫码成功后返回对应的结果 */ scanCode(param: ScanCodeParam): void; // 蓝牙相关 /**初始化蓝牙适配器 */ openBluetoothAdapter(param: CallbackParam): void; /**关闭蓝牙模块 调用该方法将断开所有已建立的链接并释放系统资源 */ closeBluetoothAdapter(param: CallbackParam): void; /**获取本机蓝牙适配器状态 */ getBluetoothAdapterState(param: BluetoothAdapterStateParam): void; /**监听蓝牙适配器状态变化事件 */ onBluetoothAdapterStateChange(param: BluetoothAdapterStateChangeParam): void; /**开始搜寻附近的蓝牙外围设备 */ startBluetoothDevicesDiscovery(param: BluetoothDevicesDiscoveryParam): void; /**停止搜寻附近的蓝牙外围设备 */ stopBluetoothDevicesDiscovery(param: CallbackWithErrMsgParam): void; /**获取所有已发现的蓝牙设备 包括已经和本机处于连接状态的设备 */ getBluetoothDevices(param: BluetoothDevicesParam): void; /**监听寻找到新设备的事件 */ onBluetoothDeviceFound(callback: (devices: Array<BluetoothDevice>) => void): void; /**根据 uuid 获取处于已连接状态的设备 */ getConnectedBluetoothDevices(param: ConnectedBluetoothDevicesParam): void; /**连接低功耗蓝牙设备 */ createBLEConnection(param: BLEConnectionParam): void; /**断开与低功耗蓝牙设备的连接 */ closeBLEConnection(param: BLEConnectionParam): void; /**监听低功耗蓝牙连接的错误事件 包括设备丢失 连接异常断开等等 */ onBLEConnectionStateChange(callback: (res: { deviceId: string; connected: boolean }) => void): void; /**获取蓝牙设备所有 service */ getBLEDeviceServices(param: BLEDeviceServicesParam): void; /**获取蓝牙设备所有 characteristic */ getBLEDeviceCharacteristics(param: BLEDeviceCharacteristicsParam): void; /**读取低功耗蓝牙设备的特征值的二进制数据值 */ readBLECharacteristicValue(parm: BLECharacteristicValueParam): void; /**向低功耗蓝牙设备特征值中写入二进制数据 */ writeBLECharacteristicValue(param: WriteBLECharacteristicValueParam): void; /**启用低功耗蓝牙设备特征值变化时的 notify 功能 */ notifyBLECharacteristicValueChange(param: BLECharacteristicValueChangedParam): void; /**监听低功耗蓝牙设备的特征值变化 必须先启用notify */ onBLECharacteristicValueChange(callback: (res: { deviceId: string; connected: boolean; characteristicId: string; value: ArrayBuffer }) => void): void; /**调起用户编辑收货地址原生界面 并在编辑完成后返回用户选择的地址 */ chooseAddress(param: AddressParam): void; /**调起客户端小程序设置界面 返回用户设置的操作结果 */ openSetting(param: SettingParam): void; /**获取用户的当前设置 */ getSetting(param: SettingParam): void; /**提前授权 */ authorize(param: AuthorizeParam): void; /**关闭所有页面 打开到应用内的某个页面 */ reLaunch(param: ReLaunchParam): void; /**将 ArrayBuffer 数据转成 Base64 字符串 */ arrayBufferToBase64(data: ArrayBuffer): string; /**将 Base64 字符串转成 ArrayBuffer 数据 */ base64ToArrayBuffer(data: string): ArrayBuffer; /**显示 loading 提示框 */ showLoading(param: LoadingParam): void; /**隐藏消息提示框 */ hideLoading(): void; /**开始监听加速度数据 */ startAccelerometer(param: CallbackParam): void; /**停止监听加速度数据 */ stopAccelerometer(param: CallbackParam): void; /**设置系统剪贴板的内容 */ setClipboardData(param: SetClipboardParam): void; /**获取系统剪贴板内容 */ getClipboardData(param: CallbackParam): void; /**批量添加卡券 */ addCard(param: CardParam): void; /**查看微信卡包中的卡券 */ openCard(param: CardParam): void; /**监听网络状态变化 */ onNetworkStatusChange(callback: (res: { isConnected: boolean; networkType: string; }) => void): void; /**显示分享按钮 */ showShareMenu(param: ShareMenuParam): void; /**隐藏分享按钮 */ hideShareMenu(param: CallbackParam): void; /**获取分享详细信息 */ getShareInfo(param: ShareInfoParam): void; /**更新转发属性 */ updateShareMenu(param: ShareMenuParam): void; /**获取第三方平台自定义的数据字段 */ getExtConfig(param: ExtConfigParam): void; /**获取第三方平台自定义的数据字段的同步接口 */ getExtConfigSync(): object; /** * 判断小程序的API 回调 参数 组件等是否在当前版本可用 * @param param 使用${API}.${method}.${param}.${options}或者${component}.${attribute}.${option}方式来调用 */ canIUse(param: string): never; /**开始搜索附近的iBeacon设备 */ startBeaconDiscovery(param: CallbackWithErrMsgParam): void; /**停止搜索附近的iBeacon设备 */ stopBeaconDiscovery(param: CallbackWithErrMsgParam): void; /**获取所有已搜索到的iBeacon设备 */ getBeacons(param: BeaconsParam): void; /**监听 iBeacon 设备的更新事件 */ onBeaconUpdate(callback: (res: { beacons: Array<IBeacon> }) => void): void; /**监听 iBeacon 服务的状态变化 */ onBeaconServiceChange(callback: (res: { /**服务目前是否可用 */available: boolean; /**目前是否处于搜索状态 */discovering: boolean }) => void): void; /**获取屏幕亮度 */ getScreenBrightness(param: GetScreenBrightnessParam): void; /**设置屏幕亮度 */ setScreenBrightness(param: SetScreenBrightnessParam): void; /**保存联系人到系统通讯录 */ addPhoneContact(param: AddPhoneContactParam): void; /**使手机发生较长时间的振动 400ms */ vibrateLong(param: CallbackParam): void; /**使手机发生较短时间的振动 15ms */ vibrateShort(param: CallbackParam): void; /**获取用户过去三十天微信运动步数 需要先调用 wx.login 接口 */ getWeRunData(param: GetWeRunDataParam): void; /**保存图片到系统相册 需要用户授权 scope.writePhotosAlbum */ saveImageToPhotosAlbum(param: SaveImageToPhotosAlbumParam): void; /**保存视频到系统相册 */ saveVideoToPhotosAlbum(param: SaveImageToPhotosAlbumParam): void; /**获取全局唯一的背景音频管理器 */ getBackgroundAudioManager(): BackgroundAudioManager; /**打开同一公众号下关联的另一个小程序 */ navigateToMiniProgram(param: NavigateToMiniProgramParam): void; /**返回到上一个小程序 只有在当前小程序是被其他小程序打开时可以调用成功 */ navigateBackMiniProgram(param: NavigateBackMiniProgramParam): void; /** * 返回一个SelectorQuery对象实例 * 可以在这个实例上使用select等方法选择节点 并使用boundingClientRect等方法选择需要查询的信息 */ createSelectorQuery(): SelectorQuery; /**获取文件信息 */ getFileInfo(param: GetFileInfoParam): never; /**监听用户主动截屏事件 用户使用系统截屏按键截屏时触发此事件 */ onUserCaptureScreen(callback?: Function): never; /**将页面滚动到目标位置 单位px */ pageScrollTo(scrollTop: number): never; /**支持小程序修改标题栏颜色 */ setNavigationBarColor(param: SetNavigationBarColorParam): never; /**设置是否打开调试开关 此开关对正式版也能生效 */ setEnableDebug(param: SetEnableDebugParam): never; /**设置是否保持常亮状态 仅在当前小程序生效 离开小程序后设置失效 */ setKeepScreenOn(param: SetKeepScreenOnParam): never; /** * @since 1.5.0 * @description 获取本机支持的 SOTER 生物认证方式 */ checkIsSupportSoterAuthentication(param: CheckIsSupportSoterAuthenticationParam): never; /** * @since 1.5.0 * @description 开始 SOTER 生物认证 */ startSoterAuthentication(param: StartSoterAuthenticationParam): never; /**获取设备内是否录入如指纹等生物信息的接口 */ checkIsSoterEnrolledInDevice(param: CheckIsSoterEnrolledInDeviceParam): never; /** * @since 1.5.0 * @description 选择用户的发票抬头 */ chooseInvoiceTitle(param: ChooseInvoiceTitleParam): never; /** * 获取日志管理器对象 * @since 2.1.0 */ getLogManager(): LogManager; } // #endregion // #region interfaces interface CallbackParam { /**接口调用成功的回调函数 */ success?: (res?: any) => void; /**接口调用失败的回调函数 */ fail?: (res?: any) => void; /**接口调用结束的回调函数(调用成功/失败都会执行) */ complete?: Function; } interface CallbackWithErrMsgParam extends CallbackParam { success?: (res?: {/**成功:ok 错误:详细信息 */errMsg: string }) => void; } interface RequestParam extends CallbackParam { /**开发者服务器接口地址 */ url: string; /**请求的参数 */ data?: Object | string; /**设置请求的 header,header 中不能设置 Referer */ header?: Object /**默认为 GET 有效值:OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT */ method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'; /**如果设为json 会尝试对返回的数据做一次 JSON.parse */ dataType?: string; /** * @description 设置响应的数据类型 * @since 1.7.0 */ responseType?: 'text' | 'arraybuffer'; /**收到开发者服务成功返回的回调函数 res = { data: '开发者服务器返回的内容' } */ success?: (res?: HttpResponse) => void; } interface RequestTask { abort(): never; } interface HttpResponse { data?: Object | string | ArrayBuffer; errMsg: string; statusCode: number; /**@since 1.2.0 */ header?: Object; } interface UploadParam extends CallbackParam { /**开发者服务器 url */ url: string; /**要上传文件资源的路径 */ filePath: string; /**文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ name: string; /**HTTP 请求 Header , header 中不能设置 Referer */ header?: Object; /**HTTP 请求中其他额外的 form data */ formData?: Object; } interface UploadTask { onProgressUpdate: (res: { progress: number; totalBytesSent: number; totalBytesExpectedToSend: number; }) => never; abort(): never; } interface DownloadParam extends CallbackParam { /**下载资源的 url */ url: string; /** * 下载资源的类型 * 用于客户端识别处理 有效值: image|audio|video */ type?: string; /**HTTP 请求 Header */ header?: Object; /** 下载成功后以 tempFilePath 的形式传给页面 res = { tempFilePath: '文件的临时路径' } */ success?: (res?: { tempFilePath: string }) => void } interface DownloadTask { onProgressUpdate: (res: { progress: number; totalBytesWritten: number; totalBytesExpectedToWrite: number; }) => never; abort(): never; } interface ConnectSocketParam extends CallbackParam { /**开发者服务器接口地址 必须是 HTTPS 协议 且域名必须是后台配置的合法域名 */ url: string; /**请求的数据 */ data?: Object; /** HTTP Header header 中不能设置 Referer */ header?: Object; /**默认是GET 有效值为: OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT */ method?: string; /**子协议数组 */ protocols?: Array<string>; } interface SocketMessage extends CallbackParam { /**需要发送的内容 */ data: string | ArrayBuffer; } interface CloseSocketParam extends CallbackParam { /**一个数字值表示关闭连接的状态号 表示连接被关闭的原因 如果这个参数没有被指定 默认的取值是1000 */ code?: number; /**一个可读的字符串 表示连接被关闭的原因 这个字符串必须是不长于123字节的UTF-8 文本 */ reason?: string; } interface ChooseImageParam extends CallbackParam { /**最多可以选择的图片张数 默认9 */ count?: number; /**original 原图 compressed 压缩图 默认二者都有 */ sizeType?: Array<string>; /**album 从相册选图 camera 使用相机 默认二者都有 */ sourceType?: Array<string>; } interface PreviewImageParam extends CallbackParam { /**当前显示图片的链接 不填则默认为 urls 的第一张 */ current?: string; /**需要预览的图片链接列表 */ urls: Array<string>; } interface ImageInfoParam extends CallbackParam { /**图片的路径 可以是相对路径 临时文件路径 存储文件路径 */ src: string; success?: (res?: { width: number, height: number }) => void; } interface RecordParam extends CallbackParam { duration?: number; success?: (res?: { tempFilePath: string }) => void; } interface RecorderManager { /**开始录音 */ start(options: RecorderManagerStartOption): void; /**暂停录音 */ pause(): void; /**继续录音 */ resume(): void; /**停止录音 */ stop(): void; /**录音开始事件 */ onStart: () => void; /**录音暂停事件 */ onPause: () => void; /**录音停止事件 会回调文件地址 */ onStop: (res?: { tempPath: string }) => void; /**已录制完指定帧大小的文件 会回调录音分片结果数据。如果设置了 frameSize 则会回调此事件 */ onFrameRecorded: (res?: { frameBuffer: ArrayBuffer; isLastFrame: boolean }) => void; /**录音错误事件 会回调错误信息 */ onError: (res?: { errMsg: string }) => void; } interface RecorderManagerStartOption { /** * 指定录音的时长 单位 ms 如果传入了合法的 duration 在到达指定的 duration 后会自动停止录音 最大值 600000(10 分钟),默认值 60000(1分钟) */ duration?: number; /**采样率 */ sampleRate?: 8000 | 16000 | 44100; /**录音通道数 */ numberOfChannels?: 1 | 2; encodeBitRate?: 8000 | 11025 | 12000 | 16000 | 22050 | 24000 | 32000 | 44100 | 48000; /**音频格式 */ format?: 'aac' | 'mp3'; /**指定帧大小 单位 KB 传入 frameSize 后 每录制指定帧大小的内容后 会回调录制的文件内容 不指定则不会回调 暂仅支持 mp3 格式 */ frameSize?: number; } interface VoiceParam extends CallbackParam { /**需要播放的语音文件的文件路径 */ filePath: string; } interface GetBackgroundAudioPlayerStateParam extends CallbackParam { success?: (res?: BackgroundAudioPlayerState) => void; } interface BackgroundAudioPlayerState { /**选定音频的长度 单位:s 只有在当前有音乐播放时返回 */ duration: number; /**选定音频的播放位置 单位:s 只有在当前有音乐播放时返回 */ currentPosition: number; /** 播放状态 2:没有音乐在播放 1:播放中 0:暂停中 */ status: number; /**音频的下载进度 整数 80 代表 80% 只有在当前有音乐播放时返回 */ downloadPercent: number; /**歌曲数据链接 只有在当前有音乐播放时返回 */ dataUrl: string; } interface PlayBackgroundAudioParam extends CallbackParam { /**音乐链接 */ dataUrl: string; /**音乐标题 */ title?: string; /**封面URL */ coverImgUrl?: string; } interface SeekBackgroundAudioParam extends CallbackParam { /**音乐位置 单位:秒 */ position: number; } interface SaveFileParam extends CallbackParam { /**需要保存的文件的临时路径 */ tempFilePath: string; success?: (res?: { savedFilePath?: string }) => void; } interface FileListParam extends CallbackParam { success?: (res?: { errMsg: string, fileList: Array<FileInfo> }) => void; } interface FileInfo { /**文件的本地路径 */ filePath: string; /**文件的保存时的时间戳 从1970/01/01 08:00:00到当前时间的秒数 */ createTime: number; /**文件大小 单位B */ size: number; } interface FileInfoParam extends CallbackParam { /**文件路径 */ filePath: string; success?: (res?: { errMsg: string, size: number, createTime: number }) => void; } interface RemoveFileParam extends CallbackParam { /**需要删除的文件路径 */ filePath: string; } interface OpenDocumentParam extends CallbackParam { /**文件路径 可通过 downFile 获得 */ filePath: string; /**文件类型 指定文件类型打开文件 */ fileType?: 'doc' | 'xls' | 'ppt' | 'pdf' | 'docx' | 'xlsx' | 'pptx'; } interface ChooseVideoParam extends CallbackParam { /**album 从相册选视频 camera 使用相机拍摄 默认为:['album', 'camera'] */ sourceType?: Array<string>; /** * @since 1.6.0 * @description 是否压缩所选的视频源文件 默认值为true 需要压缩 */ compressed?: boolean; /**拍摄视频最长拍摄时间 单位秒 最长支持60秒 */ maxDuration?: number; /**前置或者后置摄像头 默认为前后都有 即:['front', 'back'] */ camera?: Array<string>; /**接口调用成功 返回视频文件的临时文件路径 */ success?: (res?: VideoInfo) => void; } interface AudioContext { /**设置音频的地址 */ setSrc(src: string): void; /**播放 */ play(): void; /**暂停 */ pause(): void; /**跳转到指定位置 单位 s */ seek(position: number): void; } interface InnerAudioContext { /**音频的数据链接 用于直接播放 */ src: string; /**开始播放的位置 单位:s 默认 0 */ startTime: number; /**是否自动开始播放 默认 false */ autoplay: boolean; /**是否循环播放 默认 false */ loop: boolean; /**是否遵循系统静音开关 当此参数为 false 时 即使用户打开了静音开关 也能继续发出声音 默认值 true */ obeyMuteSwitch: boolean; /**当前音频的长度 单位:s 只有在当前有合法的 src 时返回 */ readonly duration: number; /**当前音频的播放位置 单位:s 只有在当前有合法的 src 时返回 时间不取整 保留小数点后 6 位 */ readonly currentTime: number; /**当前是是否暂停或停止状态 true 表示暂停或停止 false 表示正在播放 */ readonly paused: boolean; /**音频缓冲的时间点 仅保证当前播放时间点到此时间点内容已缓冲 */ readonly buffered: number; /**播放 */ play(): void; /**暂停 */ pause(): void; /**停止 */ stop(): void; /**跳转到指定位置 单位 s */ seek(position: number): void; /**销毁当前实例 */ destroy(): void; /**音频进入可以播放状态 但不保证后面可以流畅播放 */ onCanplay: () => void; /**音频播放事件 */ onPlay: () => void; /**音频暂停事件 */ onPause: () => void; /**音频停止事件 */ onStop: () => void; /**音频自然播放结束事件 */ onEnded: () => void; /**音频播放进度更新事件 */ onTimeUpdate: () => void; /**音频播放错误事件 */ onError: () => void; /**音频加载中事件 当音频因为数据不足 需要停下来加载时会触发 */ onWaiting: () => void; /**音频进行 seek 操作事件 */ onSeeking: () => void; /**音频完成 seek 操作事件 */ onSeeked: () => void; } interface VideoContext { /**播放 */ play(): never; /**暂停 */ pause(): never; /**跳转到指定位置 单位 s */ seek(position: number): never; /**发送弹幕 danmu 包含两个属性 text,color */ sendDanmu(danmu: { text: string, color: string }): never; /**设置倍速播放 支持的倍率有 0.5/0.8/1.0/1.25/1.5 */ playbackRate(rate: number): never; /**进入全屏 */ requestFullScreen(): never; /**退出全屏 */ exitFullScreen(): never; } interface VideoInfo { /**选定视频的临时文件路径 */ tempFilePath: string; /**选定视频的时间长度 */ duration: number; /**选定视频的数据量大小 */ size: number; /**返回选定视频的长 */ height: number; /**返回选定视频的宽 */ width: number; } interface CameraContext { /**拍照 可指定质量 成功则返回图片 */ takePhoto(param: CameraContextTakePhotoParam): void; /**开始录像 */ startRecord(param: CameraContextStartRecordParam): void; /**结束录像 成功则返回封面与视频 */ stopRecord(param: CameraContextStopRecord): void; } interface CameraContextTakePhotoParam extends CallbackParam { /**成像质量 值为high, normal, low 默认normal */ quality?: 'high' | 'normal' | 'low'; success?: (res?: { tempImagePath: string }) => void; } interface CameraContextStartRecordParam extends CallbackParam { /**超过30s或页面onHide时会结束录像 */ timeoutCallback?: (res?: { tempThumbPath: string; tempVideoPath: string }) => void; } interface CameraContextStopRecord extends CallbackParam { success?: (res?: { tempThumbPath: string; tempVideoPath: string }) => void; } interface SetStorageParam extends CallbackParam { /**本地缓存中的指定的 key */ key: string; /**需要存储的内容 */ data: any; } interface GetStorageParam extends CallbackParam { /**本地缓存中的指定的 key */ key: string; success: (res?: { data: any }) => void; } interface RemoveStorageParam extends CallbackParam { key: string; success?: (res?: { data: any }) => void; } interface StorageInfoParam extends CallbackParam { success: (res?: { data: StorageInfo }) => void; } interface StorageInfo { /**当前storage中所有的key */ keys: Array<string>; /**当前占用的空间大小 单位kb */ currentSize: number; /**限制的空间大小 单位kb */ limitSize: number; } interface GetLocationParam extends CallbackParam { /**默认为 wgs84 返回 gps 坐标 gcj02 返回可用于wx.openLocation的坐标 */ type?: string; /**接口调用成功的回调函数 */ success: (res?: LocationInfo) => void; } interface TranslateMarkerParam extends CallbackParam { /**指定marker */ markerId: number; /**指定marker移动到的目标点 */ destination: any; /**移动过程中是否自动旋转marker */ autoRotate: boolean; /**marker的旋转角度 */ rotate: number /**动画持续时长 默认值1000ms 平移与旋转分别计算 */ duration?: number; /**动画结束回调函数 */ animationEnd?: Function; } interface LocationInfo { /**纬度 浮点数 范围为 -90~90 负数表示南纬 */ latitude: number; /**经度 浮点数 范围为 -180~180 负数表示西经 */ longitude: number; /**速度 浮点数 单位 m/s */ speed: number; /**位置的精确度 */ accuracy: number; /**高度 单位 m */ altitude: number; /**垂直精度 单位 m Android 无法获取 返回 0 */ verticalAccuracy: number; /**水平精度 单位 m */ horizontalAccuracy: number; } interface OpenLocationParam extends CallbackParam { /**纬度 范围为 -90~90 负数表示南纬 */ latitude: number; /**经度 范围为 -180~180 负数表示西经 */ longitude: number; /**缩放比例 范围1~28 默认为28 */ scale?: number; /**位置名 */ name?: string; /**地址的详细说明 */ address?: string; } interface ChooseLocationParam extends CallbackParam { success: (res?: ChoosedLoaction) => void; } interface ChoosedLoaction { /**位置名称 */ name: string; /**详细地址 */ address: string; /**纬度 浮点数 范围为-90~90 负数表示南纬 */ latitude: number; /**经度 浮点数 范围为-180~180 负数表示西经 */ longitude: number } interface NetworkTypeParam extends CallbackParam { success: (res?: { /**返回网络类型2g|3g|4g|wifi */networkType: string }) => void; } interface SystemInfoParam extends CallbackParam { success: (res?: SystemInfo) => void; } interface SystemInfo { /**手机品牌 */ brand: string; /**手机型号 */ model: string; /**设备像素比 */ pixelRatio: string; /**窗口宽度 */ windowWidth: string; /**窗口高度 */ windowHeight: string; /**微信设置的语言 */ language: string; /**微信版本号 */ version: string; /**操作系统版本 */ system: string; /**客户端平台 */ platform: string; /**屏幕宽度 */ screenWidth: string; /**屏幕高度 */ screenHeight: string; /**用户字体大小设置 */ fontSizeSetting: string; /**客户端基础库版本 */ SDKVersion: string; } interface UpdateManager { applyUpdate: Function; onCheckForUpdate(callback: Function): void; onUpdateFailed(callback: Function): void; onUpdateReady(callback: Function): void; } interface AccelerometerInfo { /**X 轴 */ x: number; /**Y 轴 */ y: number; /**Z 轴 */ z: number; } interface CompassInfo { /**面对的方向度数 */ direction: number; } interface PhoneCallParam extends CallbackParam { /**需要拨打的电话号码 */ phoneNumber: string; success?: () => void; } interface ToastParam extends CallbackParam { /**提示的内容 */ title: string; /**图标 只支持 success|loading|none */ icon?: 'success' | 'loading' | 'none'; /**自定义图标的本地路径 image 的优先级高于 icon */ image?: string; /**提示的延迟时间 单位毫秒 默认 1500 最大为10000 */ duration?: number; /**是否显示透明蒙层 防止触摸穿透 默认 false */ mask?: boolean; } interface ModalParam extends CallbackParam { /**提示的标题 */ title: string; /**提示的内容 */ content: string; /**是否显示取消按钮 默认为 false */ showCancel?: boolean; /**取消按钮的文字 默认为 取消 最多 4 个字符 */ cancelText?: string; /**取消按钮的文字颜色 默认为 #000000 */ cancelColor?: string; /**确定按钮的文字 默认为 确定 最多 4 个字符 */ confirmText?: string; /**确定按钮的文字颜色 默认为 #3CC51F */ confirmColor?: string; /** * 接口调用成功的回调函数 * 返回res.confirm==1时 表示用户点击确定按钮 */ success?: (res?: { confirm: boolean, cancel: boolean }) => void; } interface ActionSheetParam extends CallbackParam { /**按钮的文字数组 数组长度最大为10个 */ itemList: Array<string>; /**按钮的文字颜色 默认为 #000000 */ itemColor?: string; success?: (res?: ActionSheetResponse) => void; } interface ActionSheetResponse { /**用户是否取消选择 */ cancel: boolean; /**用户点击的按钮 从上到下的顺序 从0开始 */ tapIndex: number; } interface TopBarTextParam extends CallbackParam { /**置顶栏文字内容 */ text: string; } interface NavigationBarTitleParam extends CallbackParam { /**页面标题 */ title?: string; } interface NavigateToParam extends CallbackParam { /**需要跳转的应用内页面的路径 */ url: string; } interface AnimationParam { /**动画持续时间 单位ms 默认值 400 */ duration?: number; /**定义动画的效果 默认值 linear 有效值 linear,ease,ease-in,ease-in-out,ease-out,step-start,step-end */ timingFunction?: string; /**动画延迟时间 单位 ms 默认值 0 */ delay?: string; /**设置transform- origin 默认为"50% 50% 0" */ transformOrigin?: string; } /** * 动画实例可以调用以下方法来描述动画 * 调用结束后会返回自身 * 支持链式调用的写法 */ interface Animation { /** * 通过动画实例的export方法导出动画数据传递给组件的animation属性 * export 方法每次调用后会清掉之前的动画操作 */ export(): void; /** * 调用动画操作方法后要调用 step() 来表示一组动画完成 * 可以在一组动画中调用任意多个动画方法 * 一组动画中的所有动画会同时开始 * 一组动画完成后才会进行下一组动画 * step 可以传入一个跟 wx.createAnimation() 一样的配置参数用于指定当前组动画的配置 */ step(): void; /** * 透明度 * @param value 参数范围 0~1 */ opacity(value: number): Animation; /**颜色值 */ backgroundColor(color: string): Animation; /** * 长度值 * @param length 如果传入 Number 则默认使用 px 可传入其他自定义单位的长度值 */ width(length: number | string): Animation; /** * 长度值 * @param length 如果传入 Number 则默认使用 px 可传入其他自定义单位的长度值 */ height(length: number | string): Animation; /** * 长度值 * @param length 如果传入 Number 则默认使用 px 可传入其他自定义单位的长度值 */ top(length: number | string): Animation; /** * 长度值 * @param length 如果传入 Number 则默认使用 px 可传入其他自定义单位的长度值 */ left(length: number | string): Animation; /** * 长度值 * @param length 如果传入 Number 则默认使用 px 可传入其他自定义单位的长度值 */ bottom(length: number | string): Animation; /** * 长度值 * @param length 如果传入 Number 则默认使用 px 可传入其他自定义单位的长度值 */ right(length: number | string): Animation; /**deg的范围-180~180 从原点顺时针旋转一个deg角度 */ rotate(deg: number): Animation; /**deg的范围-180~180 在X轴旋转一个deg角度 */ rotateX(deg: number): Animation; /**deg的范围-180~180 在Y轴旋转一个deg角度 */ rotateY(deg: number): Animation; /**deg的范围-180~180 在Z轴旋转一个deg角度 */ rotateZ(deg: number): Animation; rotate3d(x: number, y: number, z: number, deg: number): Animation; /**一个参数时 表示在X轴 Y轴同时缩放sx倍数 两个参数时表示在X轴缩放sx倍数 在Y轴缩放sy倍数 */ scale(sx: number, sy?: number): Animation; /**在X轴缩放sx倍数 */ scaleX(sx: number): Animation; /**在Y轴缩放sy倍数 */ scaleY(sy: number): Animation; /**在Z轴缩放sz倍数 */ scaleZ(sz: number): Animation; /**在X轴缩放sx倍数 在Y轴缩放sy倍数 在Z轴缩放sz倍数 */ scale3d(sx: number, sy: number, sz: number): Animation; /**一个参数时 表示在X轴偏移tx 单位px 两个参数时 表示在X轴偏移tx 在Y轴偏移ty 单位px */ translate(tx: number, ty?: number): Animation; /**在X轴偏移tx 单位px */ translateX(tx: number): Animation; /**在Y轴偏移tx 单位px */ translateY(ty: number): Animation; /**在Z轴偏移tx 单位px */ translateZ(tz: number): Animation; /**在X轴偏移tx 在Y轴偏移ty 在Z轴偏移tz 单位px */ translate3d(tx: number, ty: number, tz: number): Animation; /**参数范围-180~180 一个参数时 Y轴坐标不变 X轴坐标延顺时针倾斜ax度 两个参数时 分别在X轴倾斜ax度 在Y轴倾斜ay度 */ skew(ax: number, ay?: number): Animation; /**参数范围-180~180 Y轴坐标不变 X轴坐标延顺时针倾斜ax度 */ skewX(ax: number): Animation; /**参数范围-180~180 X轴坐标不变 Y轴坐标延顺时针倾斜ay度 */ skewY(ay: number): Animation; matrix(a: number, b: number, c: number, d: number, tx: number, ty: number): Animation; matrix3d(a1: number, b1: number, c1: number, d1: number, a2: number, b2: number, c2: number, d2: number, a3: number, b3: number, c3: number, d3: number, a4: number, b4: number, c4: number, d4: number): void; } /** * context只是一个记录方法调用的容器 * 用于生成记录绘制行为的actions数组 * context跟<canvas/>不存在对应关系 * 一个context生成画布的绘制动作数组可以应用于多个<canvas/> */ interface CanvasContext { /**获取当前context上存储的绘图动作 */ getActions(): Array<any>; /**清空当前的存储绘图动作 */ clearActions(): void; /** * 对横纵坐标进行缩放 * 在调用scale方法后 * 之后创建的路径其横纵坐标会被缩放 * 多次调用scale 倍数会相乘 * @param scaleWidth 横坐标缩放的倍数 * 1=100% 0.5=50% 2=200% 依次类推 * @param scaleHeight 纵坐标轴缩放的倍数 * 1=100% 0.5=50% 2=200% 依次类推 */ scale(scaleWidth: number, scaleHeight: number): void; /** * 对坐标轴进行顺时针旋转 * 以原点为中心 * 原点可以用 translate方法修改 * 顺时针旋转当前坐标轴 * 多次调用rotate * 旋转的角度会叠加 * @param rotate 旋转角度 以弧度计 * degrees*Math.PI/180 degrees范围为0~360 */ rotate(rotate: number): void; /** * 对坐标原点进行缩放 * 对当前坐标系的原点(0,0)进行变换 * 默认的坐标系原点为页面左上角 * @param x 水平坐标平移量 * @param y 竖直坐标平移量 */ translate(x: number, y: number): void; /**保存当前坐标轴的缩放 旋转 平移信息 */ save(): void; /**恢复之前保存过的坐标轴的缩放 旋转 平移信息 */ restore(): void; /** * 在给定的矩形区域内 清除画布上的像素 * @param x 矩形区域左上角的x坐标 * @param y 矩形区域左上角的y坐标 * @param width 矩形区域的宽度 * @param height 矩形区域的高度 */ clearRect(x: number, y: number, width: number, height: number): void; /** * 在画布上绘制被填充的文本 * @param text 在画布上输出的文本 * @param x 绘制文本的左上角x坐标位置 * @param y 绘制文本的左上角y坐标位置 */ fillText(text: string, x?: number, y?: number): void; /** * 在画布上绘制图像 图像保持原始尺寸 * @param imageResource 通过chooseImage得到一个文件路径或者一个项目目录内的图片 所要绘制的图片资源 * @param x 图像左上角的x坐标 * @param y 图像左上角的y坐标 * @param width 图像宽度 * @param height 图像高度 */ drawImage(imageResource: string, x?: number, y?: number, width?: number, height?: number): void; /**对当前路径进行填充 */ fill(): void; /**对当前路径进行描边 */ stroke(): void; /** * 开始一个路径 * 开始创建一个路径 需要调用fill或者stroke才会使用路径进行填充或描边 同一个路径内的多次setFillStyle setStrokeStyle setLineWidth等设置 以最后一次设置为准 */ beginPath(): void; /**关闭一个路径 */ closePath(): void; /** * 把路径移动到画布中的指定点 但不创建线条 */ moveTo(x: number, y: number): void; /** * 添加一个新点 然后在画布中创建从该点到最后指定点的线条 * @param x 目标位置的x坐标 * @param y 目标位置的y坐标 */ lineTo(x: number, y: number): void; /** * 添加一个矩形路径到当前路径 * @param x 矩形路径左上角的x坐标 * @param y 矩形路径左上角的y坐标 * @param width 矩形路径的宽度 * @param height 矩形路径的高度 */ rect(x: number, y: number, width: number, height: number): void; /** * 画一条弧线 * @param x 圆的x坐标 * @param y 圆的y坐标 * @param r 圆的半径 * @param sAngle 起始弧度 单位弧度(在3点钟方向) * @param eAngle 终止弧度 * @param counterclockwise 指定弧度的方向是逆时针还是顺时针 默认是false 即顺时针 */ arc(x: number, y: number, r: number, sAngle: number, eAngle: number, counterclockwise?: boolean): void; /** * 创建二次贝塞尔曲线路径 * @param cpx 贝塞尔控制点的x坐标 * @param cpy 贝塞尔控制点的y坐标 * @param x 结束点的x坐标 * @param y 结束点的y坐标 */ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; /** * 创建三次方贝塞尔曲线路径 * @param cp1x 第一个贝塞尔控制点的x坐标 * @param cp1y 第一个贝塞尔控制点的y坐标 * @param cp2x 第二个贝塞尔控制点的x坐标 * @param cp2y 第二个贝塞尔控制点的y坐标 * @param x 结束点的x坐标 * @param y 结束点的y坐标 */ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; /** * 设置纯色填充 * @param color 设置为填充样式的颜色 'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 */ setFillStyle(color: string): void; /** * 设置纯色描边 * @param color 设置为填充样式的颜色 'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 */ setStrokeStyle(color: string): void; /** * 设置阴影 * @param offsetX 阴影相对于形状在水平方向的偏移 * @param offsetY 阴影相对于形状在竖直方向的偏移 * @param blur 阴影的模糊级别 数值越大越模糊 0~100 * @param color 阴影的颜色 'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 */ setShadow(offsetX: number, offsetY: number, blur: number, color: string): void; /**设置字体的字号 */ setFontSize(fontSize: number): void; /**设置线条的宽度 */ setLineWidth(lineWidth: number): void; /**设置线条的结束端点样式 */ setLineCap(lineCap: 'butt' | 'round' | 'square'): void; /** * 设置两条线相交时 * 所创建的拐角类型 */ setLineJoin(lineJoin: 'bevel' | 'round' | 'miter'): void; /** * 设置最大斜接长度 * 斜接长度指的是在两条线交汇处内角和外角之间的距离 * 当 setLineJoin为 miter 时才有效 * 超过最大倾斜长度的 * 连接处将以 lineJoin 为 bevel 来显示 */ setMiterLimit(miterLimit: number): void; /** * 填充一个矩形 * @param x 矩形路径左上角的x坐标 * @param y 矩形路径左上角的y坐标 * @param width 矩形路径的宽度 * @param height 矩形路径的高度 */ fillRect(x: number, y: number, width: number, height: number): void; /** * 画一个矩形(非填充) * @param x 矩形路径左上角的x坐标 * @param y 矩形路径左上角的y坐标 * @param width 矩形路径的宽度 * @param height 矩形路径的高度 */ strokeRect(x: number, y: number, width: number, height: number): void; /** * 创建一个线性的渐变颜色 * @param x0 起点的x坐标 * @param y0 起点的y坐标 * @param x1 终点的x坐标 * @param y1 终点的y坐标 */ createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; /** * 创建一个圆形的渐变颜色 * @param x 圆心的x坐标 * @param y 圆心的y坐标 * @param r 圆的半径 */ createCircularGradient(x: number, y: number, r: number): CanvasGradient; /**用于设置文字的对齐 */ setTextAlign(align: 'left' | 'center' | 'right'): void; /**用于设置文字的水平对齐 */ setTextBaseline(textBaseline: 'top' | 'bottom' | 'middle' | 'normal'): void; /** * @description 将之前在绘图上下文中的描述(路径 变形 样式) 画到 canvas 中 * @since 1.7.0 */ draw(reserve?: boolean, callback?: Function): void; } interface CanvasToTempFilePathParam extends CallbackParam { /**画布标识 传入 <canvas/> 的 cavas-id */ canvasId: string; /**画布x轴起点 默认0 */ x?: number; /**画布y轴起点 默认0 */ y?: number; /**画布宽度 默认为canvas宽度 - x */ width?: number; /**画布高度 默认为canvas高度 - y */ height?: number; /**输出图片宽度 默认为width */ destWidth?: number; /**输出图片高度 默认为height */ destHeight?: number; /** * @description 目标文件的类型 默认为 'png' * @since 1.7.0 */ fileType?: 'jpg' | 'png'; /** * @description 图片的质量 取值范围为 (0,1] 不在范围内时当作1.0处理 * @since 1.7.0 */ quality?: number; } interface CanvasGradient { /** * 指定颜色渐变点的位置和颜色 * @param position 位置必须位于0到1之间 */ addColorStop(position: number, color: string): void; } interface DrawCanvasParam { /**画布标识 传入 <canvas/> 的 cavas-id */ canvasId: string; /** * 绘图动作数组 * 由wx.createContext创建的context * 调用getActions方法导出绘图动作数组 */ actions: Array<any>; } interface LoginParam extends CallbackParam { success?: (res?: LoginResult) => void; } interface LoginResult { /**调用结果 */ errMsg: string; /** * 用户允许登录后 * 回调内容会带上code(有效期五分钟) * 开发者需要将code发送到开发者服务器后台 * 使用code换取session_key api * 将code换成openid和session_key */ code: string } interface UserInfoParam extends CallbackParam { /**是否带上登录态信息 * 当 withCredentials 为 true 时 要求此前有调用过 wx.login 且登录态尚未过期 * 此时返回的数据会包含 encryptedData iv 等敏感信息 * 当 withCredentials 为 false 时不要求有登录态 * 返回的数据不包含 encryptedData iv 等敏感信息 */ withCredentials?: boolean; /**指定返回用户信息的语言 zh_CN 简体中文 zh_TW 繁体中文 en 英文 */ lang?: string; success?: (res?: UserInfo) => void; } interface WxUserInfo { /**用户昵称 */ nickName: string; /**用户头像 最后一个数值代表正方形头像大小(有0 46 64 96 132数值可选 0代表640*640正方形头像) 用户没有头像时该项为空 若用户更换头像 原有头像URL将失效 */ avatarUrl: string; /**用户的性别 值为1时是男性 值为2时是女性 值为0时是未知 */ gender: string; /**用户所在城市 */ city: string; /**用户所在省份 */ province: string; /**用户所在国家 */ country: string; /**用户的语言 简体中文为zh_CN */ language: string; } interface UserInfo { /**用户信息对象 不包含 openid 等敏感信息 */ userInfo: WxUserInfo; /**不包括敏感信息的原始数据字符串 用于计算签名 */ rawData: string; /**使用sha1(rawData + sessionkey) 得到字符串 用于校验用户信息 */ signature: string; /**包括敏感数据在内的完整用户信息的加密数据 */ encryptedData: string; /**加密算法的初始向量 */ iv: string; } interface RequestPaymentParam extends CallbackParam { /**时间戳从1970年1月1日00: 00:00至今的秒数 即当前的时间 */ timeStamp: number; /**随机字符串 长度为32个字符以下 */ nonceStr: string; /**统一下单接口返回的prepay_id参数值 提交格式如 prepay_id=* */ package: string; /**签名算法 暂支持 MD5 */ signType: string; /**签名 具体签名方案参见微信公众号支付帮助文档 */ paySign: string; } interface Target { /**组件的id */ id: string; /**组件的类型 */ tagName: string; /**组件上由`data-`开头的自定义属性组成的集合 */ dataset: any; } /** * 事件对象 * 如无特殊说明 当组件触发事件时 逻辑层绑定该事件的处理函数会收到一个事件对象 */ interface BaseEvent { /**事件类型 */ type: string; /** * 事件生成时的时间戳 * 页面打开到触发事件所经过的毫秒数 */ timeStamp: number; /**触发事件的源组件 */ target: Target; /**事件绑定的当前组件 */ currentTarget: Target } interface Touch { /**触摸点的标识符 */ identifier: number; /**距离文档左上角的距离 文档的左上角为原点 横向为X轴 */ pageX: number; /**距离文档左上角的距离 文档的左上角为原点 纵向为Y轴 */ pageY: number; /**距离页面可显示区域(屏幕除去导航条)左上角距离 横向为X轴 */ clientX: number; /**距离页面可显示区域(屏幕除去导航条)左上角距离 纵向为Y轴 */ clientY: number; } interface TouchEvent extends BaseEvent { /**每个元素为一个 Touch 对象(canvas 触摸事件中携带的 touches 是 CanvasTouch 数组) 表示当前停留在屏幕上的触摸点 */ touches: Array<Touch>; /**表示有变化的触摸点 如从无变有(touchstart) 位置变化(touchmove) 从有变无(touchend touchcancel) */ changedTouches: Array<Touch>; } interface CustomEvent extends BaseEvent { /** * 额外的信息 * 自定义事件所携带的数据 如表单组件的提交事件会携带用户的输入 媒体的错误事件会携带错误信息 */ detail: any; } interface SwitchTabParam extends CallbackParam { /**需要跳转的 tabBar 页面的路径(需在 app.json 的 tabBar 字段定义的页面) 路径后不能带参数 */ url: string; } interface ScanCodeParam extends CallbackParam { /**是否只能从相机扫码 不允许从相册选择图片 */ onlyFromCamera?: boolean; success?: (res?: ScanCodeResult) => void; } interface ScanCodeResult { /**所扫码的内容 */ result: string; /**所扫码的类型 */ scanType: string; /**所扫码的字符集 */ charSet: string; /**当所扫的码为当前小程序的合法二维码时 会返回此字段 内容为二维码携带的 path */ path: string; } /**通过 mapId 跟一个 <map/> 组件绑定 通过它可以操作对应的 <map/> 组件 */ interface MapContext { /**获取当前地图中心的经纬度 返回的是 gcj02 坐标系 可以用于 wx.openLocation */ getCenterLocation(param: GetLocationParam): void; /**将地图中心移动到当前定位点 需要配合map组件的show-location使用 */ moveToLocation(): void; /**平移marker 带动画 */ translateMarker(param: TranslateMarkerParam): void; /**缩放视野展示所有经纬度 */ includePoints(param: { points: Array<{ latitude: number, longitude: number; }>; padding?: Array<any> }): void; /**获取当前地图的视野范围 */ getRegion(param: CallbackParam): void; /**获取当前地图的缩放级别 */ getScale(param: CallbackParam): void; } /**自定以分享内容 */ interface PageShareData extends CallbackWithErrMsgParam { /**分享标题 默认 当前小程序名称 */ title?: string; /**分享描述 默认 当前小程序名称 */ desc?: string; /**分享路径 当前页面 path 必须是以 / 开头的完整路径 */ path?: string; /**自定义图片路径 可以是本地文件路 代码包文件路径或者网络图片路径 支持PNG及JPG 不传入 imageUrl 则使用默认截图 */ imageUrl?: string; success?: (res?: { errMsg: string; shareTickets?: Array<string> }) => void; } interface BluetoothAdapterStateParam extends CallbackParam { success?: (res?: { adapterState: AdapterState, /**成功:ok 错误:详细信息 */errMsg: string }) => void; } /**蓝牙适配器状态信息 */ interface AdapterState { /**是否正在搜索设备 */ discovering: boolean; /**蓝牙适配器是否可用 */ available: boolean; } interface BluetoothAdapterStateChangeParam extends CallbackParam { success?: (res?: AdapterState) => void; } interface BluetoothDevicesDiscoveryParam extends CallbackWithErrMsgParam { /**蓝牙设备主 service 的 uuid 列表 */ services: Array<string>; } interface BluetoothDevicesParam extends CallbackParam { /**蓝牙设备主 service 的 uuid 列表 */ services: Array<string>; success: (res: { devices: Array<BluetoothDevice>, /**成功:ok 错误:详细信息 */errMsg: string }) => void; } interface BluetoothDevice { /** 蓝牙设备名称 某些设备可能没有 */ name: string; /**低功耗设备广播名称 某些设备可能没有 */ localName: string; /**用于区分设备的 id */ deviceId: string; /**当前蓝牙设备的信号强度 */ RSSI: number; /**当前蓝牙设备的广播内容 */ advertisData: ArrayBuffer; } interface ConnectedBluetoothDevicesParam extends CallbackParam { /**蓝牙设备主 service 的 uuid 列表 */ services: Array<string>; success: (res: { devices: Array<{ /**蓝牙设备名称 某些设备可能没有 */name: string, /**用于区分设备的 id */deviceId: string }>, /**成功:ok 错误:详细信息 */errMsg: string }) => void; } interface BLEConnectionParam extends CallbackWithErrMsgParam { /**蓝牙设备 id 参考 getDevices 接口 */ deviceId: string; } interface BLEDeviceServicesParam extends CallbackParam { deviceId: string; success: (res: { services: Array<{ /**蓝牙设备服务的 uuid */uuid: string; /**该服务是否为主服务 */isPrimary: boolean }>; /**成功:ok 错误:详细信息 */errMsg: string }) => void; } interface BLEDeviceCharacteristicsParam extends CallbackParam { /**蓝牙设备 id 参考 device 对象 */ deviceId: string; /**蓝牙服务 uuid */ serviceId: string; success: (res: { characteristics: Array<{ uuid: string; properties: { read: boolean; write: boolean; notify: boolean; indicate: boolean; } }>; errMsg: string; }) => void; } interface BLECharacteristicValueParam extends CallbackParam { /**蓝牙设备 id 参考 device 对象 */ deviceId: string; /**蓝牙服务 uuid */ serviceId: string; /**蓝牙特征值的 uuid */ characteristicId: string; success: (res: { characteristic: { characteristicId: string; serviceId: object; value: ArrayBuffer; }; errMsg: string; }) => void; } interface WriteBLECharacteristicValueParam extends CallbackWithErrMsgParam { /**蓝牙设备 id */ deviceId: string; /**蓝牙特征值对应服务的 uuid */ serviceId: string; /**蓝牙特征值的 uuid */ characteristicId: string; /**蓝牙设备特征值对应的二进制值 */ value: ArrayBuffer; } interface BLECharacteristicValueChangedParam extends CallbackWithErrMsgParam { /**蓝牙设备 id */ deviceId: string; /**蓝牙特征值对应服务的 uuid */ serviceId: string; /**蓝牙特征值的 uuid */ characteristicId: string; state: boolean; } interface AddressParam extends CallbackParam { success: (res?: AddressData) => void; } interface AddressData { /**获取编辑收货地址成功返回 'openAddress:ok' */ errMsg?: string; /**收货人姓名 */ userName?: string; /**邮编 */ postalCode?: string; /**国标收货地址第一级地址(省) */ provinceName?: string; /**国标收货地址第二级地址(市) */ cityName?: string; /**国标收货地址第三级地址(国家) */ countryName?: string; /**详细收货地址信息 */ detailInfo?: string; /**收货地址国家码 */ nationCode?: string; /**收货人手机号码 */ telNumber?: string; } interface SettingParam extends CallbackParam { success: (res: { /**用户信息 */ 'scope.userInfo': boolean; /**地理位置 */ 'scope.userLocation': boolean; /**通讯地址 */ 'scope.address': boolean; /**录音功能 */ 'scope.record': boolean; /**保存到相册 */ 'scope.writePhotosAlbum': boolean; }) => void; } interface AuthorizeParam extends CallbackWithErrMsgParam { scope: string; } interface ReLaunchParam extends CallbackParam { /** * 需要跳转的应用内非 tabBar 的页面的路径 * 路径后可以带参数 * 参数与路径之间使用?分隔 * 参数键与参数值用=相连 * 不同参数用&分隔 * 如 'path?key=value&key2=value2' */ url: string; } interface LoadingParam extends CallbackParam { /**提示的内容 */ title: string; /**是否显示透明蒙层 防止触摸穿透 默认 false */ mask?: boolean; } interface SetClipboardParam extends CallbackParam { data: string; } interface CardParam extends CallbackWithErrMsgParam { /**需要添加的卡券列表 */ cardList: Array<any>; } interface LaunchData { /**打开小程序的路径 */ path: string; /**打开小程序的query */ query: object; /**打开小程序的场景值 */ scene: number; shareTicket: string; } interface ShareInfoParam extends CallbackParam { shareTicket: string; success: (res: { /**错误信息 */ errMsg: string; /**不包括敏感信息的原始数据字符串 用于计算签名 */ rawData: string; /**使用sha1(rawData+sessionkey)得到字符串 用于校验分享信息 */ signature: string; /**包括敏感数据在内的完整分享信息的加密数据 */ encryptedData: string; /**加密算法的初始向量 */ iv: string; }) => void; } interface ExtConfigParam extends CallbackParam { success: (res: { errMsg: string; extConfig: object }) => void; } interface ShareMenuParam extends CallbackParam { /**是否使用带 shareTicket 的分享 */ withShareTicket?: boolean; } interface BeaconsParam extends CallbackParam { success: (res: { errMsg: string; beacons: Array<IBeacon> }) => void; } interface IBeacon { /** iBeacon 设备广播的 uuid */ uuid: string; /** iBeacon 设备的主 id */ major: string; /**iBeacon 设备的次 id */ minor: string; /** 表示设备距离的枚举值 */ proximity: number; /** iBeacon 设备的距离 */ accuracy: number; /**表示设备的信号强度 */ rssi: number; } interface GetScreenBrightnessParam extends CallbackParam { success: (res?: { errMsg: string; value: number; }) => void; } interface SetScreenBrightnessParam extends CallbackParam { /**屏幕亮度值 范围 0~1 0 最暗 1 最亮 */ value: number; } interface AddPhoneContactParam extends CallbackWithErrMsgParam { /**头像本地文件路径 */ photoFilePath?: string; /**昵称 */ nickName?: string; /**姓氏 */ lastName?: string; /**中间名 */ middleName?: string; /**名字 */ firstName: string; /** 备注 */ remark?: string; /**手机号 */ mobilePhoneNumber?: string; /**微信号 */ weChatNumber?: string; /**联系地址国家 */ addressCountry?: string; /**联系地址省份 */ addressState?: string; /**联系地址城市 */ addressCity?: string; /**联系地址街道 */ addressStreet?: string; /**联系地址邮政编码 */ addressPostalCode?: string; /**公司 */ organization?: string; /**职位 */ title?: string; /**工作传真 */ workFaxNumber?: string; /**工作电话 */ workPhoneNumber?: string; /**公司电话 */ hostNumber: string; /**电子邮件 */ email?: string; /**网站 */ url?: string; /**工作地址国家 */ workAddressCountry?: string; /**工作地址省份 */ workAddressState?: string; /**工作地址城市 */ workAddressCity?: string; /**工作地址街道 */ workAddressStreet?: string; /**工作地址邮政编码 */ workAddressPostalCode?: string; /**住宅传真 */ homeFaxNumber?: string; /**住宅电话 */ homePhoneNumber?: string; /**住宅地址国家 */ homeAddressCountry?: string; /**住宅地址省份 */ homeAddressState?: string; /**住宅地址城市 */ homeAddressCity?: string; /**住宅地址街道 */ homeAddressStreet?: string; /**住宅地址邮政编码 */ homeAddressPostalCode?: string; } interface GetWeRunDataParam extends CallbackParam { success?: (res: { errMsg: string; encryptedData: string }) => void; } interface SaveImageToPhotosAlbumParam extends CallbackWithErrMsgParam { /**图片文件路径 可以是临时文件路径也可以是永久文件路径 */ filePath: string; } interface BackgroundAudioManager { /** 当前音频的长度 单位 s 只有在当前有合法的 src 时返回 */ readonly duration: number; /** 当前音频的播放位置 单位 s 只有在当前有合法的 src 时返回 */ readonly currentTime: number; /** 当前是是否暂停或停止状态 true 表示暂停或停止 false 表示正在播放 */ readonly paused: boolean; /**音频的数据源 默认为空字符串 当设置了新的 src 时 会自动开始播放 */ src: string; /** 音频开始播放的位置 单位 s */ startTime: number; /**音频缓冲的时间点仅保证当前播放时间点到此时间点内容已缓冲 */ readonly buffered: number; /** 音频标题 用于做原生音频播放器音频标题 原生音频播放器中的分享功能 分享出去的卡片标题 也将使用该值 */ title: string; /**专辑名 原生音频播放器中的分享功能 分享出去的卡片简介 也将使用该值 */ epname: string; /**歌手名 原生音频播放器中的分享功能 分享出去的卡片简介 也将使用该值 */ singer: string; /**封面图url 用于做原生音频播放器背景图 原生音频播放器中的分享功能 分享出去的卡片配图及背景也将使用该图 */ coverImgUrl: string; /** 页面链接 原生音频播放器中的分享功能 分享出去的卡片简介 也将使用该值 */ webUrl: string; /**播放 */ play(): void; /**暂停 */ pause(): void; /**停止 */ stop(): void; /**跳转到指定位置 单位 s */ seek(position: number): void; /**背景音频进入可以播放状态 但不保证后面可以流畅播放 */ onCanplay(callback: Function): void; /**背景音频播放事件 */ onPlay(callback: Function): void; /**背景音频暂停事件 */ onPause(callback: Function): void; /**背景音频停止事件 */ onStop(callback: Function): void; /**背景音频自然播放结束事件 */ onEnded(callback: Function): void; /**背景音频播放进度更新事件 */ onTimeUpdate(callback: Function): void; /**用户在系统音乐播放面板点击上一曲事件 iOS only */ onPrev(callback: Function): void; /**用户在系统音乐播放面板点击下一曲事件 iOS only */ onNext(callback: Function): void; /**背景音频播放错误事件 */ onError(callback: Function): void; /**音频加载中事件 当音频因为数据不足 需要停下来加载时会触发 */ onWaiting(callback: Function): void; } interface NavigateToMiniProgramParam extends CallbackWithErrMsgParam { /**要打开的小程序 appId*/ appId: string; /**打开的页面路径 如果为空则打开首页 */ path?: string /**需要传递给目标小程序的数据 目标小程序可在 App.onLaunch() App.onShow() 中获取到这份数据 */ extraData?: object; /**要打开的小程序版本 有效值 develop trial release*/ envVersion?: string; } interface NavigateBackMiniProgramParam extends CallbackWithErrMsgParam { /**需要返回给上一个小程序的数据 上一个小程序可在 App.onShow() 中获取到这份数据 */ extraData: object; } interface SelectorQuery { /**在当前页面下选择第一个匹配选择器selector的节点 返回一个NodesRef对象实例 */ select(selector: string): NodesRef; /**在当前页面下选择匹配选择器selector的节点 返回一个NodesRef对象实例 */ selectAll(selector: string): NodesRef; /**选择显示区域 可用于获取显示区域的尺寸 滚动位置等信息 */ selectViewport(): NodesRef; exec(callback?: (res: Array<any>) => void): void; } interface NodesRef { /**添加节点的布局位置的查询请求 相对于显示区域 以像素为单位 */ boundingClientRect(callback: (rect: WxClientRect | Array<WxClientRect>) => void): SelectorQuery; /**添加节点的滚动位置查询请求 以像素为单位 */ scrollOffset(callback: (rects: WxScrollOffset) => void): SelectorQuery; /**获取节点的相关信息 需要获取的字段在fields中指定 */ fields(fields: NodeField, callback: (res: any) => void): SelectorQuery; } interface WxClientRect extends ClientRect { id: string; dataset: any; } interface WxScrollOffset { id: string; dataset: any; scrollLeft: number; scrollTop: number; } interface NodeField { id?: boolean; dataset?: boolean; rect?: boolean; size?: boolean; scrollOffset?: boolean; } interface GetFileInfoParam extends CallbackParam { /**本地文件路径 */ filePath: string; /**计算文件摘要的算法 默认值 md5 */ digestAlgorithm?: 'md5' | 'sha1'; success: (res: { size: number; digest: string; errMsg: string }) => void; } interface SetNavigationBarColorParam extends CallbackWithErrMsgParam { frontColor: string; backgroundColor: string; animation?: { duration?: number; timingFunc?: 'linear' | 'easeIn' | 'easeOut' | 'easeInOut'; } } interface SetEnableDebugParam extends CallbackWithErrMsgParam { enableDebug: boolean; } interface SetKeepScreenOnParam extends CallbackWithErrMsgParam { keepScreenOn: boolean; } interface CheckIsSupportSoterAuthenticationParam extends CallbackParam { success?: (res: { supportMode: Array<'fingerPrint' | 'facial' | 'speech'>, errMsg: string; }) => void; } interface StartSoterAuthenticationParam extends CallbackParam { /**请求使用的可接受的生物认证方式 */ requestAuthModes: Array<string>; /**挑战因子 挑战因子为调用者为此次生物鉴权准备的用于签名的字符串关键是别信息 将作为result_json的一部分 供调用者识别本次请求 */ challenge: string; /**验证描述 即识别过程中显示在界面上的对话框提示内容 */ authContent?: string; success?: (res: { errCode: number; authMode: string; resultJSON: string; resultJSONSignature: string; errMsg: string; }) => void; } interface CheckIsSoterEnrolledInDeviceParam extends CallbackParam { checkAuthMode: 'fingerPrint' | 'facial' | 'speech'; success?: (res: { isEnrolled: boolean, errMsg: string; }) => void; } interface ChooseInvoiceTitleParam extends CallbackParam { success?: (res: InvoiceTitle) => void; } interface InvoiceTitle { /**抬头类型 0 单位 1 个人 */ type: string; /**抬头名称 */ title: string; /**抬头税号 */ taxNumber: string; /**单位地址 */ companyAddress: string; /**手机号码 */ telephone: string; /**银行名称 */ bankName: string; /**银行账号 */ bankAccount: string; /**接口调用结果 */ errMsg: string; } interface LogManager { warn(...arg: Array<any>): void; log(...arg: Array<any>): void; info(...arg: Array<any>): void; debug(...arg: Array<any>): void; } // #endregion }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [iotthingsgraph](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotthingsgraph.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Iotthingsgraph extends PolicyStatement { public servicePrefix = 'iotthingsgraph'; /** * Statement provider for service [iotthingsgraph](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotthingsgraph.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Associates a device with a concrete thing that is in the user's registry. A thing can be associated with only one device at a time. If you associate a thing with a new device id, its previous association will be removed. * * Access Level: Write * * Dependent actions: * - iot:DescribeThing * - iot:DescribeThingGroup * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_AssociateEntityToThing.html */ public toAssociateEntityToThing() { return this.to('AssociateEntityToThing'); } /** * Creates a workflow template. Workflows can be created only in the user's namespace. (The public namespace contains only entities.) The workflow can contain only entities in the specified namespace. The workflow is validated against the entities in the latest version of the user's namespace unless another namespace version is specified in the request. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_CreateFlowTemplate.html */ public toCreateFlowTemplate() { return this.to('CreateFlowTemplate'); } /** * Creates an instance of a system with specified configurations and Things. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_CreateSystemInstance.html */ public toCreateSystemInstance() { return this.to('CreateSystemInstance'); } /** * Creates a system. The system is validated against the entities in the latest version of the user's namespace unless another namespace version is specified in the request. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_CreateSystemTemplate.html */ public toCreateSystemTemplate() { return this.to('CreateSystemTemplate'); } /** * Deletes a workflow. Any new system or system instance that contains this workflow will fail to update or deploy. Existing system instances that contain the workflow will continue to run (since they use a snapshot of the workflow taken at the time of deploying the system instance). * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_DeleteFlowTemplate.html */ public toDeleteFlowTemplate() { return this.to('DeleteFlowTemplate'); } /** * Deletes the specified namespace. This action deletes all of the entities in the namespace. Delete the systems and flows in the namespace before performing this action. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_DeleteNamespace.html */ public toDeleteNamespace() { return this.to('DeleteNamespace'); } /** * Deletes a system instance. Only instances that have never been deployed, or that have been undeployed from the target can be deleted. Users can create a new system instance that has the same ID as a deleted system instance. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_DeleteSystemInstance.html */ public toDeleteSystemInstance() { return this.to('DeleteSystemInstance'); } /** * Deletes a system. New system instances can't contain the system after its deletion. Existing system instances that contain the system will continue to work because they use a snapshot of the system that is taken when it is deployed. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_DeleteSystemTemplate.html */ public toDeleteSystemTemplate() { return this.to('DeleteSystemTemplate'); } /** * Deploys the system instance to the target specified in CreateSystemInstance. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_DeploySystemInstance.html */ public toDeploySystemInstance() { return this.to('DeploySystemInstance'); } /** * Deprecates the specified workflow. This action marks the workflow for deletion. Deprecated flows can't be deployed, but existing system instances that use the flow will continue to run. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_DeprecateFlowTemplate.html */ public toDeprecateFlowTemplate() { return this.to('DeprecateFlowTemplate'); } /** * Deprecates the specified system. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_DeprecateSystemTemplate.html */ public toDeprecateSystemTemplate() { return this.to('DeprecateSystemTemplate'); } /** * Gets the latest version of the user's namespace and the public version that it is tracking. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_DescribeNamespace.html */ public toDescribeNamespace() { return this.to('DescribeNamespace'); } /** * Dissociates a device entity from a concrete thing. The action takes only the type of the entity that you need to dissociate because only one entity of a particular type can be associated with a thing. * * Access Level: Write * * Dependent actions: * - iot:DescribeThing * - iot:DescribeThingGroup * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_DissociateEntityFromThing.html */ public toDissociateEntityFromThing() { return this.to('DissociateEntityFromThing'); } /** * Gets descriptions of the specified entities. Uses the latest version of the user's namespace by default. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_GetEntities.html */ public toGetEntities() { return this.to('GetEntities'); } /** * Gets the latest version of the DefinitionDocument and FlowTemplateSummary for the specified workflow. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_GetFlowTemplate.html */ public toGetFlowTemplate() { return this.to('GetFlowTemplate'); } /** * Gets revisions of the specified workflow. Only the last 100 revisions are stored. If the workflow has been deprecated, this action will return revisions that occurred before the deprecation. This action won't work for workflows that have been deleted. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_GetFlowTemplateRevisions.html */ public toGetFlowTemplateRevisions() { return this.to('GetFlowTemplateRevisions'); } /** * Gets the status of a namespace deletion task. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_GetNamespaceDeletionStatus.html */ public toGetNamespaceDeletionStatus() { return this.to('GetNamespaceDeletionStatus'); } /** * Gets a system instance. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_GetSystemInstance.html */ public toGetSystemInstance() { return this.to('GetSystemInstance'); } /** * Gets a system. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_GetSystemTemplate.html */ public toGetSystemTemplate() { return this.to('GetSystemTemplate'); } /** * Gets revisions made to the specified system template. Only the previous 100 revisions are stored. If the system has been deprecated, this action will return the revisions that occurred before its deprecation. This action won't work with systems that have been deleted. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_GetSystemTemplateRevisions.html */ public toGetSystemTemplateRevisions() { return this.to('GetSystemTemplateRevisions'); } /** * Gets the status of the specified upload. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_GetUploadStatus.html */ public toGetUploadStatus() { return this.to('GetUploadStatus'); } /** * Lists details of a single workflow execution * * Access Level: List * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_ListFlowExecutionMessages.html */ public toListFlowExecutionMessages() { return this.to('ListFlowExecutionMessages'); } /** * Lists all tags for a given resource * * Access Level: List * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Searches for entities of the specified type. You can search for entities in your namespace and the public namespace that you're tracking. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_SearchEntities.html */ public toSearchEntities() { return this.to('SearchEntities'); } /** * Searches for workflow executions of a system instance * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_SearchFlowExecutions.html */ public toSearchFlowExecutions() { return this.to('SearchFlowExecutions'); } /** * Searches for summary information about workflows. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_SearchFlowTemplates.html */ public toSearchFlowTemplates() { return this.to('SearchFlowTemplates'); } /** * Searches for system instances in the user's account. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_SearchSystemInstances.html */ public toSearchSystemInstances() { return this.to('SearchSystemInstances'); } /** * Searches for summary information about systems in the user's account. You can filter by the ID of a workflow to return only systems that use the specified workflow. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_SearchSystemTemplates.html */ public toSearchSystemTemplates() { return this.to('SearchSystemTemplates'); } /** * Searches for things associated with the specified entity. You can search by both device and device model. * * Access Level: Read * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_SearchThings.html */ public toSearchThings() { return this.to('SearchThings'); } /** * Tag a specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Removes the system instance and associated triggers from the target. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_UndeploySystemInstance.html */ public toUndeploySystemInstance() { return this.to('UndeploySystemInstance'); } /** * Untag a specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Updates the specified workflow. All deployed systems and system instances that use the workflow will see the changes in the flow when it is redeployed. The workflow can contain only entities in the specified namespace. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_UpdateFlowTemplate.html */ public toUpdateFlowTemplate() { return this.to('UpdateFlowTemplate'); } /** * Updates the specified system. You don't need to run this action after updating a workflow. Any system instance that uses the system will see the changes in the system when it is redeployed. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_UpdateSystemTemplate.html */ public toUpdateSystemTemplate() { return this.to('UpdateSystemTemplate'); } /** * Asynchronously uploads one or more entity definitions to the user's namespace. * * Access Level: Write * * https://docs.aws.amazon.com/thingsgraph/latest/APIReference/{APIReferenceDocPage}API_UploadEntityDefinitions.html */ public toUploadEntityDefinitions() { return this.to('UploadEntityDefinitions'); } protected accessLevelList: AccessLevelList = { "Write": [ "AssociateEntityToThing", "CreateFlowTemplate", "CreateSystemInstance", "CreateSystemTemplate", "DeleteFlowTemplate", "DeleteNamespace", "DeleteSystemInstance", "DeleteSystemTemplate", "DeploySystemInstance", "DeprecateFlowTemplate", "DeprecateSystemTemplate", "DissociateEntityFromThing", "UndeploySystemInstance", "UpdateFlowTemplate", "UpdateSystemTemplate", "UploadEntityDefinitions" ], "Read": [ "DescribeNamespace", "GetEntities", "GetFlowTemplate", "GetFlowTemplateRevisions", "GetNamespaceDeletionStatus", "GetSystemInstance", "GetSystemTemplate", "GetSystemTemplateRevisions", "GetUploadStatus", "SearchEntities", "SearchFlowExecutions", "SearchFlowTemplates", "SearchSystemInstances", "SearchSystemTemplates", "SearchThings" ], "List": [ "ListFlowExecutionMessages", "ListTagsForResource" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type Workflow to the statement * * https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-models-tdm-iot-workflow.html * * @param namespacePath - Identifier for the namespacePath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onWorkflow(namespacePath: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iotthingsgraph:${Region}:${Account}:Workflow/${NamespacePath}'; arn = arn.replace('${NamespacePath}', namespacePath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type System to the statement * * https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-models-tdm-iot-system.html * * @param namespacePath - Identifier for the namespacePath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onSystem(namespacePath: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iotthingsgraph:${Region}:${Account}:System/${NamespacePath}'; arn = arn.replace('${NamespacePath}', namespacePath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type SystemInstance to the statement * * https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-models-tdm-iot-sdc-deployconfig.html * * @param namespacePath - Identifier for the namespacePath. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onSystemInstance(namespacePath: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iotthingsgraph:${Region}:${Account}:Deployment/${NamespacePath}'; arn = arn.replace('${NamespacePath}', namespacePath); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import * as chai from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as cp from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import rimraf = require('rimraf'); import * as vscode from 'vscode'; import { DotnetAcquisitionAlreadyInstalled, DotnetCoreAcquisitionWorker, DotnetPreinstallDetected, IDotnetAcquireContext, IDotnetAcquireResult, MockEnvironmentVariableCollection, MockEventStream, MockExtensionConfiguration, MockExtensionContext, MockInstallationValidator, MockTelemetryReporter, MockWindowDisplayWorker, NoInstallAcquisitionInvoker, SdkInstallationDirectoryProvider, } from 'vscode-dotnet-runtime-library'; import * as extension from '../../extension'; import { uninstallSDKExtension } from '../../ExtensionUninstall'; const assert = chai.assert; chai.use(chaiAsPromised); /* tslint:disable:no-any */ suite('DotnetCoreAcquisitionExtension End to End', function() { this.retries(3); const storagePath = path.join(__dirname, 'tmp'); const mockState = new MockExtensionContext(); const extensionPath = path.join(__dirname, '/../../..'); const logPath = path.join(__dirname, 'logs'); const mockDisplayWorker = new MockWindowDisplayWorker(); const environmentVariableCollection = new MockEnvironmentVariableCollection(); let extensionContext: vscode.ExtensionContext; this.beforeAll(async () => { extensionContext = { subscriptions: [], globalStoragePath: storagePath, globalState: mockState, extensionPath, logPath, environmentVariableCollection, } as any; extension.activate(extensionContext, { telemetryReporter: new MockTelemetryReporter(), extensionConfiguration: new MockExtensionConfiguration([{extensionId: 'ms-dotnettools.sample-extension', path: 'foo'}], true), displayWorker: mockDisplayWorker, }); }); test('Activate', async () => { // Commands should now be registered assert.exists(extensionContext); assert.isAbove(extensionContext.subscriptions.length, 0); }); test('Detect Preinstalled SDK', async () => { // Set up acquisition worker const context = new MockExtensionContext(); const eventStream = new MockEventStream(); const installDirectoryProvider = new SdkInstallationDirectoryProvider(storagePath); const acquisitionWorker = new DotnetCoreAcquisitionWorker({ storagePath: '', extensionState: context, eventStream, acquisitionInvoker: new NoInstallAcquisitionInvoker(eventStream), installationValidator: new MockInstallationValidator(eventStream), timeoutValue: 10, installDirectoryProvider, }); const version = '5.0'; // Write 'preinstalled' SDKs const dotnetDir = installDirectoryProvider.getInstallDir(version); const dotnetExePath = path.join(dotnetDir, `dotnet${ os.platform() === 'win32' ? '.exe' : '' }`); const sdkDir50 = path.join(dotnetDir, 'sdk', version); const sdkDir31 = path.join(dotnetDir, 'sdk', '3.1'); fs.mkdirSync(sdkDir50, { recursive: true }); fs.mkdirSync(sdkDir31, { recursive: true }); fs.writeFileSync(dotnetExePath, ''); // Assert preinstalled SDKs are detected const result = await acquisitionWorker.acquireSDK(version); assert.equal(path.dirname(result.dotnetPath), dotnetDir); const preinstallEvents = eventStream.events .filter(event => event instanceof DotnetPreinstallDetected) .map(event => event as DotnetPreinstallDetected);     assert.equal(preinstallEvents.length, 2);     assert.exists(preinstallEvents.find(event => event.version === '5.0'));     assert.exists(preinstallEvents.find(event => event.version === '3.1')); const alreadyInstalledEvent = eventStream.events .find(event => event instanceof DotnetAcquisitionAlreadyInstalled) as DotnetAcquisitionAlreadyInstalled;     assert.exists(alreadyInstalledEvent);     assert.equal(alreadyInstalledEvent.version, '5.0'); // Clean up storage rimraf.sync(dotnetDir); }); test('Install Status Command with Preinstalled SDK', async () => { // Set up acquisition worker const context = new MockExtensionContext(); const eventStream = new MockEventStream(); const installDirectoryProvider = new SdkInstallationDirectoryProvider(storagePath); const acquisitionWorker = new DotnetCoreAcquisitionWorker({ storagePath: '', extensionState: context, eventStream, acquisitionInvoker: new NoInstallAcquisitionInvoker(eventStream), installationValidator: new MockInstallationValidator(eventStream), timeoutValue: 10, installDirectoryProvider, }); const version = '5.0'; // Ensure nothing is returned when there is no preinstalled SDK const noPreinstallResult = await acquisitionWorker.acquireSDKStatus(version); assert.isUndefined(noPreinstallResult); // Write 'preinstalled' SDK const dotnetDir = installDirectoryProvider.getInstallDir(version); const dotnetExePath = path.join(dotnetDir, `dotnet${ os.platform() === 'win32' ? '.exe' : '' }`); const sdkDir50 = path.join(dotnetDir, 'sdk', version); fs.mkdirSync(sdkDir50, { recursive: true }); fs.writeFileSync(dotnetExePath, ''); // Assert preinstalled SDKs are detected const result = await acquisitionWorker.acquireSDKStatus(version); assert.equal(path.dirname(result!.dotnetPath), dotnetDir); // Clean up storage rimraf.sync(dotnetDir); }); test('Install Command', async () => { const context: IDotnetAcquireContext = { version: '5.0', requestingExtensionId: 'ms-dotnettools.sample-extension' }; const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquire', context); assert.exists(result); assert.exists(result!.dotnetPath); assert.include(result!.dotnetPath, '.dotnet'); const sdkDir = fs.readdirSync(path.join(path.dirname(result!.dotnetPath), 'sdk'))[0]; assert.include(sdkDir, context.version); if (os.platform() === 'win32') { assert.include(result!.dotnetPath, process.env.APPDATA!); } assert.isTrue(fs.existsSync(result!.dotnetPath)); // Clean up storage await vscode.commands.executeCommand('dotnet-sdk.uninstallAll'); }).timeout(100000); test('Install Command with Unknown Extension Id', async () => { const context: IDotnetAcquireContext = { version: '5.0', requestingExtensionId: 'unknown' }; return assert.isRejected(vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquire', context)); }).timeout(100000); test('Install Command Sets the PATH', async () => { const context: IDotnetAcquireContext = { version: '5.0', requestingExtensionId: 'ms-dotnettools.sample-extension' }; const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquire', context); assert.exists(result); assert.exists(result!.dotnetPath); const expectedPath = path.dirname(result!.dotnetPath); const pathVar = environmentVariableCollection.variables.PATH; assert.include(pathVar, expectedPath); let pathResult: string; if (os.platform() === 'win32') { pathResult = cp.execSync(`%SystemRoot%\\System32\\reg.exe query "HKCU\\Environment" /v "Path"`).toString(); } else if (os.platform() === 'darwin') { pathResult = fs.readFileSync(path.join(os.homedir(), '.zshrc')).toString(); } else { pathResult = fs.readFileSync(path.join(os.homedir(), '.profile')).toString(); } assert.include(pathResult, expectedPath); // Clean up storage await vscode.commands.executeCommand('dotnet-sdk.uninstallAll'); }).timeout(100000); test('Install Status Command', async () => { const context: IDotnetAcquireContext = { version: '5.0', requestingExtensionId: 'ms-dotnettools.sample-extension' }; let result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquireStatus', context); assert.isUndefined(result); await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquire', context); result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquireStatus', context); assert.exists(result); assert.exists(result!.dotnetPath); assert.isTrue(fs.existsSync(result!.dotnetPath)); // Clean up storage await vscode.commands.executeCommand('dotnet-sdk.uninstallAll'); }).timeout(100000); test('Uninstall Command', async () => { const context: IDotnetAcquireContext = { version: '3.1', requestingExtensionId: 'ms-dotnettools.sample-extension' }; const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquire', context); assert.exists(result); assert.exists(result!.dotnetPath); const sdkDir = fs.readdirSync(path.join(path.dirname(result!.dotnetPath), 'sdk'))[0]; assert.include(sdkDir, context.version); assert.isTrue(fs.existsSync(result!.dotnetPath!)); await vscode.commands.executeCommand('dotnet-sdk.uninstallAll'); assert.isFalse(fs.existsSync(result!.dotnetPath)); }).timeout(100000); test('Install Multiple Versions', async () => { // Install 3.1 let version = '3.1'; let result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquire', { version, requestingExtensionId: 'ms-dotnettools.sample-extension' }); assert.exists(result); assert.exists(result!.dotnetPath); let sdkDirs = fs.readdirSync(path.join(path.dirname(result!.dotnetPath), 'sdk')); assert.isNotEmpty(sdkDirs.filter(dir => dir.includes(version))); // Install 5.0 version = '5.0'; result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquire', { version, requestingExtensionId: 'ms-dotnettools.sample-extension' }); assert.exists(result); assert.exists(result!.dotnetPath); sdkDirs = fs.readdirSync(path.join(path.dirname(result!.dotnetPath), 'sdk')); assert.isNotEmpty(sdkDirs.filter(dir => dir.includes(version))); // 5.0 and 3.1 SDKs should still be installed sdkDirs = fs.readdirSync(path.join(path.dirname(result!.dotnetPath), 'sdk')); assert.isNotEmpty(sdkDirs.filter(dir => dir.includes('3.1'))); assert.isNotEmpty(sdkDirs.filter(dir => dir.includes('5.0'))); // Clean up storage await vscode.commands.executeCommand('dotnet-sdk.uninstallAll'); }).timeout(600000); test('Extension Uninstall Removes SDKs', async () => { const context: IDotnetAcquireContext = { version: '5.0', requestingExtensionId: 'ms-dotnettools.sample-extension' }; const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet-sdk.acquire', context); assert.exists(result); assert.exists(result!.dotnetPath); uninstallSDKExtension(); assert.isFalse(fs.existsSync(result!.dotnetPath)); }).timeout(100000); });
the_stack
import React from 'react'; import { render, cleanup } from '@testing-library/react'; import { Animator, ENTERED, ENTERING, EXITED, EXITING } from '@arwes/animator'; import anime from 'animejs'; import { makeJestMoveTimeTo } from '../../test-utils/makeJestMoveTimeTo'; import { ActJestMoveTimeTo, makeActJestMoveTimeTo } from '../../test-utils/makeActJestMoveTimeTo'; import { AnimatedSettings, AnimatedSettingsTransitionFunction } from '../constants'; import { Animated } from './Animated.component'; jest.useFakeTimers(); jest.mock('animejs'); let actJestMoveTimeTo: ActJestMoveTimeTo; beforeEach(() => { (anime as any).mockReset(); (anime as any).mockImplementation(() => { const mock: any = jest.fn(); mock.remove = jest.fn(); return mock; }); const jestMoveTimeTo = makeJestMoveTimeTo(); actJestMoveTimeTo = makeActJestMoveTimeTo(jestMoveTimeTo); }); afterEach(cleanup); describe('Objects Settings', () => { test('Should transition "animated.entering" with object setting', () => { const Example: React.FC = () => { const [activate, setActivate] = React.useState(false); React.useEffect(() => { const timeout = setTimeout(() => setActivate(true), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate, duration: { enter: 127 } }}> <Animated animated={{ entering: { opacity: 1 } }} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; actJestMoveTimeTo(999); expect(anime).not.toHaveBeenCalled(); actJestMoveTimeTo(1001); expect(anime).toHaveBeenCalledWith({ targets: element, easing: 'easeOutSine', duration: 127, opacity: 1 }); }); test('Should transition "animated.entered" with object setting', () => { const Example: React.FC = () => { const [activate, setActivate] = React.useState(false); React.useEffect(() => { const timeout = setTimeout(() => setActivate(true), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate, duration: { enter: 127 } }}> <Animated animated={{ entered: { width: 100 } }} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; actJestMoveTimeTo(1000 + 127 - 1); expect(anime).not.toHaveBeenCalled(); actJestMoveTimeTo(1000 + 127 + 1); expect(anime).toHaveBeenCalledWith({ targets: element, easing: 'easeOutSine', duration: 127, width: 100 }); }); test('Should transition "animated.exiting" with object setting', () => { const Example: React.FC = () => { const [activate, setActivate] = React.useState(true); React.useEffect(() => { const timeout = setTimeout(() => setActivate(false), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate, duration: { exit: 176 } }}> <Animated animated={{ exiting: { width: 913 } }} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; actJestMoveTimeTo(999); expect(anime).not.toHaveBeenCalled(); actJestMoveTimeTo(1001); expect(anime).toHaveBeenCalledWith({ targets: element, easing: 'easeOutSine', duration: 176, width: 913 }); }); test('Should transition "animated.exited" with object setting', () => { const Example: React.FC = () => { const [activate, setActivate] = React.useState(true); React.useEffect(() => { const timeout = setTimeout(() => setActivate(false), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate, duration: { exit: 176 } }}> <Animated animated={{ exited: { scale: 1.75 } }} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; // Initial call. expect(anime).toHaveBeenNthCalledWith(1, { targets: element, easing: 'easeOutSine', duration: 176, scale: 1.75 }); actJestMoveTimeTo(1000 + 176 - 1); expect(anime).toHaveBeenCalledTimes(1); actJestMoveTimeTo(1000 + 176 + 1); expect(anime).toHaveBeenCalledTimes(2); expect(anime).toHaveBeenNthCalledWith(2, { targets: element, easing: 'easeOutSine', duration: 176, scale: 1.75 }); }); test('Should run transitions on "animated" array of object transitions', () => { const animated: AnimatedSettings[] = [ { entering: { width: 200 }, exiting: { width: 20 } }, { entering: { height: 300 }, exiting: { height: 30 } } ]; const Example: React.FC = () => { const [activate, setActivate] = React.useState(false); React.useEffect(() => { const t1 = setTimeout(() => setActivate(true), 1000); const t2 = setTimeout(() => setActivate(false), 2000); return () => { clearTimeout(t1); clearTimeout(t2); }; }, []); return ( <Animator animator={{ activate, duration: { enter: 80, exit: 90 } }}> <Animated animated={animated} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; actJestMoveTimeTo(999); expect(anime).not.toHaveBeenCalled(); actJestMoveTimeTo(1001); expect(anime).toHaveBeenCalledTimes(2); expect(anime).toHaveBeenNthCalledWith(1, { targets: element, easing: 'easeOutSine', duration: 80, width: 200 }); expect(anime).toHaveBeenNthCalledWith(2, { targets: element, easing: 'easeOutSine', duration: 80, height: 300 }); actJestMoveTimeTo(1999); expect(anime).toHaveBeenCalledTimes(2); actJestMoveTimeTo(2001); expect(anime).toHaveBeenCalledTimes(4); expect(anime).toHaveBeenNthCalledWith(3, { targets: element, easing: 'easeOutSine', duration: 90, width: 20 }); expect(anime).toHaveBeenNthCalledWith(4, { targets: element, easing: 'easeOutSine', duration: 90, height: 30 }); }); }); describe('Functions Settings', () => { test('Should transition "animated.entering" with function setting', () => { const entering: AnimatedSettingsTransitionFunction = jest.fn(); const Example: React.FC = () => { const [activate, setActivate] = React.useState(false); React.useEffect(() => { const timeout = setTimeout(() => setActivate(true), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate, duration: { enter: 127 } }}> <Animated animated={{ entering }} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; actJestMoveTimeTo(999); expect(entering).not.toHaveBeenCalled(); actJestMoveTimeTo(1001); expect(entering).toHaveBeenCalledWith({ target: element, duration: 127, transitionTarget: expect.any(Function) }); }); test('Should transition "animated.entered" with function setting', () => { const entered: AnimatedSettingsTransitionFunction = jest.fn(); const Example: React.FC = () => { const [activate, setActivate] = React.useState(false); React.useEffect(() => { const timeout = setTimeout(() => setActivate(true), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate, duration: { enter: 127 } }}> <Animated animated={{ entered }} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; actJestMoveTimeTo(1000 + 127 - 1); expect(entered).not.toHaveBeenCalled(); actJestMoveTimeTo(1000 + 127 + 1); expect(entered).toHaveBeenCalledWith({ target: element, duration: 127, transitionTarget: expect.any(Function) }); }); test('Should transition "animated.exiting" with function setting', () => { const exiting: AnimatedSettingsTransitionFunction = jest.fn(); const Example: React.FC = () => { const [activate, setActivate] = React.useState(true); React.useEffect(() => { const timeout = setTimeout(() => setActivate(false), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate, duration: { exit: 814 } }}> <Animated animated={{ exiting }} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; actJestMoveTimeTo(1); expect(exiting).not.toHaveBeenCalled(); actJestMoveTimeTo(1001); expect(exiting).toHaveBeenCalledWith({ target: element, duration: 814, transitionTarget: expect.any(Function) }); }); test('Should transition "animated.exited" with function setting', () => { const exited: AnimatedSettingsTransitionFunction = jest.fn(); const Example: React.FC = () => { const [activate, setActivate] = React.useState(true); React.useEffect(() => { const timeout = setTimeout(() => setActivate(false), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate, duration: { exit: 814 } }}> <Animated animated={{ exited }} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; expect(exited).toHaveBeenNthCalledWith(1, { target: element, duration: 814, transitionTarget: expect.any(Function) }); actJestMoveTimeTo(1000 + 814 - 1); expect(exited).toHaveBeenCalledTimes(1); actJestMoveTimeTo(1000 + 814 + 1); expect(exited).toHaveBeenCalledTimes(2); expect(exited).toHaveBeenNthCalledWith(2, { target: element, duration: 814, transitionTarget: expect.any(Function) }); }); test('Should run transitions on "animated" array of function transitions', () => { const animated1Entering = jest.fn(); const animated1Exiting = jest.fn(); const animated2Entering = jest.fn(); const animated2Exiting = jest.fn(); const animated: AnimatedSettings[] = [ { entering: animated1Entering, exiting: animated1Exiting }, { entering: animated2Entering, exiting: animated2Exiting } ]; const Example: React.FC = () => { const [activate, setActivate] = React.useState(false); React.useEffect(() => { const t1 = setTimeout(() => setActivate(true), 1000); const t2 = setTimeout(() => setActivate(false), 2000); return () => { clearTimeout(t1); clearTimeout(t2); }; }, []); return ( <Animator animator={{ activate, duration: { enter: 80, exit: 90 } }}> <Animated animated={animated} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; actJestMoveTimeTo(999); expect(animated1Entering).not.toHaveBeenCalled(); expect(animated1Exiting).not.toHaveBeenCalled(); expect(animated2Entering).not.toHaveBeenCalled(); expect(animated2Exiting).not.toHaveBeenCalled(); actJestMoveTimeTo(1001); expect(animated1Entering).toHaveBeenCalledTimes(1); expect(animated2Entering).toHaveBeenCalledTimes(1); expect(animated1Entering).toHaveBeenCalledWith({ target: element, duration: 80, transitionTarget: expect.any(Function) }); expect(animated2Entering).toHaveBeenCalledWith({ target: element, duration: 80, transitionTarget: expect.any(Function) }); expect(animated1Exiting).not.toHaveBeenCalled(); expect(animated2Exiting).not.toHaveBeenCalled(); actJestMoveTimeTo(1999); expect(animated1Entering).toHaveBeenCalledTimes(1); expect(animated2Entering).toHaveBeenCalledTimes(1); expect(animated1Exiting).not.toHaveBeenCalled(); expect(animated2Exiting).not.toHaveBeenCalled(); actJestMoveTimeTo(2001); expect(animated1Entering).toHaveBeenCalledTimes(1); expect(animated2Entering).toHaveBeenCalledTimes(1); expect(animated1Exiting).toHaveBeenCalledTimes(1); expect(animated2Exiting).toHaveBeenCalledTimes(1); expect(animated1Exiting).toHaveBeenCalledWith({ target: element, duration: 90, transitionTarget: expect.any(Function) }); expect(animated2Exiting).toHaveBeenCalledWith({ target: element, duration: 90, transitionTarget: expect.any(Function) }); }); [ENTERING, ENTERED, EXITING, EXITED].forEach(transitionName => { test(`Should provide "transitionTarget" on "${transitionName}" and execute transition on target element`, () => { const transitionFn: AnimatedSettingsTransitionFunction = params => { params.transitionTarget({ translateX: 777 }); }; const Example: React.FC = () => { const [activate, setActivate] = React.useState(true); React.useEffect(() => { const timeout = setTimeout(() => setActivate(false), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate }}> <Animated animated={{ [transitionName]: transitionFn }} /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLDivElement; // Enough time for all types of transitions to execute. actJestMoveTimeTo(2000); expect(anime).toHaveBeenCalledWith({ targets: element, easing: 'easeOutSine', duration: 100, // Transition durations default. translateX: 777 }); }); test(`Should provide "transitionTarget" on "${transitionName}" and execute transition on target element with CSS selector`, () => { const transitionFn: AnimatedSettingsTransitionFunction = params => { params.transitionTarget({ selector: '.child-element', scaleY: 444 }); }; const Example: React.FC = () => { const [activate, setActivate] = React.useState(true); React.useEffect(() => { const timeout = setTimeout(() => setActivate(false), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate }}> <Animated animated={{ [transitionName]: transitionFn }}> <div className='child-element' /> </Animated> </Animator> ); }; const { container } = render(<Example />); // Since it uses querySelectorAll inside. const selectorElementsTarget = container.querySelectorAll('.child-element'); // Enough time for all types of transitions to execute. actJestMoveTimeTo(2000); expect(anime).toHaveBeenCalledWith({ targets: selectorElementsTarget, easing: 'easeOutSine', duration: 100, // Transition durations default. scaleY: 444 }); }); }); }); test('Should not call "anime" if no settings are provided', () => { const Example: React.FC = () => { const [activate, setActivate] = React.useState(false); React.useEffect(() => { const timeout = setTimeout(() => setActivate(true), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate }}> <Animated /> </Animator> ); }; render(<Example />); actJestMoveTimeTo(1); expect(anime).not.toHaveBeenCalled(); actJestMoveTimeTo(1001); expect(anime).not.toHaveBeenCalled(); }); test('Should set "style.visibility=hidden" when EXITED', () => { const Example: React.FC = () => { const [activate, setActivate] = React.useState(true); React.useEffect(() => { const timeout = setTimeout(() => setActivate(false), 1000); return () => clearTimeout(timeout); }, []); return ( <Animator animator={{ activate }}> <Animated /> </Animator> ); }; const { container } = render(<Example />); const element = container.firstChild as HTMLElement; // Since the component has initial state EXITED.. expect(element.style.visibility).toBe('hidden'); actJestMoveTimeTo(1); expect(element.style.visibility).toBe(''); actJestMoveTimeTo(1099); expect(element.style.visibility).toBe(''); actJestMoveTimeTo(1101); expect(element.style.visibility).toBe('hidden'); }); test.todo('Animated transition transitionTarget');
the_stack
import assert from "assert"; import { URL } from "url"; import { Cache, CacheError, CachedMeta } from "@miniflare/cache"; import { Request, RequestInitCfProperties, Response } from "@miniflare/core"; import { RequestContext, Storage } from "@miniflare/shared"; import { getObjectProperties, utf8Decode, utf8Encode, waitsForInputGate, waitsForOutputGate, } from "@miniflare/shared-test"; import { MemoryStorage } from "@miniflare/storage-memory"; import { WebSocketPair } from "@miniflare/web-sockets"; import anyTest, { Macro, TestInterface, ThrowsExpectation } from "ava"; import { Request as BaseRequest, Response as BaseResponse, HeadersInit, RequestInfo, } from "undici"; import { testResponse } from "./helpers"; interface Context { storage: Storage; clock: { timestamp: number }; cache: Cache; } const test = anyTest as TestInterface<Context>; test.beforeEach((t) => { const clock = { timestamp: 1_000_000 }; // 1000s const clockFunction = () => clock.timestamp; const storage = new MemoryStorage(undefined, clockFunction); const cache = new Cache(storage, { clock: clockFunction }); t.context = { storage, clock, cache }; }); // Cache:* tests adapted from Cloudworker: // https://github.com/dollarshaveclub/cloudworker/blob/4976f88c3d2629fbbd4ca49da88b9c8bf048ce0f/lib/runtime/cache/__tests__/cache.test.js const putMacro: Macro<[RequestInfo], Context> = async (t, req) => { const { storage, cache } = t.context; await cache.put(req, testResponse()); const stored = await storage.get<CachedMeta>("http://localhost:8787/test"); t.not(stored, undefined); t.not(stored?.expiration, undefined); assert(stored?.expiration); // for TypeScript t.is(stored.expiration, 1000 + 3600); t.not(stored.metadata, undefined); assert(stored.metadata); // for TypeScript t.is(stored.metadata.status, 200); t.deepEqual(stored.metadata.headers, [ ["cache-control", "max-age=3600"], ["content-type", "text/plain; charset=utf8"], ]); t.is(utf8Decode(stored.value), "value"); }; putMacro.title = (providedTitle) => `Cache: puts ${providedTitle}`; test("request", putMacro, new BaseRequest("http://localhost:8787/test")); test("string request", putMacro, "http://localhost:8787/test"); test("url request", putMacro, new URL("http://localhost:8787/test")); test("Cache: doesn't cache WebSocket responses", async (t) => { const { cache } = t.context; const pair = new WebSocketPair(); const res = new Response(null, { status: 101, webSocket: pair["0"], }); await t.throwsAsync(cache.put("http://localhost:8787/", res), { instanceOf: TypeError, message: "Cannot cache WebSocket upgrade response.", }); }); test("Cache: only puts GET requests", async (t) => { const { cache } = t.context; for (const method of ["POST", "PUT", "PATCH", "DELETE"]) { await t.throwsAsync( cache.put( new BaseRequest(`http://localhost:8787/${method}`, { method }), testResponse() ), { instanceOf: TypeError, message: "Cannot cache response to non-GET request.", } ); } }); test("Cache: doesn't cache partial content responses", async (t) => { const { cache } = t.context; const res = new Response("body", { status: 206, headers: { "content-range": "bytes 0-4/8" }, }); await t.throwsAsync(cache.put("http://localhost:8787/", res), { instanceOf: TypeError, message: "Cannot cache response to a range request (206 Partial Content).", }); }); test("Cache: doesn't cache vary all responses", async (t) => { const { cache } = t.context; let res = new Response("body", { headers: { vary: "*" }, }); await t.throwsAsync(cache.put("http://localhost:8787/", res), { instanceOf: TypeError, message: "Cannot cache response with 'Vary: *' header.", }); res = new Response("body", { headers: { vary: "user-agent, *" }, }); await t.throwsAsync(cache.put("http://localhost:8787/", res), { instanceOf: TypeError, message: "Cannot cache response with 'Vary: *' header.", }); }); test("Cache: respects cache key", async (t) => { const { storage, cache } = t.context; const req1 = new Request("http://localhost/", { cf: { cacheKey: "1" } }); const req2 = new Request("http://localhost/", { cf: { cacheKey: "2" } }); const res1 = testResponse("value1"); const res2 = testResponse("value2"); await cache.put(req1, res1); await cache.put(req2, res2); t.true(await storage.has("1")); t.true(await storage.has("2")); const match1 = await cache.match(req1); const match2 = await cache.match(req2); t.is(await match1?.text(), "value1"); t.is(await match2?.text(), "value2"); }); test("Cache: put respects cf cacheTtl", async (t) => { const { clock, cache } = t.context; await cache.put( new Request("http://localhost/test", { cf: { cacheTtl: 1 } }), new BaseResponse("value") ); t.not(await cache.match("http://localhost/test"), undefined); clock.timestamp += 500; t.not(await cache.match("http://localhost/test"), undefined); clock.timestamp += 500; t.is(await cache.match("http://localhost/test"), undefined); }); test("Cache: put respects cf cacheTtlByStatus", async (t) => { const { clock, cache } = t.context; const cf: RequestInitCfProperties = { cacheTtlByStatus: { "200-299": 2, "? :D": 99, "404": 1, "500-599": 0 }, }; const headers = { "Cache-Control": "max-age=5" }; const req200 = new Request("http://localhost/200", { cf }); const req201 = new Request("http://localhost/201", { cf }); const req302 = new Request("http://localhost/302", { cf }); const req404 = new Request("http://localhost/404", { cf }); const req599 = new Request("http://localhost/599", { cf }); await cache.put(req200, new BaseResponse(null, { status: 200, headers })); await cache.put(req201, new BaseResponse(null, { status: 201, headers })); await cache.put(req302, new BaseResponse(null, { status: 302, headers })); await cache.put(req404, new BaseResponse(null, { status: 404, headers })); await cache.put(req599, new BaseResponse(null, { status: 599, headers })); // Check all but 5xx responses cached t.not(await cache.match("http://localhost/200"), undefined); t.not(await cache.match("http://localhost/201"), undefined); t.not(await cache.match("http://localhost/302"), undefined); t.not(await cache.match("http://localhost/404"), undefined); t.is(await cache.match("http://localhost/599"), undefined); // Check 404 response expires after 1 second clock.timestamp += 1000; t.not(await cache.match("http://localhost/200"), undefined); t.not(await cache.match("http://localhost/201"), undefined); t.not(await cache.match("http://localhost/302"), undefined); t.is(await cache.match("http://localhost/404"), undefined); // Check 2xx responses expire after 2 seconds clock.timestamp += 1000; t.is(await cache.match("http://localhost/200"), undefined); t.is(await cache.match("http://localhost/201"), undefined); t.not(await cache.match("http://localhost/302"), undefined); // Check 302 response expires after 5 seconds clock.timestamp += 3000; t.is(await cache.match("http://localhost/302"), undefined); }); test("Cache: put increments subrequest count", async (t) => { const { cache } = t.context; const ctx = new RequestContext(); await ctx.runWith(() => cache.put("http://localhost:8787/", testResponse())); t.is(ctx.subrequests, 1); }); test("Cache: put waits for output gate to open before storing", (t) => { const { cache } = t.context; return waitsForOutputGate( t, () => cache.put("http://localhost:8787/", testResponse()), () => cache.match("http://localhost:8787/") ); }); test("Cache: put waits for input gate to open before returning", (t) => { const { cache } = t.context; return waitsForInputGate(t, () => cache.put("http://localhost:8787/", testResponse()) ); }); const matchMacro: Macro<[RequestInfo], Context> = async (t, req) => { const { cache } = t.context; await cache.put( new BaseRequest("http://localhost:8787/test"), testResponse() ); const cached = await cache.match(req); t.not(cached, undefined); assert(cached); // for TypeScript t.is(cached.status, 200); t.deepEqual( [...cached.headers], [ ["cache-control", "max-age=3600"], ["cf-cache-status", "HIT"], ["content-type", "text/plain; charset=utf8"], ] ); t.is(await cached?.text(), "value"); }; matchMacro.title = (providedTitle) => `Cache: matches ${providedTitle}`; test("request", matchMacro, new BaseRequest("http://localhost:8787/test")); test("string request", matchMacro, "http://localhost:8787/test"); test("url request", matchMacro, new URL("http://localhost:8787/test")); test("Cache: only matches non-GET requests when ignoring method", async (t) => { const { cache } = t.context; await cache.put( new BaseRequest("http://localhost:8787/test"), testResponse() ); const req = new BaseRequest("http://localhost:8787/test", { method: "POST" }); t.is(await cache.match(req), undefined); t.not(await cache.match(req, { ignoreMethod: true }), undefined); }); test("Cache: match increments subrequest count", async (t) => { const { cache } = t.context; const ctx = new RequestContext(); await ctx.runWith(() => cache.match("http://localhost:8787/")); t.is(ctx.subrequests, 1); }); test("Cache: match MISS waits for input gate to open before returning", async (t) => { const { cache } = t.context; await waitsForInputGate(t, () => cache.match("http://localhost:8787/")); }); test("Cache: match HIT waits for input gate to open before returning", async (t) => { const { cache } = t.context; await cache.put("http://localhost:8787/", testResponse()); await waitsForInputGate(t, () => cache.match("http://localhost:8787/")); }); test("Cache: match throws if attempting to load cached response created with Miniflare 1", async (t) => { const { storage, cache } = t.context; const value = JSON.stringify({ status: 200, headers: { "Cache-Control": ["max-age=3600"] }, body: "Ym9keQ==", // body in base64 }); await storage.put("http://localhost:8787/test", { value: utf8Encode(value) }); await t.throwsAsync(cache.match("http://localhost:8787/test"), { instanceOf: CacheError, code: "ERR_DESERIALIZATION", message: "Unable to deserialize stored cached data due to missing metadata.\n" + "The cached data storage format changed in Miniflare 2. You cannot " + "load cached data created with Miniflare 1 and must delete it.", }); }); const deleteMacro: Macro<[RequestInfo], Context> = async (t, req) => { const { storage, cache } = t.context; await cache.put( new BaseRequest("http://localhost:8787/test"), testResponse() ); t.not(await storage.get("http://localhost:8787/test"), undefined); t.true(await cache.delete(req)); t.is(await storage.get("http://localhost:8787/test"), undefined); t.false(await cache.delete(req)); }; deleteMacro.title = (providedTitle) => `Cache: deletes ${providedTitle}`; test("request", deleteMacro, new BaseRequest("http://localhost:8787/test")); test("string request", deleteMacro, "http://localhost:8787/test"); test("url request", deleteMacro, new URL("http://localhost:8787/test")); test("Cache: only deletes non-GET requests when ignoring method", async (t) => { const { cache } = t.context; await cache.put( new BaseRequest("http://localhost:8787/test"), testResponse() ); const req = new BaseRequest("http://localhost:8787/test", { method: "POST" }); t.false(await cache.delete(req)); t.true(await cache.delete(req, { ignoreMethod: true })); }); test("Cache: delete increments subrequest count", async (t) => { const { cache } = t.context; const ctx = new RequestContext(); await ctx.runWith(() => cache.delete("http://localhost:8787/")); t.is(ctx.subrequests, 1); }); test("Cache: delete waits for output gate to open before deleting", async (t) => { const { cache } = t.context; await cache.put("http://localhost:8787/", testResponse()); await waitsForOutputGate( t, () => cache.delete("http://localhost:8787/"), async () => !(await cache.match("http://localhost:8787/")) ); }); test("Cache: delete waits for input gate to open before returning", async (t) => { const { cache } = t.context; await cache.put("http://localhost:8787/", testResponse()); await waitsForInputGate(t, () => cache.delete("http://localhost:8787/")); }); const expireMacro: Macro< [{ headers: HeadersInit; expectedTtl: number }], Context > = async (t, { headers, expectedTtl }) => { const { clock, cache } = t.context; await cache.put( new BaseRequest("http://localhost:8787/test"), new BaseResponse("value", { headers }) ); t.not(await cache.match("http://localhost:8787/test"), undefined); clock.timestamp += expectedTtl / 2; t.not(await cache.match("http://localhost:8787/test"), undefined); clock.timestamp += expectedTtl / 2; t.is(await cache.match("http://localhost:8787/test"), undefined); }; expireMacro.title = (providedTitle) => `Cache: expires after ${providedTitle}`; test("Expires", expireMacro, { headers: { Expires: new Date(1000000 + 2000).toUTCString() }, expectedTtl: 2000, }); test("Cache-Control's max-age", expireMacro, { headers: { "Cache-Control": "max-age=1" }, expectedTtl: 1000, }); test("Cache-Control's s-maxage", expireMacro, { headers: { "Cache-Control": "s-maxage=1, max-age=10" }, expectedTtl: 1000, }); const isCachedMacro: Macro< [{ headers: { [key: string]: string }; cached: boolean }], Context > = async (t, { headers, cached }) => { const { storage, cache } = t.context; await cache.put( new BaseRequest("http://localhost:8787/test"), new BaseResponse("value", { headers: { ...headers, Expires: new Date(Date.now() + 2000).toUTCString(), }, }) ); const storedValue = await storage.get("http://localhost:8787/test"); (cached ? t.not : t.is)(storedValue, undefined); const cachedRes = await cache.match("http://localhost:8787/test"); (cached ? t.not : t.is)(cachedRes, undefined); }; isCachedMacro.title = (providedTitle) => `Cache: ${providedTitle}`; test("does not cache with private Cache-Control", isCachedMacro, { headers: { "Cache-Control": "private" }, cached: false, }); test("does not cache with no-store Cache-Control", isCachedMacro, { headers: { "Cache-Control": "no-store" }, cached: false, }); test("does not cache with no-cache Cache-Control", isCachedMacro, { headers: { "Cache-Control": "no-cache" }, cached: false, }); test("does not cache with Set-Cookie", isCachedMacro, { headers: { "Set-Cookie": "key=value" }, cached: false, }); test( "caches with Set-Cookie if Cache-Control private=set-cookie", isCachedMacro, { headers: { "Cache-Control": "private=set-cookie", "Set-Cookie": "key=value", }, cached: true, } ); test("Cache: hides implementation details", (t) => { const { cache } = t.context; t.deepEqual(getObjectProperties(cache), ["delete", "match", "put"]); }); test("Cache: operations throw outside request handler", async (t) => { const cache = new Cache(new MemoryStorage(), { blockGlobalAsyncIO: true }); const ctx = new RequestContext(); const expectations: ThrowsExpectation = { instanceOf: Error, message: /^Some functionality, such as asynchronous I\/O/, }; await t.throwsAsync( cache.put("http://localhost:8787/", testResponse()), expectations ); await t.throwsAsync(cache.match("http://localhost:8787/"), expectations); await t.throwsAsync(cache.delete("http://localhost:8787/"), expectations); await ctx.runWith(() => cache.put("http://localhost:8787/", testResponse())); await ctx.runWith(() => cache.match("http://localhost:8787/")); await ctx.runWith(() => cache.delete("http://localhost:8787/")); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { ReservationsSummaries } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ConsumptionManagementClient } from "../consumptionManagementClient"; import { ReservationSummary, Datagrain, ReservationsSummariesListByReservationOrderNextOptionalParams, ReservationsSummariesListByReservationOrderOptionalParams, ReservationsSummariesListByReservationOrderAndReservationNextOptionalParams, ReservationsSummariesListByReservationOrderAndReservationOptionalParams, ReservationsSummariesListNextOptionalParams, ReservationsSummariesListOptionalParams, ReservationsSummariesListByReservationOrderResponse, ReservationsSummariesListByReservationOrderAndReservationResponse, ReservationsSummariesListResponse, ReservationsSummariesListByReservationOrderNextResponse, ReservationsSummariesListByReservationOrderAndReservationNextResponse, ReservationsSummariesListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing ReservationsSummaries operations. */ export class ReservationsSummariesImpl implements ReservationsSummaries { private readonly client: ConsumptionManagementClient; /** * Initialize a new instance of the class ReservationsSummaries class. * @param client Reference to the service client */ constructor(client: ConsumptionManagementClient) { this.client = client; } /** * Lists the reservations summaries for daily or monthly grain. * @param reservationOrderId Order Id of the reservation * @param grain Can be daily or monthly * @param options The options parameters. */ public listByReservationOrder( reservationOrderId: string, grain: Datagrain, options?: ReservationsSummariesListByReservationOrderOptionalParams ): PagedAsyncIterableIterator<ReservationSummary> { const iter = this.listByReservationOrderPagingAll( reservationOrderId, grain, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByReservationOrderPagingPage( reservationOrderId, grain, options ); } }; } private async *listByReservationOrderPagingPage( reservationOrderId: string, grain: Datagrain, options?: ReservationsSummariesListByReservationOrderOptionalParams ): AsyncIterableIterator<ReservationSummary[]> { let result = await this._listByReservationOrder( reservationOrderId, grain, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByReservationOrderNext( reservationOrderId, grain, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByReservationOrderPagingAll( reservationOrderId: string, grain: Datagrain, options?: ReservationsSummariesListByReservationOrderOptionalParams ): AsyncIterableIterator<ReservationSummary> { for await (const page of this.listByReservationOrderPagingPage( reservationOrderId, grain, options )) { yield* page; } } /** * Lists the reservations summaries for daily or monthly grain. * @param reservationOrderId Order Id of the reservation * @param reservationId Id of the reservation * @param grain Can be daily or monthly * @param options The options parameters. */ public listByReservationOrderAndReservation( reservationOrderId: string, reservationId: string, grain: Datagrain, options?: ReservationsSummariesListByReservationOrderAndReservationOptionalParams ): PagedAsyncIterableIterator<ReservationSummary> { const iter = this.listByReservationOrderAndReservationPagingAll( reservationOrderId, reservationId, grain, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByReservationOrderAndReservationPagingPage( reservationOrderId, reservationId, grain, options ); } }; } private async *listByReservationOrderAndReservationPagingPage( reservationOrderId: string, reservationId: string, grain: Datagrain, options?: ReservationsSummariesListByReservationOrderAndReservationOptionalParams ): AsyncIterableIterator<ReservationSummary[]> { let result = await this._listByReservationOrderAndReservation( reservationOrderId, reservationId, grain, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByReservationOrderAndReservationNext( reservationOrderId, reservationId, grain, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByReservationOrderAndReservationPagingAll( reservationOrderId: string, reservationId: string, grain: Datagrain, options?: ReservationsSummariesListByReservationOrderAndReservationOptionalParams ): AsyncIterableIterator<ReservationSummary> { for await (const page of this.listByReservationOrderAndReservationPagingPage( reservationOrderId, reservationId, grain, options )) { yield* page; } } /** * Lists the reservations summaries for the defined scope daily or monthly grain. * @param scope The scope associated with reservations summaries operations. This includes * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope (legacy), * and * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' * for BillingProfile scope (modern). * @param grain Can be daily or monthly * @param options The options parameters. */ public list( scope: string, grain: Datagrain, options?: ReservationsSummariesListOptionalParams ): PagedAsyncIterableIterator<ReservationSummary> { const iter = this.listPagingAll(scope, grain, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(scope, grain, options); } }; } private async *listPagingPage( scope: string, grain: Datagrain, options?: ReservationsSummariesListOptionalParams ): AsyncIterableIterator<ReservationSummary[]> { let result = await this._list(scope, grain, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext(scope, grain, continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( scope: string, grain: Datagrain, options?: ReservationsSummariesListOptionalParams ): AsyncIterableIterator<ReservationSummary> { for await (const page of this.listPagingPage(scope, grain, options)) { yield* page; } } /** * Lists the reservations summaries for daily or monthly grain. * @param reservationOrderId Order Id of the reservation * @param grain Can be daily or monthly * @param options The options parameters. */ private _listByReservationOrder( reservationOrderId: string, grain: Datagrain, options?: ReservationsSummariesListByReservationOrderOptionalParams ): Promise<ReservationsSummariesListByReservationOrderResponse> { return this.client.sendOperationRequest( { reservationOrderId, grain, options }, listByReservationOrderOperationSpec ); } /** * Lists the reservations summaries for daily or monthly grain. * @param reservationOrderId Order Id of the reservation * @param reservationId Id of the reservation * @param grain Can be daily or monthly * @param options The options parameters. */ private _listByReservationOrderAndReservation( reservationOrderId: string, reservationId: string, grain: Datagrain, options?: ReservationsSummariesListByReservationOrderAndReservationOptionalParams ): Promise< ReservationsSummariesListByReservationOrderAndReservationResponse > { return this.client.sendOperationRequest( { reservationOrderId, reservationId, grain, options }, listByReservationOrderAndReservationOperationSpec ); } /** * Lists the reservations summaries for the defined scope daily or monthly grain. * @param scope The scope associated with reservations summaries operations. This includes * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope (legacy), * and * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' * for BillingProfile scope (modern). * @param grain Can be daily or monthly * @param options The options parameters. */ private _list( scope: string, grain: Datagrain, options?: ReservationsSummariesListOptionalParams ): Promise<ReservationsSummariesListResponse> { return this.client.sendOperationRequest( { scope, grain, options }, listOperationSpec ); } /** * ListByReservationOrderNext * @param reservationOrderId Order Id of the reservation * @param grain Can be daily or monthly * @param nextLink The nextLink from the previous successful call to the ListByReservationOrder method. * @param options The options parameters. */ private _listByReservationOrderNext( reservationOrderId: string, grain: Datagrain, nextLink: string, options?: ReservationsSummariesListByReservationOrderNextOptionalParams ): Promise<ReservationsSummariesListByReservationOrderNextResponse> { return this.client.sendOperationRequest( { reservationOrderId, grain, nextLink, options }, listByReservationOrderNextOperationSpec ); } /** * ListByReservationOrderAndReservationNext * @param reservationOrderId Order Id of the reservation * @param reservationId Id of the reservation * @param grain Can be daily or monthly * @param nextLink The nextLink from the previous successful call to the * ListByReservationOrderAndReservation method. * @param options The options parameters. */ private _listByReservationOrderAndReservationNext( reservationOrderId: string, reservationId: string, grain: Datagrain, nextLink: string, options?: ReservationsSummariesListByReservationOrderAndReservationNextOptionalParams ): Promise< ReservationsSummariesListByReservationOrderAndReservationNextResponse > { return this.client.sendOperationRequest( { reservationOrderId, reservationId, grain, nextLink, options }, listByReservationOrderAndReservationNextOperationSpec ); } /** * ListNext * @param scope The scope associated with reservations summaries operations. This includes * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope (legacy), * and * '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' * for BillingProfile scope (modern). * @param grain Can be daily or monthly * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( scope: string, grain: Datagrain, nextLink: string, options?: ReservationsSummariesListNextOptionalParams ): Promise<ReservationsSummariesListNextResponse> { return this.client.sendOperationRequest( { scope, grain, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByReservationOrderOperationSpec: coreClient.OperationSpec = { path: "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/providers/Microsoft.Consumption/reservationSummaries", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ReservationSummariesListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.filter, Parameters.apiVersion, Parameters.grain], urlParameters: [Parameters.$host, Parameters.reservationOrderId], headerParameters: [Parameters.accept], serializer }; const listByReservationOrderAndReservationOperationSpec: coreClient.OperationSpec = { path: "/providers/Microsoft.Capacity/reservationorders/{reservationOrderId}/reservations/{reservationId}/providers/Microsoft.Consumption/reservationSummaries", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ReservationSummariesListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.filter, Parameters.apiVersion, Parameters.grain], urlParameters: [ Parameters.$host, Parameters.reservationOrderId, Parameters.reservationId ], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/{scope}/providers/Microsoft.Consumption/reservationSummaries", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ReservationSummariesListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.filter, Parameters.apiVersion, Parameters.startDate, Parameters.endDate, Parameters.grain, Parameters.reservationId1, Parameters.reservationOrderId1 ], urlParameters: [Parameters.$host, Parameters.scope], headerParameters: [Parameters.accept], serializer }; const listByReservationOrderNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ReservationSummariesListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.filter, Parameters.apiVersion, Parameters.grain], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.reservationOrderId ], headerParameters: [Parameters.accept], serializer }; const listByReservationOrderAndReservationNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ReservationSummariesListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.filter, Parameters.apiVersion, Parameters.grain], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.reservationOrderId, Parameters.reservationId ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ReservationSummariesListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.filter, Parameters.apiVersion, Parameters.startDate, Parameters.endDate, Parameters.grain, Parameters.reservationId1, Parameters.reservationOrderId1 ], urlParameters: [Parameters.$host, Parameters.scope, Parameters.nextLink], headerParameters: [Parameters.accept], serializer };
the_stack
declare module '@shopify/draggable/lib/draggable.bundle.legacy' { export * from '@shopify/draggable'; } declare module '@shopify/draggable/lib/es5/draggable.bundle' { export * from '@shopify/draggable'; } declare module '@shopify/draggable/lib/es5/draggable.bundle.legacy' { export * from '@shopify/draggable'; } declare module '@shopify/draggable' { abstract class AbstractEvent<DataT = { [key: string]: any }> { constructor(data: DataT); static readonly type: string; // Abstract, waiting on https://github.com/Microsoft/TypeScript/issues/14600 static readonly cancelable: boolean; // Abstract, waiting on https://github.com/Microsoft/TypeScript/issues/14600 readonly type: string; readonly cancelable: boolean; cancel(): void; canceled(): boolean; clone(): AbstractEvent<DataT>; } export { AbstractEvent as BaseEvent }; type GetEventByEventName<eventName> = eventName extends 'draggable:initialize' ? DraggableInitializedEvent : eventName extends 'draggable:destroy' ? DraggableDestroyEvent : eventName extends 'drag:start' ? DragStartEvent : eventName extends 'drag:move' ? DragMoveEvent : eventName extends 'drag:over' ? DragOverEvent : eventName extends 'drag:over:container' ? DragOverContainerEvent : eventName extends 'drag:out' ? DragOutEvent : eventName extends 'drag:out:container' ? DragOutContainerEvent : eventName extends 'drag:stop' ? DragStopEvent : eventName extends 'drag:stopped' ? DragStoppedEvent : eventName extends 'drag:pressure' ? DragPressureEvent : eventName extends 'mirror:create' ? MirrorCreateEvent : eventName extends 'mirror:created' ? MirrorCreatedEvent : eventName extends 'mirror:attached' ? MirrorAttachedEvent : eventName extends 'mirror:move' ? MirrorMoveEvent : eventName extends 'mirror:moved' ? MirrorMovedEvent : eventName extends 'mirror:destroy' ? MirrorDestroyEvent : eventName extends 'droppable:start' ? DroppableStartEvent : eventName extends 'droppable:dropped' ? DroppableDroppedEvent : eventName extends 'droppable:returned' ? DroppableReturnedEvent : eventName extends 'droppable:stop' ? DroppableStopEvent : eventName extends 'sortable:start' ? SortableStartEvent : eventName extends 'sortable:sort' ? SortableSortEvent : eventName extends 'sortable:sorted' ? SortableSortedEvent : eventName extends 'sortable:stop' ? SortableStopEvent : eventName extends 'swappable:start' ? SwappableStartEvent : eventName extends 'swappable:swap' ? SwappableSwapEvent : eventName extends 'swappable:swapped' ? SwappableSwappedEvent : eventName extends 'swappable:stop' ? SwappableStopEvent : eventName extends 'collidable:in' ? CollidableInEvent : eventName extends 'collidable:out' ? CollidableOutEvent : eventName extends 'snap:in' ? SnapInEvent : eventName extends 'snap:out' ? SnapOutEvent : AbstractEvent; export interface DelayOptions { mouse?: number; drag?: number; touch?: number; } /** * DragEvent */ export class DragEvent extends AbstractEvent { readonly source: HTMLElement; readonly originalSource: HTMLElement; readonly mirror: HTMLElement; readonly sourceContainer: HTMLElement; readonly sensorEvent: SensorEvent; readonly originalEvent: Event; } export class DragStartEvent extends DragEvent { } export class DragMoveEvent extends DragEvent { } export class DragOverEvent extends DragEvent { readonly overContainer: HTMLElement; readonly over: HTMLElement; } export class DragOutEvent extends DragEvent { readonly overContainer: HTMLElement; readonly over: HTMLElement; } export class DragOverContainerEvent extends DragEvent { readonly overContainer: HTMLElement; } export class DragOutContainerEvent extends DragEvent { readonly overContainer: HTMLElement; } export class DragPressureEvent extends DragEvent { readonly pressure: number; } export class DragStopEvent extends DragEvent { } export class DragStoppedEvent extends DragEvent { } /** * DraggableEvent */ export type DraggableEventNames = 'draggable:initialize' | 'draggable:destroy' | 'drag:start' | 'drag:move' | 'drag:over' | 'drag:over:container' | 'drag:out' | 'drag:out:container' | 'drag:stop' | 'drag:pressure' | MirrorEventNames; export class DraggableEvent extends AbstractEvent { readonly draggable: Draggable; } export class DraggableInitializedEvent extends DraggableEvent { } export class DraggableDestroyEvent extends DraggableEvent { } export type DraggableClassNames = 'body:dragging' | 'container:dragging' | 'source:dragging' | 'source:placed' | 'container:placed' | 'draggable:over' | 'container:over' | 'source:original' | 'mirror'; export type DraggableContainer = HTMLElement | HTMLElement[] | NodeList; export interface DraggableOptions { draggable?: string; distance?: number; handle?: string | NodeList | HTMLElement[] | HTMLElement | ((currentElement: HTMLElement) => HTMLElement); delay?: number | DelayOptions; plugins?: Array<typeof AbstractPlugin>; sensors?: Sensor[]; classes?: { [key in DraggableClassNames]: string | string[] }; announcements?: AnnouncementOptions; collidables?: Collidables; mirror?: MirrorOptions; scrollable?: ScrollableOptions; swapAnimation?: SwapAnimationOptions; sortAnimation?: SortAnimationOptions; } export class Draggable<EventListType = DraggableEventNames> { static Plugins: { Announcement: typeof Announcement, Focusable: typeof Focusable, Mirror: typeof Mirror, Scrollable: typeof Scrollable }; constructor(containers: DraggableContainer, options?: DraggableOptions); destroy(): void; on<T extends EventListType>(eventName: T, callback: (event: GetEventByEventName<T>) => void): this; off<T extends EventListType>(eventName: T, callback: (event: GetEventByEventName<T>) => void): this; trigger(event: AbstractEvent): void; addPlugin(...plugins: Array<typeof AbstractPlugin>): this; removePlugin(...plugins: Array<typeof AbstractPlugin>): this; addSensor(...sensors: Array<typeof Sensor>): this; removeSensor(...sensors: Array<typeof Sensor>): this; addContainer(...containers: HTMLElement[]): this; removeContainer(...containers: HTMLElement[]): this; getClassNameFor(name: DraggableClassNames): string; getClassNamesFor(name: DraggableClassNames): string[]; isDragging(): boolean; getDraggableElementsForContainer(container: HTMLElement): HTMLElement[]; } export abstract class AbstractPlugin { protected draggable: Draggable; constructor(draggable: Draggable); protected abstract attach(): void; protected abstract detach(): void; } export { AbstractPlugin as BasePlugin }; /** * Announcement Plugin */ export interface AnnouncementOptions { expire: number; [key: string]: string | (() => string) | number; } class Announcement extends AbstractPlugin { options: AnnouncementOptions; protected attach(): void; protected detach(): void; } /** * Focusable Plugin */ class Focusable extends AbstractPlugin { protected attach(): void; protected detach(): void; getElements(): HTMLElement[]; } /** * Mirror Plugin */ export type MirrorEventNames = 'mirror:create' | 'mirror:created' | 'mirror:attached' | 'mirror:move' | 'mirror:destroy'; export class MirrorEvent extends AbstractEvent { readonly source: HTMLElement; readonly originalSource: HTMLElement; readonly sourceContainer: HTMLElement; readonly sensorEvent: SensorEvent; readonly originalEvent: Event; } export class MirrorCreateEvent extends MirrorEvent { } export class MirrorCreatedEvent extends MirrorEvent { readonly mirror: HTMLElement; } export class MirrorAttachedEvent extends MirrorEvent { readonly mirror: HTMLElement; } export class MirrorMoveEvent extends MirrorEvent { readonly mirror: HTMLElement; readonly passedThreshX: boolean; readonly passedThreshY: boolean; } export class MirrorMovedEvent extends MirrorEvent { readonly mirror: HTMLElement; readonly passedThreshX: boolean; readonly passedThreshY: boolean; } export class MirrorDestroyEvent extends MirrorEvent { readonly mirror: HTMLElement; } export interface MirrorOptions { xAxis?: boolean; yAxis?: boolean; constrainDimensions?: boolean; cursorOffsetX?: number; cursorOffsetY?: number; appendTo?: string | HTMLElement | ((source: HTMLElement) => HTMLElement); } class Mirror extends AbstractPlugin { protected attach(): void; protected detach(): void; getElements(): HTMLElement[]; } /** * Scrollable Plugin */ export interface ScrollableOptions { speed?: number; sensitivity?: number; scrollableElements?: HTMLElement[]; } class Scrollable extends AbstractPlugin { protected attach(): void; protected detach(): void; } /** * Sensors */ export class SensorEvent extends AbstractEvent { readonly originalEvent: Event; readonly clientX: number; readonly clientY: number; readonly target: HTMLElement; readonly container: HTMLElement; readonly pressure: number; } export class DragStartSensorEvent extends SensorEvent { } export class DragMoveSensorEvent extends SensorEvent { } export class DragStopSensorEvent extends SensorEvent { } export class DragPressureSensorEvent extends SensorEvent { } export interface SensorOptions { delay?: number | DelayOptions; } export class Sensor { constructor(containers: HTMLElement | HTMLElement[] | NodeList, options?: SensorOptions); attach(): this; detach(): this; addContainer(...containers: HTMLElement[]): void; removeContainer(...containers: HTMLElement[]): void; trigger(element: HTMLElement, sensorEvent: SensorEvent): SensorEvent; } export interface Sensors { DragSensor: typeof DragSensor; } export class DragSensor extends Sensor { } export class ForceTouchSensor extends Sensor { } export class MouseSensor extends Sensor { } export class TouchSensor extends Sensor { } /** * Droppable */ export type DroppableEventNames = 'droppable:start' | 'droppable:dropped' | 'droppable:returned' | 'droppable:stop' | DraggableEventNames; export class DroppableEvent extends AbstractEvent { readonly dragEvent: DragEvent; } export class DroppableStartEvent extends DroppableEvent { dropzone: HTMLElement; } export class DroppableDroppedEvent extends DroppableEvent { dropzone: HTMLElement; } export class DroppableReturnedEvent extends DroppableEvent { dropzone: HTMLElement; } export class DroppableStopEvent extends DroppableEvent { dropzone: HTMLElement; } export type DroppableClassNames = DraggableClassNames | 'droppable:active' | 'droppable:occupied'; export interface DroppableOptions extends DraggableOptions { dropzone: string | NodeList | HTMLElement[] | (() => NodeList | HTMLElement[]); classes?: { [key in DroppableClassNames]: string }; } export class Droppable<T = DroppableEventNames> extends Draggable<T> { constructor(containers: DraggableContainer, options: DroppableOptions); getClassNameFor(name: DroppableClassNames): string; } /** * Sortable */ export type SortableEventNames = 'sortable:start' | 'sortable:sort' | 'sortable:sorted' | 'sortable:stop' | DraggableEventNames; export class SortableEvent extends AbstractEvent { readonly dragEvent: DragEvent; } export class SortableStartEvent extends SortableEvent { readonly startIndex: number; readonly startContainer: HTMLElement; } export class SortableSortEvent extends SortableEvent { readonly oldIndex: number; readonly newIndex: number; readonly oldContainer: HTMLElement; readonly newContainer: HTMLElement; } export class SortableSortedEvent extends SortableEvent { readonly oldIndex: number; readonly newIndex: number; readonly oldContainer: HTMLElement; readonly newContainer: HTMLElement; } export class SortableStopEvent extends SortableEvent { readonly oldIndex: number; readonly newIndex: number; readonly oldContainer: HTMLElement; readonly newContainer: HTMLElement; } export class Sortable<T = SortableEventNames> extends Draggable<T> { } /** * Swappable */ export type SwappableEventNames = 'swappable:start' | 'swappable:swap' | 'swappable:swapped' | 'swappable:stop' | DraggableEventNames; export class SwappableEvent extends AbstractEvent { readonly dragEvent: DragEvent; } export class SwappableStartEvent extends SwappableEvent { } export class SwappableSwapEvent extends SwappableEvent { readonly over: HTMLElement; readonly overContainer: HTMLElement; } export class SwappableSwappedEvent extends SwappableEvent { readonly swappedElement: HTMLElement; } export class SwappableStopEvent extends SwappableEvent { } export class Swappable<T = SwappableEventNames> extends Draggable<T> { } /** * Collidable Plugin */ export type CollidableEventNames = 'collidable:in' | 'collidable:out'; export class CollidableEvent extends AbstractEvent { readonly dragEvent: DragEvent; readonly collidingElement: HTMLElement; } export class CollidableInEvent extends CollidableEvent { } export class CollidableOutEvent extends CollidableEvent { } export type Collidables = string | NodeList | HTMLElement[] | (() => NodeList | HTMLElement[]); class Collidable extends AbstractPlugin { protected attach(): void; protected detach(): void; } /** * ResizeMirror Plugin */ class ResizeMirror extends AbstractPlugin { protected attach(): void; protected detach(): void; } /** * Snappable Plugin */ export type SnappableEventNames = 'snap:in' | 'snap:out'; export class SnapEvent extends AbstractEvent { readonly dragEvent: DragEvent; readonly snappable: HTMLElement; } export class SnapInEvent extends SnapEvent { } export class SnapOutEvent extends SnapEvent { } class Snappable extends AbstractPlugin { protected attach(): void; protected detach(): void; } /** * SwapAnimation Plugin */ export interface SwapAnimationOptions { duration: number; easingFunction: string; horizontal: boolean; } class SwapAnimation extends AbstractPlugin { protected attach(): void; protected detach(): void; } /** * SortAnimation */ export interface SortAnimationOptions { duration?: number; easingFunction?: string; } class SortAnimation extends AbstractPlugin { protected attach(): void; protected detach(): void; } export const Plugins: { Collidable: typeof Collidable, SwapAnimation: typeof SwapAnimation, SortAnimation: typeof SortAnimation, ResizeMirror: typeof ResizeMirror, Snappable: typeof Snappable, }; }
the_stack
import { AfterContentInit, AfterViewInit, Directive, ElementRef, EventEmitter, HostBinding, HostListener, Input, OnChanges, OnDestroy, OnInit, Optional, Output, Self, SimpleChange, SkipSelf } from '@angular/core'; import { animationFrameScheduler, EMPTY, scheduled, Subject, Subscription } from 'rxjs'; import { debounce } from 'rxjs/operators'; import { SelectionEventsEmitter, RTSelectionEvent } from './providers/selection-events-emitter'; import { RTSelectionEventsHelper } from './providers/selection-events-helper'; import { RTSelectionService } from './providers/selection.service'; import { SelectableDirective } from './selectable.directive'; import { SelectionCheckboxForDirective } from './selection-checkbox-for.directive'; interface SelectableElement { selectable: SelectableDirective | SelectionCheckboxForDirective; element: HTMLElement; } @Directive({ exportAs: 'rtSelectionArea', providers: [RTSelectionService, RTSelectionEventsHelper], selector: '[rtSelectionArea]' }) export class SelectionAreaDirective implements SelectionEventsEmitter, AfterContentInit, OnChanges, OnInit, AfterViewInit, OnDestroy { private selectableItems: SelectableElement[] = []; private childSelectionCheckboxes: SelectableElement[] = []; private childSelectionAreas = new Set<SelectionAreaDirective>(); private selectablesChangedSubscription: Subscription; private selectablesChangedSubject = new Subject<(SelectableDirective | SelectionCheckboxForDirective)[]>(); private childSelectionAreasChangedSubscription: Subscription; private childSelectionAreasChangedSubject = new Subject<Set<SelectionAreaDirective>>(); @HostBinding('tabIndex') public tabIndex = 0; @Input() public set preventEventsDefaults(value: boolean) { this.selectionEventsHelper.preventEventsDefaults = value; } @Input() public set stopEventsPropagation(value: boolean) { this.selectionEventsHelper.stopEventsPropagation = value; } @Input() public set horizontal(value: boolean) { this.selectionEventsHelper.horizontal = value; } @Input() public set multiple(value: boolean) { this.selectionEventsHelper.multiple = value; } @Input() public set toggleOnly(value: boolean) { this.selectionEventsHelper.toggleOnly = value; } @Input() public autoSelectFirst = false; @Input() public set trackBy(value: (index: number, item: any) => any) { if (typeof value !== 'function') { throw new Error('trackBy parameter value must be a function'); } this.selectionService.trackByFn = value; } @Output() public readonly itemSelected: EventEmitter<RTSelectionEvent> = new EventEmitter<RTSelectionEvent>(); @Output() public readonly itemDeselected: EventEmitter<RTSelectionEvent> = new EventEmitter<RTSelectionEvent>(); @Output() public readonly selectionChanged: EventEmitter<RTSelectionEvent> = new EventEmitter<RTSelectionEvent>(); constructor( @SkipSelf() @Optional() private parentSelectionArea: SelectionAreaDirective, @Self() public selectionService: RTSelectionService, @Self() public selectionEventsHelper: RTSelectionEventsHelper) { this.selectionService.areaEventsEmitter = this; this.selectionEventsHelper = selectionEventsHelper; } ngOnInit() { this.selectablesChangedSubscription = this.selectablesChangedSubject.pipe( debounce(() => scheduled(EMPTY, animationFrameScheduler)) ).subscribe(items => this.buildSelectionSource(items)); this.childSelectionAreasChangedSubscription = this.childSelectionAreasChangedSubject.pipe( debounce(() => scheduled(EMPTY, animationFrameScheduler)) ).subscribe(items => this.buildSelectionServicesList(items)); } ngAfterViewInit() { this.parentSelectionArea?.registerChildSelectionArea(this); } public ngOnDestroy(): void { this.selectionService.deselectAll(); this.selectionService.destroy(); this.parentSelectionArea?.unregisterChildSelectionArea(this); this.selectablesChangedSubscription?.unsubscribe(); this.childSelectionAreasChangedSubscription?.unsubscribe(); } public ngOnChanges(changes: { multiple?: SimpleChange; autoSelectFirst?: SimpleChange }): void { if (false === this.selectionService.hasSelections() && changes.autoSelectFirst && changes.autoSelectFirst.currentValue === true) { this.selectionService.selectIndex(0, false); } if (changes.multiple && changes.multiple.currentValue === false) { const selectedIndexes = this.selectionService.getSelectedIndexes(); if (selectedIndexes.length > 1) { selectedIndexes.splice(0, 1); selectedIndexes.forEach(index => { this.selectionService.deselectIndex(index); }); } } } @HostListener('keydown', ['$event.ctrlKey', '$event.shiftKey', '$event.keyCode', '$event.preventDefault', '$event.stopPropagation', '$event']) public keyDownHandler( ctrlKeyPressed: boolean, shiftKeyPressed: boolean, keyCode: number, preventDefaultFn: () => void, stopPropagationFn: () => void, executionContext: any ): void { if (this.selectionEventsHelper.keyboardHandler(ctrlKeyPressed, shiftKeyPressed, keyCode)) { if (this.selectionEventsHelper.preventEventsDefaults && preventDefaultFn) { preventDefaultFn.call(executionContext); } if (this.selectionEventsHelper.stopEventsPropagation && stopPropagationFn) { stopPropagationFn.call(executionContext); } } } //#region callbacks for DOM descendants public registerSelectable(selectable: SelectableDirective, elementRef: ElementRef): void { const element = elementRef.nativeElement as HTMLElement; let i = 0; for (; i < this.selectableItems.length; i++) { if (this.selectableItems[i].element.compareDocumentPosition(element) & document.DOCUMENT_POSITION_PRECEDING) { this.selectableItems.splice(i, 0, { element, selectable }); break; } } if (i === this.selectableItems.length) { this.selectableItems.push({element, selectable}); } this.selectablesChangedSubject.next(this.selectableItems.map(x => x.selectable)); } public unregisterSelectable(selectable: SelectableDirective): void { const idx = this.selectableItems.findIndex(x => x.selectable === selectable); if (idx >= 0) { this.selectableItems.splice(idx, 1); } this.selectablesChangedSubject.next(this.selectableItems.map(x => x.selectable)); } public registerSelectionCheckbox(checkbox: SelectionCheckboxForDirective, elementRef: ElementRef): void { const element = elementRef.nativeElement as HTMLElement; let i = 0; for (; i < this.childSelectionCheckboxes.length; i++) { if (this.childSelectionCheckboxes[i].element.compareDocumentPosition(element) & document.DOCUMENT_POSITION_PRECEDING) { this.childSelectionCheckboxes.splice(i, 0, { element, selectable: checkbox }); break; } } if (i === this.childSelectionCheckboxes.length) { this.childSelectionCheckboxes.push({element, selectable: checkbox}); } this.selectablesChangedSubject.next(this.childSelectionCheckboxes.map(x => x.selectable)); } public unregisterSelectionCheckbox(checkbox: SelectionCheckboxForDirective): void { const idx = this.childSelectionCheckboxes.findIndex(x => x.selectable === checkbox); if (idx >= 0) { this.childSelectionCheckboxes.splice(idx, 1); } this.selectablesChangedSubject.next(this.childSelectionCheckboxes.map(x => x.selectable)); } public registerChildSelectionArea(selectionArea: SelectionAreaDirective): void { if (!this.childSelectionAreas.has(selectionArea)) { this.childSelectionAreas.add(selectionArea); this.childSelectionAreasChangedSubject.next(this.childSelectionAreas); } } public unregisterChildSelectionArea(selectionArea: SelectionAreaDirective): void { if (this.childSelectionAreas.has(selectionArea)) { this.childSelectionAreas.delete(selectionArea); this.childSelectionAreasChangedSubject.next(this.childSelectionAreas); } } //#endregion public ngAfterContentInit(): void { if (this.selectableItems.length > 0) { this.buildSelectionSource(this.selectableItems.map(item => item.selectable)); } if (this.childSelectionCheckboxes.length > 0) { this.buildSelectionSource(this.childSelectionCheckboxes.map(item => item.selectable)); } this.buildSelectionServicesList(this.childSelectionAreas); } private buildSelectionSource(items: (SelectableDirective | SelectionCheckboxForDirective)[]): void { let index = 0; this.selectionService.eventEmitters = items.map(item => { if (item.index !== null && item.index !== index) { this.selectionService.deselectIndex(item.index); } item.index = index++; return item; }); this.selectionService.items = items.map(item => item.item); if (this.selectionService.items.length > 0) { setTimeout(() => { // since we've modify collection on first render, // to prevent error 'Expression has changed after it was checked' we've do selection after render if (this.selectionService.items.length > 0) { this.selectionService.checkSelection(); // repeats first element selection since checking can deselect all elements if (false === this.selectionService.hasSelections() && this.autoSelectFirst) { this.selectionService.selectIndex(0, false); } } }, 0); } } private buildSelectionServicesList(items: Set<SelectionAreaDirective>): void { this.selectionService.childSelectionServices = Array.from(items) .filter(area => area !== this) .map(area => area.selectionService); } }
the_stack
// Files that export a single object. export { default as AriaListMixin } from "./base/AriaListMixin.js"; export { default as AriaMenuMixin } from "./base/AriaMenuMixin.js"; export { default as AriaRoleMixin } from "./base/AriaRoleMixin.js"; export { default as AttributeMarshallingMixin } from "./core/AttributeMarshallingMixin.js"; export { default as CalendarElementMixin } from "./base/CalendarElementMixin.js"; export { default as ComposedFocusMixin } from "./base/ComposedFocusMixin.js"; export { default as ContentItemsMixin } from "./base/ContentItemsMixin.js"; export { default as CurrentMixin } from "./base/CurrentMixin.js"; export { default as CursorAPIMixin } from "./base/CursorAPIMixin.js"; export { default as CursorInViewMixin } from "./base/CursorInViewMixin.js"; export { default as CursorSelectMixin } from "./base/CursorSelectMixin.js"; export { default as DarkModeMixin } from "./base/DarkModeMixin.js"; export { default as DelegateCursorMixin } from "./base/DelegateCursorMixin.js"; export { default as DelegateFocusMixin } from "./base/DelegateFocusMixin.js"; export { default as DelegateInputLabelMixin } from "./base/DelegateInputLabelMixin.js"; export { default as DelegateInputSelectionMixin } from "./base/DelegateInputSelectionMixin.js"; export { default as DelegateItemsMixin } from "./base/DelegateItemsMixin.js"; export { default as DialogModalityMixin } from "./base/DialogModalityMixin.js"; export { default as DirectionCursorMixin } from "./base/DirectionCursorMixin.js"; export { default as DisabledMixin } from "./base/DisabledMixin.js"; export { default as EffectMixin } from "./base/EffectMixin.js"; export { default as FocusCaptureMixin } from "./base/FocusCaptureMixin.js"; export { default as FocusVisibleMixin } from "./base/FocusVisibleMixin.js"; export { default as FormElementMixin } from "./base/FormElementMixin.js"; export { default as HoverMixin } from "./base/HoverMixin.js"; export { default as ItemsAPIMixin } from "./base/ItemsAPIMixin.js"; export { default as ItemsCursorMixin } from "./base/ItemsCursorMixin.js"; export { default as ItemsMultiSelectMixin } from "./base/ItemsMultiSelectMixin.js"; export { default as ItemsTextMixin } from "./base/ItemsTextMixin.js"; export { default as KeyboardDirectionMixin } from "./base/KeyboardDirectionMixin.js"; export { default as KeyboardMixin } from "./base/KeyboardMixin.js"; export { default as KeyboardPagedCursorMixin } from "./base/KeyboardPagedCursorMixin.js"; export { default as KeyboardPrefixCursorMixin } from "./base/KeyboardPrefixCursorMixin.js"; export { default as LanguageDirectionMixin } from "./base/LanguageDirectionMixin.js"; export { default as MultiSelectAPIMixin } from "./base/MultiSelectAPIMixin.js"; export { default as MultiSelectToggleMixin } from "./base/MultiSelectToggleMixin.js"; export { default as MultiSelectValueAPIMixin } from "./base/MultiSelectValueAPIMixin.js"; export { default as OpenCloseMixin } from "./base/OpenCloseMixin.js"; export { default as OverlayMixin } from "./base/OverlayMixin.js"; export { default as PageNumbersMixin } from "./base/PageNumbersMixin.js"; export { default as AlertDialog } from "./plain/PlainAlertDialog.js"; export { default as ArrowDirectionButton } from "./plain/PlainArrowDirectionButton.js"; export { default as ArrowDirectionMixin } from "./plain/PlainArrowDirectionMixin.js"; export { default as AutoCompleteComboBox } from "./plain/PlainAutoCompleteComboBox.js"; export { default as AutoCompleteInput } from "./plain/PlainAutoCompleteInput.js"; export { default as AutoSizeTextarea } from "./plain/PlainAutoSizeTextarea.js"; export { default as Backdrop } from "./plain/PlainBackdrop.js"; export { default as BorderButton } from "./plain/PlainBorderButton.js"; export { default as Button } from "./plain/PlainButton.js"; export { default as ButtonMixin } from "./plain/PlainButtonMixin.js"; export { default as CalendarDay } from "./plain/PlainCalendarDay.js"; export { default as CalendarDayButton } from "./plain/PlainCalendarDayButton.js"; export { default as CalendarDayNamesHeader } from "./plain/PlainCalendarDayNamesHeader.js"; export { default as CalendarDays } from "./plain/PlainCalendarDays.js"; export { default as CalendarMonth } from "./plain/PlainCalendarMonth.js"; export { default as CalendarMonthNavigator } from "./plain/PlainCalendarMonthNavigator.js"; export { default as CalendarMonthYearHeader } from "./plain/PlainCalendarMonthYearHeader.js"; export { default as Carousel } from "./plain/PlainCarousel.js"; export { default as CarouselMixin } from "./plain/PlainCarouselMixin.js"; export { default as CarouselSlideshow } from "./plain/PlainCarouselSlideshow.js"; export { default as CarouselWithThumbnails } from "./plain/PlainCarouselWithThumbnails.js"; export { default as CenteredStrip } from "./plain/PlainCenteredStrip.js"; export { default as CenteredStripHighlight } from "./plain/PlainCenteredStripHighlight.js"; export { default as CenteredStripOpacity } from "./plain/PlainCenteredStripOpacity.js"; export { default as CheckListItem } from "./plain/PlainCheckListItem.js"; export { default as ComboBox } from "./plain/PlainComboBox.js"; export { default as ComboBoxMixin } from "./plain/PlainComboBoxMixin.js"; export { default as CrossfadeStage } from "./plain/PlainCrossfadeStage.js"; export { default as DateComboBox } from "./plain/PlainDateComboBox.js"; export { default as DateInput } from "./plain/PlainDateInput.js"; export { default as Dialog } from "./plain/PlainDialog.js"; export { default as Drawer } from "./plain/PlainDrawer.js"; export { default as DrawerMixin } from "./plain/PlainDrawerMixin.js"; export { default as DrawerWithGrip } from "./plain/PlainDrawerWithGrip.js"; export { default as DropdownList } from "./plain/PlainDropdownList.js"; export { default as ExpandCollapseToggle } from "./plain/PlainExpandCollapseToggle.js"; export { default as ExpandablePanel } from "./plain/PlainExpandablePanel.js"; export { default as ExpandableSection } from "./plain/PlainExpandableSection.js"; export { default as Explorer } from "./plain/PlainExplorer.js"; export { default as FilterComboBox } from "./plain/PlainFilterComboBox.js"; export { default as FilterListBox } from "./plain/PlainFilterListBox.js"; export { default as HamburgerMenuButton } from "./plain/PlainHamburgerMenuButton.js"; export { default as Hidden } from "./plain/PlainHidden.js"; export { default as Input } from "./plain/PlainInput.js"; export { default as InputMixin } from "./plain/PlainInputMixin.js"; export { default as ListBox } from "./plain/PlainListBox.js"; export { default as ListBoxMixin } from "./plain/PlainListBoxMixin.js"; export { default as ListComboBox } from "./plain/PlainListComboBox.js"; export { default as ListExplorer } from "./plain/PlainListExplorer.js"; export { default as ListWithSearch } from "./plain/PlainListWithSearch.js"; export { default as Menu } from "./plain/PlainMenu.js"; export { default as MenuButton } from "./plain/PlainMenuButton.js"; export { default as MenuItem } from "./plain/PlainMenuItem.js"; export { default as MenuSeparator } from "./plain/PlainMenuSeparator.js"; export { default as ModalBackdrop } from "./plain/PlainModalBackdrop.js"; export { default as ModalOverlayMixin } from "./plain/PlainModalOverlayMixin.js"; export { default as Modes } from "./plain/PlainModes.js"; export { default as MultiSelectListBox } from "./plain/PlainMultiSelectListBox.js"; export { default as NumberSpinBox } from "./plain/PlainNumberSpinBox.js"; export { default as OpenCloseToggle } from "./plain/PlainOpenCloseToggle.js"; export { default as Option } from "./plain/PlainOption.js"; export { default as OptionList } from "./plain/PlainOptionList.js"; export { default as Overlay } from "./plain/PlainOverlay.js"; export { default as OverlayFrame } from "./plain/PlainOverlayFrame.js"; export { default as PageDot } from "./plain/PlainPageDot.js"; export { default as PlayControlsMixin } from "./plain/PlainPlayControlsMixin.js"; export { default as Popup } from "./plain/PlainPopup.js"; export { default as PopupButton } from "./plain/PlainPopupButton.js"; export { default as PopupSource } from "./plain/PlainPopupSource.js"; export { default as ProgressSpinner } from "./plain/PlainProgressSpinner.js"; export { default as PullToRefresh } from "./plain/PlainPullToRefresh.js"; export { default as RepeatButton } from "./plain/PlainRepeatButton.js"; export { default as SelectableButton } from "./plain/PlainSelectableButton.js"; export { default as Slideshow } from "./plain/PlainSlideshow.js"; export { default as SlideshowWithPlayControls } from "./plain/PlainSlideshowWithPlayControls.js"; export { default as SlidingPages } from "./plain/PlainSlidingPages.js"; export { default as SlidingStage } from "./plain/PlainSlidingStage.js"; export { default as SpinBox } from "./plain/PlainSpinBox.js"; export { default as SpinBoxMixin } from "./plain/PlainSpinBoxMixin.js"; export { default as TabButton } from "./plain/PlainTabButton.js"; export { default as TabStrip } from "./plain/PlainTabStrip.js"; export { default as Tabs } from "./plain/PlainTabs.js"; export { default as Toast } from "./plain/PlainToast.js"; export { default as TooltipButton } from "./plain/PlainTooltipButton.js"; export { default as PopupDragSelectMixin } from "./base/PopupDragSelectMixin.js"; export { default as PopupListMixin } from "./base/PopupListMixin.js"; export { default as PopupModalityMixin } from "./base/PopupModalityMixin.js"; export { default as PopupToggleMixin } from "./base/PopupToggleMixin.js"; export { default as ReactiveElement } from "./core/ReactiveElement.js"; export { default as ReactiveMixin } from "./core/ReactiveMixin.js"; export { default as RepeatMousedownMixin } from "./base/RepeatMousedownMixin.js"; export { default as ResizeMixin } from "./base/ResizeMixin.js"; export { default as SelectableMixin } from "./base/SelectableMixin.js"; export { default as SelectedTextAPIMixin } from "./base/SelectedTextAPIMixin.js"; export { default as SelectedValueAPIMixin } from "./base/SelectedValueAPIMixin.js"; export { default as ShadowTemplateMixin } from "./core/ShadowTemplateMixin.js"; export { default as SingleSelectAPIMixin } from "./base/SingleSelectAPIMixin.js"; export { default as SlotContentMixin } from "./base/SlotContentMixin.js"; export { default as SlotItemsMixin } from "./base/SlotItemsMixin.js"; export { default as SwipeCommandsMixin } from "./base/SwipeCommandsMixin.js"; export { default as SwipeDirectionMixin } from "./base/SwipeDirectionMixin.js"; export { default as TapCursorMixin } from "./base/TapCursorMixin.js"; export { default as TimerCursorMixin } from "./base/TimerCursorMixin.js"; export { default as TouchSwipeMixin } from "./base/TouchSwipeMixin.js"; export { default as TrackTextSelectionMixin } from "./base/TrackTextSelectionMixin.js"; export { default as TrackpadSwipeMixin } from "./base/TrackpadSwipeMixin.js"; export { default as TransitionEffectMixin } from "./base/TransitionEffectMixin.js"; export { default as UpDownToggle } from "./base/UpDownToggle.js"; export { default as WrappedStandardElement } from "./base/WrappedStandardElement.js"; // Files that export multiple objects. // As of Sept 2019, there's no way to simultaneously import a collection of // objects and then export them as a named object, so we have to do the import // and export in separate steps. import * as accessibilityImport from "./base/accessibility.js"; // @ts-ignore export const accessibility = accessibilityImport; import * as calendarImport from "./base/calendar.js"; // @ts-ignore export const calendar = calendarImport; import * as constantsImport from "./base/constants.js"; // @ts-ignore export const constants = constantsImport; import * as contentImport from "./base/content.js"; // @ts-ignore export const content = contentImport; import * as fractionalSelectionImport from "./base/fractionalSelection.js"; // @ts-ignore export const fractionalSelection = fractionalSelectionImport; import * as internalImport from "./base/internal.js"; // @ts-ignore export const internal = internalImport; import * as layoutPopupImport from "./base/layoutPopup.js"; // @ts-ignore export const layoutPopup = layoutPopupImport; import * as scrollingImport from "./base/scrolling.js"; // @ts-ignore export const scrolling = scrollingImport; import * as domImport from "./core/dom.js"; // @ts-ignore export const dom = domImport; import * as htmlLiteralsImport from "./core/htmlLiterals.js"; // @ts-ignore export const htmlLiterals = htmlLiteralsImport; import * as templateImport from "./core/template.js"; // @ts-ignore export const template = templateImport;
the_stack
* @module Core */ import * as hash from "object-hash"; import * as path from "path"; import { BriefcaseDb, IModelDb, IModelJsNative, IpcHost } from "@itwin/core-backend"; import { Id64String } from "@itwin/core-bentley"; import { FormatProps, UnitSystemKey } from "@itwin/core-quantity"; import { Content, ContentDescriptorRequestOptions, ContentFlags, ContentRequestOptions, ContentSourcesRequestOptions, DefaultContentDisplayTypes, Descriptor, DescriptorOverrides, DiagnosticsOptionsWithHandler, DisplayLabelRequestOptions, DisplayLabelsRequestOptions, DisplayValueGroup, DistinctValuesRequestOptions, ElementProperties, ElementPropertiesRequestOptions, FilterByInstancePathsHierarchyRequestOptions, FilterByTextHierarchyRequestOptions, getLocalesDirectory, HierarchyCompareInfo, HierarchyCompareOptions, HierarchyRequestOptions, InstanceKey, isSingleElementPropertiesRequestOptions, Key, KeySet, LabelDefinition, MultiElementPropertiesRequestOptions, Node, NodeKey, NodePathElement, Paged, PagedResponse, PresentationError, PresentationStatus, Prioritized, Ruleset, SelectClassInfo, SelectionScope, SelectionScopeRequestOptions, SingleElementPropertiesRequestOptions, } from "@itwin/presentation-common"; import { PRESENTATION_BACKEND_ASSETS_ROOT, PRESENTATION_COMMON_ASSETS_ROOT } from "./Constants"; import { buildElementsProperties, getElementIdsByClass, getElementsCount } from "./ElementPropertiesHelper"; import { createDefaultNativePlatform, NativePlatformDefinition, NativePlatformRequestTypes, NativePresentationDefaultUnitFormats, NativePresentationKeySetJSON, NativePresentationUnitSystem, } from "./NativePlatform"; import { RulesetManager, RulesetManagerImpl } from "./RulesetManager"; import { RulesetVariablesManager, RulesetVariablesManagerImpl } from "./RulesetVariablesManager"; import { SelectionScopesHelper } from "./SelectionScopesHelper"; import { UpdatesTracker } from "./UpdatesTracker"; import { getElementKey } from "./Utils"; /** * Presentation manager working mode. * @public */ export enum PresentationManagerMode { /** * Presentation manager assumes iModels are opened in read-only mode and avoids doing some work * related to reacting to changes in iModels. */ ReadOnly, /** * Presentation manager assumes iModels are opened in read-write mode and it may need to * react to changes. This involves some additional work and gives slightly worse performance. */ ReadWrite, } /** * Presentation hierarchy cache mode. * @beta */ export enum HierarchyCacheMode { /** * Hierarchy cache is created in memory. */ Memory = "memory", /** * Hierarchy cache is created on disk. In this mode hierarchy cache is persisted between iModel * openings. */ Disk = "disk", /** * Hierarchy cache is created on disk. In this mode everything is cached in memory while creating hierarchy level * and persisted in disk cache when whole hierarchy level is created. */ Hybrid = "hybrid", } /** * Configuration for hierarchy cache. * @beta */ export type HierarchyCacheConfig = MemoryHierarchyCacheConfig | DiskHierarchyCacheConfig | HybridCacheConfig; /** * Base interface for all [[HierarchyCacheConfig]] implementations. * @beta */ export interface HierarchyCacheConfigBase { mode: HierarchyCacheMode; } /** * Configuration for in-memory hierarchy cache. * @beta */ export interface MemoryHierarchyCacheConfig extends HierarchyCacheConfigBase { mode: HierarchyCacheMode.Memory; } /** * Configuration for persistent disk hierarchy cache. * @beta */ export interface DiskHierarchyCacheConfig extends HierarchyCacheConfigBase { mode: HierarchyCacheMode.Disk; /** * A directory for Presentation hierarchy cache. If set, the directory must exist. * * The default directory depends on the iModel and the way it's opened. */ directory?: string; } /** * Configuration for the experimental hybrid hierarchy cache. * * Hybrid cache uses a combination of in-memory and disk caches, which should make it a better * alternative for cases when there are lots of simultaneous requests. * * @beta */ export interface HybridCacheConfig extends HierarchyCacheConfigBase { mode: HierarchyCacheMode.Hybrid; /** Configuration for disk cache used to persist hierarchies. */ disk?: DiskHierarchyCacheConfig; } /** * Configuration for content cache. * @public */ export interface ContentCacheConfig { /** * Maximum number of content descriptors cached in memory for quicker paged content requests. * * Defaults to `100`. * * @alpha */ size?: number; } /** * A data structure that associates unit systems with a format. The associations are used for * assigning default unit formats for specific phenomenons (see [[PresentationManagerProps.defaultFormats]]). * * @public */ export interface UnitSystemFormat { unitSystems: UnitSystemKey[]; format: FormatProps; } /** * Properties that can be used to configure [[PresentationManager]] * @public */ export interface PresentationManagerProps { /** * Path overrides for presentation assets. Need to be overriden by application if it puts these assets someplace else than the default. * * By default paths to asset directories are determined during the call of [[Presentation.initialize]] using this algorithm: * * - for `presentation-backend` assets: * * - if path of `.js` file that contains [[PresentationManager]] definition contains "presentation-backend", assume the package is in `node_modules` and the directory structure is: * - `assets/*\*\/*` * - `presentation-backend/{presentation-backend source files}` * * which means the assets can be found through a relative path `../assets/` from the JS file being executed. * * - for `presentation-common` assets: * * - if path of `.js` files of `presentation-common` package contain "presentation-common", assume the package is in `node_modules` and the directory structure is: * - `assets/*\*\/*` * - `presentation-common/{presentation-common source files}` * * which means the assets can be found through a relative path `../assets/` from the package's source files. * * - in both cases, if we determine that source files are not in `node_modules`, assume the backend is webpacked into a single file with assets next to it: * - `assets/*\*\/*` * - `{source file being executed}.js` * * which means the assets can be found through a relative path `./assets/` from the `{source file being executed}`. * * The overrides can be specified as a single path (when assets of both `presentation-backend` and `presentation-common` packages are merged into a single directory) or as an object with two separate paths for each package. */ presentationAssetsRoot?: string | { /** Path to `presentation-backend` assets */ backend: string; /** Path to `presentation-common` assets */ common: string; }; /** * A list of directories containing application's presentation rulesets. */ rulesetDirectories?: string[]; /** * A list of directories containing application's supplemental presentation rulesets. */ supplementalRulesetDirectories?: string[]; /** * A list of directories containing application's locale-specific localized * string files (in simplified i18next v3 format) */ localeDirectories?: string[]; /** * Sets the active locale to use when localizing presentation-related * strings. It can later be changed through [[PresentationManager.activeLocale]]. */ defaultLocale?: string; /** * Sets the active unit system to use for formatting property values with * units. Default presentation units are used if this is not specified. The active unit * system can later be changed through [[PresentationManager.activeUnitSystem]] or overriden for each request * through request options. */ defaultUnitSystem?: UnitSystemKey; /** * A map of default unit formats to use for formatting properties that don't have a presentation format * in requested unit system. */ defaultFormats?: { [phenomenon: string]: UnitSystemFormat; }; /** * Should schemas preloading be enabled. If true, presentation manager listens * for `BriefcaseDb.onOpened` event and force pre-loads all ECSchemas. */ enableSchemasPreload?: boolean; /** * A number of worker threads to use for handling presentation requests. Defaults to `2`. */ workerThreadsCount?: number; /** * Presentation manager working mode. Backends that use iModels in read-write mode should * use `ReadWrite`, others might want to set to `ReadOnly` for better performance. * * Defaults to [[PresentationManagerMode.ReadWrite]]. */ mode?: PresentationManagerMode; /** * The interval (in milliseconds) used to poll for presentation data changes. Only has * effect in read-write mode (see [[mode]]). * * @alpha */ updatesPollInterval?: number; /** Options for caching. */ caching?: { /** * Hierarchies-related caching options. * @beta */ hierarchies?: HierarchyCacheConfig; /** Content-related caching options. */ content?: ContentCacheConfig; }; /** * Use [SQLite's Memory-Mapped I/O](https://sqlite.org/mmap.html) for worker connections. This mode improves performance of handling * requests with high I/O intensity, e.g. filtering large tables on non-indexed columns. No downsides have been noticed. * * Set to a falsy value to turn off. `true` for memory-mapping the whole iModel. Number value for memory-mapping the specified amount of bytes. * * @alpha */ useMmap?: boolean | number; /** * An identifier which helps separate multiple presentation managers. It's * mostly useful in tests where multiple presentation managers can co-exist * and try to share the same resources, which we don't want. With this identifier * set, managers put their resources into id-named subdirectories. * * @internal */ id?: string; /** @internal */ addon?: NativePlatformDefinition; } /** * Backend Presentation manager which pulls the presentation data from * an iModel using native platform. * * @public */ export class PresentationManager { private _props: PresentationManagerProps; private _nativePlatform?: NativePlatformDefinition; private _rulesets: RulesetManager; private _isDisposed: boolean; private _disposeIModelOpenedListener?: () => void; private _updatesTracker?: UpdatesTracker; /** Get / set active locale used for localizing presentation data */ public activeLocale: string | undefined; /** Get / set active unit system used to format property values with units */ public activeUnitSystem: UnitSystemKey | undefined; /** * Creates an instance of PresentationManager. * @param props Optional configuration properties. */ constructor(props?: PresentationManagerProps) { this._props = props ?? {}; this._isDisposed = false; const mode = props?.mode ?? PresentationManagerMode.ReadWrite; const isChangeTrackingEnabled = (mode === PresentationManagerMode.ReadWrite && !!props?.updatesPollInterval); if (props && props.addon) { this._nativePlatform = props.addon; } else { const nativePlatformImpl = createDefaultNativePlatform({ id: this._props.id ?? "", localeDirectories: createLocaleDirectoryList(props), taskAllocationsMap: createTaskAllocationsMap(props), mode, isChangeTrackingEnabled, cacheConfig: createCacheConfig(this._props.caching?.hierarchies), contentCacheSize: this._props.caching?.content?.size, defaultFormats: toNativeUnitFormatsMap(this._props.defaultFormats), useMmap: this._props.useMmap, }); this._nativePlatform = new nativePlatformImpl(); } this.setupRulesetDirectories(props); if (props) { this.activeLocale = props.defaultLocale; this.activeUnitSystem = props.defaultUnitSystem; } this._rulesets = new RulesetManagerImpl(this.getNativePlatform); if (this._props.enableSchemasPreload) this._disposeIModelOpenedListener = BriefcaseDb.onOpened.addListener(this.onIModelOpened); if (IpcHost.isValid && isChangeTrackingEnabled) { this._updatesTracker = UpdatesTracker.create({ nativePlatformGetter: this.getNativePlatform, pollInterval: props.updatesPollInterval!, }); } } /** * Dispose the presentation manager. Must be called to clean up native resources. */ public dispose() { if (this._nativePlatform) { this.getNativePlatform().dispose(); this._nativePlatform = undefined; } if (this._disposeIModelOpenedListener) this._disposeIModelOpenedListener(); if (this._updatesTracker) { this._updatesTracker.dispose(); this._updatesTracker = undefined; } this._isDisposed = true; } /** Properties used to initialize the manager */ public get props() { return this._props; } /** * Get rulesets manager */ public rulesets(): RulesetManager { return this._rulesets; } /** * Get ruleset variables manager for specific ruleset * @param rulesetId Id of the ruleset to get variables manager for */ public vars(rulesetId: string): RulesetVariablesManager { return new RulesetVariablesManagerImpl(this.getNativePlatform, rulesetId); } // eslint-disable-next-line @typescript-eslint/naming-convention private onIModelOpened = (imodel: BriefcaseDb) => { const imodelAddon = this.getNativePlatform().getImodelAddon(imodel); // eslint-disable-next-line @typescript-eslint/no-floating-promises this.getNativePlatform().forceLoadSchemas(imodelAddon); }; /** @internal */ public getNativePlatform = (): NativePlatformDefinition => { if (this._isDisposed) throw new PresentationError(PresentationStatus.NotInitialized, "Attempting to use Presentation manager after disposal"); return this._nativePlatform!; }; private setupRulesetDirectories(props?: PresentationManagerProps) { const supplementalRulesetDirectories = [path.join(getPresentationBackendAssetsRoot(props?.presentationAssetsRoot), "supplemental-presentation-rules")]; if (props && props.supplementalRulesetDirectories) { props.supplementalRulesetDirectories.forEach((dir) => { if (-1 === supplementalRulesetDirectories.indexOf(dir)) supplementalRulesetDirectories.push(dir); }); } this.getNativePlatform().setupSupplementalRulesetDirectories(supplementalRulesetDirectories); const primaryRulesetDirectories = [path.join(getPresentationBackendAssetsRoot(props?.presentationAssetsRoot), "primary-presentation-rules")]; if (props && props.rulesetDirectories) { props.rulesetDirectories.forEach((dir) => { if (-1 === primaryRulesetDirectories.indexOf(dir)) primaryRulesetDirectories.push(dir); }); } this.getNativePlatform().setupRulesetDirectories(primaryRulesetDirectories); } private getRulesetIdObject(rulesetOrId: Ruleset | string): { uniqueId: string, parts: { id: string, hash?: string } } { if (typeof rulesetOrId === "object") { const hashedId = hash.MD5(rulesetOrId); return { uniqueId: `${rulesetOrId.id}-${hashedId}`, parts: { id: rulesetOrId.id, hash: hashedId, }, }; } return { uniqueId: rulesetOrId, parts: { id: rulesetOrId } }; } /** @internal */ public getRulesetId(rulesetOrId: Ruleset | string) { return this.getRulesetIdObject(rulesetOrId).uniqueId; } private ensureRulesetRegistered(rulesetOrId: Ruleset | string): string { if (typeof rulesetOrId === "object") { const rulesetWithNativeId = { ...rulesetOrId, id: this.getRulesetId(rulesetOrId) }; return this.rulesets().add(rulesetWithNativeId).id; } return rulesetOrId; } /** Registers given ruleset and replaces the ruleset with its ID in the resulting object */ private registerRuleset<TOptions extends { rulesetOrId: Ruleset | string }>(options: TOptions) { const { rulesetOrId, ...strippedOptions } = options; const registeredRulesetId = this.ensureRulesetRegistered(rulesetOrId); return { rulesetId: registeredRulesetId, strippedOptions }; } /** * Retrieves nodes * @public */ public async getNodes(requestOptions: Prioritized<Paged<HierarchyRequestOptions<IModelDb, NodeKey>>>): Promise<Node[]> { const { rulesetId, strippedOptions: { parentKey, ...strippedOptions } } = this.registerRuleset(requestOptions); const params = { requestId: parentKey ? NativePlatformRequestTypes.GetChildren : NativePlatformRequestTypes.GetRootNodes, rulesetId, ...strippedOptions, nodeKey: parentKey, }; return this.request(params, Node.listReviver); } /** * Retrieves nodes count * @public */ public async getNodesCount(requestOptions: Prioritized<HierarchyRequestOptions<IModelDb, NodeKey>>): Promise<number> { const { rulesetId, strippedOptions: { parentKey, ...strippedOptions } } = this.registerRuleset(requestOptions); const params = { requestId: parentKey ? NativePlatformRequestTypes.GetChildrenCount : NativePlatformRequestTypes.GetRootNodesCount, rulesetId, ...strippedOptions, nodeKey: parentKey, }; return this.request(params); } /** * Retrieves paths from root nodes to children nodes according to specified instance key paths. Intersecting paths will be merged. * TODO: Return results in pages * @public */ public async getNodePaths(requestOptions: Prioritized<FilterByInstancePathsHierarchyRequestOptions<IModelDb>>): Promise<NodePathElement[]> { const { rulesetId, strippedOptions: { instancePaths, ...strippedOptions } } = this.registerRuleset(requestOptions); const params = { requestId: NativePlatformRequestTypes.GetNodePaths, rulesetId, ...strippedOptions, paths: instancePaths.map((p) => p.map((s) => InstanceKey.toJSON(s))), }; return this.request(params, NodePathElement.listReviver); } /** * Retrieves paths from root nodes to nodes containing filter text in their label. * TODO: Return results in pages * @public */ public async getFilteredNodePaths(requestOptions: Prioritized<FilterByTextHierarchyRequestOptions<IModelDb>>): Promise<NodePathElement[]> { const { rulesetId, strippedOptions } = this.registerRuleset(requestOptions); const params = { requestId: NativePlatformRequestTypes.GetFilteredNodePaths, rulesetId, ...strippedOptions, }; return this.request(params, NodePathElement.listReviver); } /** @beta */ public async getContentSources(requestOptions: Prioritized<ContentSourcesRequestOptions<IModelDb>>): Promise<SelectClassInfo[]> { const params = { requestId: NativePlatformRequestTypes.GetContentSources, rulesetId: "ElementProperties", ...requestOptions, }; const reviver = (key: string, value: any) => { return key === "" ? SelectClassInfo.listFromCompressedJSON(value.sources, value.classesMap) : value; }; return this.request(params, reviver); } /** * Retrieves the content descriptor which can be used to get content * @public */ public async getContentDescriptor(requestOptions: Prioritized<ContentDescriptorRequestOptions<IModelDb, KeySet>>): Promise<Descriptor | undefined> { const { rulesetId, strippedOptions } = this.registerRuleset(requestOptions); const params = { requestId: NativePlatformRequestTypes.GetContentDescriptor, rulesetId, ...strippedOptions, keys: getKeysForContentRequest(requestOptions.keys, (map) => bisElementInstanceKeysProcessor(requestOptions.imodel, map)), }; const reviver = (key: string, value: any) => { return key === "" ? Descriptor.fromJSON(value) : value; }; return this.request(params, reviver); } /** * Retrieves the content set size based on the supplied content descriptor override * @public */ public async getContentSetSize(requestOptions: Prioritized<ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet>>): Promise<number> { const { rulesetId, strippedOptions: { descriptor, ...strippedOptions } } = this.registerRuleset(requestOptions); const params = { requestId: NativePlatformRequestTypes.GetContentSetSize, rulesetId, ...strippedOptions, keys: getKeysForContentRequest(requestOptions.keys, (map) => bisElementInstanceKeysProcessor(requestOptions.imodel, map)), descriptorOverrides: createContentDescriptorOverrides(descriptor), }; return this.request(params); } /** * Retrieves the content based on the supplied content descriptor override. * @public */ public async getContent(requestOptions: Prioritized<Paged<ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet>>>): Promise<Content | undefined> { const { rulesetId, strippedOptions: { descriptor, ...strippedOptions } } = this.registerRuleset(requestOptions); const params = { requestId: NativePlatformRequestTypes.GetContent, rulesetId, ...strippedOptions, keys: getKeysForContentRequest(requestOptions.keys, (map) => bisElementInstanceKeysProcessor(requestOptions.imodel, map)), descriptorOverrides: createContentDescriptorOverrides(descriptor), }; return this.request(params, Content.reviver); } /** * Retrieves distinct values of specific field from the content based on the supplied content descriptor override. * @param requestOptions Options for the request * @return A promise object that returns either distinct values on success or an error string on error. * @public */ public async getPagedDistinctValues(requestOptions: Prioritized<DistinctValuesRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet>>): Promise<PagedResponse<DisplayValueGroup>> { const { rulesetId, strippedOptions } = this.registerRuleset(requestOptions); const { descriptor, keys, ...strippedOptionsNoDescriptorAndKeys } = strippedOptions; const params = { requestId: NativePlatformRequestTypes.GetPagedDistinctValues, rulesetId, ...strippedOptionsNoDescriptorAndKeys, keys: getKeysForContentRequest(keys, (map) => bisElementInstanceKeysProcessor(requestOptions.imodel, map)), descriptorOverrides: createContentDescriptorOverrides(descriptor), }; const reviver = (key: string, value: any) => { return key === "" ? { total: value.total, items: value.items.map(DisplayValueGroup.fromJSON), } : value; }; return this.request(params, reviver); } /** * Retrieves property data in a simplified format for a single element specified by ID. * @beta */ public async getElementProperties(requestOptions: Prioritized<SingleElementPropertiesRequestOptions<IModelDb>>): Promise<ElementProperties | undefined>; /** * Retrieves property data in simplified format for multiple elements specified by class * or all element. * @alpha */ public async getElementProperties(requestOptions: Prioritized<MultiElementPropertiesRequestOptions<IModelDb>>): Promise<PagedResponse<ElementProperties>>; public async getElementProperties(requestOptions: Prioritized<ElementPropertiesRequestOptions<IModelDb>>): Promise<ElementProperties | undefined | PagedResponse<ElementProperties>> { if (isSingleElementPropertiesRequestOptions(requestOptions)) { const { elementId, ...optionsNoElementId } = requestOptions; const content = await this.getContent({ ...optionsNoElementId, descriptor: { displayType: DefaultContentDisplayTypes.PropertyPane, contentFlags: ContentFlags.ShowLabels, }, rulesetOrId: "ElementProperties", keys: new KeySet([{ className: "BisCore:Element", id: elementId }]), }); const properties = buildElementsProperties(content); return properties[0]; } return this.getMultipleElementProperties(requestOptions); } private async getMultipleElementProperties(requestOptions: Prioritized<MultiElementPropertiesRequestOptions<IModelDb>>) { const { elementClasses, paging, ...optionsNoElementClasses } = requestOptions; const elementsCount = getElementsCount(requestOptions.imodel, requestOptions.elementClasses); const elementIds = getElementIdsByClass(requestOptions.imodel, elementClasses, paging); const elementProperties: ElementProperties[] = []; for (const entry of elementIds) { const properties = await buildElementsPropertiesInPages(entry[0], entry[1], async (keys) => { const content = await this.getContent({ ...optionsNoElementClasses, descriptor: { displayType: DefaultContentDisplayTypes.PropertyPane, contentFlags: ContentFlags.ShowLabels, }, rulesetOrId: "ElementProperties", keys, }); return buildElementsProperties(content); }); elementProperties.push(...properties); } return { total: elementsCount, items: elementProperties }; } /** * Retrieves display label definition of specific item * @public */ public async getDisplayLabelDefinition(requestOptions: Prioritized<DisplayLabelRequestOptions<IModelDb, InstanceKey>>): Promise<LabelDefinition> { const params = { requestId: NativePlatformRequestTypes.GetDisplayLabel, ...requestOptions, key: InstanceKey.toJSON(requestOptions.key), }; return this.request(params, LabelDefinition.reviver); } /** * Retrieves display label definitions of specific items * @public */ public async getDisplayLabelDefinitions(requestOptions: Prioritized<Paged<DisplayLabelsRequestOptions<IModelDb, InstanceKey>>>): Promise<LabelDefinition[]> { const concreteKeys = requestOptions.keys.map((k) => { if (k.className === "BisCore:Element") return getElementKey(requestOptions.imodel, k.id); return k; }).filter<InstanceKey>((k): k is InstanceKey => !!k); const contentRequestOptions: ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet> = { ...requestOptions, rulesetOrId: "RulesDrivenECPresentationManager_RulesetId_DisplayLabel", descriptor: { displayType: DefaultContentDisplayTypes.List, contentFlags: ContentFlags.ShowLabels | ContentFlags.NoFields, }, keys: new KeySet(concreteKeys), }; const content = await this.getContent(contentRequestOptions); return concreteKeys.map((key) => { const item = content ? content.contentSet.find((it) => it.primaryKeys.length > 0 && InstanceKey.compare(it.primaryKeys[0], key) === 0) : undefined; if (!item) return { displayValue: "", rawValue: "", typeName: "" }; return item.label; }); } /** * Retrieves available selection scopes. * @public */ public async getSelectionScopes(_requestOptions: SelectionScopeRequestOptions<IModelDb>): Promise<SelectionScope[]> { return SelectionScopesHelper.getSelectionScopes(); } /** * Computes selection set based on provided selection scope. * @public */ public async computeSelection(requestOptions: SelectionScopeRequestOptions<IModelDb> & { ids: Id64String[], scopeId: string }): Promise<KeySet> { const { ids, scopeId, ...opts } = requestOptions; // eslint-disable-line @typescript-eslint/no-unused-vars return SelectionScopesHelper.computeSelection(opts, ids, scopeId); } private async request<TParams extends { diagnostics?: DiagnosticsOptionsWithHandler, requestId: string, imodel: IModelDb, locale?: string, unitSystem?: UnitSystemKey }, TResult>(params: TParams, reviver?: (key: string, value: any) => any): Promise<TResult> { const { requestId, imodel, locale, unitSystem, diagnostics, ...strippedParams } = params; const imodelAddon = this.getNativePlatform().getImodelAddon(imodel); const nativeRequestParams: any = { requestId, params: { locale: normalizeLocale(locale ?? this.activeLocale), unitSystem: toOptionalNativeUnitSystem(unitSystem ?? this.activeUnitSystem), ...strippedParams, }, }; let diagnosticsListener; if (diagnostics) { const { handler: tempDiagnosticsListener, ...diagnosticsOptions } = diagnostics; diagnosticsListener = tempDiagnosticsListener; nativeRequestParams.params.diagnostics = diagnosticsOptions; } const response = await this.getNativePlatform().handleRequest(imodelAddon, JSON.stringify(nativeRequestParams)); diagnosticsListener && response.diagnostics && diagnosticsListener([response.diagnostics]); return JSON.parse(response.result, reviver); } /** * Compares two hierarchies specified in the request options * @public */ public async compareHierarchies(requestOptions: HierarchyCompareOptions<IModelDb, NodeKey>): Promise<HierarchyCompareInfo> { if (!requestOptions.prev.rulesetOrId && !requestOptions.prev.rulesetVariables) return { changes: [] }; const { strippedOptions: { prev, rulesetVariables, ...options } } = this.registerRuleset(requestOptions); const currRulesetId = this.getRulesetIdObject(requestOptions.rulesetOrId); const prevRulesetId = prev.rulesetOrId ? this.getRulesetIdObject(prev.rulesetOrId) : currRulesetId; if (prevRulesetId.parts.id !== currRulesetId.parts.id) throw new PresentationError(PresentationStatus.InvalidArgument, "Can't compare rulesets with different IDs"); const currRulesetVariables = rulesetVariables ?? []; const prevRulesetVariables = prev.rulesetVariables ?? currRulesetVariables; const params = { requestId: NativePlatformRequestTypes.CompareHierarchies, ...options, prevRulesetId: prevRulesetId.uniqueId, currRulesetId: currRulesetId.uniqueId, prevRulesetVariables: JSON.stringify(prevRulesetVariables), currRulesetVariables: JSON.stringify(currRulesetVariables), expandedNodeKeys: JSON.stringify(options.expandedNodeKeys ?? []), }; return this.request(params, (key: string, value: any) => ((key === "") ? HierarchyCompareInfo.fromJSON(value) : value)); } } function addInstanceKey(classInstancesMap: Map<string, Set<string>>, key: InstanceKey) { let set = classInstancesMap.get(key.className); // istanbul ignore else if (!set) { set = new Set(); classInstancesMap.set(key.className, set); } set.add(key.id); } function bisElementInstanceKeysProcessor(imodel: IModelDb, classInstancesMap: Map<string, Set<string>>) { const elementClassName = "BisCore:Element"; const elementIds = classInstancesMap.get(elementClassName); if (elementIds) { const deleteElementIds = new Array<string>(); elementIds.forEach((elementId) => { const concreteKey = getElementKey(imodel, elementId); if (concreteKey && concreteKey.className !== elementClassName) { deleteElementIds.push(elementId); addInstanceKey(classInstancesMap, { className: concreteKey.className, id: elementId }); } }); for (const id of deleteElementIds) elementIds.delete(id); } } /** @internal */ export function getKeysForContentRequest(keys: Readonly<KeySet>, classInstanceKeysProcessor?: (keys: Map<string, Set<string>>) => void): NativePresentationKeySetJSON { const result: NativePresentationKeySetJSON = { instanceKeys: [], nodeKeys: [], }; const classInstancesMap = new Map<string, Set<string>>(); keys.forEach((key) => { if (Key.isNodeKey(key)) result.nodeKeys.push(key); if (Key.isInstanceKey(key)) addInstanceKey(classInstancesMap, key); }); if (classInstanceKeysProcessor) classInstanceKeysProcessor(classInstancesMap); for (const entry of classInstancesMap) { if (entry[1].size > 0) result.instanceKeys.push([entry["0"], [...entry[1]]]); } return result; } const createContentDescriptorOverrides = (descriptorOrOverrides: Descriptor | DescriptorOverrides): DescriptorOverrides => { if (descriptorOrOverrides instanceof Descriptor) return descriptorOrOverrides.createDescriptorOverrides(); return descriptorOrOverrides; }; const createLocaleDirectoryList = (props?: PresentationManagerProps) => { const localeDirectories = [getLocalesDirectory(getPresentationCommonAssetsRoot(props?.presentationAssetsRoot))]; if (props && props.localeDirectories) { props.localeDirectories.forEach((dir) => { if (-1 === localeDirectories.indexOf(dir)) localeDirectories.push(dir); }); } return localeDirectories; }; const createTaskAllocationsMap = (props?: PresentationManagerProps) => { const count = props?.workerThreadsCount ?? 2; return { [Number.MAX_SAFE_INTEGER]: count, }; }; const normalizeLocale = (locale?: string) => { if (!locale) return undefined; return locale.toLocaleLowerCase(); }; const normalizeDirectory = (directory?: string) => { return directory ? path.resolve(directory) : ""; }; const toNativeUnitSystem = (unitSystem: UnitSystemKey) => { switch (unitSystem) { case "imperial": return NativePresentationUnitSystem.BritishImperial; case "metric": return NativePresentationUnitSystem.Metric; case "usCustomary": return NativePresentationUnitSystem.UsCustomary; case "usSurvey": return NativePresentationUnitSystem.UsSurvey; } }; const toOptionalNativeUnitSystem = (unitSystem: UnitSystemKey | undefined) => { return unitSystem ? toNativeUnitSystem(unitSystem) : undefined; }; const toNativeUnitFormatsMap = (map: { [phenomenon: string]: UnitSystemFormat } | undefined) => { if (!map) return undefined; const nativeFormatsMap: NativePresentationDefaultUnitFormats = {}; Object.keys(map).forEach((phenomenon) => { const unitSystemsFormat = map[phenomenon]; nativeFormatsMap[phenomenon] = { unitSystems: unitSystemsFormat.unitSystems.map(toNativeUnitSystem), format: unitSystemsFormat.format, }; }); return nativeFormatsMap; }; const createCacheConfig = (config?: HierarchyCacheConfig): IModelJsNative.ECPresentationHierarchyCacheConfig => { if (config?.mode === HierarchyCacheMode.Disk) return { ...config, directory: normalizeDirectory(config.directory) }; if (config?.mode === HierarchyCacheMode.Hybrid) return { ...config, disk: config.disk ? { ...config.disk, directory: normalizeDirectory(config.disk.directory) } : undefined }; if (config?.mode === HierarchyCacheMode.Memory) return config; return { mode: HierarchyCacheMode.Disk, directory: "" }; }; const getPresentationBackendAssetsRoot = (ovr?: string | { backend: string }) => { if (typeof ovr === "string") return ovr; if (typeof ovr === "object") return ovr.backend; return PRESENTATION_BACKEND_ASSETS_ROOT; }; const getPresentationCommonAssetsRoot = (ovr?: string | { common: string }) => { if (typeof ovr === "string") return ovr; if (typeof ovr === "object") return ovr.common; return PRESENTATION_COMMON_ASSETS_ROOT; }; const ELEMENT_PROPERTIES_CONTENT_BATCH_SIZE = 100; async function buildElementsPropertiesInPages(className: string, ids: string[], getter: (keys: KeySet) => Promise<ElementProperties[]>) { const elementProperties: ElementProperties[] = []; const elementIds = [...ids]; while (elementIds.length > 0) { const idsPage = elementIds.splice(0, ELEMENT_PROPERTIES_CONTENT_BATCH_SIZE); const keys = new KeySet(idsPage.map((id) => ({ id, className }))); elementProperties.push(...(await getter(keys))); } return elementProperties; }
the_stack
module android.view{ import View = android.view.View; import Rect = android.graphics.Rect; import ArrayList = java.util.ArrayList; /** * The algorithm used for finding the next focusable view in a given direction * from a view that currently has focus. */ export class FocusFinder{ private static sFocusFinder:FocusFinder; /** * Get the focus finder for this thread. */ static getInstance():FocusFinder{ if(!FocusFinder.sFocusFinder){ FocusFinder.sFocusFinder = new FocusFinder(); } return FocusFinder.sFocusFinder; } mFocusedRect = new Rect(); mOtherRect = new Rect(); mBestCandidateRect = new Rect(); private mSequentialFocusComparator = new SequentialFocusComparator(); private mTempList = new ArrayList<View>(); /** * Find the next view to take focus in root's descendants, starting from the view * that currently is focused. * @param root Contains focused. Cannot be null. * @param focused Has focus now. * @param direction Direction to look. * @return The next focusable view, or null if none exists. */ findNextFocus(root:ViewGroup, focused:View, direction:number):View{ return this._findNextFocus(root, focused, null, direction); } /** * Find the next view to take focus in root's descendants, searching from * a particular rectangle in root's coordinates. * @param root Contains focusedRect. Cannot be null. * @param focusedRect The starting point of the search. * @param direction Direction to look. * @return The next focusable view, or null if none exists. */ findNextFocusFromRect(root:ViewGroup, focusedRect:Rect, direction:number) { this.mFocusedRect.set(focusedRect); return this._findNextFocus(root, null, this.mFocusedRect, direction); } private _findNextFocus(root:ViewGroup, focused:View, focusedRect:android.graphics.Rect, direction:number):View { let next = null; if (focused != null) { next = this.findNextUserSpecifiedFocus(root, focused, direction); } if (next != null) { return next; } let focusables = this.mTempList; try { focusables.clear(); root.addFocusables(focusables, direction); if (!focusables.isEmpty()) { next = this.__findNextFocus(root, focused, focusedRect, direction, focusables); } } finally { focusables.clear(); } return next; } private findNextUserSpecifiedFocus(root:ViewGroup, focused:View, direction:number):View { // check for user specified next focus let userSetNextFocus = focused.findUserSetNextFocus(root, direction); if (userSetNextFocus != null && userSetNextFocus.isFocusable() && (!userSetNextFocus.isInTouchMode() || userSetNextFocus.isFocusableInTouchMode())) { return userSetNextFocus; } return null; } private __findNextFocus(root:ViewGroup, focused:View, focusedRect:android.graphics.Rect, direction:number, focusables:ArrayList<View>):View { if (focused != null) { if (focusedRect == null) { focusedRect = this.mFocusedRect; } // fill in interesting rect from focused focused.getFocusedRect(focusedRect); root.offsetDescendantRectToMyCoords(focused, focusedRect); } else { if (focusedRect == null) { focusedRect = this.mFocusedRect; // make up a rect at top left or bottom right of root switch (direction) { case View.FOCUS_RIGHT: case View.FOCUS_DOWN: this.setFocusTopLeft(root, focusedRect); break; case View.FOCUS_FORWARD: this.setFocusTopLeft(root, focusedRect); break; case View.FOCUS_LEFT: case View.FOCUS_UP: this.setFocusBottomRight(root, focusedRect); break; case View.FOCUS_BACKWARD: this.setFocusBottomRight(root, focusedRect); } } } switch (direction) { case View.FOCUS_FORWARD: case View.FOCUS_BACKWARD: return this.findNextFocusInRelativeDirection(focusables, root, focused, focusedRect, direction); case View.FOCUS_UP: case View.FOCUS_DOWN: case View.FOCUS_LEFT: case View.FOCUS_RIGHT: return this.findNextFocusInAbsoluteDirection(focusables, root, focused, focusedRect, direction); default: throw new Error("Unknown direction: " + direction); } } private findNextFocusInRelativeDirection(focusables:ArrayList<View>, root:ViewGroup, focused:View, focusedRect:Rect, direction:number) { try { // Note: This sort is stable. this.mSequentialFocusComparator.setRoot(root); //this.mSequentialFocusComparator.setIsLayoutRtl(root.isLayoutRtl()); this.mSequentialFocusComparator.sort(focusables); //Collections.sort(focusables, mSequentialFocusComparator); } finally { this.mSequentialFocusComparator.recycle(); } const count = focusables.size(); switch (direction) { case View.FOCUS_FORWARD: return FocusFinder.getNextFocusable(focused, focusables, count); case View.FOCUS_BACKWARD: return FocusFinder.getPreviousFocusable(focused, focusables, count); } return focusables.get(count - 1); } private setFocusBottomRight(root:ViewGroup, focusedRect:Rect) { const rootBottom = root.getScrollY() + root.getHeight(); const rootRight = root.getScrollX() + root.getWidth(); focusedRect.set(rootRight, rootBottom, rootRight, rootBottom); } private setFocusTopLeft(root:ViewGroup, focusedRect:Rect) { const rootTop = root.getScrollY(); const rootLeft = root.getScrollX(); focusedRect.set(rootLeft, rootTop, rootLeft, rootTop); } private findNextFocusInAbsoluteDirection(focusables:ArrayList<View>, root:ViewGroup, focused:View, focusedRect:Rect, direction:number) { // initialize the best candidate to something impossible // (so the first plausible view will become the best choice) this.mBestCandidateRect.set(focusedRect); switch(direction) { case View.FOCUS_LEFT: this.mBestCandidateRect.offset(focusedRect.width() + 1, 0); break; case View.FOCUS_RIGHT: this.mBestCandidateRect.offset(-(focusedRect.width() + 1), 0); break; case View.FOCUS_UP: this.mBestCandidateRect.offset(0, focusedRect.height() + 1); break; case View.FOCUS_DOWN: this.mBestCandidateRect.offset(0, -(focusedRect.height() + 1)); } let closest:View = null; let numFocusables = focusables.size(); for (let i = 0; i < numFocusables; i++) { let focusable = focusables.get(i); // only interested in other non-root views if (focusable == focused || focusable == root) continue; // get focus bounds of other view in same coordinate system focusable.getFocusedRect(this.mOtherRect); root.offsetDescendantRectToMyCoords(focusable, this.mOtherRect); if (this.isBetterCandidate(direction, focusedRect, this.mOtherRect, this.mBestCandidateRect)) { this.mBestCandidateRect.set(this.mOtherRect); closest = focusable; } } return closest; } private static getNextFocusable(focused:View, focusables:ArrayList<View>, count:number):View { if (focused != null) { let position = focusables.lastIndexOf(focused); if (position >= 0 && position + 1 < count) { return focusables.get(position + 1); } } if (!focusables.isEmpty()) { return focusables.get(0); } return null; } private static getPreviousFocusable(focused:View, focusables:ArrayList<View>, count:number):View { if (focused != null) { let position = focusables.indexOf(focused); if (position > 0) { return focusables.get(position - 1); } } if (!focusables.isEmpty()) { return focusables.get(count - 1); } return null; } /** * Is rect1 a better candidate than rect2 for a focus search in a particular * direction from a source rect? This is the core routine that determines * the order of focus searching. * @param direction the direction (up, down, left, right) * @param source The source we are searching from * @param rect1 The candidate rectangle * @param rect2 The current best candidate. * @return Whether the candidate is the new best. */ isBetterCandidate(direction:number, source:Rect, rect1:Rect, rect2:Rect):boolean { // to be a better candidate, need to at least be a candidate in the first // place :) if (!this.isCandidate(source, rect1, direction)) { return false; } // we know that rect1 is a candidate.. if rect2 is not a candidate, // rect1 is better if (!this.isCandidate(source, rect2, direction)) { return true; } // if rect1 is better by beam, it wins if (this.beamBeats(direction, source, rect1, rect2)) { return true; } // if rect2 is better, then rect1 cant' be :) if (this.beamBeats(direction, source, rect2, rect1)) { return false; } // otherwise, do fudge-tastic comparison of the major and minor axis return (this.getWeightedDistanceFor( FocusFinder.majorAxisDistance(direction, source, rect1), FocusFinder.minorAxisDistance(direction, source, rect1)) < this.getWeightedDistanceFor( FocusFinder.majorAxisDistance(direction, source, rect2), FocusFinder.minorAxisDistance(direction, source, rect2))); } /** * One rectangle may be another candidate than another by virtue of being * exclusively in the beam of the source rect. * @return Whether rect1 is a better candidate than rect2 by virtue of it being in src's * beam */ beamBeats(direction:number, source:Rect, rect1:Rect, rect2:Rect):boolean { const rect1InSrcBeam = this.beamsOverlap(direction, source, rect1); const rect2InSrcBeam = this.beamsOverlap(direction, source, rect2); // if rect1 isn't exclusively in the src beam, it doesn't win if (rect2InSrcBeam || !rect1InSrcBeam) { return false; } // we know rect1 is in the beam, and rect2 is not // if rect1 is to the direction of, and rect2 is not, rect1 wins. // for example, for direction left, if rect1 is to the left of the source // and rect2 is below, then we always prefer the in beam rect1, since rect2 // could be reached by going down. if (!this.isToDirectionOf(direction, source, rect2)) { return true; } // for horizontal directions, being exclusively in beam always wins if ((direction == View.FOCUS_LEFT || direction == View.FOCUS_RIGHT)) { return true; } // for vertical directions, beams only beat up to a point: // now, as long as rect2 isn't completely closer, rect1 wins // e.g for direction down, completely closer means for rect2's top // edge to be closer to the source's top edge than rect1's bottom edge. return (FocusFinder.majorAxisDistance(direction, source, rect1) < FocusFinder.majorAxisDistanceToFarEdge(direction, source, rect2)); } /** * Fudge-factor opportunity: how to calculate distance given major and minor * axis distances. Warning: this fudge factor is finely tuned, be sure to * run all focus tests if you dare tweak it. */ getWeightedDistanceFor(majorAxisDistance:number, minorAxisDistance:number):number { return 13 * majorAxisDistance * majorAxisDistance + minorAxisDistance * minorAxisDistance; } /** * Is destRect a candidate for the next focus given the direction? This * checks whether the dest is at least partially to the direction of (e.g left of) * from source. * * Includes an edge case for an empty rect (which is used in some cases when * searching from a point on the screen). */ isCandidate(srcRect:Rect, destRect:Rect, direction:number):boolean { switch (direction) { case View.FOCUS_LEFT: return (srcRect.right > destRect.right || srcRect.left >= destRect.right) && srcRect.left > destRect.left; case View.FOCUS_RIGHT: return (srcRect.left < destRect.left || srcRect.right <= destRect.left) && srcRect.right < destRect.right; case View.FOCUS_UP: return (srcRect.bottom > destRect.bottom || srcRect.top >= destRect.bottom) && srcRect.top > destRect.top; case View.FOCUS_DOWN: return (srcRect.top < destRect.top || srcRect.bottom <= destRect.top) && srcRect.bottom < destRect.bottom; } throw new Error("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}."); } /** * Do the "beams" w.r.t the given direction's axis of rect1 and rect2 overlap? * @param direction the direction (up, down, left, right) * @param rect1 The first rectangle * @param rect2 The second rectangle * @return whether the beams overlap */ beamsOverlap(direction:number, rect1:Rect, rect2:Rect):boolean { switch (direction) { case View.FOCUS_LEFT: case View.FOCUS_RIGHT: return (rect2.bottom >= rect1.top) && (rect2.top <= rect1.bottom); case View.FOCUS_UP: case View.FOCUS_DOWN: return (rect2.right >= rect1.left) && (rect2.left <= rect1.right); } throw new Error("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}."); } /** * e.g for left, is 'to left of' */ isToDirectionOf(direction:number, src:Rect, dest:Rect):boolean { switch (direction) { case View.FOCUS_LEFT: return src.left >= dest.right; case View.FOCUS_RIGHT: return src.right <= dest.left; case View.FOCUS_UP: return src.top >= dest.bottom; case View.FOCUS_DOWN: return src.bottom <= dest.top; } throw new Error("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}."); } /** * @return The distance from the edge furthest in the given direction * of source to the edge nearest in the given direction of dest. If the * dest is not in the direction from source, return 0. */ static majorAxisDistance(direction:number, source:Rect, dest:Rect):number { return Math.max(0, FocusFinder.majorAxisDistanceRaw(direction, source, dest)); } static majorAxisDistanceRaw(direction:number, source:Rect, dest:Rect):number { switch (direction) { case View.FOCUS_LEFT: return source.left - dest.right; case View.FOCUS_RIGHT: return dest.left - source.right; case View.FOCUS_UP: return source.top - dest.bottom; case View.FOCUS_DOWN: return dest.top - source.bottom; } throw new Error("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}."); } /** * @return The distance along the major axis w.r.t the direction from the * edge of source to the far edge of dest. If the * dest is not in the direction from source, return 1 (to break ties with * {@link #majorAxisDistance}). */ static majorAxisDistanceToFarEdge(direction:number, source:Rect, dest:Rect):number { return Math.max(1, FocusFinder.majorAxisDistanceToFarEdgeRaw(direction, source, dest)); } static majorAxisDistanceToFarEdgeRaw(direction:number, source:Rect, dest:Rect):number { switch (direction) { case View.FOCUS_LEFT: return source.left - dest.left; case View.FOCUS_RIGHT: return dest.right - source.right; case View.FOCUS_UP: return source.top - dest.top; case View.FOCUS_DOWN: return dest.bottom - source.bottom; } throw new Error("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}."); } /** * Find the distance on the minor axis w.r.t the direction to the nearest * edge of the destination rectangle. * @param direction the direction (up, down, left, right) * @param source The source rect. * @param dest The destination rect. * @return The distance. */ static minorAxisDistance(direction:number, source:Rect, dest:Rect):number { switch (direction) { case View.FOCUS_LEFT: case View.FOCUS_RIGHT: // the distance between the center verticals return Math.abs( ((source.top + source.height() / 2) - ((dest.top + dest.height() / 2)))); case View.FOCUS_UP: case View.FOCUS_DOWN: // the distance between the center horizontals return Math.abs( ((source.left + source.width() / 2) - ((dest.left + dest.width() / 2)))); } throw new Error("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}."); } /** * Find the nearest touchable view to the specified view. * * @param root The root of the tree in which to search * @param x X coordinate from which to start the search * @param y Y coordinate from which to start the search * @param direction Direction to look * @param deltas Offset from the <x, y> to the edge of the nearest view. Note that this array * may already be populated with values. * @return The nearest touchable view, or null if none exists. */ findNearestTouchable(root:ViewGroup, x:number, y:number, direction:number, deltas:number[]):View { let touchables = root.getTouchables(); let minDistance = Number.MAX_SAFE_INTEGER; let closest = null; let numTouchables = touchables.size(); let edgeSlop = ViewConfiguration.get().getScaledEdgeSlop(); let closestBounds = new Rect(); let touchableBounds = this.mOtherRect; for (let i = 0; i < numTouchables; i++) { let touchable = touchables.get(i); // get visible bounds of other view in same coordinate system touchable.getDrawingRect(touchableBounds); root.offsetRectBetweenParentAndChild(touchable, touchableBounds, true, true); if (!this.isTouchCandidate(x, y, touchableBounds, direction)) { continue; } let distance = Number.MAX_SAFE_INTEGER; switch (direction) { case View.FOCUS_LEFT: distance = x - touchableBounds.right + 1; break; case View.FOCUS_RIGHT: distance = touchableBounds.left; break; case View.FOCUS_UP: distance = y - touchableBounds.bottom + 1; break; case View.FOCUS_DOWN: distance = touchableBounds.top; break; } if (distance < edgeSlop) { // Give preference to innermost views if (closest == null || closestBounds.contains(touchableBounds) || (!touchableBounds.contains(closestBounds) && distance < minDistance)) { minDistance = distance; closest = touchable; closestBounds.set(touchableBounds); switch (direction) { case View.FOCUS_LEFT: deltas[0] = -distance; break; case View.FOCUS_RIGHT: deltas[0] = distance; break; case View.FOCUS_UP: deltas[1] = -distance; break; case View.FOCUS_DOWN: deltas[1] = distance; break; } } } } return closest; } /** * Is destRect a candidate for the next touch given the direction? */ private isTouchCandidate(x:number, y:number, destRect:Rect, direction:number):boolean { switch (direction) { case View.FOCUS_LEFT: return destRect.left <= x && destRect.top <= y && y <= destRect.bottom; case View.FOCUS_RIGHT: return destRect.left >= x && destRect.top <= y && y <= destRect.bottom; case View.FOCUS_UP: return destRect.top <= y && destRect.left <= x && x <= destRect.right; case View.FOCUS_DOWN: return destRect.top >= y && destRect.left <= x && x <= destRect.right; } throw new Error("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}."); } } /** * Sorts views according to their visual layout and geometry for default tab order. * This is used for sequential focus traversal. */ class SequentialFocusComparator { mFirstRect = new Rect(); mSecondRect = new Rect(); mRoot:ViewGroup; private mIsLayoutRtl = false; recycle() { this.mRoot = null; } setRoot(root:ViewGroup) { this.mRoot = root; } private getRect(view:View, rect:Rect) { view.getDrawingRect(rect); this.mRoot.offsetDescendantRectToMyCoords(view, rect); } private compareFn = (first:View, second:View):number=>{ if (first == second) { return 0; } this.getRect(first, this.mFirstRect); this.getRect(second, this.mSecondRect); if (this.mFirstRect.top < this.mSecondRect.top) { return -1; } else if (this.mFirstRect.top > this.mSecondRect.top) { return 1; } else if (this.mFirstRect.left < this.mSecondRect.left) { return this.mIsLayoutRtl ? 1 : -1; } else if (this.mFirstRect.left > this.mSecondRect.left) { return this.mIsLayoutRtl ? -1 : 1; } else if (this.mFirstRect.bottom < this.mSecondRect.bottom) { return -1; } else if (this.mFirstRect.bottom > this.mSecondRect.bottom) { return 1; } else if (this.mFirstRect.right < this.mSecondRect.right) { return this.mIsLayoutRtl ? 1 : -1; } else if (this.mFirstRect.right > this.mSecondRect.right) { return this.mIsLayoutRtl ? -1 : 1; } else { // The view are distinct but completely coincident so we consider // them equal for our purposes. Since the sort is stable, this // means that the views will retain their layout order relative to one another. return 0; } } sort(array:ArrayList<View>){ array.sort(this.compareFn); } } }
the_stack
import React, { useContext, useState, ChangeEvent, FormEvent } from 'react' import StoreContext from '../../lib/stores/context' import Button from '../Button' import TextField from '@material-ui/core/TextField' import { requestArtifactRun, RunParameters } from '../../lib/api/run'; interface RunViewProps { type: string, asset: { [key: string]: any, parameters?: any[] } setRunLink?: Function } function RunView(props: RunViewProps) { const { asset, type } = props const { store } = useContext(StoreContext) const { api, kfp } = store.settings.endpoints const API = api.value ? api.value : api.default const KFP = kfp.value ? kfp.value : kfp.default const setRunLink = props.setRunLink var shownParams: {[key: string]: any}[] = [] var matchedUrlParams: {[key: string]: string} = {} var matches: string[] = [] // Adds all parameters that don't already have a value (from the url) // to list of parameters which we will ask the user for if (asset.parameters) { for(var assetIter = 0; assetIter < asset.parameters.length; assetIter++) { let hasMatch = false for(const key of Object.keys(asset.url_parameters)) { if (key === asset.parameters[assetIter].name) hasMatch = true } // If there is no matching url_parameter add the parameter to the form if (!hasMatch) shownParams.push(asset.parameters[assetIter]) else matches.push(asset.parameters[assetIter].name) } } // Marks all url_parameters that have a match to be loaded to the payload Object.keys(asset.url_parameters).forEach((key: string) => { matches.forEach((match: string) => { if (key === match) matchedUrlParams[key] = asset.url_parameters[key] }) }) const [ run, setRun ] = useState({ ...Object.fromEntries((shownParams || []).map( ({ name, value, default: defaultValue }) => [ name, value || defaultValue || '' ])), runname: asset.name, link: undefined, }) function handleSubmit(event: FormEvent<HTMLFormElement>) { event.preventDefault() const { link, ...parameters } = run var payload: RunParameters = {name: parameters.name} Object.keys(parameters).forEach((key: string) => { payload[key] = parameters[key] }); Object.keys(matchedUrlParams).forEach((key: string) => { payload[key] = asset.url_parameters[key] }) requestArtifactRun(API, type, asset.id, payload) .then(({ run_url })=> { setRunLink(`${KFP}/pipeline/#` + run_url) setRun({ ...run, link: run_url }) }) } return ( <div className="runview-wrapper"> <div style={{ width: '98%', height: '100%', paddingRight: '2%' }}> {run.link ? <div> <h2 className="run-form-title">View Trial Pipeline</h2> <p>The sample pipeline created for this model's trial run can be viewed at the following link:</p> <a target="_blank" rel="noopener noreferrer" href={`${KFP}/pipeline/#${run.link && run.link}`} > {`View '${run.runname || asset.name}' on Kubeflow Pipelines.`} </a> </div> : <div className="run-form"> { type === "operators" ? <h2 className="run-form-title">Install the Operator</h2> : <h2 className="run-form-title">Create a Trial Run</h2> } { type === "operators" ? <p> {`Click Install to deploy the Operator`} </p> : <p> {`Complete the following inputs and hit 'Submit' to run the ${type} in a sample pipeline.`} </p> } <form autoComplete="off" onSubmit={handleSubmit}> { type === "operator" ? <TextField autoCorrect="false" // id='runName' // className="run-name-input" label='Operator Name' // placeholder={asset.name} helperText='' value={run.runname} fullWidth margin="normal" variant="outlined" InputLabelProps={{ shrink: true, }} style={{ backgroundColor: 'blue !important', }} onChange={(e: ChangeEvent<HTMLInputElement>) => setRun({ ...run, name: e.currentTarget.value })} /> : <TextField autoCorrect="false" // id='runName' // className="run-name-input" label='Run Name' // placeholder={asset.name} helperText='Enter a name to be used for the trial run.' value={run.runname} fullWidth margin="normal" variant="outlined" InputLabelProps={{ shrink: true, }} style={{ backgroundColor: 'blue !important', }} onChange={(e: ChangeEvent<HTMLInputElement>) => setRun({ ...run, runname: e.currentTarget.value })} /> } { type === "datasets" && <TextField key="namespace" label='Namespace' helperText='Enter a namespace to be used' value={run["namespace"]} autoCorrect="false" required fullWidth margin="normal" style={{ marginBottom: '2%' }} variant="outlined" InputLabelProps={{ shrink: true, }} onChange={(e: ChangeEvent<HTMLInputElement>) => setRun({ ...run, namespace: e.currentTarget.value })} /> } { type === "notebooks" && <> <TextField key="dataset-pvc" label='Dataset PVC' helperText='Enter a dataset pvc to be used' value={run["dataset-pvc"]} autoCorrect="false" fullWidth margin="normal" style={{ marginBottom: '2%' }} variant="outlined" InputLabelProps={{ shrink: true, }} onChange={(e: ChangeEvent<HTMLInputElement>) => setRun({ ...run, dataset_pvc: e.currentTarget.value })} /> <TextField key="mount-path" label='Mount Path' helperText='Enter a mount path to be used' value={run["mount-path"]} autoCorrect="false" fullWidth margin="normal" style={{ marginBottom: '2%' }} variant="outlined" InputLabelProps={{ shrink: true, }} onChange={(e: ChangeEvent<HTMLInputElement>) => setRun({ ...run, mount_path: e.currentTarget.value })} /> </> } {shownParams && shownParams.map(({ name , description }) => ( <TextField key={name} // className="run-name-input" label={`Run ${name}`} // placeholder={asset.id} helperText={description || ''} value={run[name]} autoCorrect="false" required={(description || '').includes('Required.')} fullWidth margin="normal" style={{ marginBottom: '2%' }} variant="outlined" InputLabelProps={{ shrink: true, }} onChange={(e: ChangeEvent<HTMLInputElement>) => setRun({ ...run, [name]: e.currentTarget.value })} /> ))} <div className="submit-button-wrapper"> <Button // onClick={ this.handleSubmit } type="submit" className="hero-buttons submit-run-button" variant="contained" color="primary"> Submit </Button> </div> {/* <TextField select SelectProps={{ MenuProps: { MenuListProps: { style: { width: '100%' } } } }} label="Run Type" helperText="Select the type of trial run to perform." value={ this.state.runType } onChange={ this.handleChange('runType') } fullWidth style={{ marginBottom: '2%' }} className="model-run-item" name="runType"> { this.getRunTypes().map((name:string, i:number)=> <MenuItem key={ i } value={ name }>{ capitalized(name) }</MenuItem> )} </TextField> <TextField select SelectProps={{ MenuProps: { MenuListProps: { style: { width: '100%' } } } }} label="Platform" helperText="Select the platform to run your trial run on." value={ this.state.platform } onChange={ this.handleChange('platform') } className="model-run-item" fullWidth style={{ marginBottom: '2%' }} name="platform"> { this.getPlatforms(this.state.runType).map((name:string, i:number) => <MenuItem key={ i } value={ name }>{ name.length > 3 ? capitalized(name) : name.toUpperCase() }</MenuItem> )} </TextField> */} </form> {/* { this.state.errorState ? <p className="error-msg"> { `Run Error: Please Retry - ${ this.state.errorState }` } </p> : this.state.isLoading && <p className="upload-msg"> { `Loading...` } </p> } */} </div> } </div> </div> ) } export default RunView
the_stack
import { PathOperations } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as coreRestPipeline from "@azure/core-rest-pipeline"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DataLakeStorageClient } from "../dataLakeStorageClient"; import { PathCreateOptionalParams, PathCreateResponse, PathUpdateAction, PathSetAccessControlRecursiveMode, PathUpdateOptionalParams, PathUpdateResponse, PathLeaseAction, PathLeaseOptionalParams, PathLeaseResponse, PathReadOptionalParams, PathReadResponse, PathGetPropertiesOptionalParams, PathGetPropertiesResponse, PathDeleteOptionalParams, PathDeleteResponse } from "../models"; /** Class containing PathOperations operations. */ export class PathOperationsImpl implements PathOperations { private readonly client: DataLakeStorageClient; /** * Initialize a new instance of the class PathOperations class. * @param client Reference to the service client */ constructor(client: DataLakeStorageClient) { this.client = client; } /** * Create or rename a file or directory. By default, the destination is overwritten and if the * destination already exists and has a lease the lease is broken. This operation supports conditional * HTTP requests. For more information, see [Specifying Conditional Headers for Blob Service * Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations). * To fail if the destination already exists, use a conditional request with If-None-Match: "*". * @param options The options parameters. */ create(options?: PathCreateOptionalParams): Promise<PathCreateResponse> { return this.client.sendOperationRequest({ options }, createOperationSpec); } /** * Uploads data to be appended to a file, flushes (writes) previously uploaded data to a file, sets * properties for a file or directory, or sets access control for a file or directory. Data can only be * appended to a file. Concurrent writes to the same file using multiple clients are not supported. * This operation supports conditional HTTP requests. For more information, see [Specifying Conditional * Headers for Blob Service * Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations). * @param action The action must be "append" to upload data to be appended to a file, "flush" to flush * previously uploaded data to a file, "setProperties" to set the properties of a file or directory, * "setAccessControl" to set the owner, group, permissions, or access control list for a file or * directory, or "setAccessControlRecursive" to set the access control list for a directory * recursively. Note that Hierarchical Namespace must be enabled for the account in order to use access * control. Also note that the Access Control List (ACL) includes permissions for the owner, owning * group, and others, so the x-ms-permissions and x-ms-acl request headers are mutually exclusive. * @param mode Mode "set" sets POSIX access control rights on files and directories, "modify" modifies * one or more POSIX access control rights that pre-exist on files and directories, "remove" removes * one or more POSIX access control rights that were present earlier on files and directories * @param body Initial data * @param options The options parameters. */ update( action: PathUpdateAction, mode: PathSetAccessControlRecursiveMode, body: coreRestPipeline.RequestBodyType, options?: PathUpdateOptionalParams ): Promise<PathUpdateResponse> { return this.client.sendOperationRequest( { action, mode, body, options }, updateOperationSpec ); } /** * Create and manage a lease to restrict write and delete access to the path. This operation supports * conditional HTTP requests. For more information, see [Specifying Conditional Headers for Blob * Service * Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations). * @param xMsLeaseAction There are five lease actions: "acquire", "break", "change", "renew", and * "release". Use "acquire" and specify the "x-ms-proposed-lease-id" and "x-ms-lease-duration" to * acquire a new lease. Use "break" to break an existing lease. When a lease is broken, the lease break * period is allowed to elapse, during which time no lease operation except break and release can be * performed on the file. When a lease is successfully broken, the response indicates the interval in * seconds until a new lease can be acquired. Use "change" and specify the current lease ID in * "x-ms-lease-id" and the new lease ID in "x-ms-proposed-lease-id" to change the lease ID of an active * lease. Use "renew" and specify the "x-ms-lease-id" to renew an existing lease. Use "release" and * specify the "x-ms-lease-id" to release a lease. * @param options The options parameters. */ lease( xMsLeaseAction: PathLeaseAction, options?: PathLeaseOptionalParams ): Promise<PathLeaseResponse> { return this.client.sendOperationRequest( { xMsLeaseAction, options }, leaseOperationSpec ); } /** * Read the contents of a file. For read operations, range requests are supported. This operation * supports conditional HTTP requests. For more information, see [Specifying Conditional Headers for * Blob Service * Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations). * @param options The options parameters. */ read(options?: PathReadOptionalParams): Promise<PathReadResponse> { return this.client.sendOperationRequest({ options }, readOperationSpec); } /** * Get Properties returns all system and user defined properties for a path. Get Status returns all * system defined properties for a path. Get Access Control List returns the access control list for a * path. This operation supports conditional HTTP requests. For more information, see [Specifying * Conditional Headers for Blob Service * Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations). * @param options The options parameters. */ getProperties( options?: PathGetPropertiesOptionalParams ): Promise<PathGetPropertiesResponse> { return this.client.sendOperationRequest( { options }, getPropertiesOperationSpec ); } /** * Delete the file or directory. This operation supports conditional HTTP requests. For more * information, see [Specifying Conditional Headers for Blob Service * Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations). * @param options The options parameters. */ delete(options?: PathDeleteOptionalParams): Promise<PathDeleteResponse> { return this.client.sendOperationRequest({ options }, deleteOperationSpec); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const createOperationSpec: coreClient.OperationSpec = { path: "/{filesystem}/{path}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.PathCreateHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.PathCreateExceptionHeaders } }, queryParameters: [ Parameters.timeout, Parameters.resource, Parameters.continuation, Parameters.mode ], urlParameters: [Parameters.url, Parameters.fileSystem, Parameters.path], headerParameters: [ Parameters.accept, Parameters.requestId, Parameters.version, Parameters.cacheControl, Parameters.contentEncoding, Parameters.contentLanguage, Parameters.contentDisposition, Parameters.contentType, Parameters.renameSource, Parameters.leaseId, Parameters.sourceLeaseId, Parameters.properties, Parameters.permissions, Parameters.umask, Parameters.ifMatch, Parameters.ifNoneMatch, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince, Parameters.sourceIfMatch, Parameters.sourceIfNoneMatch, Parameters.sourceIfModifiedSince, Parameters.sourceIfUnmodifiedSince ], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/{filesystem}/{path}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.SetAccessControlRecursiveResponse, headersMapper: Mappers.PathUpdateHeaders }, 202: { headersMapper: Mappers.PathUpdateHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.PathUpdateExceptionHeaders } }, requestBody: Parameters.body, queryParameters: [ Parameters.timeout, Parameters.continuation, Parameters.action, Parameters.maxRecords, Parameters.mode1, Parameters.forceFlag, Parameters.position, Parameters.retainUncommittedData, Parameters.close ], urlParameters: [Parameters.url, Parameters.fileSystem, Parameters.path], headerParameters: [ Parameters.requestId, Parameters.version, Parameters.cacheControl, Parameters.contentEncoding, Parameters.contentLanguage, Parameters.contentDisposition, Parameters.contentType, Parameters.leaseId, Parameters.properties, Parameters.permissions, Parameters.ifMatch, Parameters.ifNoneMatch, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince, Parameters.contentType1, Parameters.accept1, Parameters.contentLength, Parameters.contentMD5, Parameters.owner, Parameters.group, Parameters.acl ], mediaType: "binary", serializer }; const leaseOperationSpec: coreClient.OperationSpec = { path: "/{filesystem}/{path}", httpMethod: "POST", responses: { 200: { headersMapper: Mappers.PathLeaseHeaders }, 201: { headersMapper: Mappers.PathLeaseHeaders }, 202: { headersMapper: Mappers.PathLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.PathLeaseExceptionHeaders } }, queryParameters: [Parameters.timeout], urlParameters: [Parameters.url, Parameters.fileSystem, Parameters.path], headerParameters: [ Parameters.accept, Parameters.requestId, Parameters.version, Parameters.leaseId, Parameters.ifMatch, Parameters.ifNoneMatch, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince, Parameters.xMsLeaseAction, Parameters.xMsLeaseDuration, Parameters.xMsLeaseBreakPeriod, Parameters.proposedLeaseId ], serializer }; const readOperationSpec: coreClient.OperationSpec = { path: "/{filesystem}/{path}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: Mappers.PathReadHeaders }, 206: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: Mappers.PathReadHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.PathReadExceptionHeaders } }, queryParameters: [Parameters.timeout], urlParameters: [Parameters.url, Parameters.fileSystem, Parameters.path], headerParameters: [ Parameters.accept, Parameters.requestId, Parameters.version, Parameters.leaseId, Parameters.ifMatch, Parameters.ifNoneMatch, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince, Parameters.range, Parameters.xMsRangeGetContentMd5 ], serializer }; const getPropertiesOperationSpec: coreClient.OperationSpec = { path: "/{filesystem}/{path}", httpMethod: "HEAD", responses: { 200: { headersMapper: Mappers.PathGetPropertiesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.PathGetPropertiesExceptionHeaders } }, queryParameters: [Parameters.timeout, Parameters.action1, Parameters.upn], urlParameters: [Parameters.url, Parameters.fileSystem, Parameters.path], headerParameters: [ Parameters.accept, Parameters.requestId, Parameters.version, Parameters.leaseId, Parameters.ifMatch, Parameters.ifNoneMatch, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince ], serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/{filesystem}/{path}", httpMethod: "DELETE", responses: { 200: { headersMapper: Mappers.PathDeleteHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.PathDeleteExceptionHeaders } }, queryParameters: [ Parameters.timeout, Parameters.continuation, Parameters.recursive ], urlParameters: [Parameters.url, Parameters.fileSystem, Parameters.path], headerParameters: [ Parameters.accept, Parameters.requestId, Parameters.version, Parameters.leaseId, Parameters.ifMatch, Parameters.ifNoneMatch, Parameters.ifModifiedSince, Parameters.ifUnmodifiedSince ], serializer };
the_stack
import React, { createElement, ForwardRefExoticComponent, ReactElement, ReactNode, useEffect, useRef, useState, } from 'react' import classnames from 'classnames' import { isElementInViewport } from './utils' type TooltipProps<T> = { label: string position?: 'top' | 'bottom' | 'left' | 'right' | undefined wrapperclasses?: string className?: string children: ReactNode } & T interface WithCustomTooltipProps<T> { asCustom: ForwardRefExoticComponent<T> } export type DefaultTooltipProps = TooltipProps<JSX.IntrinsicElements['button']> export type CustomTooltipProps<T> = TooltipProps<T> & WithCustomTooltipProps<T> export function isCustomProps<T>( props: DefaultTooltipProps | CustomTooltipProps<T> ): props is CustomTooltipProps<T> { return 'asCustom' in props } const TRIANGLE_SIZE = 5 const SPACER = 2 export function Tooltip(props: DefaultTooltipProps): ReactElement export function Tooltip<T>(props: CustomTooltipProps<T>): ReactElement export function Tooltip<FCProps = DefaultTooltipProps>( props: DefaultTooltipProps | CustomTooltipProps<FCProps> ): ReactElement { const wrapperRef = useRef<HTMLElement>(null) const triggerElementRef = useRef<HTMLElement & HTMLButtonElement>(null) const tooltipBodyRef = useRef<HTMLElement>(null) const tooltipID = useRef( `tooltip-${Math.floor(Math.random() * 900000) + 100000}` ) const [isVisible, setVisible] = useState(false) const [isShown, setIsShown] = useState(false) const [effectivePosition, setEffectivePosition] = useState< 'top' | 'bottom' | 'left' | 'right' | undefined >(undefined) const [wrapTooltip, setWrapTooltip] = useState(false) const [positionStyles, setPositionStyles] = useState({}) const { position, wrapperclasses, className } = props useEffect(() => { if (effectivePosition === 'top' || effectivePosition === 'bottom') { if ( tooltipBodyRef.current && !isElementInViewport(tooltipBodyRef.current) ) { setWrapTooltip(true) } } }, [effectivePosition]) useEffect(() => { if (isVisible) setIsShown(true) }, [effectivePosition, positionStyles]) useEffect(() => { if (!isVisible) { // Hide tooltip setIsShown(false) setWrapTooltip(false) } else { if ( triggerElementRef.current && tooltipBodyRef.current && wrapperRef.current ) { const tooltipTrigger = triggerElementRef.current const tooltipBody = tooltipBodyRef.current const wrapper = wrapperRef.current // Calculate sizing and adjustments for positioning const tooltipWidth = tooltipTrigger.offsetWidth const tooltipHeight = tooltipTrigger.offsetHeight const offsetForTopMargin = Number.parseInt( window .getComputedStyle(tooltipTrigger) .getPropertyValue('margin-top'), 10 ) const offsetForBottomMargin = Number.parseInt( window .getComputedStyle(tooltipTrigger) .getPropertyValue('margin-bottom'), 10 ) const offsetForTopPadding = Number.parseInt( window.getComputedStyle(wrapper).getPropertyValue('padding-top'), 10 ) const offsetForBottomPadding = Number.parseInt( window.getComputedStyle(wrapper).getPropertyValue('padding-bottom'), 10 ) // issue dealing with null here const offsetForTooltipBodyHeight = Number.parseInt( window.getComputedStyle(tooltipBody).getPropertyValue('height'), 10 ) const leftOffset = tooltipTrigger.offsetLeft const tooltipBodyWidth = tooltipBody.offsetWidth const adjustHorizontalCenter = tooltipWidth / 2 + leftOffset const adjustToEdgeX = tooltipWidth + TRIANGLE_SIZE + SPACER const adjustToEdgeY = tooltipHeight + TRIANGLE_SIZE + SPACER const positionTop = (): void => { setEffectivePosition('top') setPositionStyles({ marginLeft: `${adjustHorizontalCenter}px`, marginBottom: `${ adjustToEdgeY + offsetForBottomMargin + offsetForBottomPadding }px`, }) } const positionBottom = (): void => { setEffectivePosition('bottom') setPositionStyles({ marginLeft: `${adjustHorizontalCenter}px`, marginTop: `${ adjustToEdgeY + offsetForTopMargin + offsetForTopPadding }px`, }) } const positionRight = (): void => { setEffectivePosition('right') setPositionStyles({ marginBottom: '0', marginLeft: `${adjustToEdgeX + leftOffset}px`, bottom: `${ (tooltipHeight - offsetForTooltipBodyHeight) / 2 + offsetForBottomMargin + offsetForBottomPadding }px`, }) } const positionLeft = (): void => { setEffectivePosition('left') setPositionStyles({ marginBottom: '0', marginLeft: leftOffset > tooltipBodyWidth ? `${ leftOffset - tooltipBodyWidth - (TRIANGLE_SIZE + SPACER) }px` : `-${ tooltipBodyWidth - leftOffset + (TRIANGLE_SIZE + SPACER) }px`, bottom: `${ (tooltipHeight - offsetForTooltipBodyHeight) / 2 + offsetForBottomMargin + offsetForBottomPadding }px`, }) } /** * We try to set the position based on the * original intention, but make adjustments * if the element is clipped out of the viewport */ switch (position) { case 'top': positionTop() if (!isElementInViewport(tooltipBody)) { positionBottom() } break case 'bottom': positionBottom() if (!isElementInViewport(tooltipBody)) { positionTop() } break case 'right': positionRight() if (!isElementInViewport(tooltipBody)) { positionLeft() if (!isElementInViewport(tooltipBody)) { positionTop() } } break case 'left': positionLeft() if (!isElementInViewport(tooltipBody)) { positionRight() if (!isElementInViewport(tooltipBody)) { positionTop() } } break default: // skip default case break } } } }, [isVisible]) const showTooltip = (): void => { setVisible(true) } const hideTooltip = (): void => { setVisible(false) } const wrapperClasses = classnames('usa-tooltip', wrapperclasses) const tooltipBodyClasses = classnames('usa-tooltip__body', { 'is-set': isVisible, 'usa-tooltip__body--top': effectivePosition === 'top', 'usa-tooltip__body--bottom': effectivePosition === 'bottom', 'usa-tooltip__body--right': effectivePosition === 'right', 'usa-tooltip__body--left': effectivePosition === 'left', 'is-visible': isShown, // isShown is set after positioning updated, to prevent jitter when position changes 'usa-tooltip__body--wrap': isVisible && wrapTooltip, }) if (isCustomProps(props)) { const { label, asCustom, children, ...remainingProps } = props const customProps: FCProps = (remainingProps as unknown) as FCProps const triggerClasses = classnames('usa-tooltip__trigger', className) const triggerElement = createElement( asCustom, { ...customProps, ref: triggerElementRef, 'data-testid': 'triggerElement', 'aria-describedby': tooltipID.current, tabIndex: 0, title: '', onMouseEnter: showTooltip, onMouseOver: showTooltip, onFocus: showTooltip, onMouseLeave: hideTooltip, onBlur: hideTooltip, onKeyDown: hideTooltip, className: triggerClasses, }, children ) return ( <span data-testid="tooltipWrapper" ref={wrapperRef} className={wrapperClasses}> {triggerElement} <span data-testid="tooltipBody" title={label} id={tooltipID.current} ref={tooltipBodyRef} className={tooltipBodyClasses} role="tooltip" aria-hidden={!isVisible} style={positionStyles}> {label} </span> </span> ) } else { const { label, children, ...remainingProps } = props const triggerClasses = classnames( 'usa-button', 'usa-tooltip__trigger', className ) return ( <span data-testid="tooltipWrapper" ref={wrapperRef} className={wrapperClasses}> <button {...remainingProps} data-testid="triggerElement" ref={triggerElementRef} aria-describedby={tooltipID.current} tabIndex={0} type="button" className={triggerClasses} title="" onMouseEnter={showTooltip} onMouseOver={showTooltip} onFocus={showTooltip} onMouseLeave={hideTooltip} onBlur={hideTooltip} onKeyDown={hideTooltip}> {children} </button> <span data-testid="tooltipBody" title={label} id={tooltipID.current} ref={tooltipBodyRef} className={tooltipBodyClasses} role="tooltip" aria-hidden={!isVisible} style={positionStyles}> {label} </span> </span> // the span that wraps the element with have the tooltip class ) } } Tooltip.defaultProps = { position: 'top', } Tooltip.displayName = 'Tooltip'
the_stack
import { Browser } from "@syncfusion/ej2-base"; import { RichTextEditor } from './../../../src/index'; import { renderRTE, destroy, dispatchKeyEvent, dispatchEvent } from "./../render.spec"; function setCursorPoint(curDocument: Document, element: Element, point: number) { let range: Range = curDocument.createRange(); let sel: Selection = curDocument.defaultView.getSelection(); range.setStart(element, point); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } describe("'FontColor and BackgroundColor' - ColorPicker render testing", () => { let rteEle: HTMLElement; let rteObj: any; beforeEach(() => { rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor"] } }); rteEle = rteObj.element; }); afterEach(() => { destroy(rteObj); }); it("Color Picker initial rendering testing", () => { expect(rteObj.toolbarSettings.items[0]).toBe("FontColor"); expect(rteObj.toolbarSettings.items[1]).toBe("BackgroundColor"); //expect(rteEle.querySelectorAll(".e-colorpicker-wrapper")[0].classList.contains("e-font-color")).toBe(true); //expect(rteEle.querySelectorAll(".e-colorpicker-wrapper")[1].classList.contains("e-background-color")).toBe(true); }); it(" fontColor DropDown button target element as span", () => { let item:HTMLElement= rteEle.querySelector("#"+rteEle.id+"_toolbar_FontColor") expect(item.tagName==='SPAN').toBe(true); expect(item.hasAttribute('type')).toBe(false); }); }); describe(' RTE content selection with ', () => { let rteObj: RichTextEditor; let rteEle: Element; let mouseEventArgs: any; let curDocument: Document; let editNode: Element; let selectNode: Element; let innerHTML: string = `<p>First p node-0</p><p>First p node-1</p> <p class='first-p-node'>dom node<label class='first-label'>label node</label></p> <p class='second-p-node'><label class='second-label'>label node</label></p> <ul class='ul-third-node'><li>one-node</li><li>two-node</li><li>three-node</li></ul>`; beforeAll(() => { rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor"] } }); rteEle = rteObj.element; editNode = rteObj.contentModule.getEditPanel(); rteObj.contentModule.getEditPanel().innerHTML = innerHTML; curDocument = rteObj.contentModule.getDocument(); }); it("ColorPicker - Font selection", () => { selectNode = editNode.querySelector('.first-p-node'); setCursorPoint(curDocument, selectNode.childNodes[0] as Element, 1); let fontColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn")[0]; let clickEvent: MouseEvent = document.createEvent('MouseEvents'); clickEvent.initEvent('mousedown', true, true); fontColorPicker.dispatchEvent(clickEvent); fontColorPicker.click(); let fontColorPickerItem: HTMLElement = <HTMLElement>document.querySelectorAll(".e-primary.e-apply")[0]; mouseEventArgs = { target: fontColorPickerItem }; (rteObj.htmlEditorModule as any).colorPickerModule.fontColorPicker.btnClickHandler(mouseEventArgs); selectNode = editNode.querySelector('.first-p-node'); expect((selectNode.childNodes[0] as HTMLElement).style.color === 'rgb(28, 188, 81)') }); afterAll(() => { destroy(rteObj); }); }); describe(' RTE content selection with ', () => { let rteObj: RichTextEditor; let rteEle: Element; let mouseEventArgs: any; let curDocument: Document; let editNode: Element; let selectNode: Element; let innerHTML: string = `<p>First p node-0</p><p>First p node-1</p> <p class='first-p-node'>dom node<label class='first-label'>label node</label></p> <p class='second-p-node'><label class='second-label'>label node</label></p> <ul class='ul-third-node'><li>one-node</li><li>two-node</li><li>three-node</li></ul>`; beforeAll(() => { rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor"] } }); rteEle = rteObj.element; editNode = rteObj.contentModule.getEditPanel(); rteObj.contentModule.getEditPanel().innerHTML = innerHTML; curDocument = rteObj.contentModule.getDocument(); }); it("ColorPicker - Background selection", () => { selectNode = editNode.querySelector('.first-p-node'); setCursorPoint(curDocument, selectNode.childNodes[0] as Element, 1); rteObj.notify('selection-save', {}); let backgroundColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn")[1]; backgroundColorPicker.click(); let backgroundColorPickerItem: HTMLElement = <HTMLElement>document.querySelectorAll(".e-primary.e-apply")[0]; mouseEventArgs = { target: backgroundColorPickerItem }; (rteObj.htmlEditorModule as any).colorPickerModule.backgroundColorPicker.btnClickHandler(mouseEventArgs); selectNode = editNode.querySelector('.first-p-node'); expect((selectNode.childNodes[0] as HTMLElement).style.backgroundColor === 'rgb(255, 255, 0)'); backgroundColorPicker.click(); }); afterAll(() => { destroy(rteObj); }); }); describe("'FontColor and BackgroundColor' - ColorPicker render testing using mobileUA", () => { let rteEle: HTMLElement; let rteObj: any; let mobileUA: string = "Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JWR66Y) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.92 Safari/537.36"; let defaultUA: string = navigator.userAgent; beforeAll(() => { Browser.userAgent = mobileUA; rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor"] } }); rteEle = rteObj.element; }); afterAll(() => { destroy(rteObj); Browser.userAgent = defaultUA; }); it("Color Picker initial rendering testing", () => { expect(rteObj.toolbarSettings.items[0]).toBe("FontColor"); expect(rteObj.toolbarSettings.items[1]).toBe("BackgroundColor"); rteObj.notify('selection-save', {}); let backgroundColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn")[1].lastElementChild; backgroundColorPicker.click(); }); }); describe(' Readonly ', () => { let rteObj: RichTextEditor; let rteEle: Element; let innerHTML: string = `<p>First p node-0</p><p>First p node-1</p> <p class='first-p-node'>dom node<label class='first-label'>label node</label></p> <p class='second-p-node'><label class='second-label'>label node</label></p> <ul class='ul-third-node'><li>one-node</li><li>two-node</li><li>three-node</li></ul>`; beforeAll(() => { rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor", 'FontName', 'Bold'] }, readonly: true }); rteEle = rteObj.element; rteObj.contentModule.getEditPanel().innerHTML = innerHTML; }); it("ColorPicker - DropDown button Background selection", () => { rteObj.notify('selection-save', {}); let backgroundColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn")[1]; backgroundColorPicker.click(); expect((backgroundColorPicker as HTMLElement).style.background === ''); }); it("font color -selection", () => { rteObj.notify('selection-save', {}); let backgroundColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn")[2]; backgroundColorPicker.click(); expect((backgroundColorPicker as HTMLElement).style.background === ''); }); afterAll(() => { destroy(rteObj); }); }); describe(' RTE content selection with ', () => { let rteObj: RichTextEditor; let rteEle: Element; let mouseEventArgs: any; let curDocument: Document; let editNode: Element; let selectNode: Element; let innerHTML: string = `<p>First p node-0</p><p>First p node-1</p> <p class='first-p-node'>dom node<label class='first-label'>label node</label></p> <p class='second-p-node'><label class='second-label'>label node</label></p> <ul class='ul-third-node'><li>one-node</li><li>two-node</li><li>three-node</li></ul>`; beforeAll(() => { Browser.info.name = 'msie'; rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor"] } }); rteEle = rteObj.element; editNode = rteObj.contentModule.getEditPanel(); rteObj.contentModule.getEditPanel().innerHTML = innerHTML; curDocument = rteObj.contentModule.getDocument(); }); it("ColorPicker - Font selection in IE browser", () => { selectNode = editNode.querySelector('.first-p-node'); setCursorPoint(curDocument, selectNode.childNodes[0] as Element, 1); rteObj.notify('selection-save', {}); let fontColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn")[0]; fontColorPicker.click(); let fontColorPickerItem: HTMLElement = <HTMLElement>document.querySelectorAll(".e-primary.e-apply")[0]; mouseEventArgs = { target: fontColorPickerItem }; (rteObj.htmlEditorModule as any).colorPickerModule.fontColorPicker.btnClickHandler(mouseEventArgs); selectNode = editNode.querySelector('.first-p-node'); expect((selectNode.childNodes[0] as HTMLElement).style.color === 'rgb(28, 188, 81)') }); afterAll(() => { destroy(rteObj); }); }); describe(' RTE content selection with ', () => { let rteObj: RichTextEditor; let rteEle: Element; let mouseEventArgs: any; let curDocument: Document; let editNode: Element; let selectNode: Element; let innerHTML: string = `<p>First p node-0</p><p>First p node-1</p> <p class='first-p-node'>dom node<label class='first-label'>label node</label></p> <p class='second-p-node'><label class='second-label'>label node</label></p> <ul class='ul-third-node'><li>one-node</li><li>two-node</li><li>three-node</li></ul>`; beforeAll(() => { Browser.info.name = 'edge'; rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor"] } }); rteEle = rteObj.element; editNode = rteObj.contentModule.getEditPanel(); rteObj.contentModule.getEditPanel().innerHTML = innerHTML; curDocument = rteObj.contentModule.getDocument(); }); it("ColorPicker - Background selection in Edge browser", () => { selectNode = editNode.querySelector('.first-p-node'); setCursorPoint(curDocument, selectNode.childNodes[0] as Element, 1); rteObj.notify('selection-save', {}); let backgroundColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn")[1]; backgroundColorPicker.click(); let backgroundColorPickerItem: HTMLElement = <HTMLElement>document.querySelectorAll(".e-primary.e-apply")[0]; mouseEventArgs = { target: backgroundColorPickerItem }; (rteObj.htmlEditorModule as any).colorPickerModule.backgroundColorPicker.btnClickHandler(mouseEventArgs); selectNode = editNode.querySelector('.first-p-node'); expect((selectNode.childNodes[0] as HTMLElement).style.backgroundColor === 'rgb(255, 255, 0)'); }); afterAll(() => { destroy(rteObj); }); }); describe("'FontColor and BackgroundColor' - ColorPicker DROPDOWN", () => { let rteEle: HTMLElement; let rteObj: any; let mouseEventArgs: any; let editNode: Element; let selectNode: Element; beforeAll(() => { rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor"] }, fontColor: { mode: 'Picker', modeSwitcher: true }, backgroundColor: { mode: 'Picker', modeSwitcher: true }, value: `<p>First p node-0</p><p>First p node-1</p> <p class='first-p-node'>dom node<label class='first-label'>label node</label></p> <p class='second-p-node'><label class='second-label'>label node</label></p> <p class='third-p-node'>dom node</p> <ul class='ul-third-node'><li>one-node</li><li>two-node</li><li>three-node</li></ul>` }); rteEle = rteObj.element; editNode = rteObj.contentModule.getEditPanel(); }); afterAll(() => { destroy(rteObj); }); it("Color Picker initial rendering testing - 1", (done) => { selectNode = editNode.querySelector('.third-p-node'); setCursorPoint(document, selectNode.childNodes[0] as Element, 1); rteObj.notify('selection-save', {}); let backgroundColorPicker: HTMLElement = <HTMLElement>rteEle.querySelector(".e-rte-backgroundcolor-dropdown"); backgroundColorPicker.click(); dispatchEvent(document.querySelectorAll('.e-control-wrapper.e-numeric.e-float-input.e-input-group')[7].firstElementChild, 'focusin'); (document.querySelectorAll('.e-control-wrapper.e-numeric.e-float-input.e-input-group')[7].firstElementChild as any).value = '50'; dispatchKeyEvent(document.querySelectorAll('.e-control-wrapper.e-numeric.e-float-input.e-input-group')[7].firstElementChild, 'input'); dispatchKeyEvent(document.querySelectorAll('.e-control-wrapper.e-numeric.e-float-input.e-input-group')[7].firstElementChild, 'keyup', { 'key': 'a', 'keyCode': 65 }); dispatchEvent(document.querySelectorAll('.e-control-wrapper.e-numeric.e-float-input.e-input-group')[7].firstElementChild, 'change'); dispatchEvent(document.querySelectorAll('.e-control-wrapper.e-numeric.e-float-input.e-input-group')[7].firstElementChild, 'focusout'); setTimeout(() => { let backgroundColorPickerItem: HTMLElement = <HTMLElement>document.querySelectorAll(".e-primary.e-apply")[1]; mouseEventArgs = { target: backgroundColorPickerItem }; (rteObj.htmlEditorModule as any).colorPickerModule.backgroundColorPicker.btnClickHandler(mouseEventArgs); expect(selectNode.childNodes[0].nodeName.toLocaleLowerCase()).toBe("span"); expect((selectNode.childNodes[0] as HTMLElement).getAttribute('style')).toBe('background-color: rgba(255, 255, 0, 0.5);'); done(); }, 200); }); it("Color Picker initial rendering testing", () => { expect(rteObj.toolbarSettings.items[0]).toBe("FontColor"); expect(rteObj.toolbarSettings.items[1]).toBe("BackgroundColor"); rteObj.notify('selection-save', {}); let backgroundColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn .e-icons.e-icon-right")[1]; backgroundColorPicker.click(); (document.querySelector(".e-rte-backgroundcolor-colorpicker") as HTMLElement).click(); (document.querySelector(".e-rte-backgroundcolor-colorpicker").querySelector(".e-cancel") as HTMLElement).click(); (document.querySelectorAll(".e-mode-switch-btn")[1] as HTMLElement).click(); }); it("Color Picker initial rendering testing - 1", () => { selectNode = editNode.querySelector('.first-p-node'); setCursorPoint(document, selectNode.childNodes[0] as Element, 1); rteObj.notify('selection-save', {}); let backgroundColorPicker: HTMLElement = <HTMLElement>rteEle.querySelector(".e-rte-backgroundcolor-dropdown"); backgroundColorPicker.click(); (backgroundColorPicker.querySelector(".e-background-color") as HTMLElement).click(); expect(selectNode.childNodes[0].nodeName.toLocaleLowerCase()).toBe("span"); }); it("Color Picker initial rendering testing - 2", () => { selectNode = editNode.querySelector('.first-label'); setCursorPoint(document, selectNode.childNodes[0] as Element, 1); rteObj.notify('selection-save', {}); let backgroundColorPicker: HTMLElement = <HTMLElement>rteEle.querySelector(".e-background-color.e-rte-elements"); backgroundColorPicker.innerText = "ABC"; backgroundColorPicker.click(); expect(selectNode.childNodes[0].nodeName.toLocaleLowerCase()).toBe("span"); }); }); describe("EJ2-16252: 'FontColor and BackgroundColor' - selection state", () => { let rteEle: HTMLElement; let rteObj: any; let id: string; beforeAll(() => { rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor"] }, value: `<p>First p node-0</p><p>First p node-1</p> <p class='first-p-node'>dom node<label class='first-label'>label node</label></p> <p class='second-p-node'><label class='second-label'>label node</label></p> <ul class='ul-third-node'><li>one-node</li><li>two-node</li><li>three-node</li></ul>` }); rteEle = rteObj.element; id = rteEle.id; }); afterAll(() => { destroy(rteObj); }); it(" Test the default value selection in FontColor popup", () => { rteObj.notify('selection-save', {}); let fontColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn .e-icons.e-icon-right")[0]; fontColorPicker.click(); let colorPickerPopup: HTMLElement = document.getElementById(id + "_toolbar_FontColor-popup"); let selectPalette: HTMLElement = colorPickerPopup.querySelector('.e-selected'); expect(selectPalette).not.toBeNull(); expect(selectPalette.style.backgroundColor === 'rgb(255, 0, 0)').not.toBeNull(); }); it(" Test the default value selection in BackgroundColor popup", () => { rteObj.notify('selection-save', {}); let fontColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn .e-icons.e-icon-right")[1]; fontColorPicker.click(); let colorPickerPopup: HTMLElement = document.getElementById(id + "_toolbar_BackgroundColor-popup"); let selectPalette: HTMLElement = colorPickerPopup.querySelector('.e-selected'); expect(selectPalette).not.toBeNull(); expect(selectPalette.style.backgroundColor === 'rgb(255, 255, 0)').not.toBeNull(); }); }); describe("EJ2-16252: 'FontColor and BackgroundColor' - Default value set", () => { let rteEle: HTMLElement; let rteObj: any; let id: string; beforeAll(() => { rteObj = renderRTE({ toolbarSettings: { items: ["FontColor", "BackgroundColor"] }, fontColor: { default: '#823b0b' }, backgroundColor: { default: '#006666' }, value: `<p>First p node-0</p><p>First p node-1</p> <p class='first-p-node'>dom node<label class='first-label'>label node</label></p> <p class='second-p-node'><label class='second-label'>label node</label></p> <ul class='ul-third-node'><li>one-node</li><li>two-node</li><li>three-node</li></ul>` }); rteEle = rteObj.element; id = rteEle.id; }); afterAll(() => { destroy(rteObj); }); it(" Test the default value selection in FontColor popup", () => { rteObj.notify('selection-save', {}); let fontColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn .e-icons.e-icon-right")[0]; fontColorPicker.click(); let colorPickerPopup: HTMLElement = document.getElementById(id + "_toolbar_FontColor-popup"); let selectPalette: HTMLElement = colorPickerPopup.querySelector('.e-selected'); expect(selectPalette).not.toBeNull(); expect(selectPalette.style.backgroundColor === 'rgb(130, 59, 11)').not.toBeNull(); }); it(" Test the default value selection in BackgroundColor popup", () => { rteObj.notify('selection-save', {}); let fontColorPicker: HTMLElement = <HTMLElement>rteEle.querySelectorAll(".e-toolbar-item .e-dropdown-btn .e-icons.e-icon-right")[1]; fontColorPicker.click(); let colorPickerPopup: HTMLElement = document.getElementById(id + "_toolbar_BackgroundColor-popup"); let selectPalette: HTMLElement = colorPickerPopup.querySelector('.e-selected'); expect(selectPalette).not.toBeNull(); expect(selectPalette.style.backgroundColor === 'rgb(0, 102, 102)').not.toBeNull(); }); });
the_stack
import * as freedomMocker from '../lib/freedom/mocks/mock-freedom-in-module-env'; import * as freedom_mocks from '../mocks/freedom-mocks'; declare var freedom: freedom.FreedomInModuleEnv; freedom = freedomMocker.makeMockFreedomInModuleEnv({ 'core.online': () => { return new freedom_mocks.MockFreedomOnline(); }, 'core.storage': () => { return new freedom_mocks.MockFreedomStorage(); }, 'metrics': () => { return new freedom_mocks.MockMetrics(); }, 'pgp': () => { return new freedom_mocks.PgpProvider() }, 'portControl': () => { return new Object }, }); import * as social from '../interfaces/social'; import * as rappor_metrics from './metrics'; import * as social_network from './social'; import * as local_storage from './storage'; import * as local_instance from './local-instance'; import * as constants from './constants'; import * as uproxy_core_api from '../interfaces/uproxy_core_api'; import * as ui_connector from './ui_connector'; import ui = ui_connector.connector; class MockSocial { public on = () => {} public emit = () => {} public manifest = () => {} public login = () => {} public logout = () => {} public sendMessage = () => { return Promise.resolve(); } public inviteUser = () => { return Promise.resolve({data: 'InviteTokenData'}); } } // Valid message that won't have side effects on network/user/instance objects. var VALID_MESSAGE = { type: social.PeerMessageType.INSTANCE_REQUEST, data: <any>null }; var freedomClient :freedom.Social.ClientState = { userId: 'mockmyself', clientId: 'fakemyself', status: 'ONLINE', timestamp: 12345 }; var fakeFreedomClient :freedom.Social.ClientState = { userId: 'mockmyself', clientId: 'fakemyself', status: 'ONLINE', timestamp: 12345 }; describe('freedomClientToUproxyClient', () => { beforeEach(() => { spyOn(console, 'log'); }); var uproxyClient = social_network.freedomClientToUproxyClient(freedomClient); it('converts status to enum', () => { expect(uproxyClient.status).toEqual(social.ClientStatus.ONLINE); }); it('copies non-status fields unchanged', () => { expect(uproxyClient.userId).toEqual(freedomClient.userId); expect(uproxyClient.clientId).toEqual(freedomClient.clientId); expect(uproxyClient.timestamp).toEqual(freedomClient.timestamp); }); }); describe('social_network.FreedomNetwork', () => { // Mock social providers. freedom['SOCIAL-badmock'] = <any>(() => { return new MockSocial(); }); freedom['SOCIAL-mock'] = <any>(() => { return new MockSocial(); }); freedom['SOCIAL-mock'].api = 'social'; freedom['SOCIAL-Quiver'] = <any>(() => { return new MockSocial(); }); freedom['SOCIAL-Quiver'].api = 'social2'; var loginPromise :Promise<void>; var metrics :rappor_metrics.Metrics; beforeEach(() => { // Spy / override log messages to keep test output clean. spyOn(console, 'log'); metrics = new rappor_metrics.FreedomMetrics(null); }); it('initialize networks', () => { social_network.initializeNetworks(); expect(social_network.networks['badmock']).not.toBeDefined(); expect(social_network.networks['mock']).toBeDefined(); expect(social_network.networks['mock']).toEqual({}); }); it('begins with empty roster', () => { var network = new social_network.FreedomNetwork('mock', metrics); expect(network.roster).toEqual({}); }); describe('login & logout', () => { var network = new social_network.FreedomNetwork('mock', metrics); it('can log in', (done) => { // TODO: figure out how jasmine clock works and add it back // jasmine.clock().install(); var storage = new local_storage.Storage; var fulfillFunc :Function; var onceLoggedIn = new Promise((F, R) => { fulfillFunc = F; }); spyOn(network['freedomApi_'], 'login').and.returnValue(onceLoggedIn); var fulfillStorage :Function; var onceStorageDone = new Promise((F, R) => { fulfillStorage = F; }); var restoreFunc = network.restoreFromStorage.bind(network); spyOn(network, 'restoreFromStorage').and.callFake(() => { restoreFunc().then(() => { fulfillStorage(); }) }); var savedToStorage :Promise<void>[] = []; savedToStorage.push(storage.save('mockmockmyself', { instanceId: 'dummy-instance-id', keyHash: '', bytesReceived: 0, bytesSent: 0, description: 'my computer', isOnline: false, localGettingFromRemote: social.GettingState.NONE, localSharingWithRemote: social.SharingState.NONE })); savedToStorage.push(storage.save( 'dummy-instance-id/roster/somefriend', '')); Promise.all(savedToStorage).then(() => { loginPromise = network.login(uproxy_core_api.LoginType.INITIAL); return loginPromise; }).then(() => { expect(network.myInstance).toBeDefined(); expect(network['myInstance'].userId).toEqual( fakeFreedomClient.userId); expect(network['myInstance'].instanceId).toEqual( 'dummy-instance-id'); var freedomClientState :freedom.Social.ClientState = { userId: 'fakeuser', clientId: 'fakeclient', status: 'ONLINE', timestamp: 12345 }; onceStorageDone.then(() => { expect(Object.keys(network.roster).length).toEqual(1); expect(network.getUser('somefriend')).toBeDefined(); // Add user to the roster; network.handleClientState(freedomClientState); expect(Object.keys(network.roster).length).toEqual(2); var friend = network.getUser('fakeuser'); expect(friend).toBeDefined(); //spyOn(friend, 'monitor'); // Advance clock 5 seconds and make sure monitoring was called. // jasmine.clock().tick(60000); //expect(friend.monitor).toHaveBeenCalled(); done(); }); }); fulfillFunc(fakeFreedomClient); // We need to tick a clock in order promises to be resolved. //jasmine.clock().tick(1); }); it('errors if network login fails', (done) => { loginPromise = network['onceLoggedIn_']; network['onceLoggedIn_'] = null; // Pretend the social API's login failed. spyOn(network['freedomApi_'], 'login').and.returnValue( Promise.reject(new Error('mock failure'))); network.login(uproxy_core_api.LoginType.INITIAL).catch(done); //jasmine.clock().tick(1); }); it('can log out', (done) => { network['onceLoggedIn_'] = loginPromise; // Pretend the social API's logout succeeded. spyOn(network['freedomApi_'], 'logout').and.returnValue(Promise.resolve()); var friend = network.getUser('fakeuser'); expect(friend).toBeDefined(); //spyOn(friend, 'monitor'); // Monitoring is still running. //jasmine.clock().tick(60000); //expect(friend.monitor).toHaveBeenCalled(); network.logout().then(() => { // (<any>friend.monitor).calls.reset(); // jasmine.clock().tick(60000); // expect(friend.monitor).not.toHaveBeenCalled(); // jasmine.clock().uninstall(); }).then(done); // We need to tick a clock in order promises to be resolved. // jasmine.clock().tick(1); }); }); // describe login & logout describe('handler promise delays', () => { // Hijack the social api login promise to delay at the right time. var handlerPromise :Promise<void>; var fakeLoginFulfill :Function; var foo = jasmine.createSpyObj('foo', [ 'bar', ]); // var delayed :Function; it('delays handler until login', () => { var network = new social_network.FreedomNetwork('mock', metrics); spyOn(network['freedomApi_'], 'login').and.returnValue( new Promise((F, R) => { fakeLoginFulfill = F; })); expect(network['onceLoggedIn_']).toBeDefined(); network.login(uproxy_core_api.LoginType.INITIAL); // Will complete in the next spec. // handlerPromise = delayed('hooray'); handlerPromise = network['delayForLogin_'](foo.bar)('hooray'); expect(foo.bar).not.toHaveBeenCalled(); }); it('fires handler once logged-in', (done) => { fakeLoginFulfill(fakeFreedomClient); handlerPromise.then(() => { expect(foo['bar']).toHaveBeenCalledWith('hooray'); }).then(done); }); }); // describe handler promise delays describe('incoming events', () => { var network = new social_network.FreedomNetwork('mock', metrics); it('adds a new user for |onUserProfile|', (done) => { network.myInstance = new local_instance.LocalInstance(network, 'fakeId'); expect(Object.keys(network.roster).length).toEqual(0); network.handleUserProfile({ userId: 'mockuser', name: 'mock1', timestamp: Date.now() }); expect(Object.keys(network.roster).length).toEqual(1); var user = network.getUser('mockuser'); expect(user).toBeDefined; expect(user.name).toEqual('mock1'); done(); }); it('updates existing user', (done) => { expect(Object.keys(network.roster).length).toEqual(1); var user = network.getUser('mockuser'); spyOn(user, 'update').and.callThrough(); network.handleUserProfile({ userId: 'mockuser', name: 'newname', timestamp: Date.now() }); expect(user.update).toHaveBeenCalled(); expect(user).toBeDefined; expect(user.name).toEqual('newname'); done(); }); it('passes |onClientState| to correct user', () => { var user = network.getUser('mockuser'); spyOn(user, 'handleClient'); var freedomClientState :freedom.Social.ClientState = { userId: 'mockuser', clientId: 'fakeclient', status: 'ONLINE', timestamp: 12345 }; network.handleClientState(freedomClientState); expect(user.handleClient).toHaveBeenCalledWith( social_network.freedomClientToUproxyClient(freedomClientState)); }); it('adds placeholder when receiving ClientState with userId not in roster', () => { var freedomClientState :freedom.Social.ClientState = { userId: 'im_not_here', clientId: 'fakeclient', status: 'ONLINE', timestamp: 12345 }; network.handleClientState(freedomClientState); var user = network.getUser('im_not_here'); expect(user).toBeDefined(); }); it('passes |onMessage| to correct user', () => { var user = network.getUser('mockuser'); spyOn(user, 'handleMessage'); var msg = { from: { userId: 'mockuser', clientId: 'fakeclient', status: 'ONLINE', timestamp: 12345 }, message: JSON.stringify({ 'cats': 'meow' }) }; network.handleMessage(msg); expect(user.handleMessage).toHaveBeenCalledWith('fakeclient', { 'cats': 'meow' }); }); it('adds placeholder when receiving Message with userId not in roster', () => { var msg = { from: { userId: 'im_still_not_here', clientId: 'fakeclient', status: 'ONLINE', timestamp: 12345 }, message: JSON.stringify(VALID_MESSAGE) }; network.handleMessage(msg); var user = network.getUser('im_still_not_here'); expect(user).toBeDefined(); }); }); // describe events & communication it('JSON.parse and stringify messages at the right layer', () => { var network = new social_network.FreedomNetwork('mock', metrics); spyOn(network, 'getStorePath').and.returnValue(''); network['myInstance'] = new local_instance.LocalInstance(network, 'localUserId'); var user = network.addUser('mockuser'); spyOn(user, 'handleMessage'); var inMsg = { from: { userId: 'mockuser', clientId: 'fakeclient', status: 'ONLINE', timestamp: 12345 }, message: JSON.stringify({ 'elephants': 'have trunks' }) }; spyOn(JSON, 'parse').and.callThrough(); network.handleMessage(inMsg); expect(JSON.parse).toHaveBeenCalledWith('{"elephants":"have trunks"}'); var outMsg = { type: social.PeerMessageType.INSTANCE, data: { 'tigers': 'are also cats' }, version: constants.MESSAGE_VERSION }; spyOn(JSON, 'stringify').and.callThrough(); network.send(network.getUser('mockuser'), 'fakeclient', outMsg) expect(JSON.stringify).toHaveBeenCalledWith( { type: outMsg.type, data: outMsg.data, version: constants.MESSAGE_VERSION }); }); // TODO: get this unit test to pass. /* it('Can restore a state that has multiple users', (done) => { var networkState :social.NetworkState = { name: 'mock', remember: false, userIds: ['userA', 'userB', 'userC'] } network.restoreState(networkState).then(() => { expect(network.getUser('userA')).toEqual('userA'); expect(network.getUser('userB')).toEqual('userB'); expect(network.getUser('userC')).toEqual('userC'); done(); }); }); */ });
the_stack
import React, { useEffect, useState } from 'react'; import Form from 'antd/es/form'; import { FormComponentProps } from 'antd/lib/form'; import { Button, Card, Col, Icon, Input, Modal, Row, Radio, Switch, Tooltip, Select, message } from 'antd'; import { alarm } from '../data'; import Service from '../service'; import Triggers from './triggers'; import Bind from '../../rule-engine/scene-save/bind'; import ActionAssembly from './actions'; interface Props extends FormComponentProps { close: Function; save: Function; data: Partial<alarm>, deviceId: string; } interface State { properties: any[]; data: Partial<alarm>; trigger: any[]; action: any[]; shakeLimit: any; alarmType: string; deviceList: any[]; name: string; productId: string; deviceId: string; productList: any[]; device: any; product: any; } const AlarmSave: React.FC<Props> = props => { const service = new Service('rule-engine-alarm'); const initState: State = { properties: [], data: props.data, trigger: [], action: [], shakeLimit: {}, alarmType: props.data.target || 'product', deviceList: [], name: props.data.name || '', deviceId: props.data.target === 'device' && props.data.targetId ? props.data.targetId : '', productId: props.data.targetId || '', productList: [], device: {}, product: {}, }; const [data] = useState(initState.data); const [alarmType, setAlarmType] = useState(initState.alarmType); const [properties, setProperties] = useState(initState.properties); const [trigger, setTrigger] = useState(initState.trigger); const [action, setAction] = useState(initState.action); const [bindVisible, setBindVisible] = useState(false); const [shakeLimit, setShakeLimit] = useState(initState.shakeLimit); // const [deviceList, setDeviceList] = useState(initState.deviceList); const [productList, setProductList] = useState(initState.productList); const [name, setName] = useState(initState.name); const [deviceId, setDeviceId] = useState(initState.deviceId); const [productId, setProductId] = useState(initState.productId); const [device, setDevice] = useState(initState.device); const [product, setProduct] = useState(initState.product); const submitData = () => { data.name = name; data.target = alarmType; if (alarmType === 'device') { data.targetId = deviceId; data.alarmRule = { name: device.name, deviceId: device.id, deviceName: device.name, triggers: trigger, actions: action, properties: properties, productId: device.productId, productName: device.productName, shakeLimit: shakeLimit, }; } else { data.targetId = productId; data.alarmRule = { name: product.name, productId: product.id, productName: product.name, triggers: trigger, actions: action, properties: properties, shakeLimit: shakeLimit, }; } data.state = undefined; props.save({ ...data }); }; // const getDeviceList = () => { // service.getDeviceList(props.deviceId, { paging: false }).subscribe( // (res) => { // setDeviceList(res.data) // } // ) // } const getProductList = () => { service.getProductList(props.deviceId, { paging: false }).subscribe( (res) => { setProductList(res) } ) } const getProductInfo = (id: string) => { service.getProductInfo(props.deviceId, { id: id }).subscribe( res => { setProduct(res); } ) } const getInstanceDetail = (id: string) => { service.getInstanceDetail(props.deviceId, id).subscribe( (res) => { setDevice(res); } ) } useEffect(() => { if(deviceId !== ''){ getInstanceDetail(deviceId); } if(productId !== ''){ getProductInfo(productId); } getProductList(); if (props.data.alarmRule) { setShakeLimit(props.data.alarmRule.shakeLimit ? props.data.alarmRule.shakeLimit : { enabled: false, time: undefined, threshold: undefined, alarmFirst: true }); setTrigger(props.data.alarmRule.triggers.length > 0 ? [...props.data.alarmRule.triggers] : [{ _id: 0 }]); setAction(props.data.alarmRule.actions.length > 0 ? [...props.data.alarmRule.actions] : [{ _id: 0 }]); setProperties(props.data.alarmRule.properties.length > 0 ? [...props.data.alarmRule.properties] : [{ _id: 0 }]); } else { setTrigger([{ _id: 0 }]); setAction([{ _id: 0 }]); setProperties([{ _id: 0 }]); } }, []); const removeProperties = (val: number) => { properties.splice(val, 1); setProperties([...properties]); }; return ( <Modal title={`${props.data?.id ? '编辑' : '新建'}告警1`} visible okText="确定" cancelText="取消" onOk={() => { submitData(); }} style={{ marginTop: '-3%' }} width="70%" onCancel={() => props.close()} > <div style={{ maxHeight: 750, overflowY: 'auto', overflowX: 'hidden' }}> <Form wrapperCol={{ span: 20 }} labelCol={{ span: 4 }} key='addAlarmForm'> <Row gutter={16} style={{ marginLeft: '0.1%' }}> <Col span={12}> <Form.Item key="name" label="告警名称"> <Input placeholder="输入告警名称" defaultValue={props.data.name} onBlur={event => { setName(event.target.value); }} /> </Form.Item> </Col> <Col span={12}> <Form.Item key="alarmType" label="告警类型"> <Select placeholder="请选择" defaultValue={props.data.target} disabled={!!props.data.id} onChange={(value: string) => { setAlarmType(value); }} > <Select.Option key='product' value="product">产品</Select.Option> <Select.Option key='device' value="device">设备</Select.Option> </Select> </Form.Item> </Col> { alarmType === 'product' && <Col span={12}> <Form.Item key="productId" label="产品" > <Select disabled={!!props.data.id} placeholder="请选择" defaultValue={productId} onChange={(value: string) => { setProductId(value); getProductInfo(value); }}> {productList.map((item: any) => { return ( <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option> ) })} </Select> </Form.Item> </Col> } { alarmType === 'device' && <Col span={12}> <Form.Item key="deviceId" label="设备"> <Input disabled={!!props.data.id} addonAfter={<Icon onClick={() => { setBindVisible(true); }} type='gold' title="点击选择设备" />} defaultValue={deviceId || ''} placeholder="点击选择设备" value={device?.name} readOnly /> {/* <Select placeholder="请选择" defaultValue={props.data.targetId} onChange={(value: string) => { getInstanceDetail(value); }}> {deviceList.map((item: any) => { return ( <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option> ) })} </Select> */} </Form.Item> </Col> } </Row> <Card style={{ marginBottom: 10 }} bordered={false} size="small"> <p style={{ fontSize: 16 }}>触发条件 <Tooltip title="触发条件满足条件中任意一个即可触发"> <Icon type="question-circle-o" style={{ paddingLeft: 10 }} /> </Tooltip> <Switch key='shakeLimit.enabled' checkedChildren="开启防抖" unCheckedChildren="关闭防抖" defaultChecked={shakeLimit.enabled ? shakeLimit.enabled : false} style={{ marginLeft: 20 }} onChange={(value: boolean) => { shakeLimit.enabled = value; setShakeLimit({ ...shakeLimit }) }} /> {shakeLimit.enabled && ( <> <Input style={{ width: 80, marginLeft: 3 }} size='small' key='shakeLimit.time' defaultValue={shakeLimit.time} onBlur={event => { shakeLimit.time = event.target.value; }} />秒内发生 <Input style={{ width: 80 }} size='small' key='shakeLimit.threshold' defaultValue={shakeLimit.threshold} onBlur={event => { shakeLimit.threshold = event.target.value; }} />次及以上时,处理 <Radio.Group defaultValue={shakeLimit.alarmFirst} key='shakeLimit.alarmFirst' size='small' buttonStyle="solid" onChange={event => { shakeLimit.alarmFirst = Boolean(event.target.value); }} > <Radio.Button value={true}>第一次</Radio.Button> <Radio.Button value={false}>最后一次</Radio.Button> </Radio.Group> </> )} </p> {trigger.map((item: any, index: number) => ( <div key={index}> <Triggers save={(data: any) => { trigger.splice(index, 1, data); }} trigger={item} key={`trigger_${Math.round(Math.random() * 100000)}`} metaData={alarmType === 'product' ? product?.metadata : device?.metadata} position={index} remove={(position: number) => { trigger.splice(position, 1); let data = [...trigger]; setTrigger([...data]); }} /> </div> ))} <Button icon="plus" type="link" onClick={() => { setTrigger([...trigger, { _id: Math.round(Math.random() * 100000) }]); }} > 新增触发器 </Button> </Card> <Card style={{ marginBottom: 10 }} bordered={false} size="small"> <p style={{ fontSize: 16 }}>转换 <Tooltip title="将内置的结果字段转换为自定义字段,例如:deviceId 转为 id"> <Icon type="question-circle-o" style={{ paddingLeft: 10 }} /> </Tooltip> </p> <div style={{ maxHeight: 200, overflowY: 'auto', overflowX: 'hidden', backgroundColor: '#F5F5F6', paddingTop: 10, }}> {properties.map((item: any, index: number) => ( <Row gutter={16} key={index} style={{ paddingBottom: 10, marginLeft: 13, marginRight: 3 }}> <Col span={6}> <Input placeholder="请输入属性" value={item.property} onChange={event => { properties[index].property = event.target.value; setProperties([...properties]); }} /> </Col> <Col span={6}> <Input placeholder="请输入别名" value={item.alias} onChange={event => { properties[index].alias = event.target.value; setProperties([...properties]); }} /> </Col> <Col span={12} style={{ textAlign: 'right', marginTop: 6, paddingRight: 15 }}> <a style={{ paddingTop: 7 }} onClick={() => { removeProperties(index); }} >删除</a> </Col> </Row> ))} <Col span={24} style={{ marginLeft: 20 }}> <a onClick={() => { setProperties([...properties, { _id: Math.round(Math.random() * 100000) }]); }}>添加</a> </Col> </div> </Card> <Card bordered={false} size="small"> <p style={{ fontSize: 16 }}>执行动作</p> {action.map((item: any, index) => ( <ActionAssembly deviceId={props.deviceId} key={index + Math.random()} save={(actionData: any) => { action.splice(index, 1, actionData); }} action={item} position={index} remove={(position: number) => { action.splice(position, 1); setAction([...action]); }} /> ))} <Button icon="plus" type="link" onClick={() => { setAction([...action, { _id: Math.round(Math.random() * 100000) }]); }} > 执行动作 </Button> </Card> </Form> </div> {bindVisible && ( <Bind selectionType='radio' close={() => { setBindVisible(false); }} deviceId={props.deviceId} save={(item: any) => { if (item[0]) { setBindVisible(false); getInstanceDetail(item[0]); setDeviceId(item[0]); } else { message.error('请勾选设备'); return; } }} /> )} </Modal> ); }; export default Form.create<Props>()(AlarmSave);
the_stack
import * as express from 'express'; import * as _ from 'lodash'; import StrictEventEmitter from 'strict-event-emitter-types'; import * as config from '../config'; import { transaction, Transaction } from '../db'; import * as dbFormat from '../device-state/db-format'; import { validateTargetContracts } from '../lib/contracts'; import constants = require('../lib/constants'); import { docker } from '../lib/docker-utils'; import * as logger from '../logger'; import log from '../lib/supervisor-console'; import LocalModeManager from '../local-mode'; import { ContractViolationError, InternalInconsistencyError, } from '../lib/errors'; import { lock } from '../lib/update-lock'; import App from './app'; import * as volumeManager from './volume-manager'; import * as networkManager from './network-manager'; import * as serviceManager from './service-manager'; import * as imageManager from './images'; import type { Image } from './images'; import { getExecutors, CompositionStepT } from './composition-steps'; import * as commitStore from './commit'; import Service from './service'; import Network from './network'; import Volume from './volume'; import { createV1Api } from '../device-api/v1'; import { createV2Api } from '../device-api/v2'; import { CompositionStep, generateStep } from './composition-steps'; import { InstancedAppState, TargetApps, DeviceLegacyReport, AppState, ServiceState, } from '../types/state'; import { checkTruthy } from '../lib/validation'; import { Proxyvisor } from '../proxyvisor'; import { EventEmitter } from 'events'; type ApplicationManagerEventEmitter = StrictEventEmitter< EventEmitter, { change: DeviceLegacyReport } >; const events: ApplicationManagerEventEmitter = new EventEmitter(); export const on: typeof events['on'] = events.on.bind(events); export const once: typeof events['once'] = events.once.bind(events); export const removeListener: typeof events['removeListener'] = events.removeListener.bind( events, ); export const removeAllListeners: typeof events['removeAllListeners'] = events.removeAllListeners.bind( events, ); const proxyvisor = new Proxyvisor(); const localModeManager = new LocalModeManager(); export const router = (() => { const $router = express.Router(); $router.use(express.urlencoded({ extended: true, limit: '10mb' })); $router.use(express.json({ limit: '10mb' })); createV1Api($router); createV2Api($router); $router.use(proxyvisor.router); return $router; })(); export let fetchesInProgress = 0; export let timeSpentFetching = 0; // In the case of intermediate target apply, toggle to true to avoid unintended image deletion let isApplyingIntermediate = false; export function setIsApplyingIntermediate(value: boolean = false) { isApplyingIntermediate = value; } export function resetTimeSpentFetching(value: number = 0) { timeSpentFetching = value; } const actionExecutors = getExecutors({ lockFn: lock, callbacks: { fetchStart: () => { fetchesInProgress += 1; }, fetchEnd: () => { fetchesInProgress -= 1; }, fetchTime: (time) => { timeSpentFetching += time; }, stateReport: (state) => { reportCurrentState(state); }, bestDeltaSource, }, }); export const validActions = Object.keys(actionExecutors); // Volatile state for a single container. This is used for temporarily setting a // different state for a container, such as running: false let targetVolatilePerImageId: { [imageId: number]: Partial<Service['config']>; } = {}; export const initialized = (async () => { await config.initialized; await imageManager.cleanImageData(); const cleanup = async () => { const containers = await docker.listContainers({ all: true }); await logger.clearOutOfDateDBLogs(_.map(containers, 'Id')); }; // Rather than relying on removing out of date database entries when we're no // longer using them, set a task that runs periodically to clear out the database // This has the advantage that if for some reason a container is removed while the // supervisor is down, we won't have zombie entries in the db // Once a day setInterval(cleanup, 1000 * 60 * 60 * 24); // But also run it in on startup await cleanup(); await localModeManager.init(); await serviceManager.attachToRunning(); serviceManager.listenToEvents(); imageManager.on('change', reportCurrentState); serviceManager.on('change', reportCurrentState); })(); export function getDependentState() { return proxyvisor.getCurrentStates(); } function reportCurrentState(data?: Partial<InstancedAppState>) { events.emit('change', data ?? {}); } export async function getRequiredSteps( currentApps: InstancedAppState, targetApps: InstancedAppState, ignoreImages: boolean = false, ): Promise<CompositionStep[]> { // get some required data const [downloading, availableImages] = await Promise.all([ imageManager.getDownloadingImageNames(), imageManager.getAvailable(), ]); const containerIdsByAppId = getAppContainerIds(currentApps); return await inferNextSteps(currentApps, targetApps, { ignoreImages, downloading, availableImages, containerIdsByAppId, }); } // Calculate the required steps from the current to the target state export async function inferNextSteps( currentApps: InstancedAppState, targetApps: InstancedAppState, { ignoreImages = false, downloading = [] as string[], availableImages = [] as Image[], containerIdsByAppId = {} as { [appId: number]: Dictionary<string> }, } = {}, ) { // get some required data const [{ localMode, delta }, cleanupNeeded] = await Promise.all([ config.getMany(['localMode', 'delta']), imageManager.isCleanupNeeded(), ]); if (localMode) { ignoreImages = localMode; } const currentAppIds = Object.keys(currentApps).map((i) => parseInt(i, 10)); const targetAppIds = Object.keys(targetApps).map((i) => parseInt(i, 10)); let steps: CompositionStep[] = []; // First check if we need to create the supervisor network if (!(await networkManager.supervisorNetworkReady())) { // If we do need to create it, we first need to kill any services using the api const killSteps = steps.concat(killServicesUsingApi(currentApps)); if (killSteps.length > 0) { steps = steps.concat(killSteps); } else { steps.push({ action: 'ensureSupervisorNetwork' }); } } else { if (!localMode && downloading.length === 0 && !isApplyingIntermediate) { // Avoid cleaning up dangling images while purging if (cleanupNeeded) { steps.push({ action: 'cleanup' }); } // Detect any images which must be saved/removed, except when purging, // as we only want to remove containers, remove volumes, create volumes // anew, and start containers without images being removed. steps = steps.concat( saveAndRemoveImages( currentApps, targetApps, availableImages, localMode, ), ); } // We want to remove images before moving on to anything else if (steps.length === 0) { const targetAndCurrent = _.intersection(currentAppIds, targetAppIds); const onlyTarget = _.difference(targetAppIds, currentAppIds); const onlyCurrent = _.difference(currentAppIds, targetAppIds); // For apps that exist in both current and target state, calculate what we need to // do to move to the target state for (const id of targetAndCurrent) { steps = steps.concat( currentApps[id].nextStepsForAppUpdate( { localMode, availableImages, containerIds: containerIdsByAppId[id], downloading, }, targetApps[id], ), ); } // For apps in the current state but not target, we call their "destructor" for (const id of onlyCurrent) { steps = steps.concat( await currentApps[id].stepsToRemoveApp({ localMode, downloading, containerIds: containerIdsByAppId[id], }), ); } // For apps in the target state but not the current state, we generate steps to // create the app by mocking an existing app which contains nothing for (const id of onlyTarget) { const { appId } = targetApps[id]; const emptyCurrent = new App( { appId, services: [], volumes: {}, networks: {}, }, false, ); steps = steps.concat( emptyCurrent.nextStepsForAppUpdate( { localMode, availableImages, containerIds: containerIdsByAppId[id] ?? {}, downloading, }, targetApps[id], ), ); } } } const newDownloads = steps.filter((s) => s.action === 'fetch').length; if (!ignoreImages && delta && newDownloads > 0) { // Check that this is not the first pull for an // application, as we want to download all images then // Otherwise we want to limit the downloading of // deltas to constants.maxDeltaDownloads const appImages = _.groupBy(availableImages, 'appId'); let downloadsToBlock = downloading.length + newDownloads - constants.maxDeltaDownloads; steps = steps.filter((step) => { if (step.action === 'fetch' && downloadsToBlock > 0) { const imagesForThisApp = appImages[(step as CompositionStepT<'fetch'>).image.appId]; if (imagesForThisApp == null || imagesForThisApp.length === 0) { // There isn't a valid image for the fetch // step, so we keep it return true; } else { downloadsToBlock -= 1; return false; } } else { return true; } }); } if (!ignoreImages && steps.length === 0 && downloading.length > 0) { // We want to keep the state application alive steps.push(generateStep('noop', {})); } steps = steps.concat( await proxyvisor.getRequiredSteps( availableImages, downloading, currentApps, targetApps, steps, ), ); return steps; } export async function stopAll({ force = false, skipLock = false } = {}) { const services = await serviceManager.getAll(); await Promise.all( services.map(async (s) => { return lock(s.appId, { force, skipLock }, async () => { await serviceManager.kill(s, { removeContainer: false, wait: true }); }); }), ); } // The following two function may look pretty odd, but after the move to uuids, // there's a chance that the current running apps don't have a uuid set. We // still need to be able to work on these and perform various state changes. To // do this we try to use the UUID to group the components, and if that isn't // available we revert to using the appIds instead export async function getCurrentApps(): Promise<InstancedAppState> { const componentGroups = groupComponents( await serviceManager.getAll(), await networkManager.getAll(), await volumeManager.getAll(), ); const apps: InstancedAppState = {}; for (const strAppId of Object.keys(componentGroups)) { const appId = parseInt(strAppId, 10); // TODO: get commit and release version from container const commit = await commitStore.getCommitForApp(appId); const components = componentGroups[appId]; // fetch the correct uuid from any component within the appId const uuid = [ components.services[0]?.appUuid, components.volumes[0]?.appUuid, components.networks[0]?.appUuid, ] .filter((u) => !!u) .shift()!; // If we don't have any components for this app, ignore it (this can // actually happen when moving between backends but maintaining UUIDs) if ( !_.isEmpty(components.services) || !_.isEmpty(components.volumes) || !_.isEmpty(components.networks) ) { apps[appId] = new App( { appId, appUuid: uuid, commit, services: componentGroups[appId].services, networks: _.keyBy(componentGroups[appId].networks, 'name'), volumes: _.keyBy(componentGroups[appId].volumes, 'name'), }, false, ); } } return apps; } type AppGroup = { [appId: number]: { services: Service[]; volumes: Volume[]; networks: Network[]; }; }; function groupComponents( services: Service[], networks: Network[], volumes: Volume[], ): AppGroup { const grouping: AppGroup = {}; const everyComponent: [{ appUuid?: string; appId: number }] = [ ...services, ...networks, ...volumes, ] as any; const allUuids: string[] = []; const allAppIds: number[] = []; everyComponent.forEach(({ appId, appUuid }) => { // Pre-populate the groupings grouping[appId] = { services: [], networks: [], volumes: [], }; // Save all the uuids for later if (appUuid != null) { allUuids.push(appUuid); } allAppIds.push(appId); }); // First we try to group everything by it's uuid, but if any component does // not have a uuid, we fall back to the old appId style if (everyComponent.length === allUuids.length) { const uuidGroups: { [uuid: string]: AppGroup[0] } = {}; new Set(allUuids).forEach((uuid) => { const uuidServices = services.filter( ({ appUuid: sUuid }) => uuid === sUuid, ); const uuidVolumes = volumes.filter( ({ appUuid: vUuid }) => uuid === vUuid, ); const uuidNetworks = networks.filter( ({ appUuid: nUuid }) => uuid === nUuid, ); uuidGroups[uuid] = { services: uuidServices, networks: uuidNetworks, volumes: uuidVolumes, }; }); for (const uuid of Object.keys(uuidGroups)) { // There's a chance that the uuid and the appId is different, and this // is fine. Unfortunately we have no way of knowing which is the "real" // appId (that is the app id which relates to the currently joined // backend) so we instead just choose the first and add everything to that const appId = uuidGroups[uuid].services[0]?.appId || uuidGroups[uuid].networks[0]?.appId || uuidGroups[uuid].volumes[0]?.appId; grouping[appId] = uuidGroups[uuid]; } } else { // Otherwise group them by appId and let the state engine match them later. // This will only happen once, as every target state going forward will // contain UUIDs, we just need to handle the initial upgrade const appSvcs = _.groupBy(services, 'appId'); const appVols = _.groupBy(volumes, 'appId'); const appNets = _.groupBy(networks, 'appId'); _.uniq(allAppIds).forEach((appId) => { grouping[appId].services = grouping[appId].services.concat( appSvcs[appId] || [], ); grouping[appId].networks = grouping[appId].networks.concat( appNets[appId] || [], ); grouping[appId].volumes = grouping[appId].volumes.concat( appVols[appId] || [], ); }); } return grouping; } function killServicesUsingApi(current: InstancedAppState): CompositionStep[] { const steps: CompositionStep[] = []; _.each(current, (app) => { _.each(app.services, (service) => { const isUsingSupervisorAPI = checkTruthy( service.config.labels['io.balena.features.supervisor-api'], ); if (!isUsingSupervisorAPI) { // No need to stop service as it's not using the Supervisor's API return steps; } if (service.status !== 'Stopping') { // Stop this service steps.push(generateStep('kill', { current: service })); } else if (service.status === 'Stopping') { // Wait for the service to finish stopping steps.push(generateStep('noop', {})); } }); }); return steps; } // TODO: deprecate this method. Application changes should use intermediate targets export async function executeStep( step: CompositionStep, { force = false, skipLock = false } = {}, ): Promise<void> { if (proxyvisor.validActions.includes(step.action)) { return proxyvisor.executeStepAction(step); } if (!validActions.includes(step.action)) { return Promise.reject( new InternalInconsistencyError( `Invalid composition step action: ${step.action}`, ), ); } // TODO: Find out why this needs to be cast, the typings should hold true await actionExecutors[step.action]({ ...step, force, skipLock, } as any); } // FIXME: This shouldn't be in this module export async function setTarget( apps: TargetApps, source: string, maybeTrx?: Transaction, ) { const setInTransaction = async ( $filteredApps: TargetApps, trx: Transaction, ) => { await dbFormat.setApps($filteredApps, source, trx); await trx('app') .where({ source }) .whereNotIn( 'appId', // Use apps here, rather than filteredApps, to // avoid removing a release from the database // without an application to replace it. // Currently this will only happen if the release // which would replace it fails a contract // validation check Object.values(apps).map(({ id: appId }) => appId), ) .del(); }; // We look at the container contracts here, as if we // cannot run the release, we don't want it to be added // to the database, overwriting the current release. This // is because if we just reject the release, but leave it // in the db, if for any reason the current state stops // running, we won't restart it, leaving the device // useless - The exception to this rule is when the only // failing services are marked as optional, then we // filter those out and add the target state to the database const contractViolators: { [appName: string]: string[] } = {}; const fulfilledContracts = validateTargetContracts(apps); const filteredApps = _.cloneDeep(apps); _.each( fulfilledContracts, ( { valid, unmetServices, fulfilledServices, unmetAndOptional }, appUuid, ) => { if (!valid) { contractViolators[apps[appUuid].name] = unmetServices; return delete filteredApps[appUuid]; } else { // valid is true, but we could still be missing // some optional containers, and need to filter // these out of the target state const [releaseUuid] = Object.keys(filteredApps[appUuid].releases); if (releaseUuid) { const services = filteredApps[appUuid].releases[releaseUuid].services ?? {}; filteredApps[appUuid].releases[releaseUuid].services = _.pick( services, Object.keys(services).filter((serviceName) => fulfilledServices.includes(serviceName), ), ); } if (unmetAndOptional.length !== 0) { return reportOptionalContainers(unmetAndOptional); } } }, ); let promise; if (maybeTrx != null) { promise = setInTransaction(filteredApps, maybeTrx); } else { promise = transaction((trx) => setInTransaction(filteredApps, trx)); } await promise; targetVolatilePerImageId = {}; if (!_.isEmpty(contractViolators)) { throw new ContractViolationError(contractViolators); } } export async function getTargetApps(): Promise<TargetApps> { const apps = await dbFormat.getTargetJson(); // Whilst it may make sense here to return the target state generated from the // internal instanced representation that we have, we make irreversable // changes to the input target state to avoid having undefined entries into // the instances throughout the supervisor. The target state is derived from // the database entries anyway, so these two things should never be different // (except for the volatile state) // _.each(apps, (app) => // There should only be a single release but is a simpler option _.each(app.releases, (release) => { if (!_.isEmpty(release.services)) { release.services = _.mapValues(release.services, (svc) => { if (svc.image_id && targetVolatilePerImageId[svc.image_id] != null) { return { ...svc, ...targetVolatilePerImageId }; } return svc; }); } }), ); return apps; } export function setTargetVolatileForService( imageId: number, target: Partial<Service['config']>, ) { if (targetVolatilePerImageId[imageId] == null) { targetVolatilePerImageId = {}; } targetVolatilePerImageId[imageId] = target; } export function clearTargetVolatileForServices(imageIds: number[]) { for (const imageId of imageIds) { targetVolatilePerImageId[imageId] = {}; } } export function getDependentTargets() { return proxyvisor.getTarget(); } /** * This is only used by the API. Do not use as the use of serviceIds is getting * deprecated * * @deprecated */ export async function serviceNameFromId(serviceId: number) { // We get the target here as it shouldn't matter, and getting the target is cheaper const targetApps = await getTargetApps(); for (const { releases } of Object.values(targetApps)) { const [release] = Object.values(releases); const services = release?.services ?? {}; const serviceName = Object.keys(services).find( (svcName) => services[svcName].id === serviceId, ); if (!!serviceName) { return serviceName; } } throw new InternalInconsistencyError( `Could not find a service for id: ${serviceId}`, ); } export function localModeSwitchCompletion() { return localModeManager.switchCompletion(); } export function bestDeltaSource( image: Image, available: Image[], ): string | null { if (!image.dependent) { for (const availableImage of available) { if ( availableImage.serviceName === image.serviceName && availableImage.appId === image.appId ) { return availableImage.name; } } } else { // This only makes sense for dependent devices which are still // single app. for (const availableImage of available) { if (availableImage.appId === image.appId) { return availableImage.name; } } } return null; } // We need to consider images for all apps, and not app-by-app, so we handle this here, // rather than in the App class // TODO: This function was taken directly from the old application manager, because it's // complex enough that it's not really worth changing this along with the rest of the // application-manager class. We should make this function much less opaque. // Ideally we'd have images saved against specific apps, and those apps handle the // lifecycle of said image function saveAndRemoveImages( current: InstancedAppState, target: InstancedAppState, availableImages: imageManager.Image[], localMode: boolean, ): CompositionStep[] { type ImageWithoutID = Omit<imageManager.Image, 'dockerImageId' | 'id'>; // imagesToRemove: images that // - are not used in the current state, and // - are not going to be used in the target state, and // - are not needed for delta source / pull caching or would be used for a service with delete-then-download as strategy // imagesToSave: images that // - are locally available (i.e. an image with the same digest exists) // - are not saved to the DB with all their metadata (serviceId, serviceName, etc) const allImageDockerIdsForTargetApp = (app: App) => _(app.services) .map((svc) => [svc.imageName, svc.dockerImageId]) .filter((img) => img[1] != null) .value(); const availableWithoutIds: ImageWithoutID[] = _.map( availableImages, (image) => _.omit(image, ['dockerImageId', 'id']), ); const currentImages = _.flatMap(current, (app) => _.map( app.services, (svc) => _.find(availableImages, { dockerImageId: svc.config.image, // There is no way to compare a current service to an image by // name, the only way to do it is by both commit and service name commit: svc.commit, serviceName: svc.serviceName, }) ?? _.find(availableImages, { dockerImageId: svc.config.image }), ), ) as imageManager.Image[]; const targetServices = Object.values(target).flatMap((app) => app.services); const targetImages = targetServices.map(imageManager.imageFromService); const availableAndUnused = _.filter( availableWithoutIds, (image) => !_.some(currentImages.concat(targetImages), (imageInUse) => { return _.isEqual(image, _.omit(imageInUse, ['dockerImageId', 'id'])); }), ); const imagesToDownload = _.filter( targetImages, (targetImage) => !_.some(availableImages, (available) => imageManager.isSameImage(available, targetImage), ), ); const targetImageDockerIds = _.fromPairs( _.flatMap(target, allImageDockerIdsForTargetApp), ); // Images that are available but we don't have them in the DB with the exact metadata: let imagesToSave: imageManager.Image[] = []; if (!localMode) { imagesToSave = _.filter(targetImages, (targetImage) => { const isActuallyAvailable = _.some(availableImages, (availableImage) => { // There is an image with same image name or digest // on the database if (imageManager.isSameImage(availableImage, targetImage)) { return true; } // The database image doesn't have the same name but has // the same docker id as the target image if ( availableImage.dockerImageId === targetImageDockerIds[targetImage.name] ) { return true; } return false; }); // There is no image in the database with the same metadata const isNotSaved = !_.some(availableWithoutIds, (img) => _.isEqual(img, targetImage), ); // The image is not on the database but we know it exists on the // engine because we could find it through inspectByName const isAvailableOnTheEngine = !!targetImageDockerIds[targetImage.name]; return ( (isActuallyAvailable && isNotSaved) || (!isActuallyAvailable && isAvailableOnTheEngine) ); }); } // Find images that will be be used as delta sources. Any existing image for the // same app service is considered a delta source unless the target service has set // the `delete-then-download` strategy const deltaSources = imagesToDownload .filter( (img) => // We don't need to look for delta sources for delete-then-download // services !targetServices.some( (svc) => imageManager.isSameImage(img, imageManager.imageFromService(svc)) && svc.config.labels['io.balena.update.strategy'] === 'delete-then-download', ), ) .map((img) => bestDeltaSource(img, availableImages)) .filter((img) => img != null); const proxyvisorImages = proxyvisor.imagesInUse(current, target); const imagesToRemove = availableAndUnused.filter((image) => { const notUsedForDelta = !deltaSources.includes(image.name); const notUsedByProxyvisor = !proxyvisorImages.some((proxyvisorImage) => imageManager.isSameImage(image, { name: proxyvisorImage, }), ); return notUsedForDelta && notUsedByProxyvisor; }); return imagesToSave .map((image) => ({ action: 'saveImage', image } as CompositionStep)) .concat(imagesToRemove.map((image) => ({ action: 'removeImage', image }))); } function getAppContainerIds(currentApps: InstancedAppState) { const containerIds: { [appId: number]: Dictionary<string> } = {}; Object.keys(currentApps).forEach((appId) => { const intAppId = parseInt(appId, 10); const app = currentApps[intAppId]; const services = app.services || ([] as Service[]); containerIds[intAppId] = services.reduce( (ids, s) => ({ ...ids, ...(s.serviceName && s.containerId && { [s.serviceName]: s.containerId }), }), {} as Dictionary<string>, ); }); return containerIds; } function reportOptionalContainers(serviceNames: string[]) { // Print logs to the console and dashboard, letting the // user know that we're not going to run certain services // because of their contract const message = `Not running containers because of contract violations: ${serviceNames.join( '. ', )}`; log.info(message); return logger.logSystemMessage( message, {}, 'optionalContainerViolation', true, ); } /** * This will be replaced by ApplicationManager.getState, at which * point the only place this will be used will be in the API endpoints * once, the API moves to v3 or we update the endpoints to return uuids, we will * be able to get rid of this * @deprecated */ export async function getLegacyState() { const [services, images] = await Promise.all([ serviceManager.getState(), imageManager.getState(), ]); const apps: Dictionary<any> = {}; const dependent: Dictionary<any> = {}; let releaseId: number | boolean | null | undefined = null; // ???? const creationTimesAndReleases: Dictionary<any> = {}; // We iterate over the current running services and add them to the current state // of the app they belong to. for (const service of services) { const { appId, imageId } = service; if (!appId) { continue; } if (apps[appId] == null) { apps[appId] = {}; } creationTimesAndReleases[appId] = {}; if (apps[appId].services == null) { apps[appId].services = {}; } // We only send commit if all services have the same release, and it matches the target release if (releaseId == null) { ({ releaseId } = service); } else if (releaseId !== service.releaseId) { releaseId = false; } if (imageId == null) { throw new InternalInconsistencyError( `imageId not defined in ApplicationManager.getLegacyApplicationsState: ${service}`, ); } if (apps[appId].services[imageId] == null) { apps[appId].services[imageId] = _.pick(service, ['status', 'releaseId']); creationTimesAndReleases[appId][imageId] = _.pick(service, [ 'createdAt', 'releaseId', ]); apps[appId].services[imageId].download_progress = null; } else { // There's two containers with the same imageId, so this has to be a handover apps[appId].services[imageId].releaseId = _.minBy( [creationTimesAndReleases[appId][imageId], service], 'createdAt', ).releaseId; apps[appId].services[imageId].status = 'Handing over'; } } for (const image of images) { const { appId } = image; if (!image.dependent) { if (apps[appId] == null) { apps[appId] = {}; } if (apps[appId].services == null) { apps[appId].services = {}; } if (apps[appId].services[image.imageId] == null) { apps[appId].services[image.imageId] = _.pick(image, [ 'status', 'releaseId', ]); apps[appId].services[image.imageId].download_progress = image.downloadProgress; } } else if (image.imageId != null) { if (dependent[appId] == null) { dependent[appId] = {}; } if (dependent[appId].images == null) { dependent[appId].images = {}; } dependent[appId].images[image.imageId] = _.pick(image, ['status']); dependent[appId].images[image.imageId].download_progress = image.downloadProgress; } else { log.debug('Ignoring legacy dependent image', image); } } return { local: apps, dependent }; } // TODO: this function is probably more inefficient than it needs to be, since // it tried to optimize for readability, look for a way to make it simpler export async function getState() { const [services, images] = await Promise.all([ serviceManager.getState(), imageManager.getState(), ]); type ServiceInfo = { appId: number; appUuid: string; commit: string; serviceName: string; createdAt?: Date; } & ServiceState; // Get service data from images const stateFromImages: ServiceInfo[] = images.map( ({ appId, appUuid, name, commit, serviceName, status, downloadProgress, }) => ({ appId, appUuid, image: name, commit, serviceName, status: status as string, ...(Number.isInteger(downloadProgress) && { download_progress: downloadProgress, }), }), ); // Get all services and augment service data from the image if any const stateFromServices = services .map(({ appId, appUuid, commit, serviceName, status, createdAt }) => [ // Only include appUuid if is available, if not available we'll get it from the image { appId, ...(appUuid && { appUuid }), commit, serviceName, status, createdAt, }, // Get the corresponding image to augment the service data stateFromImages.find( (img) => img.serviceName === serviceName && img.commit === commit, ), ]) // We cannot report services that do not have an image as the API // requires passing the image name .filter(([, img]) => !!img) .map(([svc, img]) => ({ ...img, ...svc } as ServiceInfo)) .map((svc, __, serviceList) => { // If the service is not running it cannot be a handover if (svc.status !== 'Running') { return svc; } // If there one or more running services with the same name and appUuid, but different // release, then we are still handing over so we need to report the appropriate // status const siblings = serviceList.filter( (s) => s.appUuid === svc.appUuid && s.serviceName === svc.serviceName && s.status === 'Running' && s.commit !== svc.commit, ); // There should really be only one element on the `siblings` array, but // we chose the oldest service to have its status reported as 'Handing over' if ( siblings.length > 0 && siblings.every((s) => svc.createdAt!.getTime() < s.createdAt!.getTime()) ) { return { ...svc, status: 'Handing over' }; } else if (siblings.length > 0) { return { ...svc, status: 'Awaiting handover' }; } return svc; }); const servicesToReport = // The full list of services is the union of images that have no container created yet stateFromImages .filter( (img) => !stateFromServices.some( (svc) => img.serviceName === svc.serviceName && img.commit === svc.commit, ), ) // With the services that have a container .concat(stateFromServices); // Get the list of commits for all appIds from the database const commitsForApp = ( await Promise.all( // Deduplicate appIds first [...new Set(servicesToReport.map((svc) => svc.appId))].map( async (appId) => ({ [appId]: await commitStore.getCommitForApp(appId), }), ), ) ).reduce((commits, c) => ({ ...commits, ...c }), {}); // Assemble the state of apps return servicesToReport.reduce( (apps, { appId, appUuid, commit, serviceName, createdAt, ...svc }) => ({ ...apps, [appUuid]: { ...(apps[appUuid] ?? {}), // Add the release_uuid if the commit has been stored in the database ...(commitsForApp[appId] && { release_uuid: commitsForApp[appId] }), releases: { ...(apps[appUuid]?.releases ?? {}), [commit]: { ...(apps[appUuid]?.releases[commit] ?? {}), services: { ...(apps[appUuid]?.releases[commit]?.services ?? {}), [serviceName]: svc, }, }, }, }, }), {} as { [appUuid: string]: AppState }, ); }
the_stack
import {ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild} from '@angular/core'; import {Subject, Subscription} from 'rxjs'; import {DeepLeftNodeChild} from '../../modules/utils/deep-left-node-child'; import {DeepRightNodeChild} from '../../modules/utils/deep-right-node-child'; import {FirstSubStringNode} from '../../modules/utils/first-sub-string-node'; import {CaretStartEndPosition} from '../../modules/utils/node/caret-start-end-position'; import {CursorLeftCoordinate} from '../../modules/utils/node/cursor-left-coordinate'; import {CursorPositionInLine} from '../../modules/utils/node/cursor-position-in-line'; import {PlaceCaretToPosition} from '../../modules/utils/node/place-caret-to-position'; import {StringWithoutEmptyNodes} from '../../modules/utils/node/string-without-empty-nodes'; import {disableViewTransactionProcessing} from '../../wall/components/wall/wall-view.model'; import {IFocusContext, IOnWallFocus, IOnWallStateChange, IWallComponent, IWallModel, IWallUiApi} from '../../wall/wall'; import { BACK_SPACE_KEY, BACK_SPACE_KEY_CODE_ANDROID, BOTTOM_KEY, DELETE_KEY, ENTER_KEY, ENTER_KEY_CODE_ANDROID, ESCAPE_KEY, FOCUS_INITIATOR, LEFT_KEY, NUMPUB_ENTER_KEY, RIGHT_KEY, TAB_KEY, TOP_KEY } from './base-text-brick.constant'; import {IBaseTextState} from './base-text-state.interface'; import {BottomKeyHandler} from './keypress-handlers/bottom-key.handler'; import {EnterKeyHandler} from './keypress-handlers/enter-key.handler'; import {LeftKeyHandler} from './keypress-handlers/left-key.handler'; import {RightKeyHandler} from './keypress-handlers/right-key.handler'; import {TopKeyHandler} from './keypress-handlers/top-key.handler'; enum LineType { first = 'FIRST', last = 'LAST' } export interface ICursorPositionInLine { isOnLastLine: boolean; isOnFirstLine: boolean; } export abstract class BaseTextBrickComponent implements OnInit, OnDestroy, IOnWallStateChange, IOnWallFocus, IWallComponent { @Input() id: string; @Input() state: IBaseTextState; @Input() wallModel: IWallModel; @Output() stateChanges: EventEmitter<IBaseTextState> = new EventEmitter(); @ViewChild('editor') editor: ElementRef; keypressHandlers = { top: new TopKeyHandler(this), enter: new EnterKeyHandler(this), left: new LeftKeyHandler(this), right: new RightKeyHandler(this), bottom: new BottomKeyHandler(this) }; wallUiApi: IWallUiApi; scope: IBaseTextState = { text: '', tabs: 0 }; maxTabNumber = 3; textChange: Subject<string> = new Subject(); textChangeSubscription: Subscription; onPasteBound: (e: ClipboardEvent) => any; ngOnInit() { if (this.state && this.state.text !== this.scope.text) { this.setTextState(this.state.text); } this.scope.tabs = this.state.tabs || 0; this.onPasteBound = this.onPaste.bind(this); this.editor.nativeElement.addEventListener('paste', this.onPasteBound); this.textChangeSubscription = this.textChange.subscribe(() => { this.setTextState(this.scope.text); this.saveCurrentState(); }); this.wallUiApi = this.wallModel.api.ui; } onWallStateChange(newState: IBaseTextState) { this.scope.tabs = this.state.tabs || this.scope.tabs; if (newState && newState.text !== this.scope.text) { this.setTextState(newState.text); } } ngOnDestroy() { this.editor.nativeElement.removeEventListener('paste', this.onPasteBound); this.textChangeSubscription.unsubscribe(); } onPaste(e: ClipboardEvent) { e.preventDefault(); const textArr = e.clipboardData.getData('text/plain') .split('\n') .map((str) => str.trim()) .filter((str) => str.length); if (textArr.length === 1) { document.execCommand('insertHTML', false, textArr[0]); } else if (textArr.length > 1) { // todo: add interface for UI api textArr.reverse().forEach((text) => this.wallModel.api.core2.addBrickAfterBrickId(this.id, 'text', {text})); } } onTextChange() { this.textChange.next(this.scope.text); } // general handler of all key events onKeyPress(e: KeyboardEvent) { if (this.isAnyMetaKeyPressed(e)) { return; } if (e.code === TOP_KEY) { this.topKeyPressed(e); } if (e.code === BOTTOM_KEY) { this.bottomKeyPressed(e); } if (e.code === LEFT_KEY && this.isCaretAtStart()) { this.leftKeyPressed(e); } if (e.code === RIGHT_KEY && this.isCaretAtEnd()) { this.rightKeyPressed(e); } if (e.code === ENTER_KEY || e.keyCode === ENTER_KEY_CODE_ANDROID || e.code === NUMPUB_ENTER_KEY) { this.enterKeyPressed(e); } if (e.keyCode === ESCAPE_KEY) { this.escapeKeyPressed(e); } if ((e.code === BACK_SPACE_KEY || e.keyCode === BACK_SPACE_KEY_CODE_ANDROID) && !this.isTextSelected()) { this.backSpaceKeyPressed(e); } if (e.code === DELETE_KEY && this.scope.text.length && this.isCaretAtEnd() && !this.isTextSelected()) { this.concatWithNextTextSupportingBrick(e); } if (e.code === TAB_KEY && this.isCaretAtStart()) { this.onTabPressed(e); } if (e.code === DELETE_KEY && this.scope.text === '') { this.onDeleteAndFocusToNext(e); } } proxyToKeyHandler(keyHandlerName: string, e: KeyboardEvent) { this.keypressHandlers[keyHandlerName].execute(e); } // key handler topKeyPressed(e: KeyboardEvent) { this.proxyToKeyHandler('top', e); } bottomKeyPressed(e: KeyboardEvent) { this.proxyToKeyHandler('bottom', e); } enterKeyPressed(e: KeyboardEvent) { this.proxyToKeyHandler('enter', e); } leftKeyPressed(e: KeyboardEvent) { this.proxyToKeyHandler('left', e); } rightKeyPressed(e) { this.proxyToKeyHandler('right', e); } escapeKeyPressed(e: KeyboardEvent) { // do nothing } onTabPressed(e: KeyboardEvent) { e.preventDefault(); this.increaseTab(); this.saveCurrentState(); } backSpaceKeyPressed(e: KeyboardEvent) { if (this.isCaretAtStart()) { if (this.scope.tabs) { this.decreaseTab(); this.saveCurrentState(); } else { if (this.scope.text.length) { this.concatWithPreviousTextSupportingBrick(e); } else { this.onDeleteAndFocusToPrevious(e); } } } } // end key handlers isCaretAtFirstLine(): boolean { return this.getCursorPositionInLine().isOnFirstLine; } isCaretAtLastLine(): boolean { return this.getCursorPositionInLine().isOnLastLine; } getCaretLeftCoordinate(): number { const sel = window.getSelection(); const leftRightText = this.getSplittedText(sel.focusOffset, sel.focusNode); return (new CursorLeftCoordinate(leftRightText.left, leftRightText.right, this.editor.nativeElement)).get(); } getCursorPositionInLine(): ICursorPositionInLine { const sel = window.getSelection(); const leftRightText = this.getSplittedText(sel.focusOffset, sel.focusNode); return new CursorPositionInLine(leftRightText.left, leftRightText.right, this.editor.nativeElement); } concatWithPreviousTextSupportingBrick(e) { const previousTextBrickId = this.wallModel.api.core2.getPreviousTextBrickId(this.id); if (previousTextBrickId) { e.preventDefault(); const previousBrickSnapshot = this.wallModel.api.core2.getBrickSnapshot(previousTextBrickId); this.wallModel.api.core2.updateBrickState(previousTextBrickId, { text: this.cleanUpText(previousBrickSnapshot.state.text) + this.scope.text }); // wait for component re-rendering setTimeout(() => { const focusContext: IFocusContext = { initiator: FOCUS_INITIATOR, details: { concatText: true, concatenationText: this.scope.text } }; // this.wallUiApi.focusOnBrickId(previousTextBrickId, focusContext); this.wallUiApi.mode.edit.focusOnBrickId(previousTextBrickId, focusContext); // remove only after focus will be established // that prevents flickering on mobile this.wallModel.api.core2.removeBrick(this.id, disableViewTransactionProcessing); }); } } concatWithNextTextSupportingBrick(e: Event) { const nextTextBrickId = this.wallModel.api.core2.getNextTextBrickId(this.id); if (nextTextBrickId) { e.preventDefault(); const nextTextBrickSnapshot = this.wallModel.api.core2.getBrickSnapshot(nextTextBrickId); const concatenationText = nextTextBrickSnapshot.state.text || ''; this.setTextState(this.scope.text + concatenationText); this.saveCurrentState(); this.wallModel.api.core2.removeBrick(nextTextBrickId, disableViewTransactionProcessing); setTimeout(() => { this.placeCaretBaseOnConcatenatedText(concatenationText); }, 10); } } onDeleteAndFocusToPrevious(e: KeyboardEvent) { e.preventDefault(); const previousTextBrickId = this.wallModel.api.core2.getPreviousTextBrickId(this.id); const nextTextBrickId = this.wallModel.api.core2.getNextBrickId(this.id); this.wallModel.api.core2.removeBrick(this.id, disableViewTransactionProcessing); if (previousTextBrickId || nextTextBrickId) { const focusContext: IFocusContext = { initiator: FOCUS_INITIATOR, details: { deletePreviousText: true } }; this.wallUiApi.mode.edit.focusOnBrickId(previousTextBrickId || nextTextBrickId, focusContext); } else { // there is any text brick on the page, add default one const newTextBrick = this.wallModel.api.core2.addDefaultBrick(); // wait until it will be rendered setTimeout(() => { this.wallUiApi.mode.edit.focusOnBrickId(newTextBrick.id); }); } } onDeleteAndFocusToNext(e: KeyboardEvent) { e.preventDefault(); const nextTextBrickId = this.wallModel.api.core2.getNextTextBrickId(this.id); if (nextTextBrickId) { this.wallModel.api.core2.removeBrick(this.id, disableViewTransactionProcessing); const focusContext: IFocusContext = { initiator: FOCUS_INITIATOR, details: { deletePreviousText: true } }; this.wallUiApi.mode.edit.focusOnBrickId(nextTextBrickId, focusContext); } } getSplittedText(offset: number, target: Node): { left: string, right: string } { return { left: this.scope.text.slice(0, offset), right: this.scope.text.slice(offset) || '' }; } // key handler end onWallFocus(context?: IFocusContext): void { console.log(`onWallFocus`); if (this.editor.nativeElement === document.activeElement) { return; } // focus by API call this.editor.nativeElement.focus(); if (!context || context.initiator !== FOCUS_INITIATOR) { return; } if (context.details.deletePreviousText) { this.placeCaretAtEnd(); } if (context.details.concatText) { this.placeCaretBaseOnConcatenatedText(context.details.concatenationText); } if (context.details.leftKey) { this.placeCaretAtEnd(); } if (context.details.rightKey) { this.placeCaretAtStart(); } if (context.details.bottomKey || context.details.topKey) { const line = context.details.bottomKey ? LineType.first : LineType.last; this.placeCaretAtLeftCoordinate(context.details.caretLeftCoordinate, line); } } setTextState(text: string = '') { this.scope.text = this.cleanUpText(text); } increaseTab() { if (this.scope.tabs < this.maxTabNumber) { this.scope.tabs++; } } decreaseTab() { if (this.scope.tabs > 0) { this.scope.tabs--; } } saveCurrentState() { this.stateChanges.emit(this.scope); } // caret helpers isTextSelected(): boolean { return !window.getSelection().isCollapsed; } placeCaretAtStart(): void { const deepLeftNode = new DeepLeftNodeChild(this.editor.nativeElement); this.placeCaretAtNodeStart(deepLeftNode.child); } placeCaretAtEnd(): void { const rightNode = new DeepRightNodeChild(this.editor.nativeElement); this.placeCaretAtNodeEnd(rightNode.child); } placeCaretAtNodeStart(el: Node) { this.placeCaretAtNodeToPosition(el, 0); } placeCaretAtNodeEnd(el: Node) { this.placeCaretAtNodeToPosition(el, el.textContent.length); } placeCaretAtNodeToPosition(el: Node, position: number) { (new PlaceCaretToPosition(el, position)).place(); } // find the node which contains concatenated text and position in this node where cursor should be placed placeCaretBaseOnConcatenatedText(concatenationText: string) { if (concatenationText !== '') { // find first level nodes for the text that was concatenated const subStringNodes = new FirstSubStringNode( this.editor.nativeElement, concatenationText ); // first level node which contains concatenated text const firstLevelSubStringNode = subStringNodes.firstLevelSubStringNodes[0]; if (firstLevelSubStringNode) { let focusNode; let position; if (firstLevelSubStringNode.nodeType === Node.TEXT_NODE) { // if first concatenated node is TEXT_NODE it might // be automatically concatenated with previous existing TEXT_NODE focusNode = firstLevelSubStringNode; // find text content for first concatenated TEXT_NODE const p = document.createElement('P'); p.innerHTML = concatenationText; const firstLevelSubStringTextContent = p.childNodes[0].textContent; // finally find cursor position position = focusNode.textContent.length - firstLevelSubStringTextContent.length; } else { focusNode = new DeepLeftNodeChild(firstLevelSubStringNode).child; position = 0; } this.placeCaretAtNodeToPosition(focusNode, position); } } } placeCaretAtLeftCoordinate(leftCoordinate: number, line: string) { // todo: find the way to set caret based on coordinate number if (line === LineType.last) { this.placeCaretAtEnd(); // this.placeCaretAtStart(); } else { this.placeCaretAtStart(); } } isCaretAtStart(): boolean { return (new CaretStartEndPosition(this.editor.nativeElement)).isCaretAtStart(); } isCaretAtEnd(): boolean { return (new CaretStartEndPosition(this.editor.nativeElement)).isCaretAtEnd(); } // remove all unnecessary tags cleanUpText(text: string): string { return (new StringWithoutEmptyNodes(text)).get(); } private isAnyMetaKeyPressed(e: KeyboardEvent): boolean { return e.shiftKey || e.altKey || e.ctrlKey || e.metaKey; } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/secretMappers"; import * as Parameters from "../models/parameters"; import { ServiceFabricMeshManagementClientContext } from "../serviceFabricMeshManagementClientContext"; /** Class representing a Secret. */ export class Secret { private readonly client: ServiceFabricMeshManagementClientContext; /** * Create a Secret. * @param {ServiceFabricMeshManagementClientContext} client Reference to the service client. */ constructor(client: ServiceFabricMeshManagementClientContext) { this.client = client; } /** * Creates a secret resource with the specified name, description and properties. If a secret * resource with the same name exists, then it is updated with the specified description and * properties. * @summary Creates or updates a secret resource. * @param resourceGroupName Azure resource group name * @param secretResourceName The name of the secret resource. * @param secretResourceDescription Description for creating a secret resource. * @param [options] The optional parameters * @returns Promise<Models.SecretCreateResponse> */ create(resourceGroupName: string, secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, options?: msRest.RequestOptionsBase): Promise<Models.SecretCreateResponse>; /** * @param resourceGroupName Azure resource group name * @param secretResourceName The name of the secret resource. * @param secretResourceDescription Description for creating a secret resource. * @param callback The callback */ create(resourceGroupName: string, secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void; /** * @param resourceGroupName Azure resource group name * @param secretResourceName The name of the secret resource. * @param secretResourceDescription Description for creating a secret resource. * @param options The optional parameters * @param callback The callback */ create(resourceGroupName: string, secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void; create(resourceGroupName: string, secretResourceName: string, secretResourceDescription: Models.SecretResourceDescription, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescription>, callback?: msRest.ServiceCallback<Models.SecretResourceDescription>): Promise<Models.SecretCreateResponse> { return this.client.sendOperationRequest( { resourceGroupName, secretResourceName, secretResourceDescription, options }, createOperationSpec, callback) as Promise<Models.SecretCreateResponse>; } /** * Gets the information about the secret resource with the given name. The information include the * description and other properties of the secret. * @summary Gets the secret resource with the given name. * @param resourceGroupName Azure resource group name * @param secretResourceName The name of the secret resource. * @param [options] The optional parameters * @returns Promise<Models.SecretGetResponse> */ get(resourceGroupName: string, secretResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretGetResponse>; /** * @param resourceGroupName Azure resource group name * @param secretResourceName The name of the secret resource. * @param callback The callback */ get(resourceGroupName: string, secretResourceName: string, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void; /** * @param resourceGroupName Azure resource group name * @param secretResourceName The name of the secret resource. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, secretResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescription>): void; get(resourceGroupName: string, secretResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescription>, callback?: msRest.ServiceCallback<Models.SecretResourceDescription>): Promise<Models.SecretGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, secretResourceName, options }, getOperationSpec, callback) as Promise<Models.SecretGetResponse>; } /** * Deletes the secret resource identified by the name. * @summary Deletes the secret resource. * @param resourceGroupName Azure resource group name * @param secretResourceName The name of the secret resource. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, secretResourceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName Azure resource group name * @param secretResourceName The name of the secret resource. * @param callback The callback */ deleteMethod(resourceGroupName: string, secretResourceName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName Azure resource group name * @param secretResourceName The name of the secret resource. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, secretResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, secretResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, secretResourceName, options }, deleteMethodOperationSpec, callback); } /** * Gets the information about all secret resources in a given resource group. The information * include the description and other properties of the Secret. * @summary Gets all the secret resources in a given resource group. * @param resourceGroupName Azure resource group name * @param [options] The optional parameters * @returns Promise<Models.SecretListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretListByResourceGroupResponse>; /** * @param resourceGroupName Azure resource group name * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): void; /** * @param resourceGroupName Azure resource group name * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): Promise<Models.SecretListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.SecretListByResourceGroupResponse>; } /** * Gets the information about all secret resources in a given resource group. The information * include the description and other properties of the secret. * @summary Gets all the secret resources in a given subscription. * @param [options] The optional parameters * @returns Promise<Models.SecretListBySubscriptionResponse> */ listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.SecretListBySubscriptionResponse>; /** * @param callback The callback */ listBySubscription(callback: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): void; listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): Promise<Models.SecretListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec, callback) as Promise<Models.SecretListBySubscriptionResponse>; } /** * Gets the information about all secret resources in a given resource group. The information * include the description and other properties of the Secret. * @summary Gets all the secret resources in a given resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.SecretListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): Promise<Models.SecretListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.SecretListByResourceGroupNextResponse>; } /** * Gets the information about all secret resources in a given resource group. The information * include the description and other properties of the secret. * @summary Gets all the secret resources in a given subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.SecretListBySubscriptionNextResponse> */ listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.SecretListBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): void; listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SecretResourceDescriptionList>, callback?: msRest.ServiceCallback<Models.SecretResourceDescriptionList>): Promise<Models.SecretListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionNextOperationSpec, callback) as Promise<Models.SecretListBySubscriptionNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const createOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/secrets/{secretResourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.secretResourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "secretResourceDescription", mapper: { ...Mappers.SecretResourceDescription, required: true } }, responses: { 200: { bodyMapper: Mappers.SecretResourceDescription }, 201: { bodyMapper: Mappers.SecretResourceDescription }, 202: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/secrets/{secretResourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.secretResourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SecretResourceDescription }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/secrets/{secretResourceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.secretResourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/secrets", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SecretResourceDescriptionList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabricMesh/secrets", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SecretResourceDescriptionList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SecretResourceDescriptionList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer }; const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SecretResourceDescriptionList }, default: { bodyMapper: Mappers.ErrorModel } }, serializer };
the_stack
import * as debug from "debug"; import { PreventIframe } from "express-msteams-host"; import { TurnContext, CardFactory, MessagingExtensionQuery, MessagingExtensionResult, MessagingExtensionAction, ActionTypes, MessagingExtensionAttachment } from "botbuilder"; // import { MessagingExtensionQuery, MessagingExtensionResult } from "botbuilder-teams"; import { IMessagingExtensionMiddlewareProcessor } from "botbuilder-teams-messagingextensions"; import { JsonDB } from 'node-json-db'; import { IDocument } from "../../model/IDocument"; import GraphController from "../../controller/GraphController"; // Initialize debug logging module const log = debug("msteams"); @PreventIframe("/documentReviewMessageMessageExtension/config.html") export default class DocumentReviewMessageMessageExtension implements IMessagingExtensionMiddlewareProcessor { private connectionName = process.env.ConnectionName; private documents: IDocument[]; public async onQuery(context: TurnContext, query: MessagingExtensionQuery): Promise<MessagingExtensionResult> { const attachments: MessagingExtensionAttachment[] = []; const adapter: any = context.adapter; const magicCode = (query.state && Number.isInteger(Number(query.state))) ? query.state : ''; const tokenResponse = await adapter.getUserToken(context, this.connectionName, magicCode); if (!tokenResponse || !tokenResponse.token) { // There is no token, so the user has not signed in yet. // Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions const signInLink = await adapter.getSignInLink(context, this.connectionName); let composeExtension: MessagingExtensionResult = { type: 'config', suggestedActions: { actions: [{ title: 'Sign in as user', value: signInLink, type: ActionTypes.OpenUrl }] } }; return Promise.resolve(composeExtension); } let documents: IDocument[] = []; if (query.parameters && query.parameters[0] && query.parameters[0].name === "initialRun") { const controller = new GraphController(); const configFilename = process.env.CONFIG_FILENAME; const settings = new JsonDB(configFilename ? configFilename : "settings", true, false); let siteID: string; let listID: string; try { siteID = settings.getData(`/${context.activity.channelData.tenant.id}/${context.activity.channelData.team.id}/${context.activity.channelData.channel.id}/siteID`); listID = settings.getData(`/${context.activity.channelData.tenant.id}/${context.activity.channelData.team.id}/${context.activity.channelData.channel.id}/listID`); } catch (err) { siteID = process.env.SITE_ID ? process.env.SITE_ID : ''; listID = process.env.LIST_ID ? process.env.LIST_ID : ''; } documents = await controller.getFiles(tokenResponse.token, siteID, listID); this.documents = documents; } else { if (query.parameters && query.parameters[0]) { const srchStr = query.parameters[0].value; documents = this.documents.filter(doc => doc.name.indexOf(srchStr) > -1 || doc.description.indexOf(srchStr) > -1 || doc.author.indexOf(srchStr) > -1 || doc.url.indexOf(srchStr) > -1 || doc.modified.toLocaleString().indexOf(srchStr) > -1 ); } } documents.forEach((doc) => { const today = new Date(); const nextReview = new Date(today.setDate(today.getDate() + 180)); const minNextReview = new Date(today.setDate(today.getDate() + 30)); const card = CardFactory.adaptiveCard( { type: "AdaptiveCard", body: [ { type: "ColumnSet", columns: [ { type: "Column", width: 25, items: [ { type: "Image", url: `https://${process.env.HOSTNAME}/assets/icon.png`, style: "Person" } ] }, { type: "Column", width: 75, items: [ { type: "TextBlock", text: doc.name, size: "Large", weight: "Bolder" }, { type: "TextBlock", text: doc.description, size: "Medium" }, { type: "TextBlock", text: `Author: ${doc.author}` }, { type: "TextBlock", text: `Modified: ${doc.modified.toLocaleDateString()}` } ] } ] } ], actions: [ { type: "Action.OpenUrl", title: "View", url: doc.url }, { type: "Action.ShowCard", title: "Review", card: { type: "AdaptiveCard", body: [ { type: "Input.Text", isVisible: false, value: doc.id, id: "id" }, { type: "Input.Text", isVisible: false, value: "reviewed", id: "action" }, { type: "Input.Date", id: "nextReview", value: nextReview.toLocaleDateString(), min: minNextReview.toLocaleDateString(), spacing: "Medium" } ], actions: [ { type: "Action.Submit", title: "Reviewed" } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", version: "1.0" } } ], $schema: "http://adaptivecards.io/schemas/adaptive-card.json", version: "1.0" }); const preview = { contentType: "application/vnd.microsoft.card.thumbnail", content: { title: doc.name, text: doc.description, images: [ { url: `https://${process.env.HOSTNAME}/assets/icon.png` } ] } }; attachments.push({ contentType: card.contentType, content: card.content, preview: preview }); }); return Promise.resolve({ type: "result", attachmentLayout: "list", attachments: attachments } as MessagingExtensionResult); } public async onCardButtonClicked(context: TurnContext, value: any): Promise<void> { const adapter: any = context.adapter; const magicCode = (value.state && Number.isInteger(Number(value.state))) ? value.state : ''; const tokenResponse = await adapter.getUserToken(context, this.connectionName, magicCode); if (!tokenResponse || !tokenResponse.token) { // There is no token, so the user has not signed in yet. return Promise.reject(); } // Handle the Action.Submit action on the adaptive card if (value.action === "reviewed") { const controller = new GraphController(); const siteID: string = process.env.SITE_ID ? process.env.SITE_ID : ''; const listID: string = process.env.LIST_ID ? process.env.LIST_ID : ''; let nextReview: Date; if (value.nextReview === null || value.nextReview === '') { const today = new Date(); nextReview = new Date(today.setDate(today.getDate() + 180)); } else { nextReview = new Date(value.nextReview); } controller.updateItem(tokenResponse.token, siteID, listID, value.id, nextReview.toString()) // For testing purposes sign out again .then(() => { adapter.signOutUser(context, this.connectionName); }); } return Promise.resolve(); } // this is used when canUpdateConfiguration is set to true public async onQuerySettingsUrl(context: TurnContext): Promise<{ title: string, value: string }> { const configFilename = process.env.CONFIG_FILENAME; const settings = new JsonDB(configFilename ? configFilename : "settings", true, false); let siteID: string; let listID: string; try { siteID = settings.getData(`/${context.activity.channelData.tenant.id}/${context.activity.channelData.team.id}/${context.activity.channelData.channel.id}/siteID`); listID = settings.getData(`/${context.activity.channelData.tenant.id}/${context.activity.channelData.team.id}/${context.activity.channelData.channel.id}/listID`); } catch (err) { siteID = process.env.SITE_ID ? process.env.SITE_ID : ''; listID = process.env.LIST_ID ? process.env.LIST_ID : ''; } return Promise.resolve({ title: "Document Review Message Configuration", value: `https://${process.env.HOSTNAME}/documentReviewMessageMessageExtension/config.html?siteID=${siteID}&listID=${listID}` }); } public async onSettings(context: TurnContext): Promise<void> { // take care of the setting returned from the dialog, with the value stored in state const setting = JSON.parse(context.activity.value.state); log(`New setting: ${setting}`); const configFilename = process.env.CONFIG_FILENAME; const settings = new JsonDB(configFilename ? configFilename : "settings", true, false); settings.push(`/${context.activity.channelData.tenant.id}/${context.activity.channelData.team.id}/${context.activity.channelData.channel.id}`, setting, false); return Promise.resolve(); } }
the_stack
import { IdType, Point, TestData, addMoreEdges, generateMaryTree, } from "../helpers"; /** * Generate a consecutive list of ids starting with first and ending with last * including both. * * @param first - Number of the first id to generate. * @param last - Number of the last id to generate. * * @returns An array of ids for example `"node0"` or `"node789"`. */ function nodeIdRange(first: number, last: number): IdType[] { return new Array(1 + last - first) .fill(null) .map((_, i): IdType => `node${first + i}`); } describe("Directed hierarchical layout", (): void => { const configs: { /** * The name that will be displayed by Cypress for given test. */ name: string; /** * Data in the same format as in `new Network(container, data, options);`. */ data: TestData; /** * Each member of this list clusters more nodes. Swallows edges refers to * how many edges disappear from the network thanks to the newly created * cluster. * * @remarks The result of this is accumulated. For example for three lists * of node ids four tests will be run: One with no clusters, one with first * cluster, one with first and second and one with first through third * clusters. */ clusterConfigs?: { nodes: IdType[]; swallowsEdges: number }[]; /** * This skips some checks that just can't be passed by a cyclic graph. */ cyclic: boolean; }[] = [ { name: "Binary tree", data: generateMaryTree(63, 2), clusterConfigs: [{ nodes: nodeIdRange(3, 6), swallowsEdges: 2 }], cyclic: false, }, { name: "5-ary tree", data: generateMaryTree(156, 5), clusterConfigs: [ { nodes: [ ...nodeIdRange(2, 3), ...nodeIdRange(11, 20), ...nodeIdRange(56, 105), ], swallowsEdges: 61, }, ], cyclic: false, }, { name: "Acyclic graph", data: addMoreEdges(generateMaryTree(63, 2)), clusterConfigs: [ { nodes: [ ...nodeIdRange(2, 3), ...nodeIdRange(11, 20), ...nodeIdRange(56, 62), ], swallowsEdges: 31, }, ], cyclic: false, }, { name: "Cyclic graph (2 nodes)", data: { nodes: [ { id: "node0", label: "Node #0" }, { id: "node1", label: "Node #1" }, ], edges: [ { id: "edge_node0-node1", from: "node0", to: "node1" }, { id: "edge_node1-node0", from: "node1", to: "node0" }, ], }, cyclic: true, }, { name: "Cyclic graph (10 nodes)", data: { nodes: [ { id: "node0", label: "Node #0" }, { id: "node1", label: "Node #1" }, { id: "node2", label: "Node #2" }, { id: "node3", label: "Node #3" }, { id: "node4", label: "Node #4" }, { id: "node5", label: "Node #5" }, { id: "node6", label: "Node #6" }, { id: "node7", label: "Node #7" }, { id: "node8", label: "Node #8" }, { id: "node9", label: "Node #9" }, ], edges: [ { id: "edge_node1-node0", from: "node1", to: "node0" }, { id: "edge_node0-node1", from: "node0", to: "node1" }, { id: "edge_node1-node2", from: "node1", to: "node2" }, { id: "edge_node2-node3", from: "node2", to: "node3" }, { id: "edge_node3-node4", from: "node3", to: "node4" }, { id: "edge_node4-node5", from: "node4", to: "node5" }, { id: "edge_node5-node6", from: "node5", to: "node6" }, { id: "edge_node6-node7", from: "node6", to: "node7" }, { id: "edge_node7-node8", from: "node7", to: "node8" }, { id: "edge_node8-node9", from: "node8", to: "node9" }, ], }, cyclic: true, }, { name: "Linear", data: { nodes: [ { id: "node0", label: "Node #0" }, { id: "node1", label: "Node #1" }, { id: "node2", label: "Node #2" }, { id: "node3", label: "Node #3" }, { id: "node4", label: "Node #4" }, { id: "node5", label: "Node #5" }, { id: "node6", label: "Node #6" }, { id: "node7", label: "Node #7" }, { id: "node8", label: "Node #8" }, { id: "node9", label: "Node #9" }, ], edges: [ { id: "edge_node0-node1", from: "node0", to: "node1" }, { id: "edge_node1-node2", from: "node1", to: "node2" }, { id: "edge_node2-node3", from: "node2", to: "node3" }, { id: "edge_node3-node4", from: "node3", to: "node4" }, { id: "edge_node4-node5", from: "node4", to: "node5" }, { id: "edge_node5-node6", from: "node5", to: "node6" }, { id: "edge_node6-node7", from: "node6", to: "node7" }, { id: "edge_node7-node8", from: "node7", to: "node8" }, { id: "edge_node8-node9", from: "node8", to: "node9" }, ], }, clusterConfigs: [ { nodes: ["node1"], swallowsEdges: 0 }, { nodes: ["node2", "node3"], swallowsEdges: 1 }, { nodes: ["node6", "node7", "node8"], swallowsEdges: 2 }, ], cyclic: false, }, ]; configs.forEach(({ clusterConfigs, cyclic, data, name }): void => { const configs = [ { nodes: [], swallowsEdges: 0 }, ...(clusterConfigs || []), ].map( ( { nodes }, i, arr ): { expectedVisibleEdges: number; nodesToCluster: Set<IdType>; } => ({ expectedVisibleEdges: data.edges.length - arr .slice(0, i + 1) .reduce((acc, { swallowsEdges }): number => acc + swallowsEdges, 0), nodesToCluster: new Set(nodes), }) ); describe(name, (): void => { it("Preparation", (): void => { cy.visVisitUniversal(); cy.visRun(({ network, nodes, edges }): void => { network.setOptions({ edges: { arrows: { to: true, }, }, layout: { hierarchical: { enabled: true, sortMethod: "directed", }, }, }); nodes.add(data.nodes); edges.add(data.edges); }); }); configs.forEach(({ expectedVisibleEdges, nodesToCluster }, cid): void => { const clusterDescribeName = cid === 0 ? "Without clustering" : `With ${cid} clusters`; describe(clusterDescribeName, (): void => { if (cid > 0) { it("Cluster", (): void => { cy.visRun(({ network }): void => { network.cluster({ clusterNodeProperties: { label: `Cluster #${cid}`, }, joinCondition: ({ id }): boolean => nodesToCluster.has(id), }); }); }); } /* * There's no point in testing running this test for cyclic graphs. * Such graphs are always invalid. */ if (!cyclic) { /** * Test that children are placed below their parents and parents * above their children. * * This also tests that the required number of edges is visible on * the canvas. Since the number is available there anyway, it can as * well be tested. */ it("Hierarchical order of nodes", (): void => { cy.visRun(({ network }): void => { const visibleNodeIds = new Set( Object.keys(network.getPositions()) ); /* * No matter how much ESLint think they're unnecessary, these two * assertions are indeed necessary. */ const visibleEdges = Object.values( ( network as unknown as { body: { edges: { fromId: string; toId: string; }[]; }; } ).body.edges ).filter( (edge): boolean => visibleNodeIds.has(edge.fromId) && visibleNodeIds.has(edge.toId) ); const invalidEdges = visibleEdges .map( ({ fromId, toId, }): { fromId: IdType; fromPosition: Point; toId: IdType; toPosition: Point; } => ({ fromId, fromPosition: network.getPositions([fromId])[fromId], toId, toPosition: network.getPositions([toId])[toId], }) ) .filter(({ fromPosition, toPosition }): boolean => { return !(fromPosition.y < toPosition.y); }); expect(invalidEdges).to.deep.equal([]); expect(visibleEdges).to.have.lengthOf(expectedVisibleEdges); }); }); /** * Test that all levels are evenly spaced without gaps. */ it("Spacing between levels", (): void => { cy.visRun(({ network }): void => { const levels = Array.from( new Set( Object.values(network.getPositions()).map( ({ y }): number => y ) ) ).sort((a, b): number => a - b); const gaps = new Array(levels.length - 1) .fill(null) .map((_, i): number => { return levels[i] - levels[i + 1]; }); expect( gaps.every((gap, _i, arr): boolean => { return gap === arr[0]; }), "All levels should be evenly spaced without gaps." ).to.be.true; }); }); } /** * Click through the entire network to ensure that: * - No node is off the canvas. * - No node is covered behind another node. * - Each node is selected after being clicked. */ it("Click through the network", (): void => { cy.visStabilizeFitAndRun(({ network }): void => { network.unselectAll(); expect(network.getSelectedNodes()).to.deep.equal([]); const visibleNodeIds = new Set( Object.keys(network.getPositions()).sort() ); for (const id of visibleNodeIds) { cy.visClickNode(id); } }); }); }); }); }); }); });
the_stack
import { EventEmitter } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { StateEditorService } from // eslint-disable-next-line max-len 'components/state-editor/state-editor-properties-services/state-editor.service'; import { StateWrittenTranslationsService } from // eslint-disable-next-line max-len 'components/state-editor/state-editor-properties-services/state-written-translations.service'; import { StateRecordedVoiceoversService } from // eslint-disable-next-line max-len 'components/state-editor/state-editor-properties-services/state-recorded-voiceovers.service'; import { WrittenTranslationObjectFactory } from 'domain/exploration/WrittenTranslationObjectFactory'; import { StateObjectFactory } from 'domain/state/StateObjectFactory'; import { StateEditorRefreshService } from 'pages/exploration-editor-page/services/state-editor-refresh.service'; import { ReadOnlyExplorationBackendApiService } from 'domain/exploration/read-only-exploration-backend-api.service'; // TODO(#7222): Remove the following block of unnnecessary imports once // the code corresponding to the spec is upgraded to Angular 8. import { importAllAngularServices } from 'tests/unit-test-utils.ajs'; // ^^^ This block is to be removed. describe('State Translation Editor Component', function() { var ctrl = null; var $q = null; var $rootScope = null; var $scope = null; var $uibModal = null; var editabilityService = null; var explorationStatesService = null; var stateEditorService = null; var stateObjectFactory = null; var stateWrittenTranslationsService = null; var translationLanguageService = null; var translationTabActiveContentIdService = null; var writtenTranslationObjectFactory = null; var mockExternalSaveEventEmitter = null; var mockActiveContentIdChangedEventEmitter = new EventEmitter(); var mockActiveLanguageChangedEventEmitter = new EventEmitter(); var stateName = 'State1'; var state = { classifier_model_id: '1', content: { content_id: 'content1', html: 'This is a html text' }, interaction: { answer_groups: [{ outcome: { dest: 'outcome 1', feedback: { content_id: 'content2', html: '' }, labelled_as_correct: true, param_changes: [], refresher_exploration_id: null }, rule_specs: [], tagged_skill_misconception_id: '' }, { outcome: { dest: 'outcome 2', feedback: { content_id: 'content3', html: '' }, labelled_as_correct: true, param_changes: [], refresher_exploration_id: null }, rule_specs: [], tagged_skill_misconception_id: '' }], confirmed_unclassified_answers: null, customization_args: {}, hints: [], id: null, solution: { answer_is_exclusive: false, correct_answer: 'This is the correct answer', explanation: { content_id: 'content1', html: 'This is a html text' } } }, linked_skill_id: null, param_changes: [], recorded_voiceovers: { voiceovers_mapping: { content_1: { en: { needs_update: false, }, es: { needs_update: true, } } } }, solicit_answer_details: true, written_translations: { translations_mapping: {} }, }; var stateObj = null; var ctrl = null; beforeEach(angular.mock.module('oppia', function($provide) { $provide.value('NgbModal', { open: () => { return { result: Promise.resolve() }; } }); })); importAllAngularServices(); beforeEach(function() { stateEditorService = TestBed.get(StateEditorService); stateObjectFactory = TestBed.get(StateObjectFactory); stateWrittenTranslationsService = TestBed.get( StateWrittenTranslationsService); writtenTranslationObjectFactory = TestBed.get( WrittenTranslationObjectFactory); }); beforeEach(angular.mock.module('oppia', function($provide) { mockExternalSaveEventEmitter = new EventEmitter(); $provide.value('ExternalSaveService', { onExternalSave: mockExternalSaveEventEmitter }); $provide.value( 'StateEditorRefreshService', TestBed.get(StateEditorRefreshService)); $provide.value('StateRecordedVoiceoversService', TestBed.get( StateRecordedVoiceoversService)); $provide.value( 'StateWrittenTranslationsService', stateWrittenTranslationsService); $provide.value( 'ReadOnlyExplorationBackendApiService', TestBed.get(ReadOnlyExplorationBackendApiService)); })); describe('when has written translation', function() { beforeEach(angular.mock.inject(function($injector, $componentController) { $q = $injector.get('$q'); $rootScope = $injector.get('$rootScope'); $uibModal = $injector.get('$uibModal'); editabilityService = $injector.get('EditabilityService'); explorationStatesService = $injector.get('ExplorationStatesService'); translationLanguageService = $injector.get('TranslationLanguageService'); translationTabActiveContentIdService = $injector.get( 'TranslationTabActiveContentIdService'); spyOn(stateEditorService, 'getActiveStateName').and.returnValue( stateName); spyOn(editabilityService, 'isEditable').and.returnValue(true); stateObj = stateObjectFactory.createFromBackendDict(stateName, state); spyOn(explorationStatesService, 'getState').and.returnValue(stateObj); spyOn(explorationStatesService, 'saveWrittenTranslation').and.callFake( () => {}); spyOn( translationLanguageService, 'getActiveLanguageDirection').and.stub(); spyOnProperty( translationLanguageService, 'onActiveLanguageChanged').and.returnValue( mockActiveLanguageChangedEventEmitter); spyOnProperty( translationTabActiveContentIdService, 'onActiveContentIdChanged').and.returnValue( mockActiveLanguageChangedEventEmitter); stateWrittenTranslationsService.init(stateName, { hasWrittenTranslation: () => true, getWrittenTranslation: () => ( writtenTranslationObjectFactory.createFromBackendDict({ data_format: 'html', translation: 'This is a html', needs_update: true }) ), updateWrittenTranslation: () => {} }); $scope = $rootScope.$new(); ctrl = $componentController('stateTranslationEditor', { $scope: $scope, StateEditorService: stateEditorService, StateWrittenTranslationsService: stateWrittenTranslationsService, WrittenTranslationObjectFactory: writtenTranslationObjectFactory }); ctrl.$onInit(); })); afterEach(() => { ctrl.$onDestroy(); }); it('should initialize $scope properties after controller is initialized', function() { expect($scope.translationEditorIsOpen).toBe(false); expect($scope.activeWrittenTranslation).toEqual( writtenTranslationObjectFactory.createFromBackendDict({ data_format: 'html', translation: 'This is a html', needs_update: true })); }); it('should not update state\'s recorded voiceovers after broadcasting' + ' externalSave when written translation doesn\'t need udpdate', function() { $scope.openTranslationEditor(); expect($scope.translationEditorIsOpen).toBe(true); stateWrittenTranslationsService.displayed = { hasWrittenTranslation: () => true, getWrittenTranslation: () => ( writtenTranslationObjectFactory.createFromBackendDict({ data_format: 'html', translation: 'This is a second html', needs_update: true }) ) }; spyOn(translationTabActiveContentIdService, 'getActiveContentId').and .returnValue('content_1'); spyOn(translationLanguageService, 'getActiveLanguageCode').and .returnValue('es'); spyOn($uibModal, 'open'); mockExternalSaveEventEmitter.emit(); expect($uibModal.open).not.toHaveBeenCalled(); }); it('should update state\'s recorded voiceovers after broadcasting' + ' externalSave event when closing modal', function() { $scope.openTranslationEditor(); expect($scope.translationEditorIsOpen).toBe(true); stateWrittenTranslationsService.displayed = { hasWrittenTranslation: () => true, getWrittenTranslation: () => ( writtenTranslationObjectFactory.createFromBackendDict({ data_format: 'html', translation: 'This is a second html', needs_update: true }) ) }; spyOn(translationTabActiveContentIdService, 'getActiveContentId').and .returnValue('content_1'); spyOn(translationLanguageService, 'getActiveLanguageCode').and .returnValue('en'); spyOn($uibModal, 'open').and.returnValue({ result: $q.resolve() }); expect( stateObj.recordedVoiceovers.getBindableVoiceovers('content_1') .en.needsUpdate).toBe(false); mockExternalSaveEventEmitter.emit(); $scope.$apply(); expect( stateObj.recordedVoiceovers.getBindableVoiceovers('content_1') .en.needsUpdate).toBe(true); }); it('should update state\'s recorded voiceovers after broadcasting' + ' externalSave event when dismissing modal', function() { $scope.openTranslationEditor(); expect($scope.translationEditorIsOpen).toBe(true); stateWrittenTranslationsService.displayed = { hasWrittenTranslation: () => true, getWrittenTranslation: () => ( writtenTranslationObjectFactory.createFromBackendDict({ data_format: 'html', translation: 'This is a second html', needs_update: true }) ) }; spyOn(translationTabActiveContentIdService, 'getActiveContentId').and .returnValue('content_1'); spyOn(translationLanguageService, 'getActiveLanguageCode').and .returnValue('en'); spyOn($uibModal, 'open').and.returnValue({ result: $q.reject() }); expect( stateObj.recordedVoiceovers.getBindableVoiceovers('content_1') .en.needsUpdate).toBe(false); mockExternalSaveEventEmitter.emit(); $scope.$apply(); expect( stateObj.recordedVoiceovers.getBindableVoiceovers('content_1') .en.needsUpdate).toBe(false); }); it('should update written translation html when clicking on save' + ' translation button', function() { spyOn( stateWrittenTranslationsService.displayed, 'updateWrittenTranslation').and.callThrough(); $scope.onSaveTranslationButtonClicked(); expect( stateWrittenTranslationsService.displayed.updateWrittenTranslation) .toHaveBeenCalled(); }); it('should cancel edit and restore values', function() { stateWrittenTranslationsService.displayed = { hasWrittenTranslation: () => true, getWrittenTranslation: () => ( writtenTranslationObjectFactory.createFromBackendDict({ data_format: 'html', translation: 'This is a second html', needs_update: true }) ) }; $scope.cancelEdit(); expect( stateWrittenTranslationsService.displayed.getWrittenTranslation() .getTranslation() ).toBe('This is a html'); }); it('should init editor when changing active content id language', function() { mockActiveContentIdChangedEventEmitter.emit('html'); expect($scope.translationEditorIsOpen).toBe(false); expect($scope.activeWrittenTranslation).toEqual( writtenTranslationObjectFactory.createFromBackendDict({ data_format: 'html', translation: 'This is a html', needs_update: true })); }); it('should init editor when changing active language', function() { mockActiveLanguageChangedEventEmitter.emit(); expect($scope.translationEditorIsOpen).toBe(false); expect($scope.activeWrittenTranslation).toEqual( writtenTranslationObjectFactory.createFromBackendDict({ data_format: 'html', translation: 'This is a html', needs_update: true })); }); }); describe('when hasn\'t written translation', function() { beforeEach(angular.mock.inject(function($injector, $componentController) { $q = $injector.get('$q'); $rootScope = $injector.get('$rootScope'); $uibModal = $injector.get('$uibModal'); editabilityService = $injector.get('EditabilityService'); explorationStatesService = $injector.get('ExplorationStatesService'); translationTabActiveContentIdService = $injector.get( 'TranslationTabActiveContentIdService'); translationLanguageService = $injector.get('TranslationLanguageService'); spyOn( translationLanguageService, 'getActiveLanguageDirection').and.stub(); spyOn(stateEditorService, 'getActiveStateName').and.returnValue( stateName); spyOn(editabilityService, 'isEditable').and.returnValue(true); stateObj = stateObjectFactory.createFromBackendDict(stateName, state); spyOn(explorationStatesService, 'getState').and.returnValue(stateObj); spyOn(explorationStatesService, 'saveWrittenTranslation').and.callFake( () => {}); spyOn( translationTabActiveContentIdService, 'getActiveDataFormat' ).and.returnValue('html'); stateWrittenTranslationsService.init(stateName, { hasWrittenTranslation: () => false, getWrittenTranslation: () => ( writtenTranslationObjectFactory.createFromBackendDict({ data_format: 'html', translation: 'This is a html', needs_update: true }) ), addWrittenTranslation: () => {} }); $scope = $rootScope.$new(); ctrl = $componentController('stateTranslationEditor', { $scope: $scope, StateEditorService: stateEditorService, StateWrittenTranslationsService: stateWrittenTranslationsService, WrittenTranslationObjectFactory: writtenTranslationObjectFactory }); ctrl.$onInit(); })); afterEach(() => { ctrl.$onDestroy(); }); it('should initialize $scope properties after controller is initialized', function() { expect($scope.translationEditorIsOpen).toBe(false); expect($scope.activeWrittenTranslation).toBe(null); }); it('should open translation editor when it is editable', function() { $scope.openTranslationEditor(); expect($scope.translationEditorIsOpen).toBe(true); expect($scope.activeWrittenTranslation).toEqual( writtenTranslationObjectFactory.createNew('html', '')); }); it('should open translation editor when it is editable and with a ' + 'Translatable object as data format', function() { $scope.dataFormat = 'set_of_unicode_string'; $scope.openTranslationEditor(); expect($scope.translationEditorIsOpen).toBe(true); expect($scope.activeWrittenTranslation).toEqual( writtenTranslationObjectFactory.createNew('set_of_unicode_string')); }); it('should mark translation as needing update', function() { spyOn( explorationStatesService, 'markWrittenTranslationAsNeedingUpdate'); $scope.activeWrittenTranslation = ( writtenTranslationObjectFactory.createNew('set_of_unicode_string')); expect($scope.activeWrittenTranslation.needsUpdate).toBeFalse(); $scope.markAsNeedingUpdate(); expect( explorationStatesService.markWrittenTranslationAsNeedingUpdate ).toHaveBeenCalled(); expect($scope.activeWrittenTranslation.needsUpdate).toBeTrue(); }); it('should add written translation html when clicking on save' + ' translation button', function() { $scope.openTranslationEditor(); spyOn( stateWrittenTranslationsService.displayed, 'addWrittenTranslation').and.callThrough(); spyOn(translationTabActiveContentIdService, 'getActiveContentId').and .returnValue('content_1'); spyOn(translationLanguageService, 'getActiveLanguageCode').and .returnValue('es'); $scope.onSaveTranslationButtonClicked(); expect( stateWrittenTranslationsService.displayed.addWrittenTranslation) .toHaveBeenCalled(); }); }); });
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/globalUsersMappers"; import * as Parameters from "../models/parameters"; import { ManagedLabsClientContext } from "../managedLabsClientContext"; /** Class representing a GlobalUsers. */ export class GlobalUsers { private readonly client: ManagedLabsClientContext; /** * Create a GlobalUsers. * @param {ManagedLabsClientContext} client Reference to the service client. */ constructor(client: ManagedLabsClientContext) { this.client = client; } /** * Gets the virtual machine details * @param userName The name of the user. * @param environmentOperationsPayload Represents payload for any Environment operations like get, * start, stop, connect * @param [options] The optional parameters * @returns Promise<Models.GlobalUsersGetEnvironmentResponse> */ getEnvironment(userName: string, environmentOperationsPayload: Models.EnvironmentOperationsPayload, options?: Models.GlobalUsersGetEnvironmentOptionalParams): Promise<Models.GlobalUsersGetEnvironmentResponse>; /** * @param userName The name of the user. * @param environmentOperationsPayload Represents payload for any Environment operations like get, * start, stop, connect * @param callback The callback */ getEnvironment(userName: string, environmentOperationsPayload: Models.EnvironmentOperationsPayload, callback: msRest.ServiceCallback<Models.GetEnvironmentResponse>): void; /** * @param userName The name of the user. * @param environmentOperationsPayload Represents payload for any Environment operations like get, * start, stop, connect * @param options The optional parameters * @param callback The callback */ getEnvironment(userName: string, environmentOperationsPayload: Models.EnvironmentOperationsPayload, options: Models.GlobalUsersGetEnvironmentOptionalParams, callback: msRest.ServiceCallback<Models.GetEnvironmentResponse>): void; getEnvironment(userName: string, environmentOperationsPayload: Models.EnvironmentOperationsPayload, options?: Models.GlobalUsersGetEnvironmentOptionalParams | msRest.ServiceCallback<Models.GetEnvironmentResponse>, callback?: msRest.ServiceCallback<Models.GetEnvironmentResponse>): Promise<Models.GlobalUsersGetEnvironmentResponse> { return this.client.sendOperationRequest( { userName, environmentOperationsPayload, options }, getEnvironmentOperationSpec, callback) as Promise<Models.GlobalUsersGetEnvironmentResponse>; } /** * Get batch operation status * @param userName The name of the user. * @param operationBatchStatusPayload Payload to get the status of an operation * @param [options] The optional parameters * @returns Promise<Models.GlobalUsersGetOperationBatchStatusResponse> */ getOperationBatchStatus(userName: string, operationBatchStatusPayload: Models.OperationBatchStatusPayload, options?: msRest.RequestOptionsBase): Promise<Models.GlobalUsersGetOperationBatchStatusResponse>; /** * @param userName The name of the user. * @param operationBatchStatusPayload Payload to get the status of an operation * @param callback The callback */ getOperationBatchStatus(userName: string, operationBatchStatusPayload: Models.OperationBatchStatusPayload, callback: msRest.ServiceCallback<Models.OperationBatchStatusResponse>): void; /** * @param userName The name of the user. * @param operationBatchStatusPayload Payload to get the status of an operation * @param options The optional parameters * @param callback The callback */ getOperationBatchStatus(userName: string, operationBatchStatusPayload: Models.OperationBatchStatusPayload, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationBatchStatusResponse>): void; getOperationBatchStatus(userName: string, operationBatchStatusPayload: Models.OperationBatchStatusPayload, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationBatchStatusResponse>, callback?: msRest.ServiceCallback<Models.OperationBatchStatusResponse>): Promise<Models.GlobalUsersGetOperationBatchStatusResponse> { return this.client.sendOperationRequest( { userName, operationBatchStatusPayload, options }, getOperationBatchStatusOperationSpec, callback) as Promise<Models.GlobalUsersGetOperationBatchStatusResponse>; } /** * Gets the status of long running operation * @param userName The name of the user. * @param operationStatusPayload Payload to get the status of an operation * @param [options] The optional parameters * @returns Promise<Models.GlobalUsersGetOperationStatusResponse> */ getOperationStatus(userName: string, operationStatusPayload: Models.OperationStatusPayload, options?: msRest.RequestOptionsBase): Promise<Models.GlobalUsersGetOperationStatusResponse>; /** * @param userName The name of the user. * @param operationStatusPayload Payload to get the status of an operation * @param callback The callback */ getOperationStatus(userName: string, operationStatusPayload: Models.OperationStatusPayload, callback: msRest.ServiceCallback<Models.OperationStatusResponse>): void; /** * @param userName The name of the user. * @param operationStatusPayload Payload to get the status of an operation * @param options The optional parameters * @param callback The callback */ getOperationStatus(userName: string, operationStatusPayload: Models.OperationStatusPayload, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatusResponse>): void; getOperationStatus(userName: string, operationStatusPayload: Models.OperationStatusPayload, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatusResponse>, callback?: msRest.ServiceCallback<Models.OperationStatusResponse>): Promise<Models.GlobalUsersGetOperationStatusResponse> { return this.client.sendOperationRequest( { userName, operationStatusPayload, options }, getOperationStatusOperationSpec, callback) as Promise<Models.GlobalUsersGetOperationStatusResponse>; } /** * Get personal preferences for a user * @param userName The name of the user. * @param personalPreferencesOperationsPayload Represents payload for any Environment operations * like get, start, stop, connect * @param [options] The optional parameters * @returns Promise<Models.GlobalUsersGetPersonalPreferencesResponse> */ getPersonalPreferences(userName: string, personalPreferencesOperationsPayload: Models.PersonalPreferencesOperationsPayload, options?: msRest.RequestOptionsBase): Promise<Models.GlobalUsersGetPersonalPreferencesResponse>; /** * @param userName The name of the user. * @param personalPreferencesOperationsPayload Represents payload for any Environment operations * like get, start, stop, connect * @param callback The callback */ getPersonalPreferences(userName: string, personalPreferencesOperationsPayload: Models.PersonalPreferencesOperationsPayload, callback: msRest.ServiceCallback<Models.GetPersonalPreferencesResponse>): void; /** * @param userName The name of the user. * @param personalPreferencesOperationsPayload Represents payload for any Environment operations * like get, start, stop, connect * @param options The optional parameters * @param callback The callback */ getPersonalPreferences(userName: string, personalPreferencesOperationsPayload: Models.PersonalPreferencesOperationsPayload, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.GetPersonalPreferencesResponse>): void; getPersonalPreferences(userName: string, personalPreferencesOperationsPayload: Models.PersonalPreferencesOperationsPayload, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.GetPersonalPreferencesResponse>, callback?: msRest.ServiceCallback<Models.GetPersonalPreferencesResponse>): Promise<Models.GlobalUsersGetPersonalPreferencesResponse> { return this.client.sendOperationRequest( { userName, personalPreferencesOperationsPayload, options }, getPersonalPreferencesOperationSpec, callback) as Promise<Models.GlobalUsersGetPersonalPreferencesResponse>; } /** * List Environments for the user * @param userName The name of the user. * @param listEnvironmentsPayload Represents the payload to list environments owned by a user * @param [options] The optional parameters * @returns Promise<Models.GlobalUsersListEnvironmentsResponse> */ listEnvironments(userName: string, listEnvironmentsPayload: Models.ListEnvironmentsPayload, options?: msRest.RequestOptionsBase): Promise<Models.GlobalUsersListEnvironmentsResponse>; /** * @param userName The name of the user. * @param listEnvironmentsPayload Represents the payload to list environments owned by a user * @param callback The callback */ listEnvironments(userName: string, listEnvironmentsPayload: Models.ListEnvironmentsPayload, callback: msRest.ServiceCallback<Models.ListEnvironmentsResponse>): void; /** * @param userName The name of the user. * @param listEnvironmentsPayload Represents the payload to list environments owned by a user * @param options The optional parameters * @param callback The callback */ listEnvironments(userName: string, listEnvironmentsPayload: Models.ListEnvironmentsPayload, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ListEnvironmentsResponse>): void; listEnvironments(userName: string, listEnvironmentsPayload: Models.ListEnvironmentsPayload, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ListEnvironmentsResponse>, callback?: msRest.ServiceCallback<Models.ListEnvironmentsResponse>): Promise<Models.GlobalUsersListEnvironmentsResponse> { return this.client.sendOperationRequest( { userName, listEnvironmentsPayload, options }, listEnvironmentsOperationSpec, callback) as Promise<Models.GlobalUsersListEnvironmentsResponse>; } /** * List labs for the user. * @param userName The name of the user. * @param [options] The optional parameters * @returns Promise<Models.GlobalUsersListLabsResponse> */ listLabs(userName: string, options?: msRest.RequestOptionsBase): Promise<Models.GlobalUsersListLabsResponse>; /** * @param userName The name of the user. * @param callback The callback */ listLabs(userName: string, callback: msRest.ServiceCallback<Models.ListLabsResponse>): void; /** * @param userName The name of the user. * @param options The optional parameters * @param callback The callback */ listLabs(userName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ListLabsResponse>): void; listLabs(userName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ListLabsResponse>, callback?: msRest.ServiceCallback<Models.ListLabsResponse>): Promise<Models.GlobalUsersListLabsResponse> { return this.client.sendOperationRequest( { userName, options }, listLabsOperationSpec, callback) as Promise<Models.GlobalUsersListLabsResponse>; } /** * Register a user to a managed lab * @param userName The name of the user. * @param registerPayload Represents payload for Register action. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ register(userName: string, registerPayload: Models.RegisterPayload, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param userName The name of the user. * @param registerPayload Represents payload for Register action. * @param callback The callback */ register(userName: string, registerPayload: Models.RegisterPayload, callback: msRest.ServiceCallback<void>): void; /** * @param userName The name of the user. * @param registerPayload Represents payload for Register action. * @param options The optional parameters * @param callback The callback */ register(userName: string, registerPayload: Models.RegisterPayload, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; register(userName: string, registerPayload: Models.RegisterPayload, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { userName, registerPayload, options }, registerOperationSpec, callback); } /** * Resets the user password on an environment This operation can take a while to complete * @param userName The name of the user. * @param resetPasswordPayload Represents the payload for resetting passwords. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ resetPassword(userName: string, resetPasswordPayload: Models.ResetPasswordPayload, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginResetPassword(userName,resetPasswordPayload,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Starts an environment by starting all resources inside the environment. This operation can take * a while to complete * @param userName The name of the user. * @param environmentOperationsPayload Represents payload for any Environment operations like get, * start, stop, connect * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ startEnvironment(userName: string, environmentOperationsPayload: Models.EnvironmentOperationsPayload, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginStartEnvironment(userName,environmentOperationsPayload,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Stops an environment by stopping all resources inside the environment This operation can take a * while to complete * @param userName The name of the user. * @param environmentOperationsPayload Represents payload for any Environment operations like get, * start, stop, connect * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ stopEnvironment(userName: string, environmentOperationsPayload: Models.EnvironmentOperationsPayload, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginStopEnvironment(userName,environmentOperationsPayload,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Resets the user password on an environment This operation can take a while to complete * @param userName The name of the user. * @param resetPasswordPayload Represents the payload for resetting passwords. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginResetPassword(userName: string, resetPasswordPayload: Models.ResetPasswordPayload, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { userName, resetPasswordPayload, options }, beginResetPasswordOperationSpec, options); } /** * Starts an environment by starting all resources inside the environment. This operation can take * a while to complete * @param userName The name of the user. * @param environmentOperationsPayload Represents payload for any Environment operations like get, * start, stop, connect * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginStartEnvironment(userName: string, environmentOperationsPayload: Models.EnvironmentOperationsPayload, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { userName, environmentOperationsPayload, options }, beginStartEnvironmentOperationSpec, options); } /** * Stops an environment by stopping all resources inside the environment This operation can take a * while to complete * @param userName The name of the user. * @param environmentOperationsPayload Represents payload for any Environment operations like get, * start, stop, connect * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginStopEnvironment(userName: string, environmentOperationsPayload: Models.EnvironmentOperationsPayload, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { userName, environmentOperationsPayload, options }, beginStopEnvironmentOperationSpec, options); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getEnvironmentOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/getEnvironment", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.expand, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "environmentOperationsPayload", mapper: { ...Mappers.EnvironmentOperationsPayload, required: true } }, responses: { 200: { bodyMapper: Mappers.GetEnvironmentResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationBatchStatusOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/getOperationBatchStatus", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "operationBatchStatusPayload", mapper: { ...Mappers.OperationBatchStatusPayload, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationBatchStatusResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationStatusOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/getOperationStatus", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "operationStatusPayload", mapper: { ...Mappers.OperationStatusPayload, required: true } }, responses: { 200: { bodyMapper: Mappers.OperationStatusResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getPersonalPreferencesOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/getPersonalPreferences", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "personalPreferencesOperationsPayload", mapper: { ...Mappers.PersonalPreferencesOperationsPayload, required: true } }, responses: { 200: { bodyMapper: Mappers.GetPersonalPreferencesResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listEnvironmentsOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/listEnvironments", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "listEnvironmentsPayload", mapper: { ...Mappers.ListEnvironmentsPayload, required: true } }, responses: { 200: { bodyMapper: Mappers.ListEnvironmentsResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listLabsOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/listLabs", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ListLabsResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const registerOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/register", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "registerPayload", mapper: { ...Mappers.RegisterPayload, required: true } }, responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginResetPasswordOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/resetPassword", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "resetPasswordPayload", mapper: { ...Mappers.ResetPasswordPayload, required: true } }, responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginStartEnvironmentOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/startEnvironment", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "environmentOperationsPayload", mapper: { ...Mappers.EnvironmentOperationsPayload, required: true } }, responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginStopEnvironmentOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.LabServices/users/{userName}/stopEnvironment", urlParameters: [ Parameters.userName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "environmentOperationsPayload", mapper: { ...Mappers.EnvironmentOperationsPayload, required: true } }, responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import * as chai from 'chai'; import { evaluateUpdatingExpression, evaluateXPath, executePendingUpdateList } from 'fontoxpath'; import * as slimdom from 'slimdom'; let documentNode: slimdom.Document; beforeEach(() => { documentNode = new slimdom.Document(); }); describe('evaluateUpdatingExpression', () => { let insertBeforeCalled = false; let removeChildCalled = false; let removeAttributeNSCalled = false; let setAttributeNSCalled = false; let setDataCalled = false; let createAttributeNSCalled = false; let createCDATASectionCalled = false; let createCommentCalled = false; let createDocumentCalled = false; let createElementNSCalled = false; let createProcessingInstructionCalled = false; let createTextNodeCalled = false; const stubbedDocumentWriter = { insertBefore: (parent, node, referenceNode) => { insertBeforeCalled = true; return node; }, removeAttributeNS: (element, namespaceURI, localName) => { removeAttributeNSCalled = true; return null; }, removeChild: (parent, child) => { removeChildCalled = true; return child; }, setAttributeNS: (element, namespaceURI, localName, value) => { setAttributeNSCalled = true; return null; }, setData: (node, data) => { setDataCalled = true; return null; }, }; const stubbedNodesFactory = { createAttributeNS: (namespaceURI, localName) => { createAttributeNSCalled = true; return documentNode.createAttributeNS(namespaceURI, localName); }, createCDATASection: (contents) => { createCDATASectionCalled = true; return documentNode.createCDATASection(contents); }, createComment: (contents) => { createCommentCalled = true; return documentNode.createComment(contents); }, createDocument: () => { createDocumentCalled = true; return documentNode.implementation.createDocument('', ''); }, createElementNS: (namespaceURI, localName) => { createElementNSCalled = true; return documentNode.createElementNS(namespaceURI, localName); }, createProcessingInstruction: (target, data) => { createProcessingInstructionCalled = true; return documentNode.createProcessingInstruction(target, data); }, createTextNode: (data) => { createTextNodeCalled = true; return documentNode.createTextNode(data); }, }; beforeEach(() => { insertBeforeCalled = false; removeChildCalled = false; removeAttributeNSCalled = false; setAttributeNSCalled = false; setDataCalled = false; createAttributeNSCalled = false; createCDATASectionCalled = false; createCommentCalled = false; createDocumentCalled = false; createElementNSCalled = false; createProcessingInstructionCalled = false; createTextNodeCalled = false; }); it('can evaluate an expression without any of the optional parameters set', async () => { documentNode.appendChild(documentNode.createElement('ele')); const result = await evaluateUpdatingExpression( 'replace node ele with <ele/>', documentNode, null, null, { returnType: evaluateXPath.NODES_TYPE } ); chai.assert.deepEqual(result.xdmValue, []); }); it('properly returns the xdmValue for updating expressions', async () => { documentNode.appendChild(documentNode.createElement('ele')); const result = await evaluateUpdatingExpression( '(replace node ele with <ele/>, 1)', documentNode ); chai.assert.deepEqual(result.xdmValue as any, 1); }); it('properly returns the xdmValue for non-updating expressions', async () => { documentNode.appendChild(documentNode.createElement('ele')); const result = await evaluateUpdatingExpression('(1)', documentNode); chai.assert.deepEqual(result.xdmValue, [1]); }); it('properly throws dynamic errors', async () => { documentNode.appendChild(documentNode.createElement('ele')); try { await evaluateUpdatingExpression('delete node ("Not a node")', documentNode); chai.assert.fail('This should have thrown a dynamic error'); } catch (err) { chai.assert.match(err, /XUTY0007/); return; } }); it('uses the passed documentWriter for replace', async () => { const ele = documentNode.createElement('ele'); ele.setAttribute('attr', 'value'); documentNode.appendChild(ele); const result = await evaluateUpdatingExpression( 'replace node $doc/ele/@attr with <ele xmlns:xxx="YYY" xxx:attr="123"/>/@*', null, null, { doc: documentNode, }, { documentWriter: stubbedDocumentWriter, nodesFactory: stubbedNodesFactory, } ); chai.assert.isFalse(insertBeforeCalled, 'insertBeforeCalled'); chai.assert.isFalse(removeChildCalled, 'removeChildCalled'); chai.assert.isFalse(removeAttributeNSCalled, 'removeAttributeNSCalled'); chai.assert.isFalse(setAttributeNSCalled, 'setAttributeNSCalled'); chai.assert.isFalse(setDataCalled, 'setDataCalled'); // TODO: Recheck this carefully chai.assert.isFalse(createElementNSCalled, 'createElementNSCalled'); chai.assert.isTrue(createAttributeNSCalled, 'createAttributeNSCalled'); chai.assert.isFalse(createCDATASectionCalled, 'createCDATASectionCalled'); chai.assert.isFalse(createCommentCalled, 'createCommentCalled'); chai.assert.isFalse(createDocumentCalled, 'createDocumentCalled'); chai.assert.isFalse(createProcessingInstructionCalled, 'createProcessingInstructionCalled'); chai.assert.isFalse(createTextNodeCalled, 'createTextNodeCalled'); executePendingUpdateList( result.pendingUpdateList, null, stubbedNodesFactory, stubbedDocumentWriter ); chai.assert.isFalse(insertBeforeCalled, 'insertBeforeCalled'); chai.assert.isFalse(removeChildCalled, 'removeChildCalled'); chai.assert.isTrue(removeAttributeNSCalled, 'removeAttributeNSCalled'); chai.assert.isTrue(setAttributeNSCalled, 'setAttributeNSCalled'); chai.assert.isFalse(setDataCalled, 'setDataCalled'); }); it('uses the passed documentWriter for attribute insertions', async () => { documentNode.appendChild(documentNode.createElement('ele')); const result = await evaluateUpdatingExpression( 'insert node attribute {"a"} {"5"} into $doc/ele', null, null, { doc: documentNode, }, { documentWriter: stubbedDocumentWriter, nodesFactory: stubbedNodesFactory, } ); executePendingUpdateList( result.pendingUpdateList, null, stubbedNodesFactory, stubbedDocumentWriter ); chai.assert.isFalse(insertBeforeCalled, 'insertBeforeCalled'); chai.assert.isFalse(removeChildCalled, 'removeChildCalled'); chai.assert.isFalse(removeAttributeNSCalled, 'removeAttributeNSCalled'); chai.assert.isTrue(setAttributeNSCalled, 'setAttributeNSCalled'); chai.assert.isFalse(setDataCalled, 'setDataCalled'); chai.assert.isFalse(createElementNSCalled, 'createElementNSCalled'); chai.assert.isTrue(createAttributeNSCalled, 'createAttributeNSCalled'); chai.assert.isFalse(createCDATASectionCalled, 'createCDATASectionCalled'); chai.assert.isFalse(createCommentCalled, 'createCommentCalled'); chai.assert.isFalse(createDocumentCalled, 'createDocumentCalled'); chai.assert.isFalse(createProcessingInstructionCalled, 'createProcessingInstructionCalled'); chai.assert.isFalse(createTextNodeCalled, 'createTextNodeCalled'); }); it('uses the passed documentWriter for setting data', async () => { documentNode .appendChild(documentNode.createElement('ele')) .appendChild(documentNode.createTextNode('test')); const result = await evaluateUpdatingExpression( 'replace value of node $doc/ele/text() with "CHANGED"', null, null, { doc: documentNode, }, { documentWriter: stubbedDocumentWriter, nodesFactory: stubbedNodesFactory, } ); executePendingUpdateList( result.pendingUpdateList, null, stubbedNodesFactory, stubbedDocumentWriter ); chai.assert.isFalse(insertBeforeCalled, 'insertBeforeCalled'); chai.assert.isFalse(removeChildCalled, 'removeChildCalled'); chai.assert.isFalse(removeAttributeNSCalled, 'removeAttributeNSCalled'); chai.assert.isFalse(setAttributeNSCalled, 'setAttributeNSCalled'); chai.assert.isTrue(setDataCalled, 'setDataCalled'); chai.assert.isFalse(createElementNSCalled, 'createElementNSCalled'); chai.assert.isFalse(createAttributeNSCalled, 'createAttributeNSCalled'); chai.assert.isFalse(createCDATASectionCalled, 'createCDATASectionCalled'); chai.assert.isFalse(createCommentCalled, 'createCommentCalled'); chai.assert.isFalse(createDocumentCalled, 'createDocumentCalled'); chai.assert.isFalse(createProcessingInstructionCalled, 'createProcessingInstructionCalled'); chai.assert.isTrue(createTextNodeCalled, 'createTextNodeCalled'); }); it('uses the passed documentWriter for insert into', async () => { documentNode.appendChild(documentNode.createElement('ele')); const result = await evaluateUpdatingExpression( 'insert node <xxx attr="attr">PRRT<!--yyy--><?pi target?></xxx> into $doc/ele', null, null, { doc: documentNode, }, { documentWriter: stubbedDocumentWriter, nodesFactory: stubbedNodesFactory, } ); chai.assert.isTrue(insertBeforeCalled, 'insertBeforeCalled'); chai.assert.isFalse(removeChildCalled, 'removeChildCalled'); chai.assert.isFalse(removeAttributeNSCalled, 'removeAttributeNSCalled'); chai.assert.isTrue(setAttributeNSCalled, 'setAttributeNSCalled'); chai.assert.isFalse(setDataCalled, 'setDataCalled'); chai.assert.isTrue(createElementNSCalled, 'createElementNSCalled'); // We set the attribute while realizing, that's why we did not create it. chai.assert.isFalse(createAttributeNSCalled, 'createAttributeNSCalled'); chai.assert.isFalse(createCDATASectionCalled, 'createCDATASectionCalled'); chai.assert.isTrue(createCommentCalled, 'createCommentCalled'); chai.assert.isFalse(createDocumentCalled, 'createDocumentCalled'); chai.assert.isTrue(createProcessingInstructionCalled, 'createProcessingInstructionCalled'); chai.assert.isTrue(createTextNodeCalled, 'createTextNodeCalled'); executePendingUpdateList( result.pendingUpdateList, null, stubbedNodesFactory, stubbedDocumentWriter ); chai.assert.isTrue(insertBeforeCalled, 'insertBeforeCalled'); chai.assert.isFalse(removeChildCalled, 'removeChildCalled'); chai.assert.isFalse(removeAttributeNSCalled, 'removeAttributeNSCalled'); chai.assert.isTrue(setAttributeNSCalled, 'setAttributeNSCalled'); chai.assert.isFalse(setDataCalled, 'setDataCalled'); }); });
the_stack
import { ComponentFixture, TestBed, async } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { IconLoaderService } from '../../../index'; import { AmexioFloatingPanelComponent } from './floatingpanel.component'; import { AmexioFormsModule } from '../../forms/amexio.forms.module'; import { SimpleChange, ElementRef, Type, Renderer2 } from '@angular/core'; describe('amexio-floating-panel', () => { let comp: AmexioFloatingPanelComponent; let fixture: ComponentFixture<AmexioFloatingPanelComponent>; let event1: any; let changes :any const rendererMock = jasmine.createSpyObj('rendererMock', ['listen']); beforeEach(() => { TestBed.configureTestingModule({ imports: [FormsModule, AmexioFormsModule], declarations: [AmexioFloatingPanelComponent], providers: [IconLoaderService, { provide: Renderer2, useValue: rendererMock }], }).compileComponents(); fixture = TestBed.createComponent(AmexioFloatingPanelComponent); comp = fixture.componentInstance; event = jasmine.createSpyObj('event', ['preventDefault', 'stopPropagation']); comp.showPanel = true; changes = new SimpleChange(null, comp.showPanel, false) }); // it('should create the app', async(() => { // const fixture = TestBed.createComponent(AmexioFloatingPanelComponent); // const comp = fixture.debugElement.componentInstance; // fixture.detectChanges(); // expect(comp).toBeTruthy(); // })); it('ngOnchanges method call if condition', () => { let element = fixture.nativeElement; let showPanel = true; comp.absolute = true; comp.showPanel = showPanel; changes['showPanel'] = true; comp.ngOnChanges(changes); fixture.detectChanges(); expect(changes['showPanel']).toEqual(true); comp.getZindex(comp.showPanel); expect(comp.absolute).toBe(true); comp.setPanelAbsolutePostion(); }); it('ngOnchanges method call else condition', () => { let element = fixture.nativeElement; let showPanel = true; comp.absolute = false; comp.showPanel = showPanel; changes['showPanel'] = true; comp.ngOnChanges(changes ); fixture.detectChanges(); expect(changes['showPanel']).toEqual(true); comp.getZindex(comp.showPanel); expect(comp.absolute).toBe(false); comp.panelStyle(); }); it('ngOnchanges method first else condition', () => { let element = fixture.nativeElement; let showPanel = true; comp.absolute = false; comp.showPanel = showPanel; changes['showPanel'] = false; comp.ngOnChanges(changes ); fixture.detectChanges(); expect(changes['showPanel']).toEqual(false); }); it('getZindex If Method', () => { let showPanel = true; comp.commanservice.zindex = 600; comp.getZindex(showPanel); expect(showPanel).toBe(true); comp.commanservice.zindex = comp.commanservice.zindex + 100; }); it('getZindex Else Method', () => { let showPanel = false; comp.commanservice.zindex = 600; comp.getZindex(showPanel); expect(showPanel).toBe(false); }); it('ngOnInit method if ', () => { comp.absolute = true; comp.draggable = true; comp.showPanel = false; comp.arrow = true; comp.relative = true; comp.ngOnInit(); expect(comp.absolute).toEqual(true); comp.relative = false; comp.height = ''; expect(comp.height).toEqual(''); comp.height = 200; comp.width = ''; expect(comp.width).toEqual(''); comp.width = 400; expect(comp.showPanel).toBeDefined(); comp.panelStyle(); expect(comp.draggable).toBeDefined(); expect(comp.arrow).toBeDefined(); comp.draggable = false; expect(comp.relative).toBeDefined(); expect(comp.draggable).toBeDefined(); comp.style['position'] = 'absolute'; }); it('ngOnInit method else ', () => { comp.relative = false; comp.draggable = false; comp.showPanel = false; comp.arrow = false; comp.absolute = false; comp.height = '440'; comp.width = '300'; comp.ngOnInit(); expect(comp.absolute).toEqual(false); expect(comp.height).not.toEqual(''); expect(comp.width).not.toEqual(''); expect(comp.showPanel).toEqual(false); expect(comp.draggable).toEqual(false); expect(comp.arrow).toEqual(false); expect(comp.relative).toEqual(false); expect(comp.draggable).toEqual(false); }); it('ngOnInit method relative-false ,draggable- true ', () => { comp.relative = false; comp.draggable = true; comp.ngOnInit(); expect(comp.relative).toEqual(false); expect(comp.draggable).toEqual(true); }); it('ngOnInit method both true ', () => { comp.relative = true; comp.draggable = true; comp.ngOnInit(); expect(comp.relative).toEqual(true); expect(comp.draggable).toEqual(true); comp.style['position'] = 'absolute'; }); it('ngOnInit method relative-true, draggable-false', () => { comp.relative = true; comp.draggable = false; comp.ngOnInit(); expect(comp.relative).toEqual(true); expect(comp.draggable).toEqual(false); }); it('panel style method if condition ', () => { comp.relative = true; comp.width = '200'; comp.panelStyle(); comp.style = {}; expect(comp.relative).toEqual(true); comp.style['position'] = 'absolute'; comp.style['display'] = 'block'; comp.style['z-index'] = comp.commanservice.zindex; comp.style['opacity'] = '1'; comp.style['box-shadow'] = '0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12)'; expect(comp.width).not.toEqual(''); comp.style['width'] = comp.width + 'px'; comp.arrowPadding(); }) it('panel style method else condition ', () => { comp.relative = false; comp.width = ''; comp.commanservice.zindex = 600; comp.panelStyle(); comp.style = {}; expect(comp.relative).toEqual(false); comp.style['position'] = 'fixed'; comp.style['display'] = 'block'; comp.style['z-index'] = comp.commanservice.zindex; comp.style['opacity'] = '1'; comp.style['box-shadow'] = '0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12)'; expect(comp.width).toEqual(''); comp.style['width'] = '400px'; expect(comp.relative).toEqual(false); comp.setPanelStylePostion(); comp.arrowPadding(); }) it('arrowPadding method', () => { comp.arrow = true; comp.arrowPadding(); expect(comp.arrow).toEqual(true); expect(comp.style['margin-top']).toBe('16px'); }); it('setpanelStyleposition', () => { comp.topPosition = '20px'; comp.bottomPosition = '20px'; comp.rightPosition = '20px'; comp.leftPosition = '20px'; comp.setPanelStylePostion(); expect(comp.style['top']).toEqual('20px'); expect(comp.style['left']).toEqual('20px'); expect(comp.style['bottom']).toEqual('20px'); expect(comp.style['right']).toEqual('20px'); }); it('changeHeaderColor method', () => { comp.gradientFlag = true; comp.changeHeaderColor(); }); it('setcolorpallete method', () => { let themeClass: any; comp.setColorPalette(themeClass); comp.themeCss = themeClass; }); it('setpanelAbsolutePosition if method', () => { comp.width = '200'; comp.commanservice.zindex = 600; comp.setPanelAbsolutePostion(); comp.style = {}; comp.style['position'] = 'absolute'; comp.style['display'] = 'block'; comp.style['z-index'] = comp.commanservice.zindex; comp.style['opacity'] = '1'; comp.style['box-shadow'] = '0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12)'; expect(comp.width).not.toEqual('') comp.style['width'] = comp.width + 'px'; comp.setPanelStylePostion(); comp.arrowPadding(); }) it('setpanelAbsolutePosition else method', () => { comp.width = ''; comp.commanservice.zindex = 600; comp.setPanelAbsolutePostion(); comp.style = {}; comp.style['position'] = 'absolute'; comp.style['display'] = 'block'; comp.style['z-index'] = comp.commanservice.zindex; comp.style['opacity'] = '1'; comp.style['box-shadow'] = '0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12)'; expect(comp.width).toEqual(''); comp.width = '400px'; comp.setPanelStylePostion(); comp.arrowPadding(); }) it('checking togglePanel method', () => { comp.showPanel = false; comp.togglePanel(); comp.showPanel = false; expect(comp.showPanel).toEqual(false); comp.onclose.subscribe((g: any) => { expect(comp.onclose).toEqual(g); }); comp.showPanelChange.subscribe((g: any) => { expect(comp.showPanelChange).toEqual(g); }); }); it('elementDrag method if call', () => { comp.pos1 = 0; comp.pos2 = 0; comp.pos3 = 0; comp.pos4 = 0; comp.bottomPosition = '20px'; comp.style = { 'bottom': '10px' }; let floatingPanel = { 'offsetTop': 1200, 'offsetLeft': 145, 'style': { 'top': '20px', 'left': '10px', 'opacity': '1' } } let e = jasmine.createSpyObj('e', ['preventDefault']); e['clientX'] = 1200; e['clientY'] = 1400; comp.elementDrag(e, floatingPanel); e = e || window.event; expect(e).toBe(e); expect(e.preventDefault).toHaveBeenCalled(); comp.pos1 = comp.pos3 - e.clientX; comp.pos2 = comp.pos4 - e.clientY; comp.pos3 = e.clientX; comp.pos4 = e.clientY; expect(comp.bottomPosition).toBeDefined(); delete comp.style['bottom']; floatingPanel.style.top = (floatingPanel.offsetTop - comp.pos2) + 'px'; floatingPanel.style.left = (floatingPanel.offsetLeft - comp.pos1) + 'px'; floatingPanel.style.opacity = '0.7'; comp.opacitiy = true; }); it('elementDrag method else call', () => { comp.pos1 = 0; comp.pos2 = 0; comp.pos3 = 0; comp.pos4 = 0; comp.style = { 'bottom': '10px' }; let floatingPanel = { 'offsetTop': 1200, 'offsetLeft': 145, 'style': { 'top': '20px', 'left': '10px', 'opacity': '1' } } // window.event = jasmine.createSpyObj('e', ['preventDefault']); window.event ['clientX'] = 1200; window.event ['clientY'] = 1400; let e ; comp.elementDrag(e, floatingPanel); e = window.event; expect(e.preventDefault).toHaveBeenCalled(); comp.pos1 = comp.pos3 - e['clientX']; comp.pos2 = comp.pos4 - e['clientY']; comp.pos3 = e['clientX']; comp.pos4 = e['clientY']; expect(comp.bottomPosition).toBeUndefined(); }); it('onMouseDown method if call', () => { comp.draggable = true; let floatingPanel = { 'offsetTop': 1200, 'offsetLeft': 145, 'style': { 'top': '20px', 'left': '10px', 'opacity': '1' } } let div = document.createElement('div'); div.setAttribute('name', 'floatingheader'); let event = jasmine.createSpyObj('e', ['preventDefault']); event['clientX'] = 1200; event['clientY'] = 1400; event['target'] = div; comp.onMouseDown(event, floatingPanel); expect(comp.draggable).toBeDefined(); expect(event.target.getAttribute('name')).toBeDefined(); expect(event.target.getAttribute('name')).toEqual('floatingheader'); event = event || window.event; expect(event).toBe(event); expect(event.preventDefault).toHaveBeenCalled(); comp.pos3 = event.clientX; comp.pos4 = event.clientY; comp.onMouseDown(event, floatingPanel); comp.documentMouseUPListener = null; comp.documentMouseMoveListener = null; expect(comp.documentMouseUPListener).toBeNull(); comp.documentMouseUPListener = rendererMock.listen('document', 'mouseup', () => comp.closeDragElement(floatingPanel)); expect(comp.documentMouseMoveListener).toBeNull(); comp.documentMouseMoveListener = rendererMock.listen('document', 'mousemove', () => comp.elementDrag(event, floatingPanel)); }); it('onMouseDown method else ', () => { let floatingPanel = { 'offsetTop': 1200, 'offsetLeft': 145, 'style': { 'top': '20px', 'left': '10px', 'opacity': '1' } } let div = document.createElement('div'); let event = jasmine.createSpyObj('e', ['preventDefault']); event['clientX'] = 1200; event['clientY'] = 1400; event['target'] = div; comp.draggable = false; comp.onMouseDown(event, floatingPanel); expect(comp.draggable).toEqual(false); expect(event.target.getAttribute('name')).toBeNull(); expect(event.target.getAttribute('name')).not.toEqual('floatingheader'); }); it('onMouseDown method if nested call --checking else condition', () => { comp.draggable = true; let floatingPanel = { 'offsetTop': 1200, 'offsetLeft': 145, 'style': { 'top': '20px', 'left': '10px', 'opacity': '1' } } let div = document.createElement('div'); div.setAttribute('name', 'floatingheader'); let event = jasmine.createSpyObj('e', ['preventDefault']); event['clientX'] = 1200; event['clientY'] = 1400; event['target'] = div; comp.onMouseDown(event, floatingPanel); expect(comp.draggable).toBeDefined(); expect(event.target.getAttribute('name')).toBeDefined(); expect(event.target.getAttribute('name')).toEqual('floatingheader'); event = window.event; expect(event).toBe(window.event) comp.pos3 = event.clientX; comp.pos4 = event.clientY; comp.documentMouseUPListener = 'kijjj'; comp.documentMouseMoveListener = 'mjkiii'; expect(comp.documentMouseUPListener).toBeDefined(); expect(comp.documentMouseMoveListener).toBeDefined(); }); });
the_stack
import popContainer from '@/components/popContainer'; import { Component, Emit, Prop, PropSync, Ref, Vue, Watch } from 'vue-property-decorator'; import { VNode } from 'vue/types/umd'; import { getDimensionModelsCanBeRelated, getMasterTableInfo } from '../../../Api/index'; import { CDataModelManage, MasterTableInfo, MstTbField } from '../../../Controller/MasterTable'; import { IDataModelManage, IMasterTableInfo } from '../../../Interface/index'; import { ModelTab } from '../../Common/index'; /** * 获取主表字段编辑 tips * @param info * @param type */ const getFieldEditableInfo = (info: object = {}, type: string) => { const operation = type === 'delete' ? '删除' : '修改'; const tips = []; if (info.isJoinField && type === 'edit') { tips.push('该字段已引用维度表数据模型,无法修改'); } if (info.isExtendedFieldDeletableEditable === false) { tips.push(`对应扩展字段不能${operation}`); } if (info.isUsedByCalcAtom) { const usedInfo = (info.calculationAtoms || []) .map(item => `${item.calculationAtomName} (${item.calculationAtomAlias})`) .join('、'); tips.push(`该字段被统计口径 ${usedInfo} 引用,无法${operation}`); } if (info.isAggregationField) { const usedInfo = (info.aggregationFieldIndicators || []) .map(item => `${item.indicatorName} (${item.indicatorAlias})`) .join('、'); tips.push(`该字段被指标 ${usedInfo} 作为聚合字段,无法${operation}`); } if (info.isConditionField) { const usedInfo = (info.conditionFieldIndicators || []) .map(item => `${item.indicatorName} (${item.indicatorAlias})`) .join('、'); tips.push(`该字段被指标 ${usedInfo} 作为过滤字段,无法${operation}`); } if (info.isUsedByOtherFields) { const usedInfo = (info.fields || []).map(item => item.fieldName).join('、'); tips.push(`该字段被 ${usedInfo} 的字段加工逻辑引用,无法${operation}`); } return tips.join('<br />'); }; /** 关联维度表数据模型 */ @Component({ components: { ModelTab, popContainer }, }) export default class ReferDimensionTable extends Vue { @Prop({ default: () => ({}) }) public readonly activeModel!: object; @Prop({ default: () => ({}) }) public readonly parentMstTableInfo!: object; @Prop({ default: () => ({}) }) public readonly relatedField!: object; @Prop() public readonly isEdit!: boolean; @Ref() public readonly mainContent!: HTMLDivElement; @Ref() public readonly dimensionFieldNameItem!: VNode; @Ref() public readonly clearConfirmPop!: VNode; @Ref() public readonly dimensionModelNode!: VNode; get mstTableDisplayName() { return `${this.activeModel.name} (${this.activeModel.displayName})`; } /** * 已经被关联的维度表集合 */ get hadRelatedModel() { const relatedMap = {}; const relation = this.parentMstTableInfo.modelRelation || []; for (const item of relation) { if (item.fieldName === this.relatedField.fieldName) { continue; } relatedMap[item.relatedModelId] = true; } return relatedMap; } /** * 获取维度模型列表 */ get filterDimensionModelList() { const isCurrent = this.activeSelectedTab === 'current'; const projectId = Number(this.activeModel.projectId); if (isCurrent) { return this.dimensionModelList.filter(model => model.project_id === projectId); } return this.dimensionModelList.filter(model => model.project_id !== projectId); } /** * 过滤与父级主表一样的模型 */ get displayDimensionModelList() { return this.filterDimensionModelList.filter( model => model.model_id !== this.parentMstTableInfo.modelId && !this.hadRelatedModel[model.model_id] ); } /** * 根据 searchkey 过滤出列表 */ get searchDimensionModelList() { return this.displayDimensionModelList.filter( model => model.model_alias.includes(this.searchKey) || model.model_name.includes(this.searchKey) ); } get curDimensionModelName() { const model = this.displayDimensionModelList.find(model => model.model_id === this.formData.dimensionModelId); return model ? `${model.model_name} (${model.model_alias})` : ''; } /** * 获取父级主表的fields * 过滤扩展字段 item.isExtendedField * 过滤空字段 item.fieldAlias && item.fieldName * 过滤已经被关联字段 item.isJoinField */ get mstFields() { const fields = this.parentMstTableInfo.fields || []; if (this.isEdit) { return fields.filter( item => !item.isExtendedField && item.fieldAlias && item.fieldName && item.fieldName !== '__time__' ); } return fields.filter( item => !item.isExtendedField && !item.isJoinField && item.fieldAlias && item.fieldName && item.fieldName !== '__time__' ); } /** * 获取父级主表的扩展fields */ get mstExpandFields() { return this.parentMstTableInfo.fields .filter(item => item.isExtendedField) .map(item => Object.assign({}, item)); } /** * 获取关联主表的字段 */ get joinField() { return this.mstFields.find(item => item.fieldName === this.formData.masterFieldName); } /** * 过滤主键字段 */ get nonPrimaryKeyFields() { const fields = this.masterTableInfo.fields .filter(item => !item.isPrimaryKey) .map(item => Object.assign({}, item, { sourceFieldName: item.fieldName, displayName: `${item.fieldName} (${item.fieldAlias})`, }) ); if (this.isEdit) { const extendsMap = {}; this.relatedField.extends.forEach(item => { extendsMap[item.sourceFieldName] = item; }); return fields.map(item => { const exist = extendsMap[item.sourceFieldName]; if (exist && exist.sourceFieldExist !== false) { return Object.assign(item, exist); } return item; }); } return fields; } get nonPrimaryKeyFieldNameMap() { const map = {}; for (const field of this.nonPrimaryKeyFields) { map[field.sourceFieldName] = true; } return map; } /** * 获取展示的维度字段 */ get displayDimensionFields() { return this.masterTableInfo.fields.filter(item => item.isPrimaryKey); } /** * 获取展示的扩展字段 */ get displayExpandFields() { return this.formData.expandFields.map((field: IDataModelManage.IMasterTableField, index: number) => { return { ...field, rules: { name: field.id ? [ { required: true, message: this.$t('必填项'), trigger: 'blur', }, { regex: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: this.$t('格式不正确_内容由字母_数字和下划线组成_且以字母开头'), trigger: 'blur', }, { message: this.$t('字段英文名重复'), validator: (value: string) => this.nameRepeatedValidator(value, index), trigger: 'blur', }, { message: this.$t('字段英文名与主表中字段名重复'), validator: this.nameRepeatedWithMstValidator, trigger: 'blur', }, { message: this.$t('该名称为系统内置,请修改名称'), validator: this.nameIsInnerValidator, trigger: 'blur', }, ] : [], alias: field.id ? [ { required: true, message: this.$t('必填项'), trigger: 'blur', }, { message: this.$t('字段中文名重复'), validator: (value: string) => this.aliasRepeatedValidator(value, index), trigger: 'blur', }, ] : [], }, }; }); } get isDisabled() { return this.formData.expandFields.some(field => field.deletable === false || field.editable === false); } get disabledTips() { const fields = this.formData.expandFields .filter(field => field.deletable === false || field.editable === false); return { disabled: !this.isDisabled, content: `当前关联表的扩展字段(${fields.map(field => field.fieldName).join('、')})有被依赖,无法修改`, }; } /** * 配置维度模型 id 规则 */ get dimensionModelIdRules() { const rules = [ { required: true, message: this.$t('请选择'), trigger: 'blur', }, ]; if (this.isEdit) { return rules.concat([ { message: this.$t(`当前被关联的维度表(${this.relatedModelName})已被删除,请重新配置`), validator: (value: string) => this.handleCheckdimensionModel(value), trigger: 'blur', }, ]); } return rules; } /** * 配置关联字段名规则 */ get relatedFieldNamedRules() { const rules = [ { required: true, message: this.$t('请选择'), trigger: 'blur', }, ]; if (this.isEdit) { return rules.concat([ { message: this.$t(`当前维度表关联字段(${this.relatedFieldName})发生变更,请重新配置`), validator: (value: string) => this.handleCheckRelatedFieldName(value), trigger: 'blur', }, ]); } return rules; } public searchKey = ''; public activeSelectedTab = 'current'; public selectorBoundary: Element = document.body; public modelPanels = [ { name: 'current', label: this.$t('当前项目') }, { name: 'common', label: this.$t('公开') }, ]; public formData: object = { dimensionModelId: '', masterFieldName: '', dimensionFieldName: '', expandFields: [], }; public rules: object = { mustSelect: [ { required: true, message: this.$t('请选择'), trigger: 'blur', }, ], selectExpand: [ { required: true, message: this.$t('扩展字段必须选择'), trigger: 'blur', }, ], }; public relatedFieldName = ''; public relatedModelName = ''; public isModelListLoading = false; public isMasterTableLoading = false; public isInitDefaultFields = true; public isInitValidator: boolean = false; public dimensionModelList: any[] = []; public hasScrollBar = false; public observer = null; public selectedExpandFields: string[] = []; public deleteExpandFields: string[] = []; /** 主表数据 */ public masterTableInfo: IDataModelManage.IMasterTableInfo = new CDataModelManage.MasterTableInfo({ modelId: 0, fields: [], modelRelation: [], }); /** 内置字段 */ public innerFieldList = [ 'timestamp', 'offset', 'bkdata_par_offset', 'dtEventTime', 'dtEventTimeStamp', 'localTime', 'thedate', 'rowtime', ]; @Watch('isEdit', { immediate: true }) public handleEditStatus(status: boolean) { if (status) { this.isInitValidator = true; this.isInitDefaultFields = false; this.formData.masterFieldName = this.relatedField.fieldName; const relation = this.parentMstTableInfo.modelRelation.find( item => item.fieldName === this.relatedField.fieldName ); if (relation) { this.formData.dimensionModelId = relation.relatedModelId; this.relatedFieldName = relation.relatedFieldName; this.relatedModelName = relation.relatedModelName; } } } @Watch('formData.dimensionModelId', { immediate: true }) public async handleChangeDimensionModelId(id: number | string) { if (id) { this.dimensionFieldNameItem && this.dimensionFieldNameItem.clearError(); this.expandFieldSelector && this.expandFieldSelector.clearError(); this.formData.dimensionFieldName = ''; this.selectedExpandFields = []; this.masterTableInfo = new CDataModelManage.MasterTableInfo({ modelId: 0, fields: [], modelRelation: [], }); await this.loadMasterTableInfo(); } } @Emit('on-cancel') public handleCancel() { } @Emit('on-save') public handleEmitSave(result: [], isEdit: boolean, isDelete = false) { // 如果有扩展字段无法回填,保存的时候会自动删除,这里处理tips if (isEdit) { const nameMap = {}; for (const field of this.nonPrimaryKeyFields) { nameMap[field.sourceFieldName] = true; } const autoDeleteExpandFields = this.selectedExpandFields.filter(name => !nameMap[name]); if (!!autoDeleteExpandFields.length) { const timer = setTimeout(() => { this.$bkMessage({ theme: 'success', delay: 3000, message: window.$t( `关联关系更新成功!同时系统已自动删除不存在扩展字段:${autoDeleteExpandFields.join('、')}` ), }); clearTimeout(timer); }, 300); } } return { result, isEdit, isDelete }; } public mounted() { this.getDimensionModelsCanBeRelated(); this.setResizeObserve(); } public beforeDestroy() { if (this.observer) { this.observer.disconnect(); this.observer = null; } } /** * 判断是否只读 * @param row */ public isReadonly(row: IDataModelManage.IMasterTableField) { return row.deletable === false || row.editable === false; } /** * 获取删除 tips * @param row * @param type */ public getDeleteTips(row: IDataModelManage.IMasterTableField, type = 'edit') { return { disabled: type === 'edit' ? row.editable !== false : row.deletable !== false, content: getFieldEditableInfo(row.editableDeletableInfo, type), interactive: false, }; } /** * 设置元素高度变动监听 */ public setResizeObserve() { const self = this; const node = this.mainContent; this.observer = new ResizeObserver(entries => { self.hasScrollBar = node.scrollHeight !== node.offsetHeight; }); this.observer.observe(node); } /** * 判断中文名是否重复 * @param alias * @param index */ public aliasRepeatedValidator(alias: string, index: number) { return !this.formData.expandFields.find( (field: IDataModelManage.IMasterTableField, expandIndex: number) => expandIndex !== index && field.fieldAlias === alias); } /** * 判断名称是否重复 * @param name * @param index */ public nameRepeatedValidator(name: string, index: number) { return !this.formData.expandFields.find( (field: IDataModelManage.IMasterTableField, expandIndex: number) => expandIndex !== index && field.fieldName === name); } /** * 判断名称是否为系统内置 * @param name */ public nameIsInnerValidator(name: string) { return !this.innerFieldList.find(item => item === name.toLocaleLowerCase()); } /** * 判断名称是否跟主表字段名称重复 * @param name */ public nameRepeatedWithMstValidator(name: string) { return !this.parentMstTableInfo.fields.find( (field: IDataModelManage.IMasterTableField) => field.fieldName === name && field.joinFieldName !== this.formData.masterFieldName); } /** * 手动触发扩展字段校验 */ public fieldFormItemValidator() { const fieldFormItemKeys = Object.keys(this.$refs).filter(key => key.indexOf('fieldFormItem_') === 0); fieldFormItemKeys.forEach(key => { const item = this.$refs[key]; if (item) { item.clearError(); item.validate('blur'); } }); } /** * 失焦事件 */ public handleBlur() { this.$nextTick(this.fieldFormItemValidator); } /** * 检查维度模型 * @param id */ public handleCheckdimensionModel(id: string | number) { return !!this.dimensionModelList.find(model => model.model_id === id); } /** * 检查关联字段名称 * @param name */ public handleCheckRelatedFieldName(name: string) { return !!this.displayDimensionFields.find(item => item.fieldName === name); } /** * 获取维度表数据模型列表 */ public getDimensionModelsCanBeRelated() { this.isModelListLoading = true; getDimensionModelsCanBeRelated(this.activeModel.modelId, this.formData.dimensionModelId || undefined, true) .then(res => { res.setData(this, 'dimensionModelList'); const model = this.dimensionModelList.find(model => model.model_id === this.formData.dimensionModelId); if (this.formData.dimensionModelId && model) { this.activeSelectedTab = model.project_id === Number(this.activeModel.projectId) ? 'current' : 'common'; } if (this.isEdit) { this.dimensionModelNode && this.dimensionModelNode.validate('', () => { const timer = setTimeout(() => { this.dimensionModelNode.validator.state === 'success' && this.dimensionFieldNameItem && this.dimensionFieldNameItem.validate(); clearTimeout(timer); }, 300); }); } }) .finally(() => { this.isModelListLoading = false; }); } /** * 获取主表信息 */ public loadMasterTableInfo() { this.isMasterTableLoading = true; getMasterTableInfo(this.formData.dimensionModelId, false, undefined, undefined, true) .then(res => { if (res.result) { this.masterTableInfo = res.data; this.initDefaultField(); // 默认填充第一个主键字段 if (!this.isEdit && this.displayDimensionFields[0]) { this.formData.dimensionFieldName = this.displayDimensionFields[0].fieldName; } } }) .finally(() => { this.isMasterTableLoading = false; this.isInitValidator = false; }); } /** * 初始化扩展字段 */ public initDefaultField() { if (this.isInitDefaultFields) { this.formData.expandFields = []; } else { // 编辑的时候回填数据 this.formData.dimensionFieldName = this.relatedFieldName; const fields = this.mstExpandFields .filter( (item: IDataModelManage.IMasterTableField) => item.joinFieldName === this.formData.masterFieldName && item.sourceModelId === this.formData.dimensionModelId ) .map((item: IDataModelManage.IMasterTableField) => Object.assign({}, item)); const allFields = fields.map((field: IDataModelManage.IMasterTableField) => field.sourceFieldName); this.selectedExpandFields = allFields.filter((name: string) => this.nonPrimaryKeyFieldNameMap[name]); this.deleteExpandFields = allFields.filter((name: string) => !this.nonPrimaryKeyFieldNameMap[name]); this.isInitDefaultFields = true; this.isInitValidator && this.$nextTick(() => { this.expandFieldSelector && this.expandFieldSelector.validate(); }); } } /** * 处理已选择的扩展字段 * @param newValues */ public handleSelectedExpandField(newValues: string[]) { // 删除 fields for (let i = this.formData.expandFields.length - 1; i >= 0; i--) { const field = this.formData.expandFields[i]; if (!newValues.includes(field.sourceFieldName)) { this.formData.expandFields.splice(i, 1); } } const addExpandFields: IDataModelManage.IMasterTableField[] = []; for (const sourceFieldName of newValues) { const originalField = this.nonPrimaryKeyFields.find( (field: IDataModelManage.IMasterTableField) => field.sourceFieldName === sourceFieldName ); if (originalField) { // 已存在的字段 const existField = this.formData.expandFields.find( (field: IDataModelManage.IMasterTableField) => field.sourceFieldName === sourceFieldName ) || {}; addExpandFields.push(Object.assign(originalField, existField)); } } this.formData.expandFields = addExpandFields; } /** * 控制字段删除 * @param row * @param index */ public handleRemoveField(row: IDataModelManage.IMasterTableField, index: number) { if (this.isReadonly(row)) { return; } this.selectedExpandFields.splice(index, 1); } /** * 保存设置信息 */ public async handleSave() { const validate = await this.$refs.dimensionForm.validate().then( validator => true, validator => false ); if (validate === false) { return false; } const result = { joinFieldName: this.formData.masterFieldName, expandFields: [], relation: { modelId: this.activeModel.modelId, fieldName: this.formData.masterFieldName, relatedModelId: this.formData.dimensionModelId, relatedFieldName: this.formData.dimensionFieldName, joinFieldUId: this.joinField && this.joinField.uid, }, }; const sourceInfo = { sourceModelId: this.formData.dimensionModelId, joinFieldName: this.formData.masterFieldName, }; for (const field of this.formData.expandFields) { if (field.id && field.fieldName && field.fieldAlias) { Object.assign(field, sourceInfo, { joinFieldUId: this.joinField && this.joinField.uid }); field.isExtendedField = true; result.expandFields.push(field); } } this.handleEmitSave(result, this.isEdit); } /** * 展示确认框 * @param e */ public handleShowConfirm(e) { this.clearConfirmPop.handlePopShow(e, { placement: 'top-end', hideOnClick: false, maxWidth: '280px' }); } /** * 隐藏确认框 */ public handleHideConfirm() { this.clearConfirmPop && this.clearConfirmPop.handlePopHidden(); } /** * 确认删除 */ public handleConfirmDelete() { const result = { joinFieldName: this.formData.masterFieldName, expandFields: [], relation: { modelId: this.activeModel.modelId, fieldName: this.formData.masterFieldName, relatedModelId: this.formData.dimensionModelId, relatedFieldName: this.formData.dimensionFieldName, joinFieldUId: this.joinField && this.joinField.uid, }, }; this.handleEmitSave(result, this.isEdit, true); this.handleHideConfirm(); } @Emit('create-model-table') public handleCreateNewModelTable() { return true; } }
the_stack
//import { SharedStreetsMetadata, SharedStreetsIntersection, SharedStreetsGeometry, SharedStreetsReference, RoadClass } from 'sharedstreets-types'; import * as turfHelpers from '@turf/helpers'; import buffer from '@turf/buffer'; import along from '@turf/along'; import envelope from '@turf/envelope'; import lineSliceAlong from '@turf/line-slice-along'; import distance from '@turf/distance'; import lineOffset from '@turf/line-offset'; import RBush from 'rbush'; import { SharedStreetsIntersection, SharedStreetsGeometry, SharedStreetsReference, SharedStreetsMetadata } from 'sharedstreets-types'; import { lonlatsToCoords } from '../src/index'; import { TilePath, getTile, TileType, TilePathGroup, getTileIdsForPolygon, TilePathParams, getTileIdsForPoint } from './tiles'; import { Graph, ReferenceSideOfStreet } from './graph'; import { reverseLineString, bboxFromPolygon } from './geom'; import { featureCollection } from '@turf/helpers'; const SHST_ID_API_URL = 'https://api.sharedstreets.io/v0.1.0/id/'; // maintains unified spaital and id indexes for tiled data export function createIntersectionGeometry(data:SharedStreetsIntersection) { var point = turfHelpers.point([data.lon, data.lat]); return turfHelpers.feature(point.geometry, {id: data.id}); } export function getReferenceLength(ref:SharedStreetsReference) { var refLength = 0; for(var locationRef of ref.locationReferences) { if(locationRef.distanceToNextRef) refLength = refLength = locationRef.distanceToNextRef } return refLength / 100; } export function createGeometry(data:SharedStreetsGeometry) { var line = turfHelpers.lineString(lonlatsToCoords(data.lonlats)); var feature = turfHelpers.feature(line.geometry, {id: data.id}); return feature; } export class TileIndex { tiles:Set<string>; objectIndex:Map<string, {}>; featureIndex:Map<string, turfHelpers.Feature<turfHelpers.Geometry>>; metadataIndex:Map<string, {}>; osmNodeIntersectionIndex:Map<string, any>; osmNodeIndex:Map<string, any>; osmWayIndex:Map<string, any>; binIndex:Map<string, turfHelpers.Feature<turfHelpers.MultiPoint>>; intersectionIndex:RBush; geometryIndex:RBush; additionalTileTypes:TileType[] = []; constructor() { this.tiles = new Set(); this.objectIndex = new Map(); this.featureIndex = new Map(); this.metadataIndex = new Map(); this.osmNodeIntersectionIndex = new Map(); this.osmNodeIndex = new Map(); this.osmWayIndex = new Map(); this.binIndex = new Map(); this.intersectionIndex = new RBush(9); this.geometryIndex = new RBush(9); } addTileType(tileType:TileType) { this.additionalTileTypes.push(tileType); } isIndexed(tilePath:TilePath):Boolean { if(this.tiles.has(tilePath.toPathString())) return true; else return false; } async indexTilesByPathGroup(tilePathGroup:TilePathGroup):Promise<boolean> { for(var tilePath of tilePathGroup) { await this.indexTileByPath(tilePath); } return false; } async indexTileByPath(tilePath:TilePath):Promise<boolean> { if(this.isIndexed(tilePath)) return true; var data:any[] = await getTile(tilePath); if(tilePath.tileType === TileType.GEOMETRY) { var geometryFeatures = []; for(var geometry of data) { if(!this.objectIndex.has(geometry.id)) { this.objectIndex.set(geometry.id, geometry); var geometryFeature = createGeometry(geometry); this.featureIndex.set(geometry.id, geometryFeature) var bboxCoords = bboxFromPolygon(geometryFeature); bboxCoords['id'] = geometry.id; geometryFeatures.push(bboxCoords); } } this.geometryIndex.load(geometryFeatures); } else if(tilePath.tileType === TileType.INTERSECTION) { var intersectionFeatures = []; for(var intersection of data) { if(!this.objectIndex.has(intersection.id)) { this.objectIndex.set(intersection.id, intersection); var intesectionFeature = createIntersectionGeometry(intersection); this.featureIndex.set(intersection.id, intesectionFeature); this.osmNodeIntersectionIndex.set(intersection.nodeId, intersection); var bboxCoords = bboxFromPolygon(intesectionFeature); bboxCoords['id'] = intersection.id; intersectionFeatures.push(bboxCoords); } } this.intersectionIndex.load(intersectionFeatures); } else if(tilePath.tileType === TileType.REFERENCE) { for(var reference of data) { this.objectIndex.set(reference.id, reference); } } else if(tilePath.tileType === TileType.METADATA) { for(var metadata of <SharedStreetsMetadata[]>data) { this.metadataIndex.set(metadata.geometryId, metadata); if(metadata.osmMetadata) { for(var waySection of metadata.osmMetadata.waySections) { if(!this.osmWayIndex.has("" + waySection.wayId)) this.osmWayIndex.set("" + waySection.wayId, []) var ways = this.osmWayIndex.get("" + waySection.wayId); ways.push(metadata); this.osmWayIndex.set("" + waySection.wayId, ways); for(var nodeId of waySection.nodeIds) { if(!this.osmNodeIndex.has("" + nodeId)) this.osmNodeIndex.set("" + nodeId, []); var nodes = this.osmNodeIndex.get("" + nodeId); nodes.push(metadata); this.osmNodeIndex.set("" + nodeId, nodes); } } } } } this.tiles.add(tilePath.toPathString()); } async getGraph(polygon:turfHelpers.Feature<turfHelpers.Polygon>, params:TilePathParams):Promise<Graph> { return null; } async intersects(polygon:turfHelpers.Feature<turfHelpers.Polygon>, searchType:TileType, buffer:number, params:TilePathParams):Promise<turfHelpers.FeatureCollection<turfHelpers.Geometry>> { var tilePaths = TilePathGroup.fromPolygon(polygon, buffer, params); if(searchType === TileType.GEOMETRY) tilePaths.addType(TileType.GEOMETRY); else if(searchType === TileType.INTERSECTION) tilePaths.addType(TileType.INTERSECTION); else throw "invalid search type must be GEOMETRY or INTERSECTION"; if(this.additionalTileTypes.length > 0) { for(var type of this.additionalTileTypes) { tilePaths.addType(type); } } await this.indexTilesByPathGroup(tilePaths); var data:turfHelpers.FeatureCollection<turfHelpers.Geometry> = featureCollection([]); if(searchType === TileType.GEOMETRY){ var bboxCoords = bboxFromPolygon(polygon); var rbushMatches = this.geometryIndex.search(bboxCoords); for(var rbushMatch of rbushMatches) { var matchedGeom = this.featureIndex.get(rbushMatch.id); data.features.push(matchedGeom); } } else if(searchType === TileType.INTERSECTION) { var bboxCoords = bboxFromPolygon(polygon); var rbushMatches = this.intersectionIndex.search(bboxCoords); for(var rbushMatch of rbushMatches) { var matchedGeom = this.featureIndex.get(rbushMatch.id); data.features.push(matchedGeom); } } return data; } async nearby(point:turfHelpers.Feature<turfHelpers.Point>, searchType:TileType, searchRadius:number, params:TilePathParams) { var tilePaths = TilePathGroup.fromPoint(point, searchRadius * 2, params); if(searchType === TileType.GEOMETRY) tilePaths.addType(TileType.GEOMETRY); else if(searchType === TileType.INTERSECTION) tilePaths.addType(TileType.INTERSECTION); else throw "invalid search type must be GEOMETRY or INTERSECTION" if(this.additionalTileTypes.length > 0) { for(var type of this.additionalTileTypes) { tilePaths.addType(type); } } await this.indexTilesByPathGroup(tilePaths); var bufferedPoint:turfHelpers.Feature<turfHelpers.Polygon> = buffer(point, searchRadius, {'units':'meters'}); var data:turfHelpers.FeatureCollection<turfHelpers.Geometry> = featureCollection([]); if(searchType === TileType.GEOMETRY){ var bboxCoords = bboxFromPolygon(bufferedPoint); var rbushMatches = this.geometryIndex.search(bboxCoords); for(var rbushMatch of rbushMatches) { var matchedGeom = this.featureIndex.get(rbushMatch.id); data.features.push(matchedGeom); } } else if(searchType === TileType.INTERSECTION) { var bboxCoords = bboxFromPolygon(bufferedPoint); var rbushMatches = this.intersectionIndex.search(bboxCoords); for(var rbushMatch of rbushMatches) { var matchedGeom = this.featureIndex.get(rbushMatch.id); data.features.push(matchedGeom); } } return data; } async geomFromOsm(wayId:string, nodeId1:string, nodeId2:string, offset:number=0):Promise<turfHelpers.Feature<turfHelpers.LineString|turfHelpers.Point>> { if(this.osmNodeIntersectionIndex.has(nodeId1) && this.osmNodeIntersectionIndex.has(nodeId2)) { var intersection1 = <SharedStreetsIntersection>this.osmNodeIntersectionIndex.get(nodeId1); var intersection2 = <SharedStreetsIntersection>this.osmNodeIntersectionIndex.get(nodeId2); var referenceCandidates:Set<string> = new Set(); for(var refId of intersection1.outboundReferenceIds) { referenceCandidates.add(refId); } for(var refId of intersection2.inboundReferenceIds) { if(referenceCandidates.has(refId)) { var geom = await this.geom(refId, null, null, offset); if(geom) { geom.properties['referenceId'] = refId; return geom; } } } } else if(this.osmWayIndex.has(wayId)) { var metadataList = <SharedStreetsMetadata[]>this.osmWayIndex.get(wayId); for(var metadata of metadataList) { var nodeIds = []; var previousNode = null; var nodeIndex = 0; var startNodeIndex = null; var endNodeIndex = null; for(var waySection of metadata.osmMetadata.waySections) { for(var nodeId of waySection.nodeIds) { var nodeIdStr = nodeId + ""; if(previousNode != nodeIdStr) { nodeIds.push(nodeIdStr); if(nodeIdStr == nodeId1) startNodeIndex = nodeIndex; if(nodeIdStr == nodeId2) endNodeIndex = nodeIndex; nodeIndex++; } previousNode = nodeIdStr; } } if(startNodeIndex != null && endNodeIndex != null) { var geometry = <SharedStreetsGeometry>this.objectIndex.get(metadata.geometryId); var geometryFeature = this.featureIndex.get(metadata.geometryId); var reference = <SharedStreetsReference>this.objectIndex.get(geometry.forwardReferenceId); if(startNodeIndex > endNodeIndex) { if(geometry.backReferenceId) { nodeIds.reverse(); startNodeIndex = (nodeIds.length - 1) - startNodeIndex; endNodeIndex = (nodeIds.length - 1) - endNodeIndex; reference = <SharedStreetsReference>this.objectIndex.get(geometry.backReferenceId); geometryFeature = <turfHelpers.Feature<turfHelpers.LineString>>JSON.parse(JSON.stringify(geometryFeature)); geometryFeature.geometry.coordinates = geometryFeature.geometry.coordinates.reverse(); } } var startLocation = 0; var endLocation = 0; var previousCoord = null; for(var j = 0; j <= endNodeIndex; j++ ){ if(previousCoord) { try { var coordDistance = distance(previousCoord, geometryFeature.geometry.coordinates[j], {units: 'meters'}); if(j <= startNodeIndex) startLocation += coordDistance; endLocation += coordDistance; } catch(e) { console.log(e); } } previousCoord = geometryFeature.geometry.coordinates[j]; } //console.log(wayId + " " + nodeId1 + " " + nodeId2 + ": " + reference.id + " " + startLocation + " " + endLocation); var geom = await this.geom(reference.id, startLocation, endLocation, offset); if(geom) { geom.properties['referenceId'] = reference.id; geom.properties['section'] = [startLocation, endLocation]; return geom; } } } } return null; } referenceToBins(referenceId:string, numBins:number, offset:number, sideOfStreet:ReferenceSideOfStreet):turfHelpers.Feature<turfHelpers.MultiPoint> { var binIndexId = referenceId + ':' + numBins + ':' + offset; if(this.binIndex.has(binIndexId)) return this.binIndex.get(binIndexId); var ref = <SharedStreetsReference>this.objectIndex.get(referenceId); var geom = <SharedStreetsGeometry>this.objectIndex.get(ref.geometryId); var feature = <turfHelpers.Feature<turfHelpers.LineString>>this.featureIndex.get(ref.geometryId); var binLength = getReferenceLength(ref) / numBins; var binPoints:turfHelpers.Feature<turfHelpers.MultiPoint> = { "type": "Feature", "properties": { "id":referenceId }, "geometry": { "type": "MultiPoint", "coordinates": [] } } try { if(offset) { if(referenceId === geom.forwardReferenceId) feature = lineOffset(feature, offset, {units: 'meters'}); else { var reverseGeom = reverseLineString(feature); feature = lineOffset(reverseGeom, offset, {units: 'meters'}); } } for(var binPosition = 0; binPosition < numBins; binPosition++) { try { var point = along(feature, (binLength * binPosition) + (binLength/2), {units:'meters'}); point.geometry.coordinates[0] = Math.round(point.geometry.coordinates[0] * 10000000) / 10000000; point.geometry.coordinates[1] = Math.round(point.geometry.coordinates[1] * 10000000) / 10000000; binPoints.geometry.coordinates.push(point.geometry.coordinates); } catch(e) { console.log(e); } } this.binIndex.set(binIndexId, binPoints); } catch(e) { console.log(e); } return binPoints; } async geom(referenceId:string, p1:number, p2:number, offset:number=0):Promise<turfHelpers.Feature<turfHelpers.LineString|turfHelpers.Point>> { if(this.objectIndex.has(referenceId)) { var ref:SharedStreetsReference = <SharedStreetsReference>this.objectIndex.get(referenceId); var geom:SharedStreetsGeometry = <SharedStreetsGeometry>this.objectIndex.get(ref.geometryId); var geomFeature:turfHelpers.Feature<turfHelpers.LineString> = JSON.parse(JSON.stringify(this.featureIndex.get(ref.geometryId))); if(geom.backReferenceId && geom.backReferenceId === referenceId) { geomFeature.geometry.coordinates = geomFeature.geometry.coordinates.reverse() } if(offset) { geomFeature = lineOffset(geomFeature, offset, {units: 'meters'}); } if(p1 < 0) p1 = 0; if(p2 < 0) p2 = 0; if(p1 == null && p2 == null) { return geomFeature; } else if(p1 && p2 == null) { return along(geomFeature, p1, {"units":"meters"}); } else if(p1 != null && p2 != null) { try { return lineSliceAlong(geomFeature, p1, p2, {"units":"meters"}); } catch(e) { //console.log(p1, p2) } } } // TODO find missing IDs via look up return null; } }
the_stack
import { newSpecPage, SpecPage } from '@stencil/core/testing'; import { DumbbellPlot } from './dumbbell-plot'; import { DumbbellPlotDefaultValues } from './dumbbell-plot-default-values'; import { scalePoint, scaleLinear, scaleTime } from 'd3-scale'; import { timeMonth } from 'd3-time'; import { rgb } from 'd3-color'; // we need to bring in our nested components as well, was required to bring in the source vs dist folder to get it to mount import { KeyboardInstructions } from '../../../node_modules/@visa/keyboard-instructions/src/components/keyboard-instructions/keyboard-instructions'; import { DataTable } from '../../../node_modules/@visa/visa-charts-data-table/src/components/data-table/data-table'; import Utils from '@visa/visa-charts-utils'; import UtilsDev from '@visa/visa-charts-utils-dev'; const { formatStats, getColors, roundTo, getContrastingStroke, getAccessibleStrokes, ensureTextContrast } = Utils; const { asyncForEach, flushTransitions, unitTestAxis, unitTestGeneric, unitTestEvent, unitTestInteraction, unitTestTooltip } = UtilsDev; describe('<dumbbell-plot>', () => { // TECH DEBT: Need to revisit class-logic-testing post PURE function refactor. // Class-logic-testing is TDD and BDD friendly. describe('class-logic', () => { it('should build', () => { expect(new DumbbellPlot()).toBeTruthy(); }); }); describe('rendered-html', () => { let page: SpecPage; let component; // START:minimal props need to be passed to component const EXPECTEDDATA = [ { date: new Date('2016-01-01T00:00:00.000Z'), category: 'CardA', value: 7670994739 }, { date: new Date('2016-02-01T00:00:00.000Z'), category: 'CardA', value: 7628909842 }, { date: new Date('2016-03-01T00:00:00.000Z'), category: 'CardA', value: 8358837379 }, { date: new Date('2016-04-01T00:00:00.000Z'), category: 'CardA', value: 8334842966 }, { date: new Date('2016-05-01T00:00:00.000Z'), category: 'CardA', value: 8588600035 }, { date: new Date('2016-06-01T00:00:00.000Z'), category: 'CardA', value: 8484192554 }, { date: new Date('2016-07-01T00:00:00.000Z'), category: 'CardA', value: 8778636197 }, { date: new Date('2016-08-01T00:00:00.000Z'), category: 'CardA', value: 8811163096 }, { date: new Date('2016-09-01T00:00:00.000Z'), category: 'CardA', value: 8462148898 }, { date: new Date('2016-10-01T00:00:00.000Z'), category: 'CardA', value: 9051933407 }, { date: new Date('2016-11-01T00:00:00.000Z'), category: 'CardA', value: 8872849978 }, { date: new Date('2016-12-01T00:00:00.000Z'), category: 'CardA', value: 9709829820 }, { date: new Date('2016-01-01T00:00:00.000Z'), category: 'CardB', value: 6570994739 }, { date: new Date('2016-02-01T00:00:00.000Z'), category: 'CardB', value: 4628909842 }, { date: new Date('2016-03-01T00:00:00.000Z'), category: 'CardB', value: 4358837379 }, { date: new Date('2016-04-01T00:00:00.000Z'), category: 'CardB', value: 5534842966 }, { date: new Date('2016-05-01T00:00:00.000Z'), category: 'CardB', value: 4388600035 }, { date: new Date('2016-06-01T00:00:00.000Z'), category: 'CardB', value: 3484192554 }, { date: new Date('2016-07-01T00:00:00.000Z'), category: 'CardB', value: 3578636197 }, { date: new Date('2016-08-01T00:00:00.000Z'), category: 'CardB', value: 6411163096 }, { date: new Date('2016-09-01T00:00:00.000Z'), category: 'CardB', value: 5262148898 }, { date: new Date('2016-10-01T00:00:00.000Z'), category: 'CardB', value: 4651933407 }, { date: new Date('2016-11-01T00:00:00.000Z'), category: 'CardB', value: 6772849978 }, { date: new Date('2016-12-01T00:00:00.000Z'), category: 'CardB', value: 5609829820 } ]; const EXPECTEDORDINALACCESSOR = 'date'; const EXPECTEDSERIESACCESSOR = 'category'; const EXPECTEDVALUEACCESSOR = 'value'; const EXPECTEDUNIQUEID = 'unique-d-plot'; const MINVALUE = 3484192554; const MAXVALUE = 9709829820; const innerMinValue = MINVALUE - (MAXVALUE - MINVALUE) * 0.15; const innerMaxValue = MAXVALUE + (MAXVALUE - MINVALUE) * 0.15; // EXTRA DATA TO ENABLE LAYOUT CHANGES const LAYOUTDATA = [ { region: 'North America', category: 'CardA', value: MINVALUE }, { region: 'CEMEA', category: 'CardA', value: 7628909842 }, { region: 'South America', category: 'CardA', value: 8334842966 }, { region: 'Asia and Pacific', category: 'CardA', value: MAXVALUE }, { region: 'North America', category: 'CardB', value: 7570994739 }, { region: 'CEMEA', category: 'CardB', value: 4628909842 }, { region: 'South America', category: 'CardB', value: 5534842966 }, { region: 'Asia and Pacific', category: 'CardB', value: 4388600035 } ]; // END:minimal props need to be passed to component // disable accessibility validation to keep output stream(terminal) clean const EXPECTEDACCESSIBILITY = { disableValidation: true }; beforeEach(async () => { page = await newSpecPage({ components: [DumbbellPlot, KeyboardInstructions, DataTable], html: '<div></div>' }); component = page.doc.createElement('dumbbell-plot'); component.uniqueID = EXPECTEDUNIQUEID; component.data = EXPECTEDDATA; component.unitTest = true; component.ordinalAccessor = EXPECTEDORDINALACCESSOR; component.seriesAccessor = EXPECTEDSERIESACCESSOR; component.valueAccessor = EXPECTEDVALUEACCESSOR; component.accessibility = EXPECTEDACCESSIBILITY; }); it('should build', () => { expect(new DumbbellPlot()).toBeTruthy(); }); describe('render', () => { beforeEach(() => { // MOCK MATH.Random TO HANDLE UNIQUE ID CODE FROM ACCESSIBILITY UTIL jest.spyOn(global.Math, 'random').mockReturnValue(0.123456789); }); afterEach(() => { // RESTORE GLOBAL FUNCTION FROM MOCK AFTER TEST jest.spyOn(global.Math, 'random').mockRestore(); }); it('should render with minimal props[data,oridnalAccessor,seriesAccessor,valueAccessor] given', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT expect(page.root).toMatchSnapshot(); }); }); describe('generic test suite', () => { Object.keys(unitTestGeneric).forEach(test => { if (unitTestGeneric[test].prop !== 'data') { const innerTestProps = unitTestGeneric[test].testDefault ? { [unitTestGeneric[test].prop]: DumbbellPlotDefaultValues[unitTestGeneric[test].prop] } : unitTestGeneric[test].prop === 'data' ? { data: EXPECTEDDATA } : unitTestGeneric[test].testProps; const innerTestSelector = unitTestGeneric[test].testSelector === 'component-name' ? 'dumbbell-plot' : unitTestGeneric[test].testSelector === '[data-testid=mark]' ? '[data-testid=marker]' : unitTestGeneric[test].testSelector; it(`${unitTestGeneric[test].prop}: ${unitTestGeneric[test].name}`, () => unitTestGeneric[test].testFunc(component, page, innerTestProps, innerTestSelector)); } }); // have to do custom data test due to how data is joined to dumbbell it('data: custom data on load', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); let counter = 0; elements.forEach(element => { counter = counter + 2; const mappedCardAData = element['__data__'].values.find(o => o.category === 'CardA'); // tslint:disable-line: no-string-literal const mappedCardBData = element['__data__'].values.find(o => o.category === 'CardB'); // tslint:disable-line: no-string-literal const expectedMonthCardAData = EXPECTEDDATA.find( o => o.date === mappedCardAData.date && o.category === 'CardA' ); const expectedMonthCardBData = EXPECTEDDATA.find( o => o.date === mappedCardBData.date && o.category === 'CardB' ); expect(mappedCardAData).toEqual(expectedMonthCardAData); expect(mappedCardBData).toEqual(expectedMonthCardBData); }); expect(counter).toEqual(24); }); it('data: custom data enter on update', async () => { // ARRANGE const BEGINNINGDATA = [EXPECTEDDATA[0], EXPECTEDDATA[1], EXPECTEDDATA[12], EXPECTEDDATA[13]]; component.data = BEGINNINGDATA; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.data = EXPECTEDDATA; await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); let counter = 0; elements.forEach(element => { counter = counter + 2; const mappedCardAData = element['__data__'].values.find(o => o.category === 'CardA'); // tslint:disable-line: no-string-literal const mappedCardBData = element['__data__'].values.find(o => o.category === 'CardB'); // tslint:disable-line: no-string-literal const expectedMonthCardAData = EXPECTEDDATA.find( o => o.date === mappedCardAData.date && o.category === 'CardA' ); const expectedMonthCardBData = EXPECTEDDATA.find( o => o.date === mappedCardBData.date && o.category === 'CardB' ); expect(mappedCardAData).toEqual(expectedMonthCardAData); expect(mappedCardBData).toEqual(expectedMonthCardBData); }); expect(counter).toEqual(24); }); it('data: custom data exit on update', async () => { // ARRANGE const EXITDATA = [EXPECTEDDATA[0], EXPECTEDDATA[12]]; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.data = EXITDATA; await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach((element, i) => { if (element['__data__'].key === 'Thu Dec 31 2015 16:00:00 GMT-0800 (Pacific Standard Time)') { const mappedCardAData = element['__data__'].values.find(o => o.category === 'CardA'); // tslint:disable-line: no-string-literal const mappedCardBData = element['__data__'].values.find(o => o.category === 'CardB'); // tslint:disable-line: no-string-literal const expectedMonthCardAData = EXPECTEDDATA.find( o => o.date === mappedCardAData.date && o.category === 'CardA' ); const expectedMonthCardBData = EXPECTEDDATA.find( o => o.date === mappedCardBData.date && o.category === 'CardB' ); expect(mappedCardAData).toEqual(expectedMonthCardAData); expect(mappedCardBData).toEqual(expectedMonthCardBData); } else { const lastTransitionKey = Object.keys(element['__transition'])[ // tslint:disable-line: no-string-literal Object.keys(element['__transition']).length - 1 // tslint:disable-line: no-string-literal ]; // tslint:disable-line: no-string-literal const transitionName = element['__transition'][lastTransitionKey].name; // tslint:disable-line: no-string-literal expect(transitionName).toEqual('exit'); } }); }); }); describe('accessibility', () => { describe('validation', () => { it('refer to generic results above for accessibility validation tests', () => { expect(true).toBeTruthy(); }); }); }); describe('base', () => { it('refer to generic results above for base tests', () => { expect(true).toBeTruthy(); }); describe('layout', () => { const EXPECTEDORDINALSCALE = scalePoint() .domain(LAYOUTDATA.map(d => d.region)) .padding(0.5) .range([0, 500]); const EXPECTEDLINEARSCALE = scaleLinear() .domain([innerMinValue, innerMaxValue]) .range([0, 500]); const EXPECTEDTIMESCALE = scaleTime() .domain([ timeMonth.offset(new Date('2016-01-01T00:00:00.000Z'), -1), timeMonth.offset(new Date('2016-12-01T00:00:00.000Z'), 1) ]) .range([0, 500]); it('should render chart horizontally when layout prop is horizontal', async () => { // ARRANGE component.data = LAYOUTDATA; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.width = 500; component.height = 500; component.margin = { bottom: 0, left: 0, right: 0, top: 0 }; component.padding = { bottom: 0, left: 0, right: 0, top: 0 }; component.layout = 'horizontal'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const lines = page.doc.querySelectorAll('[data-testid=line]'); await asyncForEach(lines, async line => { flushTransitions(line); const expectedDataRecords = LAYOUTDATA.filter(o => o.region === line['__data__'].key); // tslint:disable-line: no-string-literal expect(roundTo(parseFloat(line.getAttribute('data-centerX1')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[0].value), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerX2')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[1].value), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY1')), 4)).toEqual( roundTo(500 - EXPECTEDORDINALSCALE(expectedDataRecords[0].region), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY2')), 4)).toEqual( roundTo(500 - EXPECTEDORDINALSCALE(expectedDataRecords[1].region), 4) ); }); }); it('should render chart vertically when layout prop is vertical', async () => { // ARRANGE component.data = LAYOUTDATA; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.width = 500; component.height = 500; component.margin = { bottom: 0, left: 0, right: 0, top: 0 }; component.padding = { bottom: 0, left: 0, right: 0, top: 0 }; component.layout = 'vertical'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const lines = page.doc.querySelectorAll('[data-testid=line]'); lines.forEach(line => { flushTransitions(line); const expectedDataRecords = LAYOUTDATA.filter(o => o.region === line['__data__'].key); // tslint:disable-line: no-string-literal expect(roundTo(parseFloat(line.getAttribute('data-centerX1')), 4)).toEqual( roundTo(EXPECTEDORDINALSCALE(expectedDataRecords[0].region), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerX2')), 4)).toEqual( roundTo(EXPECTEDORDINALSCALE(expectedDataRecords[1].region), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY1')), 4)).toEqual( roundTo(500 - EXPECTEDLINEARSCALE(expectedDataRecords[0].value), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY2')), 4)).toEqual( roundTo(500 - EXPECTEDLINEARSCALE(expectedDataRecords[1].value), 4) ); }); }); it('should render chart vertically when layout prop is horizontal and oridnal access is a date', async () => { // ARRANGE component.width = 500; component.height = 500; component.margin = { bottom: 0, left: 0, right: 0, top: 0 }; component.padding = { bottom: 0, left: 0, right: 0, top: 0 }; component.layout = 'horizontal'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const lines = page.doc.querySelectorAll('[data-testid=line]'); lines.forEach(line => { flushTransitions(line); const expectedDataRecords = EXPECTEDDATA.filter( o => o.date.getTime() === new Date(line['__data__'].key).getTime() ); // tslint:disable-line: no-string-literal expect(roundTo(parseFloat(line.getAttribute('data-centerX1')), 4)).toEqual( roundTo(EXPECTEDTIMESCALE(expectedDataRecords[0].date), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerX2')), 4)).toEqual( roundTo(EXPECTEDTIMESCALE(expectedDataRecords[1].date), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY1')), 4)).toEqual( roundTo(500 - EXPECTEDLINEARSCALE(expectedDataRecords[0].value), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY2')), 4)).toEqual( roundTo(500 - EXPECTEDLINEARSCALE(expectedDataRecords[1].value), 4) ); }); }); }); }); describe('margin & padding', () => { it('refer to generic results above for margin & padding tests', () => { expect(true).toBeTruthy(); }); }); // the bbox call in d3-svg-annotations breaks due to the mockSVGElement not // having the bbox function available on it. describe.skip('annotations', () => { // TODO: need to add more precise test case for annotations label and text it('should pass annotation prop', async () => { // ARRANGE const annotations = [ { note: {}, y: [7670994739], x: ['2016-01-01'], dy: [9709829820], dx: ['2016-12-01'], className: 'dumbbell-annotation', type: 'annotationLabel', connector: { type: 'curve', curve: 'curveLinear', points: [ [['2016-02-01', '2016-01-01'], [7628909842, 7670994739]], [['2016-03-01', '2016-01-01'], [8358837379, 7670994739]], [['2016-04-01', '2016-01-01'], [8334842966, 7670994739]], [['2016-05-01', '2016-01-01'], [8588600035, 7670994739]], [['2016-06-01', '2016-01-01'], [5484192554, 7670994739]], [['2016-07-01', '2016-01-01'], [6778636197, 7670994739]], [['2016-08-01', '2016-01-01'], [8811163096, 7670994739]], [['2016-09-01', '2016-01-01'], [8462148898, 7670994739]], [['2016-10-01', '2016-01-01'], [9051933407, 7670994739]], [['2016-11-01', '2016-01-01'], [8872849978, 7670994739]] ] }, color: 'categorical_blue', parseAsDates: ['x'] }, { note: {}, y: [6570994739], x: ['2016-01-01'], dy: [5609829820], dx: ['2016-12-01'], className: 'dumbbell-annotation', type: 'annotationLabel', connector: { type: 'curve', curve: 'curveLinear', points: [ [['2016-02-01', '2016-01-01'], [4628909842, 6570994739]], [['2016-03-01', '2016-01-01'], [3358837379, 6570994739]], [['2016-04-01', '2016-01-01'], [5534842966, 6570994739]], [['2016-05-01', '2016-01-01'], [4388600035, 6570994739]], [['2016-06-01', '2016-01-01'], [7484192554, 6570994739]], [['2016-07-01', '2016-01-01'], [8978636197, 6570994739]], [['2016-08-01', '2016-01-01'], [6411163096, 6570994739]], [['2016-09-01', '2016-01-01'], [5262148898, 6570994739]], [['2016-10-01', '2016-01-01'], [4651933407, 6570994739]], [['2016-11-01', '2016-01-01'], [6772849978, 6570994739]] ] }, color: 'catecategorical_grey', parseAsDates: ['x'] } ]; component.annotations = annotations; // ACT page.root.append(component); await page.waitForChanges(); // ASSERT const annotationGroup = page.doc.querySelectorAll('[data-testid=annotation-group]'); expect(annotationGroup).toMatchSnapshot(); }); }); describe('axes', () => { describe('minValueOverride', () => { const EXPECTEDLINEARSCALE = scaleLinear() .domain([0, innerMaxValue]) .range([500, 0]); it('should baseline y axis at zero when passed on load', async () => { // ARRANGE component.minValueOverride = 0; component.height = 500; component.margin = { bottom: 0, left: 0, right: 0, top: 0 }; component.padding = { bottom: 0, left: 0, right: 0, top: 0 }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const lines = page.doc.querySelectorAll('[data-testid=line]'); lines.forEach(line => { flushTransitions(line); const expectedDataRecords = EXPECTEDDATA.filter( o => o.date.getTime() === new Date(line['__data__'].key).getTime() ); // tslint:disable-line: no-string-literal expect(roundTo(parseFloat(line.getAttribute('data-centerY1')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[0].value), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY2')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[1].value), 4) ); }); }); it('should baseline y axis at zero when passed on update', async () => { // ARRANGE component.height = 500; component.margin = { bottom: 0, left: 0, right: 0, top: 0 }; component.padding = { bottom: 0, left: 0, right: 0, top: 0 }; // ACT LOAD page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.minValueOverride = 0; await page.waitForChanges(); // ASSERT const lines = page.doc.querySelectorAll('[data-testid=line]'); lines.forEach(line => { flushTransitions(line); const expectedDataRecords = EXPECTEDDATA.filter( o => o.date.getTime() === new Date(line['__data__'].key).getTime() ); // tslint:disable-line: no-string-literal expect(roundTo(parseFloat(line.getAttribute('data-centerY1')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[0].value), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY2')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[1].value), 4) ); }); }); }); describe('maxValueOverride', () => { const EXPECTEDLINEARSCALE = scaleLinear() .domain([innerMinValue, 20000000000]) .range([500, 0]); it('should topline y axis at 20b when passed on load', async () => { // ARRANGE component.maxValueOverride = 20000000000; component.height = 500; component.margin = { bottom: 0, left: 0, right: 0, top: 0 }; component.padding = { bottom: 0, left: 0, right: 0, top: 0 }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const lines = page.doc.querySelectorAll('[data-testid=line]'); lines.forEach(line => { flushTransitions(line); const expectedDataRecords = EXPECTEDDATA.filter( o => o.date.getTime() === new Date(line['__data__'].key).getTime() ); // tslint:disable-line: no-string-literal expect(roundTo(parseFloat(line.getAttribute('data-centerY1')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[0].value), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY2')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[1].value), 4) ); }); }); it('should topline y axis at 20b when passed on update', async () => { // ARRANGE component.height = 500; component.margin = { bottom: 0, left: 0, right: 0, top: 0 }; component.padding = { bottom: 0, left: 0, right: 0, top: 0 }; // ACT LOAD page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.maxValueOverride = 20000000000; await page.waitForChanges(); // ASSERT const lines = page.doc.querySelectorAll('[data-testid=line]'); lines.forEach(line => { flushTransitions(line); const expectedDataRecords = EXPECTEDDATA.filter( o => o.date.getTime() === new Date(line['__data__'].key).getTime() ); // tslint:disable-line: no-string-literal expect(roundTo(parseFloat(line.getAttribute('data-centerY1')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[0].value), 4) ); expect(roundTo(parseFloat(line.getAttribute('data-centerY2')), 4)).toEqual( roundTo(EXPECTEDLINEARSCALE(expectedDataRecords[1].value), 4) ); }); }); }); describe('showBaselineX & showBaselineY', () => { it('baseline on xAxis and yAxis should not be visible by default', async () => { // ARRANGE component.data = LAYOUTDATA; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const baselineGroup = page.doc.querySelector('[data-testid=baseline-group]'); const xAxis = baselineGroup.querySelector('[data-testid=x-axis-mark]'); const yAxis = baselineGroup.querySelector('[data-testid=y-axis]'); flushTransitions(xAxis); flushTransitions(yAxis); expect(xAxis).toEqualAttribute('opacity', 0); expect(yAxis).toEqualAttribute('opacity', 0); }); it('should render yAxis baseline and not xAxis baseline when horizontal', async () => { // ARRANGE component.data = LAYOUTDATA; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.showBaselineX = true; component.showBaselineY = true; component.layout = 'horizontal'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const baselineGroup = page.doc.querySelector('[data-testid=baseline-group]'); const xAxis = baselineGroup.querySelector('[data-testid=x-axis]'); const yAxis = baselineGroup.querySelector('[data-testid=y-axis-mark]'); flushTransitions(xAxis); flushTransitions(yAxis); expect(xAxis).toEqualAttribute('opacity', 0); expect(yAxis).toEqualAttribute('opacity', 1); }); it('should render xAxis baseline and not yAxis baseline when vertical on load', async () => { // ARRANGE component.data = LAYOUTDATA; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.showBaselineX = true; component.showBaselineY = true; component.layout = 'vertical'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const baselineGroup = page.doc.querySelector('[data-testid=baseline-group]'); const xAxis = baselineGroup.querySelector('[data-testid=x-axis-mark]'); const yAxis = baselineGroup.querySelector('[data-testid=y-axis]'); flushTransitions(xAxis); flushTransitions(yAxis); expect(xAxis).toEqualAttribute('opacity', 1); expect(yAxis).toEqualAttribute('opacity', 0); }); it('should render xAxis baseline and not yAxis baseline when vertical on update', async () => { // ARRANGE component.data = LAYOUTDATA; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.layout = 'vertical'; // ACT LOAD page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.showBaselineX = true; component.showBaselineY = true; await page.waitForChanges(); // ASSERT const baselineGroup = page.doc.querySelector('[data-testid=baseline-group]'); const xAxis = baselineGroup.querySelector('[data-testid=x-axis-mark]'); const yAxis = baselineGroup.querySelector('[data-testid=y-axis]'); flushTransitions(xAxis); flushTransitions(yAxis); expect(xAxis).toEqualAttribute('opacity', 1); expect(yAxis).toEqualAttribute('opacity', 0); }); }); describe('generic axis tests', () => { Object.keys(unitTestAxis).forEach(test => { const monthTicks1 = [ 'Jan 16', 'Feb 16', 'Mar 16', 'Apr 16', 'May 16', 'Jun 16', 'Jul 16', 'Aug 16', 'Sep 16', 'Oct 16', 'Nov 16', 'Dec 16' ]; const monthTicks2 = [ 'Jan 2016', 'Feb 2016', 'Mar 2016', 'Apr 2016', 'May 2016', 'Jun 2016', 'Jul 2016', 'Aug 2016', 'Sep 2016', 'Oct 2016', 'Nov 2016', 'Dec 2016' ]; const numberTicks1 = ['3b', '4b', '5b', '6b', '7b', '8b', '9b', '10b']; const numberTicks2 = ['$3b', '$4b', '$5b', '$6b', '$7b', '$8b', '$9b', '$10b']; const expectedValues = { xaxis_format_default: monthTicks1, yaxis_format_default: numberTicks1, xaxis_format_load: monthTicks2, yaxis_format_load: numberTicks2, xaxis_format_update: monthTicks2, yaxis_format_update: numberTicks2, xaxis_tickInterval_load: monthTicks2, yaxis_tickInterval_load: numberTicks2, xaxis_tickInterval_update: monthTicks2, yaxis_tickInterval_update: numberTicks2 }; const innerTestProps = unitTestAxis[test].testDefault ? { [unitTestAxis[test].prop]: DumbbellPlotDefaultValues[unitTestAxis[test].prop] } : unitTestAxis[test].prop === 'data' ? { data: EXPECTEDDATA } : unitTestAxis[test].testProps; const innerTestSelector = unitTestAxis[test].testSelector === 'component-name' ? 'dumbbell-plot' : unitTestAxis[test].testSelector; it(`${unitTestAxis[test].prop}: ${unitTestAxis[test].name}`, () => unitTestAxis[test].testFunc(component, page, innerTestProps, innerTestSelector, expectedValues[test])); }); }); }); describe('interaction', () => { const commonInteractionProps = { data: LAYOUTDATA, ordinalAccessor: 'region', seriesAccessor: 'category' }; describe('data label based interaction tests', () => { const innerTestProps = commonInteractionProps; const innerTestSelector = '[data-testid=dataLabel][data-id="label-North America-CardA"]'; const innerNegTestSelector = '[data-testid=dataLabel][data-id=label-CEMEA-CardA]'; Object.keys(unitTestInteraction).forEach(test => { if (unitTestInteraction[test].prop === 'cursor') { it(`[${unitTestInteraction[test].group}] ${unitTestInteraction[test].prop}: ${ unitTestInteraction[test].name }`, () => unitTestInteraction[test].testFunc( component, page, innerTestProps, innerTestSelector, innerNegTestSelector )); } }); }); /* describe('clickStyle with interaction keys', () => { const testLoad = 'interaction_clickStyle_custom_load'; const testUpdate = 'interaction_clickStyle_custom_update'; const innerTestSelector = '[data-testid=dataLabel][data-id="label-North America-CardA"]'; const innerNegTestSelector = '[data-testid=dataLabel][data-id=label-CEMEA-CardB]'; const CUSTOMCLICKSTYLE = { color: visaColors.comp_green, stroke: outlineColor(visaColors.comp_green), strokeWidth: '1px' }; const EXPECTEDHOVEROPACITY = 0.25; const innerTestProps = { ...commonInteractionProps, ...{ clickStyle: CUSTOMCLICKSTYLE, hoverOpacity: EXPECTEDHOVEROPACITY, interactionKeys: ['category'] } }; it(`[${unitTestInteraction[testLoad].group}] ${unitTestInteraction[testLoad].prop}: ${ unitTestInteraction[testLoad].name } interactionKey group`, () => unitTestInteraction[testLoad].testFunc( component, page, innerTestProps, innerTestSelector, innerNegTestSelector )); it(`[${unitTestInteraction[testUpdate].group}] ${unitTestInteraction[testUpdate].prop}: ${ unitTestInteraction[testUpdate].name } interactionKey group`, () => unitTestInteraction[testUpdate].testFunc( component, page, innerTestProps, innerTestSelector, innerNegTestSelector )); const newInnerTestProps = { ...commonInteractionProps, ...{ clickStyle: CUSTOMCLICKSTYLE, hoverOpacity: EXPECTEDHOVEROPACITY, interactionKeys: ['category', 'region'] } }; it(`[${unitTestInteraction[testLoad].group}] ${unitTestInteraction[testLoad].prop}: ${ unitTestInteraction[testLoad].name } interactionKey value`, () => unitTestInteraction[testLoad].testFunc( component, page, newInnerTestProps, '[data-testid=dataLabel][data-id="label-North America-CardA"]', '[data-testid=dataLabel][data-id=label-CEMEA-CardA]' )); it(`[${unitTestInteraction[testUpdate].group}] ${unitTestInteraction[testUpdate].prop}: ${ unitTestInteraction[testUpdate].name } interactionKey value`, () => unitTestInteraction[testUpdate].testFunc( component, page, newInnerTestProps, '[data-testid=dataLabel][data-id="label-North America-CardA"]', '[data-testid=dataLabel][data-id=label-CEMEA-CardA]' )); }); describe('hoverStyle custom with interaction keys', () => { const testLoad = 'interaction_hoverStyle_custom_load'; const testUpdate = 'interaction_hoverStyle_custom_update'; const innerTestSelector = '[data-testid=bar][data-id=bar-Apr-17]'; const innerNegTestSelector = '[data-testid=bar][data-id=bar-Jul-17]'; const CUSTOMCLICKSTYLE = { color: visaColors.comp_green, stroke: outlineColor(visaColors.comp_green), strokeWidth: '1px' }; const EXPECTEDHOVEROPACITY = 0.25; const innerTestProps = { clickStyle: CUSTOMCLICKSTYLE, hoverOpacity: EXPECTEDHOVEROPACITY, interactionKeys: ['cat'] }; it(`[${unitTestInteraction[testLoad].group}] ${unitTestInteraction[testLoad].prop}: ${ unitTestInteraction[testLoad].name } interactionKey group`, () => unitTestInteraction[testLoad].testFunc( component, page, innerTestProps, innerTestSelector, innerNegTestSelector )); it(`[${unitTestInteraction[testUpdate].group}] ${unitTestInteraction[testUpdate].prop}: ${ unitTestInteraction[testUpdate].name } interactionKey group`, () => unitTestInteraction[testUpdate].testFunc( component, page, innerTestProps, innerTestSelector, innerNegTestSelector )); const newInnerTestProps = { clickStyle: CUSTOMCLICKSTYLE, hoverOpacity: EXPECTEDHOVEROPACITY, interactionKeys: ['cat', 'month'] }; it(`[${unitTestInteraction[testLoad].group}] ${unitTestInteraction[testLoad].prop}: ${ unitTestInteraction[testLoad].name } interactionKey value`, () => unitTestInteraction[testLoad].testFunc( component, page, newInnerTestProps, '[data-testid=bar][data-id=bar-Apr-17]', '[data-testid=bar][data-id=bar-May-17]' )); it(`[${unitTestInteraction[testUpdate].group}] ${unitTestInteraction[testUpdate].prop}: ${ unitTestInteraction[testUpdate].name } interactionKey value`, () => unitTestInteraction[testUpdate].testFunc( component, page, newInnerTestProps, '[data-testid=bar][data-id=bar-Apr-17]', '[data-testid=bar][data-id=bar-May-17]' )); }); */ }); describe('event-emitter', () => { // Open issue: https://github.com/ionic-team/stencil/issues/1964 // Jest throwing TypeError : mouseover,mouseout, focus, blur etc. // TECH-DEBT: Once above issue is resolved, write more precise test for event params. const commonInteractionProps = { data: LAYOUTDATA, ordinalAccessor: 'region', seriesAccessor: 'category' }; describe('generic event testing', () => { describe('label based events', () => { Object.keys(unitTestEvent).forEach(test => { const innerTestProps = { ...commonInteractionProps, ...{ showTooltip: false } }; const innerTestSelector = '[data-testid=dataLabel][data-id="label-North America-CardA"]'; it(`[${unitTestEvent[test].group}] ${unitTestEvent[test].prop}: ${unitTestEvent[test].name}`, () => unitTestEvent[test].testFunc(component, page, innerTestProps, innerTestSelector, LAYOUTDATA[0])); }); }); }); }); describe('data', () => { const commonInteractionProps = { data: LAYOUTDATA, ordinalAccessor: 'region', seriesAccessor: 'category' }; describe('uniqueId', () => { it('refer to generic results above for uniqueID tests', () => { expect(true).toBeTruthy(); }); }); describe('data', () => { it('refer to generic results above for data tests', () => { expect(true).toBeTruthy(); }); }); describe('sort', () => { it('should render data in ascending order of difference when sortOrder is asc', async () => { // ARRANGE const EXPECTEDSORTORDER = 'asc'; const EXPECTEDDATAASC = [ { region: 'North America', category: 'CardA', value: MINVALUE }, { region: 'South America', category: 'CardA', value: 8334842966 }, { region: 'CEMEA', category: 'CardA', value: 7628909842 }, { region: 'Asia and Pacific', category: 'CardA', value: MAXVALUE }, { region: 'North America', category: 'CardB', value: 7570994739 }, { region: 'South America', category: 'CardB', value: 5534842966 }, { region: 'CEMEA', category: 'CardB', value: 4628909842 }, { region: 'Asia and Pacific', category: 'CardB', value: 4388600035 } ]; component.sortOrder = EXPECTEDSORTORDER; Object.keys(commonInteractionProps).forEach(commonProp => { component[commonProp] = commonInteractionProps[commonProp]; }); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach((element, i) => { expect(element['__data__'].values[0]).toMatchObject(EXPECTEDDATAASC[i]); // tslint:disable-line: no-string-literal expect(element['__data__'].values[1]).toMatchObject(EXPECTEDDATAASC[i + 4]); // tslint:disable-line: no-string-literal }); }); it('should render data in ascending order of focus marker when sortOrder is focusAsc', async () => { // ARRANGE const EXPECTEDSORTORDER = 'focusAsc'; const EXPECTEDDATAASC = [ { region: 'North America', category: 'CardA', value: MINVALUE }, { region: 'CEMEA', category: 'CardA', value: 7628909842 }, { region: 'South America', category: 'CardA', value: 8334842966 }, { region: 'Asia and Pacific', category: 'CardA', value: MAXVALUE }, { region: 'North America', category: 'CardB', value: 7570994739 }, { region: 'CEMEA', category: 'CardB', value: 4628909842 }, { region: 'South America', category: 'CardB', value: 5534842966 }, { region: 'Asia and Pacific', category: 'CardB', value: 4388600035 } ]; component.sortOrder = EXPECTEDSORTORDER; component.focusMarker = { key: 'CardA', sizeFromBar: 0.75 }; Object.keys(commonInteractionProps).forEach(commonProp => { component[commonProp] = commonInteractionProps[commonProp]; }); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach((element, i) => { expect(element['__data__'].values[0]).toMatchObject(EXPECTEDDATAASC[i]); // tslint:disable-line: no-string-literal expect(element['__data__'].values[1]).toMatchObject(EXPECTEDDATAASC[i + 4]); // tslint:disable-line: no-string-literal }); }); it('should render data in ascending order of absolute difference when sortOrder is absoluteDiffAsc', async () => { // ARRANGE const EXPECTEDSORTORDER = 'absoluteDiffAsc'; const EXPECTEDDATAASC = [ { region: 'South America', category: 'CardA', value: 8334842966 }, { region: 'CEMEA', category: 'CardA', value: 7628909842 }, { region: 'North America', category: 'CardA', value: MINVALUE }, { region: 'Asia and Pacific', category: 'CardA', value: MAXVALUE }, { region: 'South America', category: 'CardB', value: 5534842966 }, { region: 'CEMEA', category: 'CardB', value: 4628909842 }, { region: 'North America', category: 'CardB', value: 7570994739 }, { region: 'Asia and Pacific', category: 'CardB', value: 4388600035 } ]; component.sortOrder = EXPECTEDSORTORDER; Object.keys(commonInteractionProps).forEach(commonProp => { component[commonProp] = commonInteractionProps[commonProp]; }); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach((element, i) => { expect(element['__data__'].values[0]).toMatchObject(EXPECTEDDATAASC[i]); // tslint:disable-line: no-string-literal expect(element['__data__'].values[1]).toMatchObject(EXPECTEDDATAASC[i + 4]); // tslint:disable-line: no-string-literal }); }); it('should render data in descending order of difference when sortOrder is desc', async () => { // ARRANGE const EXPECTEDSORTORDER = 'desc'; const EXPECTEDDATADESC = [ { region: 'Asia and Pacific', category: 'CardA', value: MAXVALUE }, { region: 'CEMEA', category: 'CardA', value: 7628909842 }, { region: 'South America', category: 'CardA', value: 8334842966 }, { region: 'North America', category: 'CardA', value: MINVALUE }, { region: 'Asia and Pacific', category: 'CardB', value: 4388600035 }, { region: 'CEMEA', category: 'CardB', value: 4628909842 }, { region: 'South America', category: 'CardB', value: 5534842966 }, { region: 'North America', category: 'CardB', value: 7570994739 } ]; component.sortOrder = EXPECTEDSORTORDER; Object.keys(commonInteractionProps).forEach(commonProp => { component[commonProp] = commonInteractionProps[commonProp]; }); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach((element, i) => { expect(element['__data__'].values[0]).toMatchObject(EXPECTEDDATADESC[i]); // tslint:disable-line: no-string-literal expect(element['__data__'].values[1]).toMatchObject(EXPECTEDDATADESC[i + 4]); // tslint:disable-line: no-string-literal }); }); it('should render data in descending order of focus marker when sortOrder is desc', async () => { // ARRANGE const EXPECTEDSORTORDER = 'focusDesc'; const EXPECTEDDATADESC = [ { region: 'Asia and Pacific', category: 'CardA', value: MAXVALUE }, { region: 'South America', category: 'CardA', value: 8334842966 }, { region: 'CEMEA', category: 'CardA', value: 7628909842 }, { region: 'North America', category: 'CardA', value: MINVALUE }, { region: 'Asia and Pacific', category: 'CardB', value: 4388600035 }, { region: 'South America', category: 'CardB', value: 5534842966 }, { region: 'CEMEA', category: 'CardB', value: 4628909842 }, { region: 'North America', category: 'CardB', value: 7570994739 } ]; component.sortOrder = EXPECTEDSORTORDER; component.focusMarker = { key: 'CardA', sizeFromBar: 0.75 }; Object.keys(commonInteractionProps).forEach(commonProp => { component[commonProp] = commonInteractionProps[commonProp]; }); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach((element, i) => { expect(element['__data__'].values[0]).toMatchObject(EXPECTEDDATADESC[i]); // tslint:disable-line: no-string-literal expect(element['__data__'].values[1]).toMatchObject(EXPECTEDDATADESC[i + 4]); // tslint:disable-line: no-string-literal }); }); it('should render data in descending order of absolute difference when sortOrder is desc', async () => { // ARRANGE const EXPECTEDSORTORDER = 'absoluteDiffDesc'; const EXPECTEDDATADESC = [ { region: 'Asia and Pacific', category: 'CardA', value: MAXVALUE }, { region: 'North America', category: 'CardA', value: MINVALUE }, { region: 'CEMEA', category: 'CardA', value: 7628909842 }, { region: 'South America', category: 'CardA', value: 8334842966 }, { region: 'Asia and Pacific', category: 'CardB', value: 4388600035 }, { region: 'North America', category: 'CardB', value: 7570994739 }, { region: 'CEMEA', category: 'CardB', value: 4628909842 }, { region: 'South America', category: 'CardB', value: 5534842966 } ]; component.sortOrder = EXPECTEDSORTORDER; component.focusMarker = { key: 'CardA', sizeFromBar: 0.75 }; Object.keys(commonInteractionProps).forEach(commonProp => { component[commonProp] = commonInteractionProps[commonProp]; }); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach((element, i) => { expect(element['__data__'].values[0]).toMatchObject(EXPECTEDDATADESC[i]); // tslint:disable-line: no-string-literal expect(element['__data__'].values[1]).toMatchObject(EXPECTEDDATADESC[i + 4]); // tslint:disable-line: no-string-literal }); }); it('should render data in default order when sortOrder is default', async () => { Object.keys(commonInteractionProps).forEach(commonProp => { component[commonProp] = commonInteractionProps[commonProp]; }); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach((element, i) => { expect(element['__data__'].values[0]).toMatchObject(LAYOUTDATA[i]); // tslint:disable-line: no-string-literal expect(element['__data__'].values[1]).toMatchObject(LAYOUTDATA[i + 4]); // tslint:disable-line: no-string-literal }); }); }); }); describe('bar', () => { // const commonInteractionProps = { data: LAYOUTDATA, ordinalAccessor: 'region', seriesAccessor: 'category' }; describe('barStyle.colorRule', () => { const EXPECTEDCOLORS = getColors('categorical', 3); it('bar color should be default on load', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach(element => { expect(element).toEqualAttribute('stroke', getContrastingStroke(EXPECTEDCOLORS[2])); expect(element).toEqualAttribute('fill', EXPECTEDCOLORS[2]); }); }); it('bar color should be greaterValue if set on load', async () => { // ARRANGE component.barStyle = { width: 1, opacity: 1, colorRule: 'greaterValue' }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach(element => { expect(element).toEqualAttribute('stroke', getContrastingStroke(EXPECTEDCOLORS[0])); expect(element).toEqualAttribute('fill', EXPECTEDCOLORS[0]); }); }); it('bar color should be focus if set on load', async () => { // ARRANGE component.focusMarker = { key: 'CardB', sizeFromBar: 4 }; component.barStyle = { width: 1, opacity: 1, colorRule: 'focus' }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach(element => { expect(element).toEqualAttribute('stroke', getContrastingStroke(EXPECTEDCOLORS[1])); expect(element).toEqualAttribute('fill', EXPECTEDCOLORS[1]); }); }); it('bar color should be greaterValue if set on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.barStyle = { width: 1, opacity: 1, colorRule: 'greaterValue' }; await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); await asyncForEach(elements, async element => { flushTransitions(element); await page.waitForChanges(); expect(element).toEqualAttribute('stroke', getContrastingStroke(EXPECTEDCOLORS[0])); expect(element).toEqualAttribute('fill', EXPECTEDCOLORS[0]); }); }); it('bar color should be focus if set on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.focusMarker = { key: 'CardA', sizeFromBar: 4 }; component.barStyle = { width: 1, opacity: 1, colorRule: 'focus' }; await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); await asyncForEach(elements, async element => { flushTransitions(element); await page.waitForChanges(); expect(element).toEqualAttribute('stroke', getContrastingStroke(EXPECTEDCOLORS[0])); expect(element).toEqualAttribute('fill', EXPECTEDCOLORS[0]); }); }); }); describe('barStyle.opacity', () => { it('bar stroke opacity should default to 1 on load', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach(element => { expect(element).toEqualAttribute('stroke-opacity', 1); }); }); it('bar stroke opacity set to 0.5 on load', async () => { // ARRANGE component.barStyle = { width: 1, opacity: 0.5, colorRule: 'default' }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach(element => { expect(element).toEqualAttribute('stroke-opacity', 0.5); }); }); it('bar stroke opacity set to 0.5 on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.barStyle = { width: 1, opacity: 0.25, colorRule: 'default' }; await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); await asyncForEach(elements, async element => { flushTransitions(element); await page.waitForChanges(); expect(element).toEqualAttribute('stroke-opacity', 0.25); }); }); }); describe('barStyle.width', () => { it('bar width should default to 1 on load', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach(element => { expect(element).toEqualAttribute('data-barSize', 1); }); }); it('bar width set to 5 on load', async () => { // ARRANGE component.barStyle = { width: 5, opacity: 1, colorRule: 'default' }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); elements.forEach(element => { expect(element).toEqualAttribute('data-barSize', 5); }); }); it('bar width set to 2.5 on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.barStyle = { width: 2.5, opacity: 1, colorRule: 'default' }; await page.waitForChanges(); // ASSERT const elements = page.doc.querySelectorAll('[data-testid=line]'); await asyncForEach(elements, async element => { flushTransitions(element); await page.waitForChanges(); expect(element).toEqualAttribute('data-barSize', 2.5); }); }); }); }); describe('labels', () => { const commonInteractionProps = { data: LAYOUTDATA, ordinalAccessor: 'region', seriesAccessor: 'category' }; describe('tooltip', () => { const tooltip1 = { tooltipLabel: { format: [], labelAccessor: ['region'], labelTitle: ['Testing123'] } }; const tooltip2 = { tooltipLabel: { format: ['', '$0[.][0]a'], labelAccessor: ['region', 'value'], labelTitle: ['Testing123', 'Count'] } }; describe('generic tooltip tests', () => { Object.keys(unitTestTooltip).forEach(test => { const innerTestSelector = '[data-testid=dataLabel][data-id="label-North America-CardA"]'; const innerTooltipProps = { tooltip_tooltipLabel_custom_load: tooltip1, tooltip_tooltipLabel_custom_update: tooltip1, tooltip_tooltipLabel_custom_format_load: tooltip2, tooltip_tooltipLabel_custom_format_update: tooltip2 }; const innerTooltipContent = { tooltip_tooltipLabel_default: '<p style="margin: 0;"><b>North America</b><br/>CardA:<b>3.5b</b></p>', tooltip_tooltipLabel_custom_load: '<p style="margin: 0;">Testing123:<b>North America</b><br></p>', tooltip_tooltipLabel_custom_update: '<p style="margin: 0;">Testing123:<b>North America</b><br></p>', tooltip_tooltipLabel_custom_format_load: '<p style="margin: 0;">Testing123:<b>North America</b><br>Count:<b>$3.5b</b><br></p>', tooltip_tooltipLabel_custom_format_update: '<p style="margin: 0;">Testing123:<b>North America</b><br>Count:<b>$3.5b</b><br></p>' }; const innerTestProps = { ...commonInteractionProps, ...unitTestTooltip[test].testProps, ...innerTooltipProps[test] }; // we have to handle clickFunc separately due to this.zooming boolean in circle-packing load it(`${unitTestTooltip[test].prop}: ${unitTestTooltip[test].name}`, () => unitTestTooltip[test].testFunc( component, page, innerTestProps, innerTestSelector, innerTooltipContent[test] )); }); }); }); describe('dataLabel', () => { describe('visible', () => { it('should render dataLabel by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); const dataLabelWrapper = page.doc.querySelector('[data-testid=dataLabel-wrapper]'); const dataLabel = page.doc.querySelector('[data-testid=dataLabel]'); expect(dataLabelWrapper).toEqualAttribute('opacity', 1); expect(dataLabel).toEqualAttribute('opacity', 1); }); it('should not render the bar data labels if visible is false on load', async () => { // ARRANGE // equal earth is the default this should match without setting prop component.dataLabel = { visible: false, labelAccessor: '' }; // ACT page.root.appendChild(component); await page.waitForChanges(); const dataLabelWrapper = page.doc.querySelector('[data-testid=dataLabel-wrapper]'); const dataLabel = page.doc.querySelector('[data-testid=dataLabel]'); expect(dataLabelWrapper).toEqualAttribute('opacity', 0); expect(dataLabel).toEqualAttribute('opacity', 1); }); it('should not render the bar data labels if visible is false on update', async () => { // ARRANGE // equal earth is the default this should match without setting prop // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.dataLabel = { visible: false, labelAccessor: '' }; await page.waitForChanges(); const dataLabelWrapper = page.doc.querySelector('[data-testid=dataLabel-wrapper]'); const dataLabel = page.doc.querySelector('[data-testid=dataLabel]'); expect(dataLabelWrapper).toEqualAttribute('opacity', 0); expect(dataLabel).toEqualAttribute('opacity', 1); }); }); describe('labelAccessor & format', () => { it('should default to the value accessor if default', async () => { // ARRANGE component.data = LAYOUTDATA; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const dataLabel = page.doc.querySelector('[data-testid=dataLabel][data-id="label-North America-CardA"]'); const expectedLabelValue = formatStats(LAYOUTDATA[0].value, '0[.][0]a'); // tslint:disable-line: no-string-literal expect(dataLabel).toEqualText(expectedLabelValue); }); it('should render specific field and format if labelAccessor is passed on load', async () => { // ARRANGE // equal earth is the default this should match without setting prop LAYOUTDATA.map(rec => (rec['random'] = Math.random())); // tslint:disable-line: no-string-literal component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.dataLabel = { visible: true, labelAccessor: 'random', format: '0[.][0][0]%', position: 'ends' }; component.data = LAYOUTDATA; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const dataLabel = page.doc.querySelector('[data-testid=dataLabel][data-id="label-North America-CardA"]'); const expectedLabelValue = formatStats(LAYOUTDATA[0]['random'], '0[.][0][0]%'); // tslint:disable-line: no-string-literal expect(dataLabel).toEqualText(expectedLabelValue); }); it('should render specific field and format if labelAccessor is passed on update', async () => { // ARRANGE // equal earth is the default this should match without setting prop LAYOUTDATA.map(rec => (rec['random'] = Math.random())); // tslint:disable-line: no-string-literal component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.dataLabel = { visible: true, labelAccessor: 'random', format: '0[.][0][0]%', position: 'ends' }; await page.waitForChanges(); // ASSERT const dataLabel = page.doc.querySelector('[data-testid=dataLabel][data-id="label-North America-CardA"]'); const expectedLabelValue = formatStats(LAYOUTDATA[0]['random'], '0[.][0][0]%'); // tslint:disable-line: no-string-literal flushTransitions(dataLabel); await page.waitForChanges(); expect(dataLabel).toEqualText(expectedLabelValue); }); }); describe('placement - vertical', () => { it('should place labels on ends of dumbbells by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=dataLabel]'); const line = page.doc.querySelector('[data-testid=line]'); expect(parseFloat(label.getAttribute('y'))).toBeLessThanOrEqual( parseFloat(line.getAttribute('data-centerY1')) ); }); it('should place labels on side of bars if passed left or right on load', async () => { // ARRANGE component.dataLabel = { visible: true, labelAccessor: 'value', format: '$0[.][0]a', placement: 'right' }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=dataLabel]'); const line = page.doc.querySelector('[data-testid=line]'); flushTransitions(label); flushTransitions(line); await page.waitForChanges(); expect(parseFloat(label.getAttribute('y'))).toEqual(parseFloat(line.getAttribute('data-centerY1'))); }); it('should place labels on side of bars if passed left or right on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.dataLabel = { visible: true, labelAccessor: 'value', format: '$0[.][0]a', placement: 'left' }; await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=dataLabel]'); const line = page.doc.querySelector('[data-testid=line]'); flushTransitions(label); flushTransitions(line); await page.waitForChanges(); expect(parseFloat(label.getAttribute('y'))).toEqual(parseFloat(line.getAttribute('data-centerY1'))); }); }); describe('placement - horizontal', () => { it('should place labels on ends of dumbbells by default', async () => { // ARRANGE component.layout = 'horizontal'; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=dataLabel]'); const line = page.doc.querySelector('[data-testid=line]'); expect(parseFloat(label.getAttribute('x'))).toBeLessThanOrEqual( parseFloat(line.getAttribute('data-centerX1')) ); }); it('should place labels on side of bars if passed top or bottom on load', async () => { // ARRANGE component.layout = 'horizontal'; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; component.dataLabel = { visible: true, labelAccessor: 'value', format: '$0[.][0]a', placement: 'top' }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=dataLabel]'); const line = page.doc.querySelector('[data-testid=line]'); flushTransitions(label); flushTransitions(line); await page.waitForChanges(); expect(parseFloat(label.getAttribute('x'))).toEqual(parseFloat(line.getAttribute('data-centerX1'))); }); it('should place labels on side of bars if passed top or bottom on update', async () => { // ARRANGE component.layout = 'horizontal'; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.dataLabel = { visible: true, labelAccessor: 'value', format: '$0[.][0]a', placement: 'bottom' }; await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=dataLabel]'); const line = page.doc.querySelector('[data-testid=line]'); flushTransitions(label); flushTransitions(line); await page.waitForChanges(); expect(parseFloat(label.getAttribute('x'))).toEqual(parseFloat(line.getAttribute('data-centerX1')) + 4); }); }); }); describe('differenceLabel', () => { describe('visible', () => { it('should not render differenceLabel by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); const dataLabel = page.doc.querySelector('[data-testid=difference-label]'); expect(dataLabel).toEqualAttribute('opacity', 0); }); it('should render differenceLabel when passed on load', async () => { // ARRANGE component.differenceLabel = { calculation: 'difference', format: '0[.][0][0]a', placement: 'left', visible: true }; // ACT page.root.appendChild(component); await page.waitForChanges(); const dataLabel = page.doc.querySelector('[data-testid=difference-label]'); flushTransitions(dataLabel); expect(dataLabel).toEqualAttribute('opacity', 1); }); it('should render differenceLabel when passed on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.differenceLabel = { calculation: 'difference', format: '0[.][0][0]a', placement: 'left', visible: true }; await page.waitForChanges(); const dataLabel = page.doc.querySelector('[data-testid=difference-label]'); expect(dataLabel).toEqualAttribute('opacity', 1); }); }); describe('calculation & format', () => { it('should render calculation difference and default format by default (though hidden)', async () => { // ARRANGE component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT page.root.appendChild(component); await page.waitForChanges(); const dataLabel = page.doc.querySelector('[data-id="difference-label-North America"]'); flushTransitions(dataLabel); await page.waitForChanges(); expect(dataLabel).toEqualText(formatStats(LAYOUTDATA[0].value - LAYOUTDATA[4].value, '0[.][0][0]a')); }); it('should render calculation middle and custom format on load (though hidden)', async () => { // ARRANGE component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; component.differenceLabel = { calculation: 'middle', format: '$0[.][0]a', placement: 'left', visible: true }; // ACT page.root.appendChild(component); await page.waitForChanges(); const dataLabel = page.doc.querySelector('[data-id="difference-label-North America"]'); flushTransitions(dataLabel); await page.waitForChanges(); expect(dataLabel).toEqualText( formatStats(LAYOUTDATA[0].value - (LAYOUTDATA[0].value - LAYOUTDATA[4].value) / 2, '$0[.][0]a') ); }); it('should render calculation middle and custom format on update (though hidden)', async () => { // ARRANGE component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.differenceLabel = { calculation: 'middle', format: '$0[.][0]a', placement: 'left', visible: true }; await page.waitForChanges(); const dataLabel = page.doc.querySelector('[data-id="difference-label-North America"]'); flushTransitions(dataLabel); await page.waitForChanges(); expect(dataLabel).toEqualText( formatStats(LAYOUTDATA[0].value - (LAYOUTDATA[0].value - LAYOUTDATA[4].value) / 2, '$0[.][0]a') ); }); }); describe('placement - vertical', () => { it('should place difference labels on left of dumbbells by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector( '[data-id="difference-label-Thu Dec 31 2015 16:00:00 GMT-0800 (Pacific Standard Time)"]' ); const line = page.doc.querySelector( '[data-id="line-Thu Dec 31 2015 16:00:00 GMT-0800 (Pacific Standard Time)"]' ); const labelPlacement = roundTo( parseFloat(line.getAttribute('data-centerY1')) + (parseFloat(line.getAttribute('data-centerY2')) - parseFloat(line.getAttribute('data-centerY1'))) / 2, 4 ); expect(roundTo(parseFloat(label.getAttribute('y')), 4)).toEqual(labelPlacement); expect(parseFloat(label.getAttribute('x')) + parseFloat(label.getAttribute('dx'))).toBeLessThan( parseFloat(line.getAttribute('data-centerX1')) ); }); it('should place labels on side of bars if passed left or right on load', async () => { // ARRANGE component.differenceLabel = { calculation: 'difference', format: '0[.][0][0]a', placement: 'right', visible: true }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector( '[data-id="difference-label-Thu Dec 31 2015 16:00:00 GMT-0800 (Pacific Standard Time)"]' ); const line = page.doc.querySelector( '[data-id="line-Thu Dec 31 2015 16:00:00 GMT-0800 (Pacific Standard Time)"]' ); flushTransitions(label); flushTransitions(line); await page.waitForChanges(); const labelPlacement = roundTo( parseFloat(line.getAttribute('data-centerY1')) + (parseFloat(line.getAttribute('data-centerY2')) - parseFloat(line.getAttribute('data-centerY1'))) / 2, 4 ); expect(roundTo(parseFloat(label.getAttribute('y')), 4)).toEqual(labelPlacement); expect(parseFloat(label.getAttribute('x')) + parseFloat(label.getAttribute('dx'))).toBeGreaterThan( parseFloat(line.getAttribute('data-centerX1')) ); }); it('should place labels on side of bars if passed left or right on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.differenceLabel = { calculation: 'difference', format: '0[.][0][0]a', placement: 'right', visible: true }; await page.waitForChanges(); // ASSERT const label = page.doc.querySelector( '[data-id="difference-label-Thu Dec 31 2015 16:00:00 GMT-0800 (Pacific Standard Time)"]' ); const line = page.doc.querySelector( '[data-id="line-Thu Dec 31 2015 16:00:00 GMT-0800 (Pacific Standard Time)"]' ); flushTransitions(label); flushTransitions(line); await page.waitForChanges(); const labelPlacement = roundTo( parseFloat(line.getAttribute('data-centerY1')) + (parseFloat(line.getAttribute('data-centerY2')) - parseFloat(line.getAttribute('data-centerY1'))) / 2, 4 ); expect(roundTo(parseFloat(label.getAttribute('y')), 4)).toEqual(labelPlacement); expect(parseFloat(label.getAttribute('x')) + parseFloat(label.getAttribute('dx'))).toBeGreaterThan( parseFloat(line.getAttribute('data-centerX1')) ); }); }); describe('placement - horizontal', () => { it('should place difference labels on tops of dumbbells by default', async () => { // ARRANGE component.layout = 'horizontal'; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-id="difference-label-North America"]'); const line = page.doc.querySelector('[data-id="line-North America"]'); const labelPlacement = roundTo( parseFloat(line.getAttribute('data-centerX1')) + (parseFloat(line.getAttribute('data-centerX2')) - parseFloat(line.getAttribute('data-centerX1'))) / 2, 4 ); expect(roundTo(parseFloat(label.getAttribute('x')), 4)).toEqual(labelPlacement); expect(parseFloat(label.getAttribute('y')) + parseFloat(label.getAttribute('dy'))).toBeLessThan( parseFloat(line.getAttribute('data-centerY1')) ); }); it('should place difference labels on bottoms of dumbbells on load', async () => { // ARRANGE component.layout = 'horizontal'; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; component.differenceLabel = { calculation: 'difference', format: '0[.][0][0]a', placement: 'bottom', visible: true }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-id="difference-label-North America"]'); const line = page.doc.querySelector('[data-id="line-North America"]'); const labelPlacement = roundTo( parseFloat(line.getAttribute('data-centerX1')) + (parseFloat(line.getAttribute('data-centerX2')) - parseFloat(line.getAttribute('data-centerX1'))) / 2, 4 ); expect(roundTo(parseFloat(label.getAttribute('x')), 4)).toEqual(labelPlacement); expect(parseFloat(label.getAttribute('y')) + parseFloat(label.getAttribute('dy'))).toBeGreaterThan( parseFloat(line.getAttribute('data-centerY1')) ); }); it('should place difference labels on bottoms of dumbbells on update', async () => { // ARRANGE component.layout = 'horizontal'; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.differenceLabel = { calculation: 'difference', format: '0[.][0][0]a', placement: 'bottom', visible: true }; await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-id="difference-label-North America"]'); const line = page.doc.querySelector('[data-id="line-North America"]'); flushTransitions(label); flushTransitions(line); await page.waitForChanges(); const labelPlacement = roundTo( parseFloat(line.getAttribute('data-centerX1')) + (parseFloat(line.getAttribute('data-centerX2')) - parseFloat(line.getAttribute('data-centerX1'))) / 2, 4 ); expect(roundTo(parseFloat(label.getAttribute('x')), 4)).toEqual(labelPlacement); expect(parseFloat(label.getAttribute('y')) + parseFloat(label.getAttribute('dy'))).toBeGreaterThan( parseFloat(line.getAttribute('data-centerY1')) ); }); }); }); describe('seriesLabel', () => { describe('visible', () => { it('should render seriesLabel by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); const dataLabel = page.doc.querySelector('[data-testid=series-label]'); flushTransitions(dataLabel); expect(dataLabel).toEqualAttribute('opacity', 1); }); it('should not render seriesLabel when passed on load', async () => { // ARRANGE component.seriesLabel = { visible: false, placement: 'right', label: [] }; // ACT page.root.appendChild(component); await page.waitForChanges(); const dataLabel = page.doc.querySelector('[data-testid=series-label]'); flushTransitions(dataLabel); expect(dataLabel).toEqualAttribute('opacity', 0); }); it('should not render seriesLabel when passed on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.seriesLabel = { visible: false, placement: 'right', label: [] }; await page.waitForChanges(); const dataLabel = page.doc.querySelector('[data-testid=series-label]'); flushTransitions(dataLabel); expect(dataLabel).toEqualAttribute('opacity', 0); }); }); describe('placement - vertical', () => { it('should place series labels on right of chart by default', async () => { // ARRANGE component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=series-label]'); const lastLine = page.doc.querySelector('[data-id="line-Asia and Pacific"]'); const innerPaddedWidth = component.width - component.margin.left - component.margin.right - component.padding.left - component.padding.right; flushTransitions(label); flushTransitions(lastLine); await page.waitForChanges(); expect(label).toEqualAttribute('y', lastLine.getAttribute('data-centerY1')); expect(label).toEqualAttribute('x', innerPaddedWidth); }); it('should place series labels on left of chart on load', async () => { // ARRANGE component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; component.seriesLabel = { visible: true, placement: 'left', label: [] }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=series-label]'); const firstLine = page.doc.querySelector('[data-id="line-North America"]'); flushTransitions(label); flushTransitions(firstLine); await page.waitForChanges(); expect(label).toEqualAttribute('y', firstLine.getAttribute('data-centerY1')); expect(label).toEqualAttribute('x', 0); }); it('should place series labels on left of chart on update', async () => { // ARRANGE component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.seriesLabel = { visible: true, placement: 'left', label: [] }; await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=series-label]'); const firstLine = page.doc.querySelector('[data-id="line-North America"]'); flushTransitions(label); flushTransitions(firstLine); await page.waitForChanges(); expect(label).toEqualAttribute('y', firstLine.getAttribute('data-centerY1')); expect(label).toEqualAttribute('x', 0); }); }); describe('placement - horizontal', () => { it('should place series labels on top of chart by default', async () => { // ARRANGE component.layout = 'horizontal'; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=series-label]'); const lastLine = page.doc.querySelector('[data-id="line-Asia and Pacific"]'); flushTransitions(label); flushTransitions(lastLine); await page.waitForChanges(); expect(label).toEqualAttribute('x', lastLine.getAttribute('data-centerX1')); expect(label).toEqualAttribute('y', 0); }); it('should place series labels on bottom of chart on load', async () => { // ARRANGE component.layout = 'horizontal'; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; component.seriesLabel = { visible: true, placement: 'bottom', label: [] }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=series-label]'); const firstLine = page.doc.querySelector('[data-id="line-North America"]'); const innerPaddedHeight = component.height - component.margin.top - component.margin.bottom - component.padding.top - component.padding.bottom; flushTransitions(label); flushTransitions(firstLine); await page.waitForChanges(); expect(label).toEqualAttribute('x', firstLine.getAttribute('data-centerX1')); expect(label).toEqualAttribute('y', innerPaddedHeight); }); it('should place series labels on bottom of chart on update', async () => { // ARRANGE component.layout = 'horizontal'; component.ordinalAccessor = 'region'; component.seriesAccessor = 'category'; component.valueAccessor = 'value'; component.data = LAYOUTDATA; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.seriesLabel = { visible: true, placement: 'bottom', label: [] }; await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=series-label]'); const firstLine = page.doc.querySelector('[data-id="line-North America"]'); const innerPaddedHeight = component.height - component.margin.top - component.margin.bottom - component.padding.top - component.padding.bottom; flushTransitions(label); flushTransitions(firstLine); await page.waitForChanges(); expect(label).toEqualAttribute('x', firstLine.getAttribute('data-centerX1')); expect(label).toEqualAttribute('y', innerPaddedHeight); }); }); describe('label', () => { it('should use values of seriesAccessor as label by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=series-label]'); expect(label).toEqualText('CardA'); }); it('should use values of label prop when passed on load', async () => { component.seriesLabel = { visible: true, placement: 'right', label: ['One', 'Two'] }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=series-label]'); expect(label).toEqualText('One'); }); it('should use values of label prop when passed on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.seriesLabel = { visible: true, placement: 'right', label: ['One', 'Two'] }; await page.waitForChanges(); // ASSERT const label = page.doc.querySelector('[data-testid=series-label]'); flushTransitions(label); await page.waitForChanges(); expect(label).toEqualText('One'); }); }); }); describe('legend', () => { describe('visible', () => { it('by default the legend should not render', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const legendSVG = page.doc.querySelector('[data-testid=legend-container]'); const legendG = legendSVG.querySelector('g').querySelector('g'); const legendContainer = legendSVG.parentNode; expect(legendContainer.getAttribute('style')).toEqual('display: none;'); expect(legendContainer).toHaveClass('dumbbell-legend'); expect(legendSVG).toEqualAttribute('opacity', 0); expect(legendG).toHaveClass('legend'); expect(legendG).toHaveClass('bar'); }); it('should render, and be visible if visible is passed', async () => { component.legend = { visible: true, interactive: false, format: '', labels: '' }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const legendSVG = page.doc.querySelector('[data-testid=legend-container]'); const legendG = legendSVG.querySelector('g').querySelectorAll('g'); const legendContainer = legendSVG.parentNode; expect(legendContainer.getAttribute('style')).toEqual('display: block;'); expect(legendSVG).toEqualAttribute('opacity', 1); expect(legendG.length).toEqual(2); }); }); describe('interactive', () => { it('should not be interactive by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const legendG = page.doc .querySelector('[data-testid=legend-container]') .querySelector('g') .querySelector('g'); expect(legendG['__on']).toBeUndefined(); // tslint:disable-line: no-string-literal }); it('should be interactive when interactive prop is true and interaction keys is series accessor on load', async () => { component.interactionKeys = ['category']; component.cursor = 'pointer'; component.legend = { visible: true, interactive: true, format: '', labels: '' }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const legendG = page.doc .querySelector('[data-testid=legend-container]') .querySelector('g') .querySelector('g'); expect(legendG['__on'].length).toEqual(3); // tslint:disable-line: no-string-literal expect(legendG.getAttribute('style')).toEqual('cursor: pointer;'); }); it('should be interactive when interactive prop is true and interaction keys is series accessor on update', async () => { // ARRANGE component.cursor = 'pointer'; component.interactionKeys = ['category']; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.legend = { visible: true, interactive: true, format: '', labels: '' }; await page.waitForChanges(); // ASSERT const legendG = page.doc .querySelector('[data-testid=legend-container]') .querySelector('g') .querySelector('g'); flushTransitions(legendG); await page.waitForChanges(); expect(legendG['__on'].length).toEqual(3); // tslint:disable-line: no-string-literal expect(legendG.getAttribute('style')).toEqual('cursor: pointer;'); }); it('should be interactive when interactive prop is true on load and interaction keys is series accessor on update', async () => { // ARRANGE component.cursor = 'pointer'; component.legend = { visible: true, interactive: true, format: '', labels: '' }; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ASSERT ONE - SHOULD NOT BE INTERACTIVE DUE TO LACK OF INTERACTION KEYS const legendGLoad = page.doc .querySelector('[data-testid=legend-container]') .querySelector('g') .querySelector('g'); expect(legendGLoad['__on']).toBeUndefined(); // tslint:disable-line: no-string-literal expect(legendGLoad.getAttribute('style')).toBeNull(); // ACT UPDATE component.interactionKeys = ['category']; await page.waitForChanges(); // ASSERT TWO - SHOULD BE INTERACTIVE AFTER SPECIFYING INTERACTION KEYS const legendGUpdate = page.doc .querySelector('[data-testid=legend-container]') .querySelector('g') .querySelector('g'); flushTransitions(legendGUpdate); await page.waitForChanges(); expect(legendGUpdate['__on'].length).toEqual(3); // tslint:disable-line: no-string-literal expect(legendGUpdate.getAttribute('style')).toEqual('cursor: pointer;'); }); }); describe('labels', () => { it('should be equal to data values by default', async () => { // ARRANGE const EXPECTEDLABELS = ['CardA', 'CardB']; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const legendGs = page.doc .querySelector('[data-testid=legend-container]') .querySelector('g') .querySelectorAll('g'); await asyncForEach(legendGs, async (legendG, i) => { const legendGText = legendG.querySelector('text'); flushTransitions(legendGText); await page.waitForChanges(); expect(legendGText).toEqualText(EXPECTEDLABELS[i]); }); }); it('should have custom labels when passed as prop', async () => { const EXPECTEDLABELS = ['Cat', 'Dog']; component.legend = { visible: true, interactive: false, labels: EXPECTEDLABELS }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const legendGs = page.doc .querySelector('[data-testid=legend-container]') .querySelector('g') .querySelectorAll('g'); await asyncForEach(legendGs, async (legendG, i) => { const legendGText = legendG.querySelector('text'); flushTransitions(legendGText); await page.waitForChanges(); expect(legendGText).toEqualText(EXPECTEDLABELS[i]); }); }); }); }); }); describe('markers', () => { const dotMult = 1; const strokeMult = 2; const arrowMult = 1; const markerAdj = 0.3125; const arrowD = 'M 0.3125 5.15625 L 10.3125 0.3125 L 10.3125 10.3125 z'; // 'M 0 5 L 10 0 L 10 10 z'; const strokeD = 'M 4.5 0.15625 L 4.5 10.15625 L 6 10.15625 L 6 0.15625 z'; // 'M 4.5 1 L 4.5 9 L 6 9 L 6 1 z'; const circleR = 5; describe('marker', () => { describe('visible', () => { it('marker should be visible by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach(marker => { expect(marker).toEqualAttribute('opacity', 1); }); }); it('marker should not be visible when false is passed on load', async () => { component.marker = { sizeFromBar: 8, type: 'dot', visible: false }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach(marker => { expect(marker).toEqualAttribute('opacity', 0); }); }); it('marker should not be visible when false is passed on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.marker = { sizeFromBar: 8, type: 'dot', visible: false }; await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach(marker => { expect(marker).toEqualAttribute('opacity', 0); }); }); }); // the new (v5) logic for creating/sizing markers has not been updated here. describe.skip('type', () => { it('marker type should be dot by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); const markerParent = markerGroup[0].parentNode; expect(markerParent).toHaveClass('dotmarkers'); markerGroup.forEach(marker => { expect(marker).toHaveClass('marker-dot'); const markerChild = marker.querySelector('circle'); expect(markerChild).toEqualAttribute('cx', circleR + markerAdj); expect(markerChild).toEqualAttribute('cy', circleR + markerAdj); expect(markerChild).toEqualAttribute('r', circleR); }); }); it('marker type should be arrow if passed on load', async () => { // ARRANGE component.marker = { sizeFromBar: 8, type: 'arrow', visible: true }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); const markerParent = markerGroup[0].parentNode; expect(markerParent).toHaveClass('arrowmarkers'); markerGroup.forEach((marker, i) => { expect(marker).toHaveClass('marker-arrow'); const markerChild = marker.querySelector('path'); expect(markerChild).toEqualAttribute('d', i % 2 === 0 ? arrowD : strokeD); }); }); it('marker type should be stroke if passed on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.marker = { sizeFromBar: 8, type: 'stroke', visible: true }; await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); const markerParent = markerGroup[0].parentNode; expect(markerParent).toHaveClass('strokemarkers'); markerGroup.forEach(marker => { expect(marker).toHaveClass('marker-stroke'); const markerChild = marker.querySelector('path'); expect(markerChild).toEqualAttribute('d', strokeD); }); }); }); describe.skip('sizeFromBar', () => { it('marker sizeFromBar should be 8 by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach(marker => { expect(marker).toEqualAttribute('markerWidth', 8 * dotMult * 2); expect(marker).toEqualAttribute('markerHeight', 8 * dotMult * 2); }); }); it('marker sizeFromBar should be 18 when passed on load', async () => { // ARRANGE component.marker = { sizeFromBar: 18, type: 'stroke', visible: true }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach(marker => { expect(marker).toEqualAttribute('markerWidth', 18 * strokeMult * 2); expect(marker).toEqualAttribute('markerHeight', 18 * strokeMult * 2); }); }); it('marker sizeFromBar should be 10 when passed on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.marker = { sizeFromBar: 10, type: 'arrow', visible: true }; await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach((marker, i) => { expect(marker).toEqualAttribute('markerWidth', 10 * (i % 2 === 0 ? arrowMult : strokeMult) * 2); expect(marker).toEqualAttribute('markerHeight', 10 * (i % 2 === 0 ? arrowMult : strokeMult) * 2); }); }); }); }); describe('focusMarker', () => { describe('key', () => { it('focusMarker key should be empty by default', async () => { // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach(marker => { expect(marker['__data__'].focus).toEqual(false); // tslint:disable-line: no-string-literal }); }); it('focusMarker key should be applied if valid and passed on load', async () => { component.focusMarker = { key: 'CardA', sizeFromBar: 12 }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach((marker, i) => { expect(marker['__data__'].focus).toEqual(i % 2 === 0); // tslint:disable-line: no-string-literal }); }); it('focusMarker key should be applied if valid and passed on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.focusMarker = { key: 'CardB', sizeFromBar: 12 }; await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach((marker, i) => { expect(marker['__data__'].focus).toEqual(i % 2 === 1); // tslint:disable-line: no-string-literal }); }); }); // the new (v5) logic for creating/sizing markers has not been updated here. describe.skip('sizeFromBar', () => { it('focusMarker sizeFromBar should be 12 (default) when focus marker is passed on load', async () => { component.focusMarker = { key: 'CardB', sizeFromBar: 12 }; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach(marker => { if (marker['__data__'].focus) { // tslint:disable-line: no-string-literal expect(marker).toEqualAttribute('markerWidth', 12 * dotMult * 2); expect(marker).toEqualAttribute('markerHeight', 12 * dotMult * 2); } else { expect(marker).toEqualAttribute('markerWidth', 8 * dotMult * 2); expect(marker).toEqualAttribute('markerHeight', 8 * dotMult * 2); } }); }); it('focusMarker sizeFromBar should be 15 when passed on update', async () => { // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.marker = { sizeFromBar: 8, type: 'arrow', visible: true }; component.focusMarker = { key: 'CardA', sizeFromBar: 15 }; await page.waitForChanges(); // ASSERT const markerGroup = page.doc.querySelectorAll('[data-testid=marker]'); markerGroup.forEach((marker, i) => { if (marker['__data__'].focus) { // tslint:disable-line: no-string-literal expect(marker).toEqualAttribute('markerWidth', 15 * arrowMult * 2); expect(marker).toEqualAttribute('markerHeight', 15 * arrowMult * 2); } else { expect(marker).toEqualAttribute('markerWidth', 8 * strokeMult * 2); expect(marker).toEqualAttribute('markerHeight', 8 * strokeMult * 2); } }); }); }); }); }); describe('reference line', () => { const referenceLines = [ { label: 'Market', labelPlacementHorizontal: 'right', labelPlacementVertical: 'bottom', value: 7500000000 } ]; const referenceStyle = { color: 'supp_pink', dashed: '', opacity: 0.65, strokeWidth: '1px' }; it('should pass referenceLines prop', async () => { // ARRANGE component.referenceLines = referenceLines; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const referenceLinesGroup = page.doc.querySelector('[data-testid=reference-line-group]'); expect(referenceLinesGroup).toMatchSnapshot(); }); it('should pass referenceStyle prop', async () => { // ARRANGE component.referenceLines = referenceLines; component.referenceStyle = referenceStyle; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const referenceLine = page.doc.querySelector('[data-testid=reference-line]'); expect(referenceLine).toMatchSnapshot(); }); }); describe('style', () => { // const checkRGB = element => element.getAttribute('fill').substr(0, 3) === 'rgb'; describe('colorPalette', () => { it('should render categorical palette by default', async () => { const EXPECTEDFILLCOLORS = getColors('categorical', 3); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markers = page.doc.querySelectorAll('[data-testid=marker]'); const line = page.doc.querySelector('[data-testid=line]'); const labels = page.doc.querySelectorAll('[data-testid=dataLabel]'); const seriesLabels = page.doc.querySelectorAll('[data-testid=series-label]'); const diffLabels = page.doc.querySelector('[data-testid=difference-label]'); expect(markers[0]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[0]); expect(markers[1]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[1]); expect(labels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(labels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(seriesLabels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(seriesLabels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(diffLabels).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[2], '#ffffff', 4.5)); expect(line).toEqualAttribute('stroke', getContrastingStroke(EXPECTEDFILLCOLORS[2])); }); it('should load diverging red to green when colorPalette is diverging_RtoG', async () => { // ARRANGE const EXPECTEDCOLORPALETTE = 'diverging_RtoG'; component.colorPalette = EXPECTEDCOLORPALETTE; const EXPECTEDFILLCOLORS = getColors(EXPECTEDCOLORPALETTE, 3); // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markers = page.doc.querySelectorAll('[data-testid=marker]'); const line = page.doc.querySelector('[data-testid=line]'); const labels = page.doc.querySelectorAll('[data-testid=dataLabel]'); const seriesLabels = page.doc.querySelectorAll('[data-testid=series-label]'); const diffLabels = page.doc.querySelector('[data-testid=difference-label]'); expect(markers[0]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[0]); expect(markers[1]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[1]); expect(labels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(labels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(seriesLabels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(seriesLabels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(diffLabels).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[2], '#ffffff', 4.5)); expect(line).toEqualAttribute('stroke', EXPECTEDFILLCOLORS[2]); }); it('should update to sequential supplement Pink when colorPalette is sequential_suppPink', async () => { // ARRANGE const EXPECTEDCOLORPALETTE = 'sequential_suppPink'; const EXPECTEDFILLCOLORS = getColors(EXPECTEDCOLORPALETTE, 3); // component.data = EXPECTEDDATALARGE; // ACT LOAD page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.colorPalette = EXPECTEDCOLORPALETTE; await page.waitForChanges(); // ASSERT const markers = page.doc.querySelectorAll('[data-testid=marker]'); const line = page.doc.querySelector('[data-testid=line]'); const labels = page.doc.querySelectorAll('[data-testid=dataLabel]'); const seriesLabels = page.doc.querySelectorAll('[data-testid=series-label]'); const diffLabels = page.doc.querySelector('[data-testid=difference-label]'); flushTransitions(labels[0]); flushTransitions(labels[1]); flushTransitions(seriesLabels[0]); flushTransitions(seriesLabels[1]); flushTransitions(diffLabels); await page.waitForChanges(); expect(markers[0]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[0]); expect(markers[1]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[1]); expect(labels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(labels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(seriesLabels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(seriesLabels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(diffLabels).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[2], '#ffffff', 4.5)); expect(line).toEqualAttribute('stroke', EXPECTEDFILLCOLORS[2]); }); }); describe('colors', () => { it('should render colors instead of palette when passed on load', async () => { const colors = ['#829e46', '#796aaf', '#7a6763']; const EXPECTEDFILLCOLORS = colors; component.colors = colors; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const markers = page.doc.querySelectorAll('[data-testid=marker]'); const line = page.doc.querySelector('[data-testid=line]'); const labels = page.doc.querySelectorAll('[data-testid=dataLabel]'); const seriesLabels = page.doc.querySelectorAll('[data-testid=series-label]'); const diffLabels = page.doc.querySelector('[data-testid=difference-label]'); expect(markers[0]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[0]); expect(markers[1]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[1]); expect(labels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(labels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(seriesLabels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(seriesLabels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(diffLabels).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[2], '#ffffff', 4.5)); expect(line).toEqualAttribute('stroke', EXPECTEDFILLCOLORS[2]); }); it('should render colors instead of palette when passed on update', async () => { const colors = ['#829e46', '#796aaf', '#7a6763']; // ["#829e46","#7a6763","#796aaf"] const EXPECTEDFILLCOLORS = colors; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.colors = colors; await page.waitForChanges(); // ASSERT const markers = page.doc.querySelectorAll('[data-testid=marker]'); const line = page.doc.querySelector('[data-testid=line]'); const labels = page.doc.querySelectorAll('[data-testid=dataLabel]'); const seriesLabels = page.doc.querySelectorAll('[data-testid=series-label]'); const diffLabels = page.doc.querySelector('[data-testid=difference-label]'); flushTransitions(labels[0]); flushTransitions(labels[1]); flushTransitions(seriesLabels[0]); flushTransitions(seriesLabels[1]); flushTransitions(diffLabels); await page.waitForChanges(); expect(markers[0]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[0]); expect(markers[1]).toEqualAttribute('fill', EXPECTEDFILLCOLORS[1]); expect(labels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(labels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(seriesLabels[0]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[0], '#ffffff', 4.5)); expect(seriesLabels[1]).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[1], '#ffffff', 4.5)); expect(diffLabels).toEqualAttribute('fill', ensureTextContrast(EXPECTEDFILLCOLORS[2], '#ffffff', 4.5)); expect(line).toEqualAttribute('stroke', EXPECTEDFILLCOLORS[2]); }); }); describe('cursor', () => { it('refer to generic interaction results above for cursor tests', () => { expect(true).toBeTruthy(); }); }); }); describe('aria-property', () => { // TODO: write unit test cases for aria-property }); describe('methods', () => { // TODO: write unit test cases for component methods if any }); }); });
the_stack
import { EarthMap } from '../earthmap'; import LngLat from '../geo/lng_lat'; import Point from '../geo/point'; import { Map } from '../map'; import { bezier, ease, interpolate, now } from '../util'; import DOM from '../utils/dom'; import HandlerManager from './handler_manager'; // deltaY value for mouse scroll wheel identification const wheelZoomDelta = 4.000244140625; // These magic numbers control the rate of zoom. Trackpad events fire at a greater // frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick const defaultZoomRate = 1 / 100; const wheelZoomRate = 1 / 450; // upper bound on how much we scale the map in any single render frame; this // is used to limit zoom rate in the case of very fast scrolling const maxScalePerFrame = 2; /** * The `ScrollZoomHandler` allows the user to zoom the map by scrolling. */ class ScrollZoomHandler { private map: Map | EarthMap; private el: HTMLElement; private enabled: boolean; private active: boolean; private zooming: boolean; private aroundCenter: boolean; private around: LngLat; private aroundPoint: Point; private type: 'wheel' | 'trackpad' | null; private lastValue: number; private timeout: number | null; // used for delayed-handling of a single wheel movement private finishTimeout: number; // used to delay final '{move,zoom}end' events private lastWheelEvent: any; private lastWheelEventTime: number; private startZoom: number; private targetZoom: number; private delta: number; private easing: (time: number) => number; private prevEase: { start: number; duration: number; easing: (_: number) => number; }; private frameId: boolean | null; private handler: HandlerManager; private defaultZoomRate: number; private wheelZoomRate: number; /** * @private */ constructor(map: Map | EarthMap, handler: HandlerManager) { this.map = map; this.el = map.getCanvasContainer(); this.handler = handler; this.delta = 0; this.defaultZoomRate = defaultZoomRate; this.wheelZoomRate = wheelZoomRate; } /** * Set the zoom rate of a trackpad * @param {number} [zoomRate=1/100] The rate used to scale trackpad movement to a zoom value. * @example * // Speed up trackpad zoom * map.scrollZoom.setZoomRate(1/25); */ public setZoomRate(zoomRate: number) { this.defaultZoomRate = zoomRate; } /** * Set the zoom rate of a mouse wheel * @param {number} [wheelZoomRate=1/450] The rate used to scale mouse wheel movement to a zoom value. * @example * // Slow down zoom of mouse wheel * map.scrollZoom.setWheelZoomRate(1/600); */ public setWheelZoomRate(zoomRate: number) { this.wheelZoomRate = zoomRate; } /** * Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled. * * @returns {boolean} `true` if the "scroll to zoom" interaction is enabled. */ public isEnabled() { return !!this.enabled; } /* * Active state is turned on and off with every scroll wheel event and is set back to false before the map * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in * progress. */ public isActive() { return !!this.active || this.finishTimeout !== undefined; } public isZooming() { return !!this.zooming; } /** * Enables the "scroll to zoom" interaction. * * @param {Object} [options] Options object. * @param {string} [options.around] If "center" is passed, map will zoom around center of map * * @example * map.scrollZoom.enable(); * @example * map.scrollZoom.enable({ around: 'center' }) */ public enable(options?: any) { if (this.isEnabled()) { return; } this.enabled = true; this.aroundCenter = options && options.around === 'center'; } /** * Disables the "scroll to zoom" interaction. * * @example * map.scrollZoom.disable(); */ public disable() { if (!this.isEnabled()) { return; } this.enabled = false; } public wheel(e: WheelEvent) { if (!this.isEnabled()) { return; } // Remove `any` cast when https://github.com/facebook/flow/issues/4879 is fixed. let value = e.deltaMode === window.WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY; const nowTime = now(); const timeDelta = nowTime - (this.lastWheelEventTime || 0); this.lastWheelEventTime = nowTime; if (value !== 0 && value % wheelZoomDelta === 0) { // This one is definitely a mouse wheel event. this.type = 'wheel'; } else if (value !== 0 && Math.abs(value) < 4) { // This one is definitely a trackpad event because it is so small. this.type = 'trackpad'; } else if (timeDelta > 400) { // This is likely a new scroll action. this.type = null; this.lastValue = value; // Start a timeout in case this was a singular event, and dely it by up to 40ms. // @ts-ignore this.timeout = setTimeout(this.onTimeout, 40, e); } else if (!this.type) { // This is a repeating event, but we don't know the type of event just yet. // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode. this.type = Math.abs(timeDelta * value) < 200 ? 'trackpad' : 'wheel'; // Make sure our delayed event isn't fired again, because we accumulate // the previous event (which was less than 40ms ago) into this event. if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; value += this.lastValue; } } // Slow down zoom if shift key is held for more precise zooming if (e.shiftKey && value) { value = value / 4; } // Only fire the callback if we actually know what type of scrolling device the user uses. if (this.type) { this.lastWheelEvent = e; this.delta -= value; if (!this.active) { this.start(e); } } e.preventDefault(); } public renderFrame() { return this.onScrollFrame(); } public reset() { this.active = false; } private onScrollFrame = () => { if (!this.frameId) { return; } this.frameId = null; if (!this.isActive()) { return; } const tr = this.map.transform; // if we've had scroll events since the last render frame, consume the // accumulated delta, and update the target zoom level accordingly if (this.delta !== 0) { // For trackpad events and single mouse wheel ticks, use the default zoom rate const zoomRate = this.type === 'wheel' && Math.abs(this.delta) > wheelZoomDelta ? this.wheelZoomRate : this.defaultZoomRate; // Scale by sigmoid of scroll wheel delta. let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this.delta * zoomRate))); if (this.delta < 0 && scale !== 0) { scale = 1 / scale; } const fromScale = typeof this.targetZoom === 'number' ? tr.zoomScale(this.targetZoom) : tr.scale; this.targetZoom = Math.min( tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale)), ); // if this is a mouse wheel, refresh the starting zoom and easing // function we're using to smooth out the zooming between wheel // events if (this.type === 'wheel') { this.startZoom = tr.zoom; this.easing = this.smoothOutEasing(200); } this.delta = 0; } const targetZoom = typeof this.targetZoom === 'number' ? this.targetZoom : tr.zoom; const startZoom = this.startZoom; const easing = this.easing; let finished = false; let zoom; if (this.type === 'wheel' && startZoom && easing) { const t = Math.min((now() - this.lastWheelEventTime) / 200, 1); const k = easing(t); zoom = interpolate(startZoom, targetZoom, k); if (t < 1) { if (!this.frameId) { this.frameId = true; } } else { finished = true; } } else { zoom = targetZoom; finished = true; } this.active = true; if (finished) { this.active = false; // @ts-ignore this.finishTimeout = setTimeout(() => { this.zooming = false; this.handler.triggerRenderFrame(); // @ts-ignore delete this.targetZoom; // @ts-ignore delete this.finishTimeout; }, 200); } return { noInertia: true, needsRenderFrame: !finished, zoomDelta: zoom - tr.zoom, around: this.aroundPoint, originalEvent: this.lastWheelEvent, }; }; private onTimeout(initialEvent: any) { this.type = 'wheel'; this.delta -= this.lastValue; if (!this.active && this.start) { this.start(initialEvent); } } private start(e: any) { if (!this.delta) { return; } if (this.frameId) { this.frameId = null; } this.active = true; if (!this.isZooming()) { this.zooming = true; } if (this.finishTimeout) { clearTimeout(this.finishTimeout); // @ts-ignore delete this.finishTimeout; } const pos = DOM.mousePos(this.el, e); this.around = LngLat.convert( this.aroundCenter ? this.map.getCenter() : this.map.unproject(pos), ); this.aroundPoint = this.map.transform.locationPoint(this.around); if (!this.frameId) { this.frameId = true; this.handler.triggerRenderFrame(); } } private smoothOutEasing(duration: number) { let easing = ease; if (this.prevEase) { const preEase = this.prevEase; const t = (now() - preEase.start) / preEase.duration; const speed = preEase.easing(t + 0.01) - preEase.easing(t); // Quick hack to make new bezier that is continuous with last const x = (0.27 / Math.sqrt(speed * speed + 0.0001)) * 0.01; const y = Math.sqrt(0.27 * 0.27 - x * x); easing = bezier(x, y, 0.25, 1); } this.prevEase = { start: now(), duration, easing, }; return easing; } } export default ScrollZoomHandler;
the_stack
namespace ts.refactor.convertToOptionalChainExpression { const refactorName = "Convert to optional chain expression"; const convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression); const toOptionalChainAction = { name: refactorName, description: convertToOptionalChainExpressionMessage, kind: "refactor.rewrite.expression.optionalChain", }; registerRefactor(refactorName, { kinds: [toOptionalChainAction.kind], getAvailableActions, getEditsForAction }); function getAvailableActions(context: RefactorContext): readonly ApplicableRefactorInfo[] { const info = getInfo(context, context.triggerReason === "invoked"); if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { return [{ name: refactorName, description: convertToOptionalChainExpressionMessage, actions: [toOptionalChainAction], }]; } if (context.preferences.provideRefactorNotApplicableReason) { return [{ name: refactorName, description: convertToOptionalChainExpressionMessage, actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }], }]; } return emptyArray; } function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined { const info = getInfo(context); Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program.getTypeChecker(), t, info, actionName) ); return { edits, renameFilename: undefined, renameLocation: undefined }; } type Occurrence = PropertyAccessExpression | ElementAccessExpression | Identifier; interface OptionalChainInfo { finalExpression: PropertyAccessExpression | ElementAccessExpression | CallExpression, occurrences: Occurrence[], expression: ValidExpression, }; type ValidExpressionOrStatement = ValidExpression | ValidStatement; /** * Types for which a "Convert to optional chain refactor" are offered. */ type ValidExpression = BinaryExpression | ConditionalExpression; /** * Types of statements which are likely to include a valid expression for extraction. */ type ValidStatement = ExpressionStatement | ReturnStatement | VariableStatement; function isValidExpression(node: Node): node is ValidExpression { return isBinaryExpression(node) || isConditionalExpression(node); } function isValidStatement(node: Node): node is ValidStatement { return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node); } function isValidExpressionOrStatement(node: Node): node is ValidExpressionOrStatement { return isValidExpression(node) || isValidStatement(node); } function getInfo(context: RefactorContext, considerEmptySpans = true): OptionalChainInfo | RefactorErrorInfo | undefined { const { file, program } = context; const span = getRefactorContextSpan(context); const forEmptySpan = span.length === 0; if (forEmptySpan && !considerEmptySpans) return undefined; // selecting fo[|o && foo.ba|]r should be valid, so adjust span to fit start and end tokens const startToken = getTokenAtPosition(file, span.start); const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); const parent = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); const expression = parent && isValidExpressionOrStatement(parent) ? getExpression(parent) : undefined; if (!expression) return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; const checker = program.getTypeChecker(); return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); } function getConditionalInfo(expression: ConditionalExpression, checker: TypeChecker): OptionalChainInfo | RefactorErrorInfo | undefined { const condition = expression.condition; const finalExpression = getFinalExpressionInChain(expression.whenTrue); if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) { return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; } if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) { return { finalExpression, occurrences: [condition], expression }; } else if (isBinaryExpression(condition)) { const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; } } function getBinaryInfo(expression: BinaryExpression): OptionalChainInfo | RefactorErrorInfo | undefined { if (expression.operatorToken.kind !== SyntaxKind.AmpersandAmpersandToken) { return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) }; }; const finalExpression = getFinalExpressionInChain(expression.right); if (!finalExpression) return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; } /** * Gets a list of property accesses that appear in matchTo and occur in sequence in expression. */ function getOccurrencesInExpression(matchTo: Expression, expression: Expression): Occurrence[] | undefined { const occurrences: Occurrence[] = []; while (isBinaryExpression(expression) && expression.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right)); if (!match) { break; } occurrences.push(match); matchTo = match; expression = expression.left; } const finalMatch = getMatchingStart(matchTo, expression); if (finalMatch) { occurrences.push(finalMatch); } return occurrences.length > 0 ? occurrences: undefined; } /** * Returns subchain if chain begins with subchain syntactically. */ function getMatchingStart(chain: Expression, subchain: Expression): PropertyAccessExpression | ElementAccessExpression | Identifier | undefined { if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) { return undefined; } return chainStartsWith(chain, subchain) ? subchain : undefined; } /** * Returns true if chain begins with subchain syntactically. */ function chainStartsWith(chain: Node, subchain: Node): boolean { // skip until we find a matching identifier. while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) { if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) break; chain = chain.expression; } // check that the chains match at each access. Call chains in subchain are not valid. while ((isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain)) || (isElementAccessExpression(chain) && isElementAccessExpression(subchain))) { if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) return false; chain = chain.expression; subchain = subchain.expression; } // check if we have reached a final identifier. return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText(); } function getTextOfChainNode(node: Node): string | undefined { if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) { return node.getText(); } if (isPropertyAccessExpression(node)) { return getTextOfChainNode(node.name); } if (isElementAccessExpression(node)) { return getTextOfChainNode(node.argumentExpression); } return undefined; } /** * Find the least ancestor of the input node that is a valid type for extraction and contains the input span. */ function getValidParentNodeContainingSpan(node: Node, span: TextSpan): ValidExpressionOrStatement | undefined { while (node.parent) { if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) { return node; } node = node.parent; } return undefined; } /** * Finds an ancestor of the input node that is a valid type for extraction, skipping subexpressions. */ function getValidParentNodeOfEmptySpan(node: Node): ValidExpressionOrStatement | undefined { while (node.parent) { if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) { return node; } node = node.parent; } return undefined; } /** * Gets an expression of valid extraction type from a valid statement or expression. */ function getExpression(node: ValidExpressionOrStatement): ValidExpression | undefined { if (isValidExpression(node)) { return node; } if (isVariableStatement(node)) { const variable = getSingleVariableOfVariableStatement(node); const initializer = variable?.initializer; return initializer && isValidExpression(initializer) ? initializer : undefined; } return node.expression && isValidExpression(node.expression) ? node.expression : undefined; } /** * Gets a property access expression which may be nested inside of a binary expression. The final * expression in an && chain will occur as the right child of the parent binary expression, unless * it is followed by a different binary operator. * @param node the right child of a binary expression or a call expression. */ function getFinalExpressionInChain(node: Expression): CallExpression | PropertyAccessExpression | ElementAccessExpression | undefined { // foo && |foo.bar === 1|; - here the right child of the && binary expression is another binary expression. // the rightmost member of the && chain should be the leftmost child of that expression. node = skipParentheses(node); if (isBinaryExpression(node)) { return getFinalExpressionInChain(node.left); } // foo && |foo.bar()()| - nested calls are treated like further accesses. else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) { return node; } return undefined; } /** * Creates an access chain from toConvert with '?.' accesses at expressions appearing in occurrences. */ function convertOccurrences(checker: TypeChecker, toConvert: Expression, occurrences: Occurrence[]): Expression { if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) { const chain = convertOccurrences(checker, toConvert.expression, occurrences); const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : undefined; const isOccurrence = lastOccurrence?.getText() === toConvert.expression.getText(); if (isOccurrence) occurrences.pop(); if (isCallExpression(toConvert)) { return isOccurrence ? factory.createCallChain(chain, factory.createToken(SyntaxKind.QuestionDotToken), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); } else if (isPropertyAccessExpression(toConvert)) { return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(SyntaxKind.QuestionDotToken), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name); } else if (isElementAccessExpression(toConvert)) { return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(SyntaxKind.QuestionDotToken), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression); } } return toConvert; } function doChange(sourceFile: SourceFile, checker: TypeChecker, changes: textChanges.ChangeTracker, info: OptionalChainInfo, _actionName: string): void { const { finalExpression, occurrences, expression } = info; const firstOccurrence = occurrences[occurrences.length - 1]; const convertedChain = convertOccurrences(checker, finalExpression, occurrences); if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { if (isBinaryExpression(expression)) { changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); } else if (isConditionalExpression(expression)) { changes.replaceNode(sourceFile, expression, factory.createBinaryExpression(convertedChain, factory.createToken(SyntaxKind.QuestionQuestionToken), expression.whenFalse) ); } } } }
the_stack
module android.widget { import DataSetObserver = android.database.DataSetObserver; import SystemClock = android.os.SystemClock; import SparseArray = android.util.SparseArray; import SoundEffectConstants = android.view.SoundEffectConstants; import View = android.view.View; import ViewGroup = android.view.ViewGroup; import Long = java.lang.Long; import Runnable = java.lang.Runnable; /** * An AdapterView is a view whose children are determined by an {@link Adapter}. * * <p> * See {@link ListView}, {@link GridView}, {@link Spinner} and * {@link Gallery} for commonly used subclasses of AdapterView. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about using AdapterView, read the * <a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> * developer guide.</p></div> */ export abstract class AdapterView<T extends Adapter> extends ViewGroup { /** * The item view type returned by {@link Adapter#getItemViewType(int)} when * the adapter does not want the item's view recycled. */ static ITEM_VIEW_TYPE_IGNORE:number = -1; /** * The item view type returned by {@link Adapter#getItemViewType(int)} when * the item is a header or footer. */ static ITEM_VIEW_TYPE_HEADER_OR_FOOTER:number = -2; /** * The position of the first child displayed */ mFirstPosition:number = 0; /** * The offset in pixels from the top of the AdapterView to the top * of the view to select during the next layout. */ mSpecificTop:number = 0 /** * Position from which to start looking for mSyncRowId */ mSyncPosition:number = 0; /** * Row id to look for when data has changed */ mSyncRowId:number = AdapterView.INVALID_ROW_ID; /** * Height of the view when mSyncPosition and mSyncRowId where set */ mSyncHeight:number = 0; /** * True if we need to sync to mSyncRowId */ mNeedSync:boolean = false; /** * Indicates whether to sync based on the selection or position. Possible * values are {@link #SYNC_SELECTED_POSITION} or * {@link #SYNC_FIRST_POSITION}. */ mSyncMode:number = 0; /** * Our height after the last layout */ private mLayoutHeight:number = 0; /** * Sync based on the selected child */ static SYNC_SELECTED_POSITION:number = 0; /** * Sync based on the first child displayed */ static SYNC_FIRST_POSITION:number = 1; /** * Maximum amount of time to spend in {@link #findSyncPosition()} */ static SYNC_MAX_DURATION_MILLIS:number = 100; /** * Indicates that this view is currently being laid out. */ mInLayout:boolean = false; /** * The listener that receives notifications when an item is selected. */ private mOnItemSelectedListener:AdapterView.OnItemSelectedListener; /** * The listener that receives notifications when an item is clicked. */ private mOnItemClickListener:AdapterView.OnItemClickListener; /** * The listener that receives notifications when an item is long clicked. */ mOnItemLongClickListener:AdapterView.OnItemLongClickListener; /** * True if the data has changed since the last layout */ mDataChanged:boolean; /** * The position within the adapter's data set of the item to select * during the next layout. */ mNextSelectedPosition:number = AdapterView.INVALID_POSITION; /** * The item id of the item to select during the next layout. */ mNextSelectedRowId:number = AdapterView.INVALID_ROW_ID; /** * The position within the adapter's data set of the currently selected item. */ mSelectedPosition:number = AdapterView.INVALID_POSITION; /** * The item id of the currently selected item. */ mSelectedRowId:number = AdapterView.INVALID_ROW_ID; /** * View to show if there are no items to show. */ private mEmptyView:View; /** * The number of items in the current adapter. */ mItemCount:number = 0; /** * The number of items in the adapter before a data changed event occurred. */ mOldItemCount:number = 0; /** * Represents an invalid position. All valid positions are in the range 0 to 1 less than the * number of items in the current adapter. */ static INVALID_POSITION:number = -1; /** * Represents an empty or invalid row id */ static INVALID_ROW_ID:number = Long.MIN_VALUE; /** * The last selected position we used when notifying */ mOldSelectedPosition:number = AdapterView.INVALID_POSITION; /** * The id of the last selected position we used when notifying */ mOldSelectedRowId:number = AdapterView.INVALID_ROW_ID; /** * Indicates what focusable state is requested when calling setFocusable(). * In addition to this, this view has other criteria for actually * determining the focusable state (such as whether its empty or the text * filter is shown). * * @see #setFocusable(boolean) * @see #checkFocus() */ private mDesiredFocusableState:boolean; private mDesiredFocusableInTouchModeState:boolean; private mSelectionNotifier:SelectionNotifier; /** * When set to true, calls to requestLayout() will not propagate up the parent hierarchy. * This is used to layout the children during a layout pass. */ mBlockLayoutRequests:boolean = false; /** * Register a callback to be invoked when an item in this AdapterView has * been clicked. * * @param listener The callback that will be invoked. */ setOnItemClickListener(listener:AdapterView.OnItemClickListener):void { this.mOnItemClickListener = listener; } /** * @return The callback to be invoked with an item in this AdapterView has * been clicked, or null id no callback has been set. */ getOnItemClickListener():AdapterView.OnItemClickListener { return this.mOnItemClickListener; } /** * Call the OnItemClickListener, if it is defined. Performs all normal * actions associated with clicking: reporting accessibility event, playing * a sound, etc. * * @param view The view within the AdapterView that was clicked. * @param position The position of the view in the adapter. * @param id The row id of the item that was clicked. * @return True if there was an assigned OnItemClickListener that was * called, false otherwise is returned. */ performItemClick(view:View, position:number, id:number):boolean { if (this.mOnItemClickListener != null) { this.playSoundEffect(SoundEffectConstants.CLICK); //if (view != null) { // view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); //} this.mOnItemClickListener.onItemClick(this, view, position, id); return true; } return false; } /** * Register a callback to be invoked when an item in this AdapterView has * been clicked and held * * @param listener The callback that will run */ setOnItemLongClickListener(listener:AdapterView.OnItemLongClickListener):void { if (!this.isLongClickable()) { this.setLongClickable(true); } this.mOnItemLongClickListener = listener; } /** * @return The callback to be invoked with an item in this AdapterView has * been clicked and held, or null id no callback as been set. */ getOnItemLongClickListener():AdapterView.OnItemLongClickListener { return this.mOnItemLongClickListener; } /** * Register a callback to be invoked when an item in this AdapterView has * been selected. * * @param listener The callback that will run */ setOnItemSelectedListener(listener:AdapterView.OnItemSelectedListener):void { this.mOnItemSelectedListener = listener; } getOnItemSelectedListener():AdapterView.OnItemSelectedListener { return this.mOnItemSelectedListener; } /** * Returns the adapter currently associated with this widget. * * @return The adapter used to provide this view's content. */ abstract getAdapter():T ; /** * Sets the adapter that provides the data and the views to represent the data * in this widget. * * @param adapter The adapter to use to create this view's content. */ abstract setAdapter(adapter:T):void ; /** * This method is not supported and throws an UnsupportedOperationException when called. * * @throws UnsupportedOperationException Every time this method is invoked. */ addView(...args):void { throw Error(`new UnsupportedOperationException("addView() is not supported in AdapterView")`); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ removeView(child:View):void { throw Error(`new UnsupportedOperationException("removeView(View) is not supported in AdapterView")`); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param index Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ removeViewAt(index:number):void { throw Error(`new UnsupportedOperationException("removeViewAt(int) is not supported in AdapterView")`); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @throws UnsupportedOperationException Every time this method is invoked. */ removeAllViews():void { throw Error(`new UnsupportedOperationException("removeAllViews() is not supported in AdapterView")`); } protected onLayout(changed:boolean, left:number, top:number, right:number, bottom:number):void { this.mLayoutHeight = this.getHeight(); } /** * Return the position of the currently selected item within the adapter's data set * * @return int Position (starting at 0), or {@link #INVALID_POSITION} if there is nothing selected. */ getSelectedItemPosition():number { return this.mNextSelectedPosition; } /** * @return The id corresponding to the currently selected item, or {@link #INVALID_ROW_ID} * if nothing is selected. */ getSelectedItemId():number { return this.mNextSelectedRowId; } /** * @return The view corresponding to the currently selected item, or null * if nothing is selected */ abstract getSelectedView():View ; /** * @return The data corresponding to the currently selected item, or * null if there is nothing selected. */ getSelectedItem():any { let adapter:T = this.getAdapter(); let selection:number = this.getSelectedItemPosition(); if (adapter != null && adapter.getCount() > 0 && selection >= 0) { return adapter.getItem(selection); } else { return null; } } /** * @return The number of items owned by the Adapter associated with this * AdapterView. (This is the number of data items, which may be * larger than the number of visible views.) */ getCount():number { return this.mItemCount; } /** * Get the position within the adapter's data set for the view, where view is a an adapter item * or a descendant of an adapter item. * * @param view an adapter item, or a descendant of an adapter item. This must be visible in this * AdapterView at the time of the call. * @return the position within the adapter's data set of the view, or {@link #INVALID_POSITION} * if the view does not correspond to a list item (or it is not currently visible). */ getPositionForView(view:View):number { let listItem:View = view; try { let v:View; while (!((v = <View><any> listItem.getParent()) == (this))) { listItem = v; } } catch (e){ return AdapterView.INVALID_POSITION; } // Search the children for the list item const childCount:number = this.getChildCount(); for (let i:number = 0; i < childCount; i++) { if (this.getChildAt(i) == (listItem)) { return this.mFirstPosition + i; } } // Child not found! return AdapterView.INVALID_POSITION; } /** * Returns the position within the adapter's data set for the first item * displayed on screen. * * @return The position within the adapter's data set */ getFirstVisiblePosition():number { return this.mFirstPosition; } /** * Returns the position within the adapter's data set for the last item * displayed on screen. * * @return The position within the adapter's data set */ getLastVisiblePosition():number { return this.mFirstPosition + this.getChildCount() - 1; } /** * Sets the currently selected item. To support accessibility subclasses that * override this method must invoke the overriden super method first. * * @param position Index (starting at 0) of the data item to be selected. */ abstract setSelection(position:number):void ; /** * Sets the view to show if the adapter is empty */ setEmptyView(emptyView:View):void { this.mEmptyView = emptyView; // If not explicitly specified this view is important for accessibility. //if (emptyView != null && emptyView.getImportantForAccessibility() == AdapterView.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { // emptyView.setImportantForAccessibility(AdapterView.IMPORTANT_FOR_ACCESSIBILITY_YES); //} const adapter:T = this.getAdapter(); const empty:boolean = ((adapter == null) || adapter.isEmpty()); this.updateEmptyStatus(empty); } /** * When the current adapter is empty, the AdapterView can display a special view * call the empty view. The empty view is used to provide feedback to the user * that no data is available in this AdapterView. * * @return The view to show if the adapter is empty. */ getEmptyView():View { return this.mEmptyView; } /** * Indicates whether this view is in filter mode. Filter mode can for instance * be enabled by a user when typing on the keyboard. * * @return True if the view is in filter mode, false otherwise. */ isInFilterMode():boolean { return false; } setFocusable(focusable:boolean):void { const adapter:T = this.getAdapter(); const empty:boolean = adapter == null || adapter.getCount() == 0; this.mDesiredFocusableState = focusable; if (!focusable) { this.mDesiredFocusableInTouchModeState = false; } super.setFocusable(focusable && (!empty || this.isInFilterMode())); } setFocusableInTouchMode(focusable:boolean):void { const adapter:T = this.getAdapter(); const empty:boolean = adapter == null || adapter.getCount() == 0; this.mDesiredFocusableInTouchModeState = focusable; if (focusable) { this.mDesiredFocusableState = true; } super.setFocusableInTouchMode(focusable && (!empty || this.isInFilterMode())); } checkFocus():void { const adapter:T = this.getAdapter(); const empty:boolean = adapter == null || adapter.getCount() == 0; const focusable:boolean = !empty || this.isInFilterMode(); // The order in which we set focusable in touch mode/focusable may matter // for the client, see View.setFocusableInTouchMode() comments for more // details super.setFocusableInTouchMode(focusable && this.mDesiredFocusableInTouchModeState); super.setFocusable(focusable && this.mDesiredFocusableState); if (this.mEmptyView != null) { this.updateEmptyStatus((adapter == null) || adapter.isEmpty()); } } /** * Update the status of the list based on the empty parameter. If empty is true and * we have an empty view, display it. In all the other cases, make sure that the listview * is VISIBLE and that the empty view is GONE (if it's not null). */ private updateEmptyStatus(empty:boolean):void { if (this.isInFilterMode()) { empty = false; } if (empty) { if (this.mEmptyView != null) { this.mEmptyView.setVisibility(View.VISIBLE); this.setVisibility(View.GONE); } else { // If the caller just removed our empty view, make sure the list view is visible this.setVisibility(View.VISIBLE); } // the state of the adapter. if (this.mDataChanged) { this.onLayout(false, this.mLeft, this.mTop, this.mRight, this.mBottom); } } else { if (this.mEmptyView != null) this.mEmptyView.setVisibility(View.GONE); this.setVisibility(View.VISIBLE); } } /** * Gets the data associated with the specified position in the list. * * @param position Which data to get * @return The data associated with the specified position in the list */ getItemAtPosition(position:number):any { let adapter:T = this.getAdapter(); return (adapter == null || position < 0) ? null : adapter.getItem(position); } getItemIdAtPosition(position:number):number { let adapter:T = this.getAdapter(); return (adapter == null || position < 0) ? AdapterView.INVALID_ROW_ID : adapter.getItemId(position); } setOnClickListener(l:View.OnClickListener):void { throw Error(`new RuntimeException("Don't call setOnClickListener for an AdapterView. " + "You probably want setOnItemClickListener instead")`); } /** * Override to prevent freezing of any views created by the adapter. */ //dispatchSaveInstanceState(container:SparseArray<Parcelable>):void { // this.dispatchFreezeSelfOnly(container); //} /** * Override to prevent thawing of any views created by the adapter. */ //dispatchRestoreInstanceState(container:SparseArray<Parcelable>):void { // this.dispatchThawSelfOnly(container); //} protected onDetachedFromWindow():void { super.onDetachedFromWindow(); this.removeCallbacks(this.mSelectionNotifier); } private selectionChanged():void { if (this.mOnItemSelectedListener != null //|| AccessibilityManager.getInstance(this.mContext).isEnabled() ) { if (this.mInLayout || this.mBlockLayoutRequests) { // new layout or invalidate requests. if (this.mSelectionNotifier == null) { this.mSelectionNotifier = new SelectionNotifier(this); } this.post(this.mSelectionNotifier); } else { this.fireOnSelected(); this.performAccessibilityActionsOnSelected(); } } } private fireOnSelected():void { if (this.mOnItemSelectedListener == null) { return; } const selection:number = this.getSelectedItemPosition(); if (selection >= 0) { let v:View = this.getSelectedView(); this.mOnItemSelectedListener.onItemSelected(this, v, selection, this.getAdapter().getItemId(selection)); } else { this.mOnItemSelectedListener.onNothingSelected(this); } } private performAccessibilityActionsOnSelected():void { //if (!AccessibilityManager.getInstance(this.mContext).isEnabled()) { // return; //} //const position:number = this.getSelectedItemPosition(); //if (position >= 0) { // // we fire selection events here not in View // this.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); //} } //dispatchPopulateAccessibilityEvent(event:AccessibilityEvent):boolean { // let selectedView:View = this.getSelectedView(); // if (selectedView != null && selectedView.getVisibility() == AdapterView.VISIBLE && selectedView.dispatchPopulateAccessibilityEvent(event)) { // return true; // } // return false; //} //onRequestSendAccessibilityEvent(child:View, event:AccessibilityEvent):boolean { // if (super.onRequestSendAccessibilityEvent(child, event)) { // // Add a record for ourselves as well. // let record:AccessibilityEvent = AccessibilityEvent.obtain(); // this.onInitializeAccessibilityEvent(record); // // Populate with the text of the requesting child. // child.dispatchPopulateAccessibilityEvent(record); // event.appendRecord(record); // return true; // } // return false; //} //onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void { // super.onInitializeAccessibilityNodeInfo(info); // info.setClassName(AdapterView.class.getName()); // info.setScrollable(this.isScrollableForAccessibility()); // let selectedView:View = this.getSelectedView(); // if (selectedView != null) { // info.setEnabled(selectedView.isEnabled()); // } //} //onInitializeAccessibilityEvent(event:AccessibilityEvent):void { // super.onInitializeAccessibilityEvent(event); // event.setClassName(AdapterView.class.getName()); // event.setScrollable(this.isScrollableForAccessibility()); // let selectedView:View = this.getSelectedView(); // if (selectedView != null) { // event.setEnabled(selectedView.isEnabled()); // } // event.setCurrentItemIndex(this.getSelectedItemPosition()); // event.setFromIndex(this.getFirstVisiblePosition()); // event.setToIndex(this.getLastVisiblePosition()); // event.setItemCount(this.getCount()); //} private isScrollableForAccessibility():boolean { let adapter:T = this.getAdapter(); if (adapter != null) { const itemCount:number = adapter.getCount(); return itemCount > 0 && (this.getFirstVisiblePosition() > 0 || this.getLastVisiblePosition() < itemCount - 1); } return false; } canAnimate():boolean { return super.canAnimate() && this.mItemCount > 0; } handleDataChanged():void { const count:number = this.mItemCount; let found:boolean = false; if (count > 0) { let newPos:number; // Find the row we are supposed to sync to if (this.mNeedSync) { // Update this first, since setNextSelectedPositionInt inspects // it this.mNeedSync = false; // See if we can find a position in the new data with the same // id as the old selection newPos = this.findSyncPosition(); if (newPos >= 0) { // Verify that new selection is selectable let selectablePos:number = this.lookForSelectablePosition(newPos, true); if (selectablePos == newPos) { // Same row id is selected this.setNextSelectedPositionInt(newPos); found = true; } } } if (!found) { // Try to use the same position if we can't find matching data newPos = this.getSelectedItemPosition(); // Pin position to the available range if (newPos >= count) { newPos = count - 1; } if (newPos < 0) { newPos = 0; } // Make sure we select something selectable -- first look down let selectablePos:number = this.lookForSelectablePosition(newPos, true); if (selectablePos < 0) { // Looking down didn't work -- try looking up selectablePos = this.lookForSelectablePosition(newPos, false); } if (selectablePos >= 0) { this.setNextSelectedPositionInt(selectablePos); this.checkSelectionChanged(); found = true; } } } if (!found) { // Nothing is selected this.mSelectedPosition = AdapterView.INVALID_POSITION; this.mSelectedRowId = AdapterView.INVALID_ROW_ID; this.mNextSelectedPosition = AdapterView.INVALID_POSITION; this.mNextSelectedRowId = AdapterView.INVALID_ROW_ID; this.mNeedSync = false; this.checkSelectionChanged(); } //this.notifySubtreeAccessibilityStateChangedIfNeeded(); } checkSelectionChanged():void { if ((this.mSelectedPosition != this.mOldSelectedPosition) || (this.mSelectedRowId != this.mOldSelectedRowId)) { this.selectionChanged(); this.mOldSelectedPosition = this.mSelectedPosition; this.mOldSelectedRowId = this.mSelectedRowId; } } /** * Searches the adapter for a position matching mSyncRowId. The search starts at mSyncPosition * and then alternates between moving up and moving down until 1) we find the right position, or * 2) we run out of time, or 3) we have looked at every position * * @return Position of the row that matches mSyncRowId, or {@link #INVALID_POSITION} if it can't * be found */ findSyncPosition():number { let count:number = this.mItemCount; if (count == 0) { return AdapterView.INVALID_POSITION; } let idToMatch:number = this.mSyncRowId; let seed:number = this.mSyncPosition; // If there isn't a selection don't hunt for it if (idToMatch == AdapterView.INVALID_ROW_ID) { return AdapterView.INVALID_POSITION; } // Pin seed to reasonable values seed = Math.max(0, seed); seed = Math.min(count - 1, seed); let endTime:number = SystemClock.uptimeMillis() + AdapterView.SYNC_MAX_DURATION_MILLIS; let rowId:number; // first position scanned so far let first:number = seed; // last position scanned so far let last:number = seed; // True if we should move down on the next iteration let next:boolean = false; // True when we have looked at the first item in the data let hitFirst:boolean; // True when we have looked at the last item in the data let hitLast:boolean; // Get the item ID locally (instead of getItemIdAtPosition), so // we need the adapter let adapter:T = this.getAdapter(); if (adapter == null) { return AdapterView.INVALID_POSITION; } while (SystemClock.uptimeMillis() <= endTime) { rowId = adapter.getItemId(seed); if (rowId == idToMatch) { // Found it! return seed; } hitLast = last == count - 1; hitFirst = first == 0; if (hitLast && hitFirst) { // Looked at everything break; } if (hitFirst || (next && !hitLast)) { // Either we hit the top, or we are trying to move down last++; seed = last; // Try going up next time next = false; } else if (hitLast || (!next && !hitFirst)) { // Either we hit the bottom, or we are trying to move up first--; seed = first; // Try going down next time next = true; } } return AdapterView.INVALID_POSITION; } /** * Find a position that can be selected (i.e., is not a separator). * * @param position The starting position to look at. * @param lookDown Whether to look down for other positions. * @return The next selectable position starting at position and then searching either up or * down. Returns {@link #INVALID_POSITION} if nothing can be found. */ lookForSelectablePosition(position:number, lookDown:boolean):number { return position; } /** * Utility to keep mSelectedPosition and mSelectedRowId in sync * @param position Our current position */ setSelectedPositionInt(position:number):void { this.mSelectedPosition = position; this.mSelectedRowId = this.getItemIdAtPosition(position); } /** * Utility to keep mNextSelectedPosition and mNextSelectedRowId in sync * @param position Intended value for mSelectedPosition the next time we go * through layout */ setNextSelectedPositionInt(position:number):void { this.mNextSelectedPosition = position; this.mNextSelectedRowId = this.getItemIdAtPosition(position); // If we are trying to sync to the selection, update that too if (this.mNeedSync && this.mSyncMode == AdapterView.SYNC_SELECTED_POSITION && position >= 0) { this.mSyncPosition = position; this.mSyncRowId = this.mNextSelectedRowId; } } /** * Remember enough information to restore the screen state when the data has * changed. * */ rememberSyncState():void { if (this.getChildCount() > 0) { this.mNeedSync = true; this.mSyncHeight = this.mLayoutHeight; if (this.mSelectedPosition >= 0) { // Sync the selection state let v:View = this.getChildAt(this.mSelectedPosition - this.mFirstPosition); this.mSyncRowId = this.mNextSelectedRowId; this.mSyncPosition = this.mNextSelectedPosition; if (v != null) { this.mSpecificTop = v.getTop(); } this.mSyncMode = AdapterView.SYNC_SELECTED_POSITION; } else { // Sync the based on the offset of the first view let v:View = this.getChildAt(0); let adapter:T = this.getAdapter(); if (this.mFirstPosition >= 0 && this.mFirstPosition < adapter.getCount()) { this.mSyncRowId = adapter.getItemId(this.mFirstPosition); } else { this.mSyncRowId = AdapterView.NO_ID; } this.mSyncPosition = this.mFirstPosition; if (v != null) { this.mSpecificTop = v.getTop(); } this.mSyncMode = AdapterView.SYNC_FIRST_POSITION; } } } } export module AdapterView{ /** * Interface definition for a callback to be invoked when an item in this * AdapterView has been clicked. */ export interface OnItemClickListener { /** * Callback method to be invoked when an item in this AdapterView has * been clicked. * <p> * Implementers can call getItemAtPosition(position) if they need * to access the data associated with the selected item. * * @param parent The AdapterView where the click happened. * @param view The view within the AdapterView that was clicked (this * will be a view provided by the adapter) * @param position The position of the view in the adapter. * @param id The row id of the item that was clicked. */ onItemClick(parent:AdapterView<any>, view:View, position:number, id:number):void ; } /** * Interface definition for a callback to be invoked when an item in this * view has been clicked and held. */ export interface OnItemLongClickListener { /** * Callback method to be invoked when an item in this view has been * clicked and held. * * Implementers can call getItemAtPosition(position) if they need to access * the data associated with the selected item. * * @param parent The AbsListView where the click happened * @param view The view within the AbsListView that was clicked * @param position The position of the view in the list * @param id The row id of the item that was clicked * * @return true if the callback consumed the long click, false otherwise */ onItemLongClick(parent:AdapterView<any>, view:View, position:number, id:number):boolean ; } /** * Interface definition for a callback to be invoked when * an item in this view has been selected. */ export interface OnItemSelectedListener { /** * <p>Callback method to be invoked when an item in this view has been * selected. This callback is invoked only when the newly selected * position is different from the previously selected position or if * there was no selected item.</p> * * Impelmenters can call getItemAtPosition(position) if they need to access the * data associated with the selected item. * * @param parent The AdapterView where the selection happened * @param view The view within the AdapterView that was clicked * @param position The position of the view in the adapter * @param id The row id of the item that is selected */ onItemSelected(parent:AdapterView<any>, view:View, position:number, id:number):void ; /** * Callback method to be invoked when the selection disappears from this * view. The selection can disappear for instance when touch is activated * or when the adapter becomes empty. * * @param parent The AdapterView that now contains no selected item. */ onNothingSelected(parent:AdapterView<any>):void ; } /** * Extra menu information provided to the * {@link android.view.View.OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) } * callback when a context menu is brought up for this AdapterView. * */ //export class AdapterContextMenuInfo implements ContextMenu.ContextMenuInfo { // // constructor(targetView:View, position:number, id:number) { // this.targetView = targetView; // this.position = position; // this.id = id; // } // // /** // * The child view for which the context menu is being displayed. This // * will be one of the children of this AdapterView. // */ // targetView:View; // // /** // * The position in the adapter for which the context menu is being // * displayed. // */ // position:number; // // /** // * The row id of the item for which the context menu is being displayed. // */ // id:number; //} export class AdapterDataSetObserver extends DataSetObserver { AdapterView_this:AdapterView<any>; //private mInstanceState:Parcelable = null; constructor(AdapterView_this:AdapterView<any>){ super(); this.AdapterView_this = AdapterView_this; } onChanged():void { this.AdapterView_this.mDataChanged = true; this.AdapterView_this.mOldItemCount = this.AdapterView_this.mItemCount; this.AdapterView_this.mItemCount = this.AdapterView_this.getAdapter().getCount(); // been repopulated with new data. //if (this.AdapterView_this.getAdapter().hasStableIds() && this.AdapterView_this.mInstanceState != null // && this.AdapterView_this.mOldItemCount == 0 && this.AdapterView_this.mItemCount > 0) { // this.AdapterView_this.onRestoreInstanceState(this.AdapterView_this.mInstanceState); // this.AdapterView_this.mInstanceState = null; //} else { this.AdapterView_this.rememberSyncState(); //} this.AdapterView_this.checkFocus(); this.AdapterView_this.requestLayout(); } onInvalidated():void { this.AdapterView_this.mDataChanged = true; //if (AdapterView.this.AdapterView_this.getAdapter().hasStableIds()) { // // Remember the current state for the case where our hosting activity is being // // stopped and later restarted // this.AdapterView_this.mInstanceState = AdapterView.this.AdapterView_this.onSaveInstanceState(); //} // Data is invalid so we should reset our state this.AdapterView_this.mOldItemCount = this.AdapterView_this.mItemCount; this.AdapterView_this.mItemCount = 0; this.AdapterView_this.mSelectedPosition = AdapterView.INVALID_POSITION; this.AdapterView_this.mSelectedRowId = AdapterView.INVALID_ROW_ID; this.AdapterView_this.mNextSelectedPosition = AdapterView.INVALID_POSITION; this.AdapterView_this.mNextSelectedRowId = AdapterView.INVALID_ROW_ID; this.AdapterView_this.mNeedSync = false; this.AdapterView_this.checkFocus(); this.AdapterView_this.requestLayout(); } clearSavedState():void { //this.AdapterView_this.mInstanceState = null; } } } class SelectionNotifier implements Runnable { AdapterView_this:AdapterView<any>; constructor(AdapterView_this:AdapterView<any>){ this.AdapterView_this = AdapterView_this; } run():void { if (this.AdapterView_this.mDataChanged) { // has been synched to the new data. if (this.AdapterView_this.getAdapter() != null) { this.AdapterView_this.post(this); } } else { this.AdapterView_this.fireOnSelected(); this.AdapterView_this.performAccessibilityActionsOnSelected(); } } } }
the_stack
import { NestedObject } from '../../../test/models' import { ModelWithCollections } from '../../../test/models/model-with-collections.model' import { Metadata } from '../../decorator/metadata/metadata' import { metadataForModel } from '../../decorator/metadata/metadata-for-model.function' import { PropertyMetadata } from '../../decorator/metadata/property-metadata.model' import { ListAttribute, NumberSetAttribute, StringSetAttribute } from '../type/attribute.type' import { CollectionMapper } from './collection.mapper' describe('collection mapper', () => { describe('to db', () => { describe('no metadata', () => { /* * Arrays */ it('arr (homogeneous string) => L', () => { const attributeValue = CollectionMapper.toDb(['value1', 'value2', 'value3']) expect(attributeValue).toEqual({ L: [{ S: 'value1' }, { S: 'value2' }, { S: 'value3' }] }) }) it('arr (homogeneous number) => L', () => { const attributeValue = CollectionMapper.toDb([5, 10]) expect(attributeValue).toEqual({ L: [{ N: '5' }, { N: '10' }] }) }) it('arr (homogeneous objects)', () => { const attributeValue = <ListAttribute>CollectionMapper.toDb([{ name: 'name1' }, { name: 'name2' }]) expect(Object.keys(attributeValue)[0]).toBe('L') expect(Array.isArray(attributeValue.L)).toBeTruthy() expect(attributeValue.L.length).toBe(2) expect(attributeValue.L).toEqual([{ M: { name: { S: 'name1' } } }, { M: { name: { S: 'name2' } } }]) }) it('arr (heterogeneous)', () => { const attributeValue = <ListAttribute>CollectionMapper.toDb(['value1', 10]) expect(Object.keys(attributeValue)[0]).toBe('L') expect(Array.isArray(attributeValue.L)).toBeTruthy() expect(attributeValue.L.length).toBe(2) expect(attributeValue.L).toEqual([{ S: 'value1' }, { N: '10' }]) }) /* * Set */ it('set (homogeneous string)', () => { const attributeValue = <StringSetAttribute>CollectionMapper.toDb(new Set(['value1', 'value2', 'value3'])) expect(Object.keys(attributeValue)[0]).toBe('SS') expect(Array.isArray(attributeValue.SS)).toBeTruthy() expect(attributeValue.SS.length).toBe(3) expect(attributeValue.SS).toEqual(['value1', 'value2', 'value3']) }) it('set (homogeneous number)', () => { const attributeValue = <NumberSetAttribute>CollectionMapper.toDb(new Set([5, 10])) expect(Object.keys(attributeValue)[0]).toBe('NS') expect(Array.isArray(attributeValue.NS)).toBeTruthy() expect(attributeValue.NS.length).toBe(2) expect(attributeValue.NS).toEqual(['5', '10']) }) it('set with objects should throw', () => { expect(() => CollectionMapper.toDb(new Set([{ name: 'name1' }, { name: 'name2' }]))).toThrow() }) it('heterogeneous set should throw', () => { expect(() => CollectionMapper.toDb(new Set(['value1', 10]))).toThrow() }) /* * neither set nor arr or not primitive in set */ it('should throw if neither array nor set', () => { expect(() => CollectionMapper.toDb(<any>{ aValue: true })).toThrow() }) it('should throw if set of non primitives', () => { expect(() => CollectionMapper.toDb(new Set([{ aValue: true }]))).toThrow() }) }) describe('with metadata', () => { const metadata: PropertyMetadata<any> = <any>{ typeInfo: { type: Array, }, isSortedCollection: true, } it('set (homogeneous, generic type is string)', () => { const attributeValue = <StringSetAttribute>CollectionMapper.toDb(new Set(['value1', 'value2', 'value3']), <any>{ typeInfo: { type: Set, genericType: String }, }) expect(Object.keys(attributeValue)[0]).toBe('SS') expect(Array.isArray(attributeValue.SS)).toBeTruthy() expect(attributeValue.SS.length).toBe(3) expect(attributeValue.SS).toEqual(['value1', 'value2', 'value3']) }) it('sorted arr (homogeneous string)', () => { const attributeValue = <ListAttribute>CollectionMapper.toDb(['value1', 'value2', 'value3'], <any>metadata) expect(Object.keys(attributeValue)[0]).toBe('L') expect(Array.isArray(attributeValue.L)).toBeTruthy() expect(attributeValue.L.length).toBe(3) expect(attributeValue.L).toEqual([{ S: 'value1' }, { S: 'value2' }, { S: 'value3' }]) }) it('sorted arr (homogeneous number)', () => { const attributeValue = <ListAttribute>CollectionMapper.toDb([5, 10], <any>metadata) expect(Object.keys(attributeValue)[0]).toBe('L') expect(Array.isArray(attributeValue.L)).toBeTruthy() expect(attributeValue.L.length).toBe(2) expect(attributeValue.L).toEqual([{ N: '5' }, { N: '10' }]) }) it('sorted set (homogeneous string)', () => { const attributeValue = <ListAttribute>( CollectionMapper.toDb(new Set(['value1', 'value2', 'value3']), <any>metadata) ) expect(Object.keys(attributeValue)[0]).toBe('L') expect(Array.isArray(attributeValue.L)).toBeTruthy() expect(attributeValue.L.length).toBe(3) expect(attributeValue.L).toEqual([{ S: 'value1' }, { S: 'value2' }, { S: 'value3' }]) }) it('sorted set (homogeneous number)', () => { const attributeValue = <ListAttribute>CollectionMapper.toDb([5, 10], <any>metadata) expect(Object.keys(attributeValue)[0]).toBe('L') expect(Array.isArray(attributeValue.L)).toBeTruthy() expect(attributeValue.L.length).toBe(2) expect(attributeValue.L).toEqual([{ N: '5' }, { N: '10' }]) }) it('set with generic number type', () => { const meta: PropertyMetadata<any, NumberSetAttribute> = { name: 'aName', nameDb: 'aName', typeInfo: { type: Set, genericType: Number, }, } const r = CollectionMapper.toDb(new Set([1, 2, 3, 5]), <any>meta) expect(r).toEqual({ NS: ['1', '2', '3', '5'] }) }) it('without generic type but actually set of numbers', () => { const meta: PropertyMetadata<any, NumberSetAttribute> = { name: 'aName', nameDb: 'aName', typeInfo: { type: Set, }, } const r = CollectionMapper.toDb(new Set([1, 2, 3, 5]), <any>meta) expect(r).toEqual({ NS: ['1', '2', '3', '5'] }) }) it('throws if explicit type is neither array nor set', () => { const meta: PropertyMetadata<any, NumberSetAttribute> = { name: 'aName', nameDb: 'aName', typeInfo: { type: Number, }, } expect(() => CollectionMapper.toDb(new Set([0, 1, 1, 2, 3, 5]), <any>meta)).toThrow() }) }) describe('with CollectionProperty decorator', () => { let metadata: Metadata<ModelWithCollections> let aDate: Date let aStringArray: string[] let aNestedObject: NestedObject beforeEach(() => { metadata = metadataForModel(ModelWithCollections) aDate = new Date() aStringArray = ['Hello', 'World'] aNestedObject = { id: 'myId' } }) it('array to (L)ist (itemType)', () => { const propMeta = metadata.forProperty('arrayOfNestedModelToList') const val: ModelWithCollections['arrayOfNestedModelToList'] = [{ updated: aDate }] expect(CollectionMapper.toDb(val, <any>propMeta)).toEqual({ L: [{ M: { updated: { S: aDate.toISOString() } } }], }) }) it('set to (L)ist (itemType)', () => { const propMeta = metadata.forProperty('setOfNestedModelToList') const val: ModelWithCollections['setOfNestedModelToList'] = new Set([{ updated: aDate }]) expect(CollectionMapper.toDb(val, <any>propMeta)).toEqual({ L: [{ M: { updated: { S: aDate.toISOString() } } }], }) }) it('array to (L)ist (nested object)', () => { const propMeta = metadata.forProperty('arrayOfObjectsToList') const val: ModelWithCollections['arrayOfObjectsToList'] = [aNestedObject] expect(CollectionMapper.toDb(val, <any>propMeta)).toEqual({ L: [{ M: { id: { S: aNestedObject.id } } }] }) }) it('set to (L)ist (nested object)', () => { const propMeta = metadata.forProperty('setOfObjectsToList') const val: ModelWithCollections['setOfObjectsToList'] = new Set([aNestedObject]) expect(CollectionMapper.toDb(val, <any>propMeta)).toEqual({ L: [{ M: { id: { S: aNestedObject.id } } }] }) }) it('array to List ', () => { const propMeta = metadata.forProperty('arrayOfStringToSet') const val: ModelWithCollections['arrayOfStringToSet'] = aStringArray expect(CollectionMapper.toDb(val, <any>propMeta)).toEqual({ L: aStringArray.map((t) => ({ S: t })) }) }) it('set to (S)et (primitive type)', () => { const propMeta = metadata.forProperty('setOfStringToSet') const val: ModelWithCollections['setOfStringToSet'] = new Set(aStringArray) expect(CollectionMapper.toDb(val, <any>propMeta)).toEqual({ SS: aStringArray }) }) }) }) describe('from db', () => { describe('no metadata', () => { /* * S(et) */ it('arr (homogeneous string)', () => { const stringSet = <Set<string>>CollectionMapper.fromDb({ SS: ['value1', 'value2', 'value3'] }) expect(stringSet instanceof Set).toBeTruthy() expect(stringSet.size).toBe(3) expect(typeof Array.from(stringSet)[0]).toBe('string') }) it('arr (homogeneous number)', () => { const numberSet = <Set<number>>CollectionMapper.fromDb({ NS: ['25', '10'] }) expect(numberSet instanceof Set).toBeTruthy() expect(numberSet.size).toBe(2) expect(typeof Array.from(numberSet)[0]).toBe('number') }) it('throws if not a L|SS|NS|BS', () => { expect(() => CollectionMapper.fromDb(<any>{ S: 'not a list' })).toThrow() }) }) }) })
the_stack
import {ResourceBase, ResourceTag} from '../resource' import {Value, List} from '../dataTypes' export class AssetPropertyVariant { StringValue?: Value<string> DoubleValue?: Value<string> BooleanValue?: Value<string> IntegerValue?: Value<string> constructor(properties: AssetPropertyVariant) { Object.assign(this, properties) } } export class SigV4Authorization { ServiceName!: Value<string> SigningRegion!: Value<string> RoleArn!: Value<string> constructor(properties: SigV4Authorization) { Object.assign(this, properties) } } export class SqsAction { RoleArn!: Value<string> UseBase64?: Value<boolean> QueueUrl!: Value<string> constructor(properties: SqsAction) { Object.assign(this, properties) } } export class PutItemInput { TableName!: Value<string> constructor(properties: PutItemInput) { Object.assign(this, properties) } } export class SnsAction { TargetArn!: Value<string> MessageFormat?: Value<string> RoleArn!: Value<string> constructor(properties: SnsAction) { Object.assign(this, properties) } } export class HttpAction { ConfirmationUrl?: Value<string> Headers?: List<HttpActionHeader> Url!: Value<string> Auth?: HttpAuthorization constructor(properties: HttpAction) { Object.assign(this, properties) } } export class PutAssetPropertyValueEntry { PropertyAlias?: Value<string> PropertyValues!: List<AssetPropertyValue> AssetId?: Value<string> EntryId?: Value<string> PropertyId?: Value<string> constructor(properties: PutAssetPropertyValueEntry) { Object.assign(this, properties) } } export class LambdaAction { FunctionArn?: Value<string> constructor(properties: LambdaAction) { Object.assign(this, properties) } } export class DynamoDBAction { TableName!: Value<string> PayloadField?: Value<string> RangeKeyField?: Value<string> HashKeyField!: Value<string> RangeKeyValue?: Value<string> RangeKeyType?: Value<string> HashKeyType?: Value<string> HashKeyValue!: Value<string> RoleArn!: Value<string> constructor(properties: DynamoDBAction) { Object.assign(this, properties) } } export class IotAnalyticsAction { RoleArn!: Value<string> ChannelName!: Value<string> BatchMode?: Value<boolean> constructor(properties: IotAnalyticsAction) { Object.assign(this, properties) } } export class IotEventsAction { InputName!: Value<string> RoleArn!: Value<string> MessageId?: Value<string> BatchMode?: Value<boolean> constructor(properties: IotEventsAction) { Object.assign(this, properties) } } export class KafkaAction { DestinationArn!: Value<string> Topic!: Value<string> Key?: Value<string> Partition?: Value<string> ClientProperties!: {[key: string]: Value<string>} constructor(properties: KafkaAction) { Object.assign(this, properties) } } export class TimestreamAction { RoleArn!: Value<string> DatabaseName!: Value<string> TableName!: Value<string> Dimensions!: List<TimestreamDimension> Timestamp?: TimestreamTimestamp BatchMode?: Value<boolean> constructor(properties: TimestreamAction) { Object.assign(this, properties) } } export class IotSiteWiseAction { RoleArn!: Value<string> PutAssetPropertyValueEntries!: List<PutAssetPropertyValueEntry> constructor(properties: IotSiteWiseAction) { Object.assign(this, properties) } } export class DynamoDBv2Action { PutItem?: PutItemInput RoleArn?: Value<string> constructor(properties: DynamoDBv2Action) { Object.assign(this, properties) } } export class CloudwatchMetricAction { MetricName!: Value<string> MetricValue!: Value<string> MetricNamespace!: Value<string> MetricUnit!: Value<string> RoleArn!: Value<string> MetricTimestamp?: Value<string> constructor(properties: CloudwatchMetricAction) { Object.assign(this, properties) } } export class S3Action { BucketName!: Value<string> Key!: Value<string> RoleArn!: Value<string> CannedAcl?: Value<string> constructor(properties: S3Action) { Object.assign(this, properties) } } export class FirehoseAction { DeliveryStreamName!: Value<string> RoleArn!: Value<string> Separator?: Value<string> BatchMode?: Value<boolean> constructor(properties: FirehoseAction) { Object.assign(this, properties) } } export class AssetPropertyTimestamp { TimeInSeconds!: Value<string> OffsetInNanos?: Value<string> constructor(properties: AssetPropertyTimestamp) { Object.assign(this, properties) } } export class AssetPropertyValue { Value!: AssetPropertyVariant Timestamp!: AssetPropertyTimestamp Quality?: Value<string> constructor(properties: AssetPropertyValue) { Object.assign(this, properties) } } export class ElasticsearchAction { Type!: Value<string> Index!: Value<string> Id!: Value<string> Endpoint!: Value<string> RoleArn!: Value<string> constructor(properties: ElasticsearchAction) { Object.assign(this, properties) } } export class KinesisAction { PartitionKey?: Value<string> StreamName!: Value<string> RoleArn!: Value<string> constructor(properties: KinesisAction) { Object.assign(this, properties) } } export class Action { S3?: S3Action CloudwatchAlarm?: CloudwatchAlarmAction CloudwatchLogs?: CloudwatchLogsAction IotEvents?: IotEventsAction Firehose?: FirehoseAction Republish?: RepublishAction StepFunctions?: StepFunctionsAction DynamoDB?: DynamoDBAction Http?: HttpAction DynamoDBv2?: DynamoDBv2Action CloudwatchMetric?: CloudwatchMetricAction IotSiteWise?: IotSiteWiseAction Elasticsearch?: ElasticsearchAction Sqs?: SqsAction Kinesis?: KinesisAction IotAnalytics?: IotAnalyticsAction Sns?: SnsAction Lambda?: LambdaAction Timestream?: TimestreamAction Kafka?: KafkaAction constructor(properties: Action) { Object.assign(this, properties) } } export class HttpAuthorization { Sigv4?: SigV4Authorization constructor(properties: HttpAuthorization) { Object.assign(this, properties) } } export class HttpActionHeader { Value!: Value<string> Key!: Value<string> constructor(properties: HttpActionHeader) { Object.assign(this, properties) } } export class RepublishAction { Qos?: Value<number> Topic!: Value<string> RoleArn!: Value<string> constructor(properties: RepublishAction) { Object.assign(this, properties) } } export class StepFunctionsAction { ExecutionNamePrefix?: Value<string> StateMachineName!: Value<string> RoleArn!: Value<string> constructor(properties: StepFunctionsAction) { Object.assign(this, properties) } } export class TopicRulePayload { RuleDisabled?: Value<boolean> ErrorAction?: Action Description?: Value<string> AwsIotSqlVersion?: Value<string> Actions!: List<Action> Sql!: Value<string> constructor(properties: TopicRulePayload) { Object.assign(this, properties) } } export class CloudwatchAlarmAction { StateValue!: Value<string> AlarmName!: Value<string> StateReason!: Value<string> RoleArn!: Value<string> constructor(properties: CloudwatchAlarmAction) { Object.assign(this, properties) } } export class CloudwatchLogsAction { LogGroupName!: Value<string> RoleArn!: Value<string> constructor(properties: CloudwatchLogsAction) { Object.assign(this, properties) } } export class TimestreamDimension { Name!: Value<string> Value!: Value<string> constructor(properties: TimestreamDimension) { Object.assign(this, properties) } } export class TimestreamTimestamp { Value!: Value<string> Unit!: Value<string> constructor(properties: TimestreamTimestamp) { Object.assign(this, properties) } } export interface TopicRuleProperties { RuleName?: Value<string> TopicRulePayload: TopicRulePayload Tags?: List<ResourceTag> } export default class TopicRule extends ResourceBase<TopicRuleProperties> { static AssetPropertyVariant = AssetPropertyVariant static SigV4Authorization = SigV4Authorization static SqsAction = SqsAction static PutItemInput = PutItemInput static SnsAction = SnsAction static HttpAction = HttpAction static PutAssetPropertyValueEntry = PutAssetPropertyValueEntry static LambdaAction = LambdaAction static DynamoDBAction = DynamoDBAction static IotAnalyticsAction = IotAnalyticsAction static IotEventsAction = IotEventsAction static KafkaAction = KafkaAction static TimestreamAction = TimestreamAction static IotSiteWiseAction = IotSiteWiseAction static DynamoDBv2Action = DynamoDBv2Action static CloudwatchMetricAction = CloudwatchMetricAction static S3Action = S3Action static FirehoseAction = FirehoseAction static AssetPropertyTimestamp = AssetPropertyTimestamp static AssetPropertyValue = AssetPropertyValue static ElasticsearchAction = ElasticsearchAction static KinesisAction = KinesisAction static Action = Action static HttpAuthorization = HttpAuthorization static HttpActionHeader = HttpActionHeader static RepublishAction = RepublishAction static StepFunctionsAction = StepFunctionsAction static TopicRulePayload = TopicRulePayload static CloudwatchAlarmAction = CloudwatchAlarmAction static CloudwatchLogsAction = CloudwatchLogsAction static TimestreamDimension = TimestreamDimension static TimestreamTimestamp = TimestreamTimestamp constructor(properties: TopicRuleProperties) { super('AWS::IoT::TopicRule', properties) } }
the_stack
import { SpreadsheetModel, CellRenderEventArgs, Spreadsheet } from '../../../src/spreadsheet/index'; import { SpreadsheetHelper } from "../util/spreadsheethelper.spec"; import { defaultData } from '../util/datasource.spec'; import { CellModel } from '../../../src/index'; import { Button } from '@syncfusion/ej2-buttons'; import { DropDownList } from '@syncfusion/ej2-dropdowns'; /** * Editing test cases */ describe('Editing ->', () => { let helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet'); let model: SpreadsheetModel; describe('Checking updated edited value ->', () => { beforeAll((done: Function) => { model = { sheets: [{ ranges: [{ dataSource: defaultData }], rows: [{ index: 1, cells: [ { index: 9, formula: '=D2' }, { index: 11, formula: '=J2' }, { index: 13, formula: '=L2' }, { index: 15, formula: '=N2' }, ] }] }] }; helper.initializeSpreadsheet(model, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Check multiple cell dependency', (done: Function) => { setTimeout(() => { helper.invoke('getData', ['Sheet1!A1:Q11']).then((values: Map<string, CellModel>) => { expect(values.get('D2').value.toString()).toEqual('10'); expect(values.get('J2').value.toString()).toEqual('10'); expect(values.get('L2').value.toString()).toEqual('10'); expect(values.get('N2').value.toString()).toEqual('10'); done(); }); }, 20); }); }); describe('UI interaction ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData, template: '<button class="e-button-template">BUTTON</button>', address: 'G10' }] }], beforeCellRender: (evt: CellRenderEventArgs) => { if (evt.element.children.length) { let template: string = evt.element.children[0].className; switch (template) { case 'e-button-template': new Button({ content: (evt.cell && evt.cell.value) ? evt.cell.value : 'Button' }, evt.element.children[0] as HTMLButtonElement); break; } } else { if (evt.rowIndex === undefined && evt.colIndex === 0) { expect(evt.address).toBe('A'); expect(evt.cell).toBeNull(); } if (evt.colIndex === undefined && evt.rowIndex === 2) { expect(evt.address).toBe('3'); expect(evt.cell).toBeNull(); } } expect(evt.element.parentElement).not.toBeUndefined(); } }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Enter key', (done: Function) => { helper.invoke('startEdit'); helper.getElement('.e-spreadsheet-edit').textContent = 'Test 1'; helper.triggerKeyNativeEvent(13); setTimeout(() => { expect(helper.getInstance().sheets[0].rows[0].cells[0].value).toBe('Test 1'); expect(helper.getInstance().sheets[0].selectedRange).toBe('A2:A2'); done(); }); }); it('Editing with key', (done: Function) => { helper.invoke('startEdit'); helper.triggerKeyEvent('keyup', 66); //helper.triggerKeyNativeEvent(66, null, null, helper.getElement('.e-spreadsheet-edit'), 'keyup'); helper.triggerKeyNativeEvent(13); setTimeout(() => { //expect(helper.getInstance().sheets[0].rows[1].cells[0].value).toBe('Casual Shoes2'); done(); }); }); it('Cancel Edit - ESC', (done: Function) => { helper.invoke('startEdit'); helper.getElement('.e-spreadsheet-edit').textContent = 'Test 2'; helper.triggerKeyNativeEvent(27); setTimeout(() => { expect(helper.getInstance().sheets[0].rows[2].cells[0].value).toBe('Sports Shoes'); done(); }); }); it('Tab key', (done: Function) => { helper.invoke('startEdit'); helper.getElement('.e-spreadsheet-edit').textContent = 'Test 2'; helper.triggerKeyNativeEvent(9); setTimeout(() => { expect(helper.getInstance().sheets[0].rows[2].cells[0].value).toBe('Test 2'); expect(helper.getInstance().sheets[0].selectedRange).toBe('B3:B3'); done(); }); }); it('F2', (done: Function) => { helper.triggerKeyNativeEvent(113); helper.getElement('.e-spreadsheet-edit').textContent = 'Test 3'; helper.triggerKeyNativeEvent(9, null, true); // Shift tab save setTimeout(() => { expect(helper.getInstance().sheets[0].rows[2].cells[1].value).toBe('Test 3'); expect(helper.getInstance().sheets[0].selectedRange).toBe('A3:A3'); done(); }); }); it('Delete', (done: Function) => { helper.triggerKeyNativeEvent(46); setTimeout(() => { expect(JSON.stringify(helper.getInstance().sheets[0].rows[2].cells[0])).toBe('{}'); done(); }); }); it('Cell template', (done: Function) => { helper.invoke('selectRange', ['G10']); helper.editInUI('Test 4') setTimeout(() => { // expect(helper.getInstance().sheets[0].rows[9].cells[6].value).toBe('Test 4'); // check this done(); }); }); it('Formula', (done: Function) => { helper.invoke('selectRange', ['K15']) helper.invoke('startEdit'); helper.getElement('.e-spreadsheet-edit').textContent = '=SUM(H2:H11)'; helper.triggerKeyNativeEvent(13); setTimeout(() => { expect(JSON.stringify(helper.getInstance().sheets[0].rows[14].cells[10])).toBe('{"value":554,"formula":"=SUM(H2:H11)"}'); done(); }); }); it('Mouse down on Formula', (done: Function) => { helper.invoke('selectRange', ['K15']) helper.invoke('startEdit'); let coords: ClientRect = helper.getElement('.e-spreadsheet-edit').getBoundingClientRect(); helper.triggerMouseAction('mousedown', { x: coords.left, y: coords.top }, null, helper.getElement('.e-spreadsheet-edit')); const selection: Selection = window.getSelection(); expect(selection.focusNode.nodeName).toBe('#text'); expect(selection.focusOffset).toBe(12); expect(selection.anchorOffset).toBe(12); const td: HTMLElement = helper.invoke('getCell', [2, 2]); coords = td.getBoundingClientRect(); helper.triggerMouseAction('mousedown', { x: coords.left, y: coords.top }, null, td); helper.triggerMouseAction('mouseup', { x: coords.left, y: coords.top }, document, td); helper.invoke('endEdit'); done(); }); it('Double click to save on formula', (done: Function) => { helper.invoke('selectRange', ['K15']); helper.invoke('startEdit'); const coords: ClientRect = helper.getElement('.e-spreadsheet-edit').getBoundingClientRect(); helper.triggerMouseAction('dblclick', { x: coords.left, y: coords.top }, null, helper.getElement('.e-spreadsheet-edit')); expect(helper.invoke('getCell', [14, 10]).classList).toContain('e-ss-edited'); expect(helper.getElement('.e-spreadsheet-edit').textContent).toBe('5:56:32 AM'); expect(helper.getInstance().editModule.isEdit).toBeTruthy(); helper.invoke('endEdit'); done(); }); it('Alt enter', (done: Function) => { helper.invoke('selectRange', ['F2']); helper.triggerKeyNativeEvent(113); const editElem: HTMLElement = helper.getElement('.e-spreadsheet-edit'); helper.triggerKeyEvent('keyup', 13, null, null, null, editElem, undefined, true); expect(editElem.textContent.split('\n').length).toBe(2); helper.triggerKeyNativeEvent(13); expect(helper.getInstance().sheets[0].rows[1].cells[5].wrap).toBeTruthy(); done(); }); it('Mouse down after alt enter', (done: Function) => { helper.triggerKeyNativeEvent(113); const editElem: HTMLElement = helper.getElement('.e-spreadsheet-edit'); helper.triggerKeyEvent('keyup', 13, null, null, null, editElem, undefined, true); const td: HTMLElement = helper.invoke('getCell', [2, 2]); const coords: ClientRect = td.getBoundingClientRect(); helper.triggerMouseAction('mousedown', { x: coords.left, y: coords.top }, null, td); helper.triggerMouseAction('mouseup', { x: coords.left, y: coords.top }, document, td); expect(helper.getInstance().sheets[0].rows[2].cells[5].wrap).toBeTruthy(); done(); }); it('Formula reference', (done: Function) => { helper.invoke('selectRange', ['F4']) helper.invoke('startEdit'); helper.getInstance().editModule.editCellData.value = '=sum('; const td: HTMLElement = helper.invoke('getCell', [3, 6]); const coords: ClientRect = td.getBoundingClientRect(); helper.triggerMouseAction('mousedown', { x: coords.left, y: coords.top }, null, td); helper.triggerMouseAction('mouseup', { x: coords.left, y: coords.top }, document, td); expect(helper.getElement('.e-spreadsheet-edit').textContent).toBe('=sum(G4') expect(td.classList).toContain('e-formularef-selection'); helper.triggerKeyNativeEvent(13); expect(JSON.stringify(helper.getInstance().sheets[0].rows[3].cells[5])).toBe('{"value":7,"formula":"=sum(G4)"}'); done(); }); }); describe('Rtl ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ enableRtl: true }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('', (done: Function) => { let td: HTMLElement = helper.invoke('getCell', [3, 5]); let coords: ClientRect = td.getBoundingClientRect(); helper.triggerMouseAction('dblclick', { x: coords.right, y: coords.top }, null, td); let ele: HTMLElement = helper.getElementFromSpreadsheet('.e-spreadsheet-edit'); // expect(ele.style.top).toBe('61px'); // expect(ele.style.right).toBe('321px'); // expect(ele.style.height).toBe('17px'); done(); }); }); describe('CR-Issues ->', () => { describe('I309407 ->', () => { beforeEach((done: Function) => { model = { sheets: [{ ranges: [{ dataSource: defaultData }] }], height: 1000, created: (): void => { helper.getInstance().cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'A1:H1'); } }; helper.initializeSpreadsheet(model, done); }); afterEach(() => { helper.invoke('destroy'); }); it('curser is moving to the 4th cell when click on the second cell after entering value in first cell', (done: Function) => { const spreadsheet: any = helper.getInstance(); expect(spreadsheet.sheets[0].selectedRange).toEqual('A1:A1'); spreadsheet.editModule.startEdit(); spreadsheet.editModule.editCellData.value = 'Customer'; helper.triggerKeyNativeEvent(13); setTimeout((): void => { expect(spreadsheet.sheets[0].selectedRange).toEqual('A2:A2'); done(); }); }); }); describe('I290629 ->', () => { beforeEach((done: Function) => { model = { sheets: [{ ranges: [{ dataSource: defaultData }] }], height: 1000, created: (): void => { helper.getInstance().cellFormat({ fontWeight: 'bold', textAlign: 'center' }, 'A1:H1'); } }; helper.initializeSpreadsheet(model, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Editing issue occurs in edge & chrome browser from my laptop - "Script error throws while editing after scrolling"', (done: Function) => { helper.invoke('goTo', ['A73']); setTimeout((): void => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].topLeftCell).toEqual('A73'); helper.edit('C90', 'Test'); setTimeout((): void => { expect(spreadsheet.sheets[0].rows[89].cells[2].value).toEqual('Test'); expect(helper.invoke('getCell', [89, 2]).textContent).toEqual('Test'); expect(helper.getElement('#' + helper.id + '_formula_input').value).toEqual('Test'); done(); }); }); }); }); describe('I282937 ->', () => { beforeAll((done: Function) => { model = { sheets: [{ name: 'Datos de asunto', showGridLines: false, columns: [{ width: 130 }, { width: 92 }, { width: 96 }], ranges: [{ template: '<input class="e-datos-asunto"/>', address: 'E5:E50' }, { template: '<input class="e-compartido"/>', address: 'H5:H50' }, { template: '<input class="e-visible"/>', address: 'I5:I50' }, { dataSource: [{ isDeleted: false }, { isDeleted: false }] }] }], created: (): void => { helper.getInstance().autoFit('1:100'); }, beforeCellRender: function (args) { const spreadsheet: Spreadsheet = helper.getInstance(); if (spreadsheet.sheets[spreadsheet.activeSheetIndex].name === 'Datos de asunto') { const target: HTMLElement = args.element.firstElementChild as HTMLElement; if (args.element.children.length) { const template = args.element.children[0].className; switch (template) { case 'e-datos-asunto': const ddl_tipo_dato = ['N - Número con decimales', 'R - Número entero', 'A - Alfanumérico', 'E - Texto Largo', 'B - Checkbox', 'D - Documento externo', 'L - Link', 'M - Mail', 'F - Fecha', 'H - Hora', 'Tnnn - Tabla de 1, 2 o 3 Niveles.', 'Vnnn - Tabla de 3 Niveles', 'Innn - Tabla de 2 Niveles', 'Onnn - Tabla con cache', 'Gnnn - Tabla sin cache', 'Snnn - Tabla de selección múltiple Simple', 'Ynnn - Tabla de selección multiple Completo', 'P - Selector de Personas ', 'U - Selector de Asuntos', 'C - Selector de Producto ']; new DropDownList({ placeholder: 'Tipo de Dato', dataSource: ddl_tipo_dato}, target ); break; case 'e-compartido': const ddl_compartido = ['S', 'N ']; new DropDownList({ placeholder: 'Compartido', dataSource: ddl_compartido}, target ); break; case 'e-visible': const ddl_visible= ['S', 'N ']; new DropDownList({ placeholder: 'Visible', dataSource: ddl_visible}, target ); break; } } } } }; helper.initializeSpreadsheet(model, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Implement CellTemplates, it does not allow me to edit the other cells', (done: Function) => { helper.invoke('startEdit'); helper.getElement('.e-spreadsheet-edit').textContent = 'Test 1'; helper.triggerKeyNativeEvent(13); setTimeout(() => { expect(helper.getInstance().sheets[0].rows[0].cells[0].value).toBe('Test 1'); expect(helper.getInstance().sheets[0].selectedRange).toBe('A2:A2'); done(); }); }); it('Edit element is not showing cell value if it contains boolean value false', (done: Function) => { helper.invoke('startEdit'); expect(helper.getInstance().sheets[0].rows[1].cells[0].value.toString()).toBe('false'); expect(helper.getElement('.e-spreadsheet-edit').textContent).toBe('FALSE'); helper.triggerKeyNativeEvent(13); done(); }); }); }); describe('CR-Issues ->', () => { describe('I267737, I267730, FB21561, EJ2-56562 ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ actionBegin: (args) => { if (args.action === 'cellDelete') { args.args.eventArgs.cancel = true; } } }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Serious issues with Time type of cell (Issue in Time number format)', (done: Function) => { helper.edit('A1', '7:00 AM'); setTimeout((): void => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].rows[0].cells[0].value).toBe('0.2916666666666667'); expect(spreadsheet.sheets[0].rows[0].cells[0].format).toBe('h:mm:ss AM/PM'); expect(helper.invoke('getCell', [0, 0]).textContent).toBe('7:00:00 AM'); helper.invoke('startEdit', []); setTimeout((): void => { expect(helper.getElement('#' + helper.id + '_edit').textContent).toBe('7:00:00 AM'); helper.invoke('endEdit', []); done(); }); }); }); it('Typing percentage value is auto formatted', (done: Function) => { helper.edit('B1', '25%'); expect(helper.invoke('getCell', [0, 1]).textContent).toBe('25%'); expect(helper.getInstance().sheets[0].rows[0].cells[1].value).toBe('0.25'); expect(helper.getInstance().sheets[0].rows[0].cells[1].format).toBe('0%'); helper.invoke('selectRange', ['A1']); helper.invoke('selectRange', ['B1']); expect(helper.getElementFromSpreadsheet('#' + helper.id + '_number_format').textContent).toBe('Percentage'); done(); }); it('Cancelling cell delete in action begin event', (done: Function) => { helper.triggerKeyNativeEvent(46); setTimeout(() => { expect(helper.getInstance().sheets[0].rows[0].cells[1].value).toBe('0.25'); expect(helper.invoke('getCell', [0, 1]).textContent).toBe('25%'); done(); }); }); }); describe('I301868, I301863 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ index: 1, value: '56' }, { value: '35' }, { formula: '=B1-C1' }] }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('number max 9 digits, at 10 or move through javascript error and unexpected auto formating on TEXT formated cell', (done: Function) => { helper.edit('D1', '1234567890'); // editing the cell conataining formula with number more than 9 digit. setTimeout((): void => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].rows[0].cells[3].value.toString()).toBe('1234567890'); expect(spreadsheet.sheets[0].rows[0].cells[3].formula).toBe(''); helper.invoke('selectRange', ['A2']); setTimeout((): void => { helper.edit('A2', '10/10/2020'); // Updated the date format value using Edting. setTimeout((): void => { expect(spreadsheet.sheets[0].rows[1].cells[0].value).toBe('44114'); expect(spreadsheet.sheets[0].rows[1].cells[0].format).toBe('mm-dd-yyyy'); expect(helper.invoke('getCell', [1, 0]).textContent).toBe('10/10/2020'); done(); }); }); }); }); }); describe('I308693 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }], selectedRange: 'A1:C3' }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('merge cell related issue (Merged cell edited state contains 2 values)', (done: Function) => { helper.invoke('merge'); helper.invoke('startEdit'); setTimeout((): void => { expect(helper.getElement('#' +helper.id + '_edit').textContent).toBe('Item Name'); done(); }); }); }); describe('fb21593 ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ value: 'text' }] }] }, {}] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Style applied is getting omitted when redo the changes', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); helper.getElement('#' + helper.id + '_underline').click(); expect(spreadsheet.sheets[0].rows[0].cells[0].style.textDecoration).toBe('underline'); helper.getElement('#' + helper.id + '_line-through').click(); expect(spreadsheet.sheets[0].rows[0].cells[0].style.textDecoration).toBe('underline line-through'); helper.getElement('#' + helper.id + '_undo').click(); expect(spreadsheet.sheets[0].rows[0].cells[0].style.textDecoration).toBe('underline'); helper.getElement('#' + helper.id + '_undo').click(); expect(spreadsheet.sheets[0].rows[0].cells[0].style).toBeNull(); helper.getElement('#' + helper.id + '_redo').click(); expect(spreadsheet.sheets[0].rows[0].cells[0].style.textDecoration).toBe('underline'); helper.getElement('#' + helper.id + '_redo').click(); expect(spreadsheet.sheets[0].rows[0].cells[0].style.textDecoration).toBe('underline line-through'); helper.invoke('selectRange', ['A2']); done(); }); it('Style applied is getting omitted when redo the changes', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); helper.invoke('startEdit'); (spreadsheet as any).editModule.editCellData.value = 'edited'; helper.getElement('#' + helper.id + ' .e-sheet-tab .e-tab-header .e-toolbar-item:nth-child(3)').click(); setTimeout((): void => { helper.getElement('#' + helper.id + ' .e-sheet-tab .e-tab-header .e-toolbar-item').click(); setTimeout((): void => { expect(spreadsheet.sheets[0].rows[1].cells[0].value).toBe('edited'); done(); }); }); }); }); describe('EJ2-58213 -> Filtering not applied properly after deleting A1 cell and script error thrown while open filer dialog', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }]}] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Delete', (done: Function) => { helper.triggerKeyNativeEvent(46); setTimeout(() => { expect(helper.getInstance().sheets[0].usedRange.rowIndex).toBe(10); expect(helper.getInstance().sheets[0].usedRange.colIndex).toBe(7); done(); }); }); }); }); });
the_stack
import React, { FC } from 'react'; import { mount, ComponentType, ReactWrapper, shallow, } from 'enzyme'; import { DefaultContentNode, NodeProvider, useNode, withNodeKey, withNode, PageEditContext, PageContextProvider, } from '@bodiless/core'; import flowRight from 'lodash/flowRight'; import flow from 'lodash/flow'; import identity from 'lodash/identity'; import { withDesign, withoutProps, HOC } from '@bodiless/fclasses'; import { asBodilessChameleon, withChameleonComponentFormControls, withChameleonContext, useChameleonContext, } from '../src/Chameleon'; import { DEFAULT_KEY } from '../src/Chameleon/withChameleonContext'; const mockSetNode = jest.fn(); // @ts-ignore Unused let mockGetNode = jest.fn(); const MockNodeProvider = ({ data, children }: any) => { const { node } = useNode() as { node: DefaultContentNode<any> }; const getters = node.getGetters(); const actions = node.getActions(); const { getNode: getNode$ } = getters; const getNode = jest.fn( (path: string[]) => data[path.join('$')] || getNode$(path), ); mockGetNode = getNode; const newNode = new DefaultContentNode( { ...actions, setNode: mockSetNode }, { ...getters, getNode }, node.path, ); return ( <NodeProvider node={newNode}> {children} </NodeProvider> ); }; const TestComponent = flowRight(withNodeKey('component'), withNode)( ({ dataKey, ...rest }: any) => { const { node } = useNode(); // @ts-ignore No index signature for node.data return <span id="test" data-node-value={node.data[dataKey] || 'undefined'} {...rest} />; }, ); const withProps = (xprops: any) => (Component: ComponentType<any>|string) => (props: any) => ( <Component {...props} {...xprops} /> ); const withTitle = (title: string): HOC => C => { const C1 = (props: any) => <C {...props} />; C1.title = title; return C1; }; const design = { A: flow(withProps({ 'data-test-a': true }), withTitle('A')), _default: withProps({ 'data-test-default': true }), }; const TestChameleon: ComponentType<any> = flowRight( withDesign(design), asBodilessChameleon('chameleon'), withoutProps('design'), withoutProps('wrap', 'unwrap'), )(TestComponent); describe('asBodilessChameleon', () => { let mockIsEdit: jest.SpyInstance<any, []>; beforeAll(() => { mockIsEdit = jest.spyOn(PageEditContext.prototype, 'isEdit', 'get'); mockIsEdit.mockReturnValue(true); }); afterAll(() => { mockIsEdit.mockRestore(); }); beforeEach(() => { mockSetNode.mockClear(); mockGetNode.mockClear(); }); describe('Chameleon Button', () => { describe('Toggle Button', () => { const callHandler = (wrapper: ReactWrapper<any, any>) => { const { getMenuOptions } = wrapper.find(PageContextProvider).props(); const options = getMenuOptions!().filter(o => o.Component !== 'group'); expect(options).toHaveLength(1); // @ts-ignore no need to simulate the event argument return options[0].handler(); }; it('Provides a toggle on button when toggled off', () => { const wrapper = mount(( <MockNodeProvider data={{}}> <TestChameleon /> </MockNodeProvider> )); callHandler(wrapper); expect(mockSetNode).toBeCalledWith(['root', 'chameleon'], { component: 'A' }); }); it('Provides a toggle off button when toggled on', () => { const wrapper = mount(( <MockNodeProvider data={{ root$chameleon: { component: 'A' } }}> <TestChameleon /> </MockNodeProvider> )); callHandler(wrapper); expect(mockSetNode).toBeCalledWith(['root', 'chameleon'], { component: null }); }); }); describe('Swap Button', () => { const getForm = (wrapper: ReactWrapper<any, any>) => { const { getMenuOptions } = wrapper.find(PageContextProvider).props(); const options = getMenuOptions!().filter(o => o.Component !== 'group'); expect(options).toHaveLength(1); // @ts-ignore no need to simulate the event argument const render = options[0].handler(); const Form = () => <>{render()}</>; return Form; }; const TestChameleonExt = withDesign({ B: flow(withProps({ 'data-test-b': true }), withTitle('B')), })(TestChameleon); it('Provides the correct initial values', () => { const wrapper = mount(( <MockNodeProvider data={{ root$chameleon: { component: 'A' } }}> <TestChameleonExt /> </MockNodeProvider> )); const Form = getForm(wrapper); const form = shallow(<Form />); const { initialValues } = form.childAt(0).props(); expect(initialValues).toEqual({ component: 'A' }); }); it('Provides the correct submit handlers', () => { const wrapper = mount(( <MockNodeProvider data={{}}> <TestChameleonExt /> </MockNodeProvider> )); const Form = getForm(wrapper); const form = shallow(<Form />); const { initialValues, submitValues } = form.childAt(0).props(); expect(initialValues.component).toBeTruthy(); const values = { component: 'A' }; submitValues(values); expect(mockSetNode).toBeCalledWith(['root', 'chameleon'], values); }); it('Provides the correct form components', () => { const wrapper = mount(( <MockNodeProvider data={{}}> <TestChameleonExt /> </MockNodeProvider> )); const Form = getForm(wrapper); const form = mount(<Form />); // First component is selected by default expect(form.find('input[value="A"]').prop('checked')).toBeTruthy(); expect(form.find('input[value="B"]').prop('checked')).toBeFalsy(); expect(form.find('label#bl-component-form-chameleon-radio-A').text()).toBe('A'); expect(form.find('label#bl-component-form-chameleon-radio-B').text()).toBe('B'); }); it('Shows the default option when it has a title', () => { const TestChameleonExt2 = withDesign({ _default: withTitle('Default'), })(TestChameleon); const wrapper = mount(( <MockNodeProvider data={{}}> <TestChameleonExt2 /> </MockNodeProvider> )); const Form = getForm(wrapper); const form = mount(<Form />); expect(form.find('input[value="A"]').prop('checked')).toBeFalsy(); expect(form.find('input[value="_default"]')).toHaveLength(1); // @TODO: Fix this case. // expect(form.find('input[value="_default"]').prop('checked')).toBeTruthy(); }); }); }); it('Applies a design correctly depending on toggle state', () => { const data = { root$chameleon: { component: 'A' } }; const Test: FC<any> = ({ data: data$ }) => ( <MockNodeProvider data={data$}> <TestChameleon /> </MockNodeProvider> ); let wrapper = mount(<Test data={data} />); expect(mockGetNode.mock.calls[0][0]).toEqual(['root', 'chameleon']); expect(wrapper.find('span#test').prop('data-test-a')).toBe(true); wrapper = mount(<Test data={{}} />); expect(wrapper.find('span#test').prop('data-test-a')).toBeUndefined(); expect(wrapper.find('span#test').prop('data-test-default')).toBe(true); }); it('Preserves the node path of the wrapped component', () => { const data = { root$chameleon: { component: 'A' }, root$component: { foo: 'bar' }, }; const Test: FC<any> = () => ( <MockNodeProvider data={data}> <TestChameleon nodeKey="cokponent" dataKey="foo" /> </MockNodeProvider> ); const wrapper = mount(<Test />); expect(wrapper.find('span#test').prop('data-node-value')).toBe('bar'); }); describe('withChameleonComponentFormControls', () => { const PropsCatcher: FC<any> = () => <></>; const PropsCatcherTest = flowRight( withDesign({ On: withTitle('On'), }), withChameleonContext('chameleon'), withChameleonComponentFormControls, )(PropsCatcher); it('Adds correct onSubmit when toggled off', () => { const wrapper = mount(( <MockNodeProvider data={{}}> <PropsCatcherTest /> </MockNodeProvider> )); const { unwrap, onSubmit } = wrapper.find(PropsCatcher).props(); expect(unwrap).toBeUndefined(); onSubmit(); expect(mockSetNode).toBeCalledWith(['root', 'chameleon'], { component: 'On' }); }); it('Adds correct unwrap when toggled on', () => { const wrapper = mount(( <MockNodeProvider data={{ root$chameleon: { component: 'On' } }}> <PropsCatcherTest /> </MockNodeProvider> )); const { unwrap, onSubmit } = wrapper.find(PropsCatcher).props(); expect(onSubmit).toBeUndefined(); unwrap(); expect(mockSetNode).toBeCalledWith(['root', 'chameleon'], { component: null }); }); it('Preserves the node path of the wrapped component', () => { const data = { root$chameleon: { component: 'A' }, root$component: { foo: 'bar' }, }; const Test = flowRight( withChameleonContext('chameleon'), withChameleonComponentFormControls, )(TestComponent) as any; const wrapper = mount(( <MockNodeProvider data={data}> <Test nodeKey="component" dataKey="foo" /> </MockNodeProvider> )); expect(wrapper.find('span#test').prop('data-node-value')).toBe('bar'); }); }); describe('withChameleonContext', () => { it('Preserves the node path of the wrapped component', () => { const data = { root$chameleon: { component: 'A' }, root$component: { foo: 'bar' }, }; const Test: FC<any> = () => ( <MockNodeProvider data={data}> <TestChameleon nodeKey="cokponent" dataKey="foo" /> </MockNodeProvider> ); const wrapper = mount(<Test />); expect(wrapper.find('span#test').prop('data-node-value')).toBe('bar'); }); const withTestDesign = withDesign({ Foo: withTitle('FooTitle'), Baz: identity, [DEFAULT_KEY]: withTitle('DefaultTitle'), }); it('Applies a design correctly', () => { const PropCatcher:any = () => null; const Test$ = () => { const { selectableComponents } = useChameleonContext(); const map = Object.keys(selectableComponents).reduce((acc, key) => ( // @ts-ignore { ...acc, [key]: selectableComponents[key].title } ), {}); return <PropCatcher map={map} />; }; const Test = flowRight( withTestDesign, withChameleonContext('chameleon'), )(Test$); const wrapper = mount(<Test />); expect(wrapper.find(PropCatcher).prop('map')) .toEqual({ Foo: 'FooTitle', _default: 'DefaultTitle' }); }); }); });
the_stack
import childProcess, { ChildProcessWithoutNullStreams } from 'child_process' import fs from 'fs' import path from 'path' import { ether } from '@openzeppelin/test-helpers' import { StakeManagerInstance, RelayHubContract, RelayHubInstance, TestTokenInstance } from '@opengsn/contracts/types/truffle-contracts' import { HttpWrapper } from '@opengsn/common/dist/HttpWrapper' import { HttpClient } from '@opengsn/common/dist/HttpClient' import { defaultGsnConfig, GSNConfig } from '@opengsn/provider/dist/GSNConfigurator' import { defaultEnvironment } from '@opengsn/common/dist/Environments' import { PrefixedHexString } from 'ethereumjs-util' import { isSameAddress, sleep } from '@opengsn/common/dist/Utils' import { RelayHubConfiguration } from '@opengsn/common/dist/types/RelayHubConfiguration' import { createServerLogger } from '@opengsn/relay/dist/ServerWinstonLogger' import { Environment, toNumber } from '@opengsn/common' import { Address, IntString } from '@opengsn/common/dist/types/Aliases' import { toBN } from 'web3-utils' require('source-map-support').install({ errorFormatterForce: true }) const RelayHub = artifacts.require('RelayHub') const RelayRegistrar = artifacts.require('RelayRegistrar') const localhostOne = 'http://localhost:8090' // start a background relay process. // rhub - relay hub contract // options: // stake, delay, pctRelayFee, url, relayOwner: parameters to pass to registerNewRelay, to stake and register it. // export async function startRelay ( relayHubAddress: string, testToken: TestTokenInstance, stakeManager: StakeManagerInstance, options: any): Promise<ChildProcessWithoutNullStreams> { const args = [] const serverWorkDir = '/tmp/gsn/test/server' // @ts-ignore fs.rmSync(serverWorkDir, { recursive: true, force: true }) args.push('--workdir', serverWorkDir) args.push('--devMode') if (options.checkInterval) { args.push('--checkInterval', options.checkInterval) } else { args.push('--checkInterval', 100) } args.push('--logLevel', 'debug') args.push('--relayHubAddress', relayHubAddress) args.push('--managerStakeTokenAddress', testToken.address) const configFile = path.resolve(__dirname, './server-config.json') args.push('--config', configFile) args.push('--ownerAddress', options.relayOwner) if (options.loggingProvider) { args.push('--loggingProvider', options.loggingProvider) } if (options.confirmationsNeeded) { args.push('--confirmationsNeeded', options.confirmationsNeeded) } if (options.ethereumNodeUrl) { args.push('--ethereumNodeUrl', options.ethereumNodeUrl) } if (options.gasPriceFactor) { args.push('--gasPriceFactor', options.gasPriceFactor) } if (options.pctRelayFee) { args.push('--pctRelayFee', options.pctRelayFee) } if (options.baseRelayFee) { args.push('--baseRelayFee', options.baseRelayFee) } if (options.checkInterval) { args.push('--checkInterval', options.checkInterval) } if (options.initialReputation) { args.push('--initialReputation', options.initialReputation) } if (options.workerTargetBalance) { args.push('--workerTargetBalance', options.workerTargetBalance) } if (options.environmentName) { args.push('--environmentName', options.environmentName) } if (options.refreshStateTimeoutBlocks) { args.push('--refreshStateTimeoutBlocks', options.refreshStateTimeoutBlocks) } const runServerPath = path.resolve(__dirname, '../../relay/dist/runServer.js') const proc: ChildProcessWithoutNullStreams = childProcess.spawn('./node_modules/.bin/ts-node', [runServerPath, ...args]) // eslint-disable-next-line @typescript-eslint/no-empty-function let relaylog = function (_: string): void {} if (options.relaylog) { relaylog = (msg: string) => msg.split('\n').forEach(line => console.log(`relay-${proc.pid.toString()}> ${line}`)) } await new Promise((resolve, reject) => { let lastresponse: string const listener = (data: any): void => { const str = data.toString().replace(/\s+$/, '') lastresponse = str relaylog(str) if (str.indexOf('Listening on port') >= 0) { // @ts-ignore proc.alreadystarted = 1 resolve(proc) } } proc.stdout.on('data', listener) proc.stderr.on('data', listener) const doaListener = (code: Object): void => { // @ts-ignore if (!proc.alreadystarted) { relaylog(`died before init code=${JSON.stringify(code)}`) reject(new Error(lastresponse)) } } proc.on('exit', doaListener.bind(proc)) }) const logger = createServerLogger('error', '', '') let res: any const http = new HttpClient(new HttpWrapper(), logger) let count1 = 3 while (count1-- > 0) { try { res = await http.getPingResponse(localhostOne) if (res) break } catch (e) { console.log('startRelay getaddr error', e) } console.log('sleep before cont.') await sleep(1000) } assert.ok(res, 'can\'t ping server') // eslint-disable-next-line @typescript-eslint/restrict-template-expressions assert.ok(res.relayWorkerAddress, `server returned unknown response ${res.toString()}`) const relayManagerAddress = res.relayManagerAddress console.log('Relay Server Address', relayManagerAddress) // @ts-ignore await web3.eth.sendTransaction({ to: relayManagerAddress, from: options.relayOwner, value: options.value ?? ether('2') }) // TODO: this entire function is a logical duplicate of 'CommandsLogic::registerRelay' // now wait for server until it sets the owner on stake manager let i = 0 while (true) { await sleep(100) const newStakeInfo = await stakeManager.getStakeInfo(relayManagerAddress) if (isSameAddress(newStakeInfo[0].owner, options.relayOwner)) { console.log('RelayServer successfully set its owner on the StakeManager') break } if (i++ === 5) { throw new Error('RelayServer failed to set its owner on the StakeManager') } } const amount = options.stake || ether('1') await stakeManager.stakeForRelayManager(testToken.address, relayManagerAddress, options.delay || 15000, amount, { from: options.relayOwner }) await sleep(500) await stakeManager.authorizeHubByOwner(relayManagerAddress, relayHubAddress, { from: options.relayOwner }) // now ping server until it "sees" the stake and funding, and gets "ready" res = '' let count = 25 while (count-- > 0) { res = await http.getPingResponse(localhostOne) if (res?.ready) break await sleep(500) } assert.ok(res.ready, 'Timed out waiting for relay to get staked and registered') // TODO: this is temporary hack to make helper test work!!! // @ts-ignore proc.relayManagerAddress = relayManagerAddress return proc } export function stopRelay (proc: ChildProcessWithoutNullStreams): void { proc?.kill() } export async function increaseTime (time: number): Promise<void> { return await new Promise((resolve, reject) => { // @ts-ignore web3.currentProvider.send({ jsonrpc: '2.0', method: 'evm_increaseTime', params: [time], id: Date.now() }, (err: Error | null) => { if (err) return reject(err) evmMine() .then((r: any) => resolve(r)) .catch((e: Error) => reject(e)) }) }) } export async function setNextBlockTimestamp (time: number | string | BN): Promise<void> { return await new Promise((resolve, reject) => { // @ts-ignore web3.currentProvider.send({ jsonrpc: '2.0', method: 'evm_setNextBlockTimestamp', params: [toNumber(time)], id: Date.now() }, (e: Error | null, r: any) => { if (e) { reject(e) } else { resolve(r) } }) }) } export async function evmMineMany (count: number): Promise<void> { if (count > 101) { throw new Error(`Mining ${count} blocks will make tests run way too long`) } for (let i = 0; i < count; i++) { await evmMine() } } export async function evmMine (): Promise<any> { return await new Promise((resolve, reject) => { // @ts-ignore web3.currentProvider.send({ jsonrpc: '2.0', method: 'evm_mine', params: [], id: Date.now() }, (e: Error | null, r: any) => { if (e) { reject(e) } else { resolve(r) } }) }) } export async function snapshot (): Promise<{ id: number, jsonrpc: string, result: string }> { return await new Promise((resolve, reject) => { // @ts-ignore web3.currentProvider.send({ jsonrpc: '2.0', method: 'evm_snapshot', id: Date.now() }, (err: Error | null, snapshotId: { id: number, jsonrpc: string, result: string }) => { if (err) { return reject(err) } return resolve(snapshotId) }) }) } export async function revert (id: string): Promise<void> { return await new Promise((resolve, reject) => { // @ts-ignore web3.currentProvider.send({ jsonrpc: '2.0', method: 'evm_revert', params: [id], id: Date.now() }, (err: Error | null, result: any) => { if (err) { return reject(err) } return resolve(result) }) }) } // encode revert reason string as a byte error returned by revert(string) export function encodeRevertReason (reason: string): PrefixedHexString { return web3.eth.abi.encodeFunctionCall({ name: 'Error', type: 'function', inputs: [{ name: 'error', type: 'string' }] }, [reason]) // return '0x08c379a0' + removeHexPrefix(web3.eth.abi.encodeParameter('string', reason)) } export async function deployHub ( stakeManager: string, penalizer: string, batchGateway: string, testToken: string, testTokenMinimumStake: IntString, configOverride: Partial<RelayHubConfiguration> = {}, environment: Environment = defaultEnvironment, hubContract: any = undefined): Promise<RelayHubInstance> { const relayHubConfiguration: RelayHubConfiguration = { ...environment.relayHubConfiguration, ...configOverride } const HubContract: RelayHubContract = hubContract ?? RelayHub const relayRegistrar = await RelayRegistrar.new() const hub: RelayHubInstance = await HubContract.new( stakeManager, penalizer, batchGateway, relayRegistrar.address, relayHubConfiguration) await hub.setMinimumStakes([testToken], [testTokenMinimumStake]) return hub } export function configureGSN (partialConfig: Partial<GSNConfig>): GSNConfig { return Object.assign({}, defaultGsnConfig, partialConfig) as GSNConfig } export async function emptyBalance (source: Address, target: Address): Promise<void> { const gasPrice = toBN(1e9) const txCost = toBN(defaultEnvironment.mintxgascost).mul(gasPrice) let balance = toBN(await web3.eth.getBalance(source)) const transferValue = balance.sub(txCost) console.log('bal=', balance.toString(), 'xfer=', transferValue.toString()) if (transferValue.gtn(0)) { await web3.eth.sendTransaction({ from: source, to: target, value: transferValue, gasPrice, gas: defaultEnvironment.mintxgascost }) } balance = toBN(await web3.eth.getBalance(source)) assert.isTrue(balance.eqn(0)) } export function disableTruffleAutoEstimateGas (truffleContract: any): void { if (truffleContract.autoGas) { truffleContract.autoGas = false } truffleContract.defaults delete truffleContract.class_defaults.gas } /** * Not all "signatures" are valid, so using a hard-coded one for predictable error message. */ export const INCORRECT_ECDSA_SIGNATURE = '0xdeadface00000a58b757da7dea5678548be5ff9b16e9d1d87c6157aff6889c0f6a406289908add9ea6c3ef06d033a058de67d057e2c0ae5a02b36854be13b0731c'
the_stack
'use strict'; /** * A tagging type for string properties that are actually URIs. */ export type DocumentUri = string; /** * Position in a text document expressed as zero-based line and character offset. * The offsets are based on a UTF-16 string representation. So a string of the form * `a𐐀b` the character offset of the character `a` is 0, the character offset of `𐐀` * is 1 and the character offset of b is 3 since `𐐀` is represented using two code * units in UTF-16. * * Positions are line end character agnostic. So you can not specify a position that * denotes `\r|\n` or `\n|` where `|` represents the character offset. */ export interface Position { /** * Line position in a document (zero-based). * If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document. * If a line number is negative, it defaults to 0. */ line: number; /** * Character offset on a line in a document (zero-based). Assuming that the line is * represented as a string, the `character` value represents the gap between the * `character` and `character + 1`. * * If the character value is greater than the line length it defaults back to the * line length. * If a line number is negative, it defaults to 0. */ character: number; } /** * A range in a text document expressed as (zero-based) start and end positions. * * If you want to specify a range that contains a line including the line ending * character(s) then use an end position denoting the start of the next line. * For example: * ```ts * { * start: { line: 5, character: 23 } * end : { line 6, character : 0 } * } * ``` */ export interface Range { /** * The range's start position */ start: Position; /** * The range's end position. */ end: Position; } /** * A text edit applicable to a text document. */ export interface TextEdit { /** * The range of the text document to be manipulated. To insert * text into a document create a range where start === end. */ range: Range; /** * The string to be inserted. For delete operations use an * empty string. */ newText: string; } /** * An event describing a change to a text document. If range and rangeLength are omitted * the new text is considered to be the full content of the document. */ export type TextDocumentContentChangeEvent = { /** * The range of the document that changed. */ range: Range; /** * The optional length of the range that got replaced. * * @deprecated use range instead. */ rangeLength?: number; /** * The new text for the provided range. */ text: string; } | { /** * The new text of the whole document. */ text: string; }; /** * A simple text document. Not to be implemented. The document keeps the content * as string. */ export interface TextDocument { /** * The associated URI for this document. Most documents have the __file__-scheme, indicating that they * represent files on disk. However, some documents may have other schemes indicating that they are not * available on disk. * * @readonly */ readonly uri: DocumentUri; /** * The identifier of the language associated with this document. * * @readonly */ readonly languageId: string; /** * The version number of this document (it will increase after each * change, including undo/redo). * * @readonly */ readonly version: number; /** * Get the text of this document. A substring can be retrieved by * providing a range. * * @param range (optional) An range within the document to return. * If no range is passed, the full content is returned. * Invalid range positions are adjusted as described in [Position.line](#Position.line) * and [Position.character](#Position.character). * If the start range position is greater than the end range position, * then the effect of getText is as if the two positions were swapped. * @return The text of this document or a substring of the text if a * range is provided. */ getText(range?: Range): string; /** * Converts a zero-based offset to a position. * * @param offset A zero-based offset. * @return A valid [position](#Position). */ positionAt(offset: number): Position; /** * Converts the position to a zero-based offset. * Invalid positions are adjusted as described in [Position.line](#Position.line) * and [Position.character](#Position.character). * * @param position A position. * @return A valid zero-based offset. */ offsetAt(position: Position): number; /** * The number of lines in this document. * * @readonly */ readonly lineCount: number; } class FullTextDocument implements TextDocument { private _uri: DocumentUri; private _languageId: string; private _version: number; private _content: string; private _lineOffsets: number[] | undefined; public constructor(uri: DocumentUri, languageId: string, version: number, content: string) { this._uri = uri; this._languageId = languageId; this._version = version; this._content = content; this._lineOffsets = undefined; } public get uri(): string { return this._uri; } public get languageId(): string { return this._languageId; } public get version(): number { return this._version; } public getText(range?: Range): string { if (range) { const start = this.offsetAt(range.start); const end = this.offsetAt(range.end); return this._content.substring(start, end); } return this._content; } public update(changes: TextDocumentContentChangeEvent[], version: number): void { for (let change of changes) { if (FullTextDocument.isIncremental(change)) { // makes sure start is before end const range = getWellformedRange(change.range); // update content const startOffset = this.offsetAt(range.start); const endOffset = this.offsetAt(range.end); this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length); // update the offsets const startLine = Math.max(range.start.line, 0); const endLine = Math.max(range.end.line, 0); let lineOffsets = this._lineOffsets!; const addedLineOffsets = computeLineOffsets(change.text, false, startOffset); if (endLine - startLine === addedLineOffsets.length) { for (let i = 0, len = addedLineOffsets.length; i < len; i++) { lineOffsets[i + startLine + 1] = addedLineOffsets[i]; } } else { if (addedLineOffsets.length < 10000) { lineOffsets.splice(startLine + 1, endLine - startLine, ...addedLineOffsets); } else { // avoid too many arguments for splice this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1)); } } const diff = change.text.length - (endOffset - startOffset); if (diff !== 0) { for (let i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) { lineOffsets[i] = lineOffsets[i] + diff; } } } else if (FullTextDocument.isFull(change)) { this._content = change.text; this._lineOffsets = undefined; } else { throw new Error('Unknown change event received'); } } this._version = version; } private getLineOffsets(): number[] { if (this._lineOffsets === undefined) { this._lineOffsets = computeLineOffsets(this._content, true); } return this._lineOffsets; } public positionAt(offset: number): Position { offset = Math.max(Math.min(offset, this._content.length), 0); let lineOffsets = this.getLineOffsets(); let low = 0, high = lineOffsets.length; if (high === 0) { return { line: 0, character: offset }; } while (low < high) { let mid = Math.floor((low + high) / 2); if (lineOffsets[mid] > offset) { high = mid; } else { low = mid + 1; } } // low is the least x for which the line offset is larger than the current offset // or array.length if no line offset is larger than the current offset let line = low - 1; return { line, character: offset - lineOffsets[line] }; } public offsetAt(position: Position) { let lineOffsets = this.getLineOffsets(); if (position.line >= lineOffsets.length) { return this._content.length; } else if (position.line < 0) { return 0; } let lineOffset = lineOffsets[position.line]; let nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length; return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); } public get lineCount() { return this.getLineOffsets().length; } private static isIncremental(event: TextDocumentContentChangeEvent): event is { range: Range; rangeLength?: number; text: string; } { let candidate: { range: Range; rangeLength?: number; text: string; } = event as any; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range !== undefined && (candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number'); } private static isFull(event: TextDocumentContentChangeEvent): event is { text: string; } { let candidate: { range?: Range; rangeLength?: number; text: string; } = event as any; return candidate !== undefined && candidate !== null && typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined; } } export namespace TextDocument { /** * Creates a new text document. * * @param uri The document's uri. * @param languageId The document's language Id. * @param version The document's initial version number. * @param content The document's content. */ export function create(uri: DocumentUri, languageId: string, version: number, content: string): TextDocument { return new FullTextDocument(uri, languageId, version, content); } /** * Updates a TextDocument by modifying its content. * * @param document the document to update. Only documents created by TextDocument.create are valid inputs. * @param changes the changes to apply to the document. * @param version the changes version for the document. * @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter. * */ export function update(document: TextDocument, changes: TextDocumentContentChangeEvent[], version: number): TextDocument { if (document instanceof FullTextDocument) { document.update(changes, version); return document; } else { throw new Error('TextDocument.update: document must be created by TextDocument.create'); } } export function applyEdits(document: TextDocument, edits: TextEdit[]): string { let text = document.getText(); let sortedEdits = mergeSort(edits.map(getWellformedEdit), (a, b) => { let diff = a.range.start.line - b.range.start.line; if (diff === 0) { return a.range.start.character - b.range.start.character; } return diff; }); let lastModifiedOffset = 0; const spans = []; for (const e of sortedEdits) { let startOffset = document.offsetAt(e.range.start); if (startOffset < lastModifiedOffset) { throw new Error('Overlapping edit'); } else if (startOffset > lastModifiedOffset) { spans.push(text.substring(lastModifiedOffset, startOffset)); } if (e.newText.length) { spans.push(e.newText); } lastModifiedOffset = document.offsetAt(e.range.end); } spans.push(text.substr(lastModifiedOffset)); return spans.join(''); } } function mergeSort<T>(data: T[], compare: (a: T, b: T) => number): T[] { if (data.length <= 1) { // sorted return data; } const p = (data.length / 2) | 0; const left = data.slice(0, p); const right = data.slice(p); mergeSort(left, compare); mergeSort(right, compare); let leftIdx = 0; let rightIdx = 0; let i = 0; while (leftIdx < left.length && rightIdx < right.length) { let ret = compare(left[leftIdx], right[rightIdx]); if (ret <= 0) { // smaller_equal -> take left to preserve order data[i++] = left[leftIdx++]; } else { // greater -> take right data[i++] = right[rightIdx++]; } } while (leftIdx < left.length) { data[i++] = left[leftIdx++]; } while (rightIdx < right.length) { data[i++] = right[rightIdx++]; } return data; } const enum CharCode { /** * The `\n` character. */ LineFeed = 10, /** * The `\r` character. */ CarriageReturn = 13, } function computeLineOffsets(text: string, isAtLineStart: boolean, textOffset = 0): number[] { const result: number[] = isAtLineStart ? [textOffset] : []; for (let i = 0; i < text.length; i++) { let ch = text.charCodeAt(i); if (ch === CharCode.CarriageReturn || ch === CharCode.LineFeed) { if (ch === CharCode.CarriageReturn && i + 1 < text.length && text.charCodeAt(i + 1) === CharCode.LineFeed) { i++; } result.push(textOffset + i + 1); } } return result; } function getWellformedRange(range: Range): Range { const start = range.start; const end = range.end; if (start.line > end.line || (start.line === end.line && start.character > end.character)) { return { start: end, end: start }; } return range; } function getWellformedEdit(textEdit: TextEdit): TextEdit { const range = getWellformedRange(textEdit.range); if (range !== textEdit.range) { return { newText: textEdit.newText, range }; } return textEdit; }
the_stack
import { expect } from "chai"; import sinon from "sinon"; import * as moq from "typemoq"; import { QueryRowFormat } from "@itwin/core-common"; import { IModelConnection } from "@itwin/core-frontend"; import { Field, NestedContentField, PropertiesField, PropertyInfo } from "@itwin/presentation-common"; import { createTestECClassInfo, createTestNestedContentField, createTestPropertiesContentField, createTestPropertyInfo, createTestRelatedClassInfo, createTestSimpleContentField, } from "@itwin/presentation-common/lib/cjs/test"; import { createFieldOrderInfos, FavoritePropertiesManager, FavoritePropertiesOrderInfo, FavoritePropertiesScope, getFieldInfos, IFavoritePropertiesStorage, } from "../../presentation-frontend"; import { PropertyFullName } from "../../presentation-frontend/favorite-properties/FavoritePropertiesManager"; describe("FavoritePropertiesManager", () => { let manager: FavoritePropertiesManager; let propertyField1: PropertiesField; let propertyField2: PropertiesField; let primitiveField: Field; let nestedContentField: NestedContentField; const storageMock = moq.Mock.ofType<IFavoritePropertiesStorage>(); let iTwinId: string; let imodelId: string; const imodelMock = moq.Mock.ofType<IModelConnection>(); before(() => { iTwinId = "itwin-id"; imodelId = "imodel-id"; propertyField1 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ classInfo: createTestECClassInfo({ name: "Schema:ClassName1" }) }) }], }); propertyField2 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ classInfo: createTestECClassInfo({ name: "Schema:ClassName2" }) }) }], }); primitiveField = createTestSimpleContentField(); nestedContentField = createTestNestedContentField({ contentClassInfo: createTestECClassInfo({ name: "Schema:NestedContentClassName" }), nestedFields: [propertyField1, propertyField2, primitiveField], }); }); beforeEach(async () => { manager = new FavoritePropertiesManager({ storage: storageMock.object }); imodelMock.setup((x) => x.iModelId).returns(() => imodelId); imodelMock.setup((x) => x.iTwinId).returns(() => iTwinId); }); afterEach(() => { manager.dispose(); storageMock.reset(); imodelMock.reset(); }); describe("initializeConnection", () => { it("loads iTwin and iModel scopes", async () => { await manager.initializeConnection(imodelMock.object); storageMock.verify(async (x) => x.loadProperties(undefined, undefined), moq.Times.once()); storageMock.verify(async (x) => x.loadProperties(iTwinId, imodelId), moq.Times.once()); storageMock.verify(async (x) => x.loadProperties(iTwinId, undefined), moq.Times.once()); }); it("loads iModel scope when iTwin scope is already loaded", async () => { await manager.initializeConnection(imodelMock.object); const imodelId2 = "imodel-id-2"; imodelMock.reset(); imodelMock.setup((x) => x.iModelId).returns(() => imodelId2); imodelMock.setup((x) => x.iTwinId).returns(() => iTwinId); await manager.initializeConnection(imodelMock.object); storageMock.verify(async (x) => x.loadProperties(undefined, undefined), moq.Times.once()); storageMock.verify(async (x) => x.loadProperties(iTwinId, imodelId2), moq.Times.once()); storageMock.verify(async (x) => x.loadProperties(iTwinId, undefined), moq.Times.once()); }); it("does not load iModel scope when iModel scope is already loaded", async () => { await manager.initializeConnection(imodelMock.object); await manager.initializeConnection(imodelMock.object); storageMock.verify(async (x) => x.loadProperties(undefined, undefined), moq.Times.once()); storageMock.verify(async (x) => x.loadProperties(iTwinId, imodelId), moq.Times.once()); storageMock.verify(async (x) => x.loadProperties(iTwinId, undefined), moq.Times.once()); }); it("removes non-favorited property order information", async () => { const globalField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "global" }) }] }); const iTwinField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "iTwin" }) }] }); const globalFieldInfos = new Set<PropertyFullName>(getFieldsInfos([globalField])); storageMock.setup(async (x) => x.loadProperties()).returns(async () => globalFieldInfos); const iTwinFieldInfos = new Set<PropertyFullName>(getFieldsInfos([iTwinField])); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny())).returns(async () => iTwinFieldInfos); const nonFavoritedField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "non-favorite" }) }] }); const allFields = [globalField, iTwinField, nonFavoritedField]; const orderInfos = getFieldsOrderInfos(allFields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); expect(globalFieldInfos.size).to.eq(1); expect(iTwinFieldInfos.size).to.eq(1); expect(orderInfos.length).to.eq(2); }); it("adds favorited property order information for those who don't have it", async () => { const withOrderInfo = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "global", classInfo: createTestECClassInfo({ name: "Schema:ClassName" }) }) }], }); const allFields = [withOrderInfo, propertyField1, nestedContentField, primitiveField]; const fieldInfos = new Set<PropertyFullName>(getFieldsInfos(allFields)); storageMock.setup(async (x) => x.loadProperties()).returns(async () => fieldInfos); const fields = [withOrderInfo]; const orderInfos = getFieldsOrderInfos(fields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); expect(fieldInfos.size).to.eq(4); expect(orderInfos.length).to.eq(4); }); }); describe("has", () => { it("throws if not initialized", () => { expect(() => manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel)).to.throw(`Favorite properties are not initialized for iModel: '${imodelId}', in iTwin: '${iTwinId}'. Call initializeConnection() with an IModelConnection to initialize.`); }); it("returns false for not favorite property field", async () => { await manager.initializeConnection(imodelMock.object); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; }); it("returns true for favorite property field", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.Global)).to.be.true; }); it("returns false for not favorite primitive fields", async () => { await manager.initializeConnection(imodelMock.object); const field = createTestSimpleContentField(); expect(manager.has(field, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; }); it("returns true for favorite primitive fields", async () => { await manager.initializeConnection(imodelMock.object); const field = createTestSimpleContentField(); await manager.add(field, imodelMock.object, FavoritePropertiesScope.Global); expect(manager.has(field, imodelMock.object, FavoritePropertiesScope.Global)).to.be.true; }); it("returns false for not favorite nested content fields", async () => { await manager.initializeConnection(imodelMock.object); const field = createTestNestedContentField({ nestedFields: [] }); expect(manager.has(field, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; }); it("returns true for favorite nested content fields", async () => { await manager.initializeConnection(imodelMock.object); const field = createTestNestedContentField({ nestedFields: [] }); await manager.add(field, imodelMock.object, FavoritePropertiesScope.Global); expect(manager.has(field, imodelMock.object, FavoritePropertiesScope.Global)).to.be.true; }); it("returns false for not favorite property fields", async () => { await manager.initializeConnection(imodelMock.object); const field = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo() }] }); expect(manager.has(field, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; }); it("returns true for favorite nested fields", async () => { await manager.initializeConnection(imodelMock.object); const field = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo() }] }); await manager.add(field, imodelMock.object, FavoritePropertiesScope.Global); expect(manager.has(field, imodelMock.object, FavoritePropertiesScope.Global)).to.be.true; }); it("returns false for not favorite nested fields", async () => { await manager.initializeConnection(imodelMock.object); const nestedField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo() }] }); const parentField = createTestNestedContentField({ nestedFields: [nestedField], }); parentField.rebuildParentship(); expect(manager.has(nestedField, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; }); it("returns true for favorite nested fields", async () => { await manager.initializeConnection(imodelMock.object); const nestedField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo() }] }); const parentField = createTestNestedContentField({ nestedFields: [nestedField], }); parentField.rebuildParentship(); await manager.add(nestedField, imodelMock.object, FavoritePropertiesScope.Global); expect(manager.has(nestedField, imodelMock.object, FavoritePropertiesScope.Global)).to.be.true; }); it("checks iModel scope for favorite properties", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel)).to.be.true; }); it("checks iTwin scope for favorite properties", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin)).to.be.true; }); }); describe("add", () => { it("throws if not initialized", async () => { await expect(manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.Global)).to.be.rejectedWith(`Favorite properties are not initialized for iModel: '${imodelId}', in iTwin: '${iTwinId}'. Call initializeConnection() with an IModelConnection to initialize.`); }); it("raises onFavoritesChanged event", async () => { await manager.initializeConnection(imodelMock.object); const s = sinon.spy(manager.onFavoritesChanged, "raiseEvent"); await manager.add(nestedContentField, imodelMock.object, FavoritePropertiesScope.Global); expect(s).to.be.calledOnce; }); it("adds to iTwin scope", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin)).to.be.true; }); it("adds to iModel scope", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel)).to.be.true; }); it("does not raise onFavoritesChanged event if property is alredy favorite", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); const s = sinon.spy(manager.onFavoritesChanged, "raiseEvent"); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); expect(s).to.be.not.called; }); it("adds new favorited properties to the end of the list", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); await manager.add(propertyField2, imodelMock.object, FavoritePropertiesScope.Global); await manager.add(primitiveField, imodelMock.object, FavoritePropertiesScope.Global); }); }); describe("remove", () => { it("throws if not initialized", async () => { await expect(manager.remove(propertyField1, imodelMock.object, FavoritePropertiesScope.Global)).to.be.rejectedWith(`Favorite properties are not initialized for iModel: '${imodelId}', in iTwin: '${iTwinId}'. Call initializeConnection() with an IModelConnection to initialize.`); }); it("removes single property field", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); await manager.remove(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; }); it("removes single nested property field", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(nestedContentField, imodelMock.object, FavoritePropertiesScope.Global); await manager.remove(nestedContentField, imodelMock.object, FavoritePropertiesScope.Global); expect(manager.has(nestedContentField, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; }); it("removes single primitive field", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(primitiveField, imodelMock.object, FavoritePropertiesScope.Global); await manager.remove(primitiveField, imodelMock.object, FavoritePropertiesScope.Global); expect(manager.has(primitiveField, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; }); it("raises onFavoritesChanged event", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(nestedContentField, imodelMock.object, FavoritePropertiesScope.Global); const s = sinon.spy(manager.onFavoritesChanged, "raiseEvent"); await manager.remove(nestedContentField, imodelMock.object, FavoritePropertiesScope.Global); expect(s).to.be.calledOnce; }); it("removes from iTwin scope", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin); await manager.remove(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin)).to.be.false; }); it("removes from iModel scope", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel); await manager.remove(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel)).to.be.false; }); it("removes from all scopes", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel); await manager.remove(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin)).to.be.false; expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel)).to.be.false; }); it("removes only from global and iTwin scopes", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel); await manager.remove(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin); expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin)).to.be.false; expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel)).to.be.true; }); it("does not raise onFavoritesChanged event if property is not favorite", async () => { await manager.initializeConnection(imodelMock.object); const s = sinon.spy(manager.onFavoritesChanged, "raiseEvent"); await manager.remove(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); expect(s).to.be.not.called; }); }); describe("clear", () => { it("throws if not initialized", async () => { await expect(manager.clear(imodelMock.object, FavoritePropertiesScope.IModel)).to.be.rejectedWith(`Favorite properties are not initialized for iModel: '${imodelId}', in iTwin: '${iTwinId}'. Call initializeConnection() with an IModelConnection to initialize.`); }); it("clears global", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(nestedContentField, imodelMock.object, FavoritePropertiesScope.Global); await manager.add(primitiveField, imodelMock.object, FavoritePropertiesScope.Global); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.Global); await manager.clear(imodelMock.object, FavoritePropertiesScope.Global); expect(manager.has(nestedContentField, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; expect(manager.has(primitiveField, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.Global)).to.be.false; }); it("clears iTwin", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(nestedContentField, imodelMock.object, FavoritePropertiesScope.ITwin); await manager.add(primitiveField, imodelMock.object, FavoritePropertiesScope.ITwin); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin); await manager.clear(imodelMock.object, FavoritePropertiesScope.ITwin); expect(manager.has(nestedContentField, imodelMock.object, FavoritePropertiesScope.ITwin)).to.be.false; expect(manager.has(primitiveField, imodelMock.object, FavoritePropertiesScope.ITwin)).to.be.false; expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.ITwin)).to.be.false; }); it("clears iModel", async () => { await manager.initializeConnection(imodelMock.object); await manager.add(nestedContentField, imodelMock.object, FavoritePropertiesScope.IModel); await manager.add(primitiveField, imodelMock.object, FavoritePropertiesScope.IModel); await manager.add(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel); await manager.clear(imodelMock.object, FavoritePropertiesScope.IModel); expect(manager.has(nestedContentField, imodelMock.object, FavoritePropertiesScope.IModel)).to.be.false; expect(manager.has(primitiveField, imodelMock.object, FavoritePropertiesScope.IModel)).to.be.false; expect(manager.has(propertyField1, imodelMock.object, FavoritePropertiesScope.IModel)).to.be.false; }); it("does not raise onFavoritesChanged event if there are no favorite properties", async () => { await manager.initializeConnection(imodelMock.object); const s = sinon.spy(manager.onFavoritesChanged, "raiseEvent"); await manager.clear(imodelMock.object, FavoritePropertiesScope.Global); expect(s).to.be.not.called; }); it("removes property order information", async () => { const globalA = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "global-a" }) }] }); const globalB = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "global-b" }) }] }); const iTwinA = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "iTwin-a" }) }] }); const globalFields = [globalA, globalB]; const globalFieldInfos = new Set<PropertyFullName>(getFieldsInfos(globalFields)); storageMock.setup(async (x) => x.loadProperties()).returns(async () => globalFieldInfos); const iTwinFields = [iTwinA]; const iTwinFieldInfos = new Set<PropertyFullName>(getFieldsInfos(iTwinFields)); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny())).returns(async () => iTwinFieldInfos); const nonFavoritedField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "non-favorite" }) }] }); const allFields = [globalA, globalB, iTwinA, nonFavoritedField]; const orderInfos = getFieldsOrderInfos(allFields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); await manager.clear(imodelMock.object, FavoritePropertiesScope.Global); expect(globalFieldInfos.size).to.eq(0); expect(iTwinFieldInfos.size).to.eq(1); expect(orderInfos.length).to.eq(1); }); }); describe("sortFields", () => { it("sorts favorite properties", async () => { const a = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a" }) }] }); const b = createTestNestedContentField({ nestedFields: [] }); const c = createTestSimpleContentField(); const d = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "d" }) }] }); const favoriteFields = [a, b, c, d]; const fieldInfos = getFieldsInfos(favoriteFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(favoriteFields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); const fields = [b, d, a, c]; manager.sortFields(imodelMock.object, fields); expect(fields[0]).to.eq(a); expect(fields[1]).to.eq(b); expect(fields[2]).to.eq(c); expect(fields[3]).to.eq(d); }); it("sorts partially non-favorite and favorite properties", async () => { const a = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a" }) }], priority: 1, name: "A" }); const b = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b" }) }], priority: 2, name: "B" }); const c = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "c" }) }], priority: 10, name: "C" }); const d = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "d" }) }], priority: 10, name: "D" }); const e = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "e" }) }], priority: 9, name: "E" }); const favoriteFields = [a, b]; const fieldInfos = getFieldsInfos(favoriteFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(favoriteFields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); const fields = [b, d, e, c, a]; manager.sortFields(imodelMock.object, fields); expect(fields[0]).to.eq(a); expect(fields[1]).to.eq(b); expect(fields[2]).to.eq(c); expect(fields[3]).to.eq(d); expect(fields[4]).to.eq(e); }); it("uses fields most recent property to sort by", async () => { /** Class hierarchy: * A <- B * Field properties: * F1 - a1, b1 * F2 - a2, b2 * F3 - a3, b3 */ const f1 = createTestPropertiesContentField({ properties: [ { property: createTestPropertyInfo({ name: "f1-1", classInfo: createTestECClassInfo({ name: "S:A" }) }) }, { property: createTestPropertyInfo({ name: "f1-2", classInfo: createTestECClassInfo({ name: "S:B" }) }) }, ], }); const f2 = createTestPropertiesContentField({ properties: [ { property: createTestPropertyInfo({ name: "f2-1", classInfo: createTestECClassInfo({ name: "S:A" }) }) }, { property: createTestPropertyInfo({ name: "f2-2", classInfo: createTestECClassInfo({ name: "S:B" }) }) }, ], }); const f3 = createTestPropertiesContentField({ properties: [ { property: createTestPropertyInfo({ name: "f3-1", classInfo: createTestECClassInfo({ name: "S:A" }) }) }, { property: createTestPropertyInfo({ name: "f3-2", classInfo: createTestECClassInfo({ name: "S:B" }) }) }, ], }); const fields = [f1, f2, f3]; const properties = [ f3.properties[0].property, f1.properties[0].property, f2.properties[0].property, f1.properties[1].property, f2.properties[1].property, f3.properties[1].property, ]; const fieldInfos = getFieldsInfos(fields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); let priority = properties.length; const orderInfos = properties.map((property: PropertyInfo): FavoritePropertiesOrderInfo => ({ parentClassName: property.classInfo.name, name: `${property.classInfo.name}:${property.name}`, orderedTimestamp: new Date(), priority: priority--, })); orderInfos[3].orderedTimestamp.setDate(orderInfos[3].orderedTimestamp.getDate() + 1); // make b1 more recent than a1 orderInfos[2].orderedTimestamp.setDate(orderInfos[2].orderedTimestamp.getDate() + 1); // make a2 more recent than b2 orderInfos[0].orderedTimestamp = orderInfos[5].orderedTimestamp; // make a3 and b3 equal storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); manager.sortFields(imodelMock.object, fields); expect(fields[0]).to.eq(f3); expect(fields[1]).to.eq(f2); expect(fields[2]).to.eq(f1); }); }); describe("changeFieldPriority", () => { it("throws if both fields are the same object", async () => { const a = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a" }) }] }); const allFields = [a]; const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); await expect(manager.changeFieldPriority(imodelMock.object, a, a, allFields)).to.be.rejectedWith("`field` can not be the same as `afterField`."); }); it("throws if given non-visible field", async () => { const a = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a" }) }] }); const b = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b" }) }] }); const allFields = [a, b]; const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); const fakeField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "does-not-exist" }) }] }); await expect(manager.changeFieldPriority(imodelMock.object, fakeField, b, allFields)).to.be.rejectedWith("Field is not contained in visible fields."); }); it("throws if given non-favorite field", async () => { const a = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a" }) }] }); const b = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b" }) }] }); const allFields = [a, b]; const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); const nonFavoriteField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "non-favorite" }) }] }); const visibleFields = [...allFields, nonFavoriteField]; await manager.initializeConnection(imodelMock.object); await expect(manager.changeFieldPriority(imodelMock.object, nonFavoriteField, b, visibleFields)).to.be.rejectedWith("Field has no property order information."); }); it("throws if given non-visible afterField", async () => { const a = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a" }) }] }); const b = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b" }) }] }); const allFields = [a, b]; const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); const fakeField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "does-not-exist" }) }] }); await expect(manager.changeFieldPriority(imodelMock.object, a, fakeField, allFields)).to.be.rejectedWith("Field is not contained in visible fields."); }); it("throws if given non-favorite afterField", async () => { const a = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a" }) }] }); const b = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b" }) }] }); const allFields = [a, b]; const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); const nonFavoriteField = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "non-favorite" }) }] }); const visibleFields = [...allFields, nonFavoriteField]; await manager.initializeConnection(imodelMock.object); await expect(manager.changeFieldPriority(imodelMock.object, a, nonFavoriteField, visibleFields)).to.be.rejectedWith("Field has no property order information."); }); it("does not query for base classes if it already has it cached", async () => { const a = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const b = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const allFields = [a, b]; const classBaseClass = [ { classFullName: "S:A", baseClassFullName: "S:A" }, { classFullName: "S:B", baseClassFullName: "S:B" }, { classFullName: "S:B", baseClassFullName: "S:A" }, ]; imodelMock.setup((x) => x.query(moq.It.isAnyString(), undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })).returns(() => createAsyncIterator(classBaseClass)); const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); const oldOrderInfo = [...orderInfos]; storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); await manager.changeFieldPriority(imodelMock.object, a, b, allFields); expect(orderInfos[0]).to.eq(oldOrderInfo[1]); // b expect(orderInfos[1]).to.eq(oldOrderInfo[0]); // a await manager.changeFieldPriority(imodelMock.object, b, a, allFields); expect(orderInfos[0]).to.eq(oldOrderInfo[0]); // a expect(orderInfos[1]).to.eq(oldOrderInfo[1]); // b imodelMock.verify((x) => x.query(moq.It.isAnyString(), undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames }), moq.Times.once()); }); it("does not change the order of irrelevant properties", async () => { /** Class hierarchy: * A * / \ * B C * Moving a1 after c: * a1 b1 * b1 a2 * a2 -> c * b2 a1 * c b2 */ const a1 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a1", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const b1 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b1", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const a2 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a2", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const b2 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b2", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const c = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "c", classInfo: createTestECClassInfo({ name: "S:C" }) }) }] }); const allFields = [a1, b1, a2, b2, c]; const visibleFields = [a1, a2, c]; // imitating a selection of a class C instance // data of table ECDbMeta.ClassHasAllBaseClasses const classBaseClass = [ { classFullName: "S:A", baseClassFullName: "S:A" }, { classFullName: "S:B", baseClassFullName: "S:B" }, { classFullName: "S:B", baseClassFullName: "S:A" }, { classFullName: "S:C", baseClassFullName: "S:C" }, { classFullName: "S:C", baseClassFullName: "S:A" }, ]; imodelMock.setup((x) => x.query(moq.It.isAnyString(), undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })).returns(() => createAsyncIterator(classBaseClass)); const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); const oldOrderInfo = [...orderInfos]; storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); await manager.changeFieldPriority(imodelMock.object, a1, c, visibleFields); expect(orderInfos[0]).to.eq(oldOrderInfo[1]); // b1 expect(orderInfos[1]).to.eq(oldOrderInfo[2]); // a2 expect(orderInfos[2]).to.eq(oldOrderInfo[4]); // c expect(orderInfos[3]).to.eq(oldOrderInfo[0]); // a1 expect(orderInfos[4]).to.eq(oldOrderInfo[3]); // b2 }); it("does not change the order of irrelevant properties when moving up", async () => { /** Class hierarchy: * A * / \ * B C * Moving a1 after c: * c c * b2 b2 * a2 -> a1 * b1 a2 * a1 b1 */ const c = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "c", classInfo: createTestECClassInfo({ name: "S:C" }) }) }] }); const b2 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b2", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const a2 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a2", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const b1 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b1", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const a1 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a1", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const allFields = [c, b2, a2, b1, a1]; const visibleFields = [c, a2, a1]; // imitating a selection of a class C instance // data of table ECDbMeta.ClassHasAllBaseClasses const classBaseClass = [ { classFullName: "S:A", baseClassFullName: "S:A" }, { classFullName: "S:B", baseClassFullName: "S:B" }, { classFullName: "S:B", baseClassFullName: "S:A" }, { classFullName: "S:C", baseClassFullName: "S:C" }, { classFullName: "S:C", baseClassFullName: "S:A" }, ]; imodelMock.setup((x) => x.query(moq.It.isAnyString(), undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })).returns(() => createAsyncIterator(classBaseClass)); const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); const oldOrderInfo = [...orderInfos]; storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); await manager.changeFieldPriority(imodelMock.object, a1, c, visibleFields); expect(orderInfos[0]).to.eq(oldOrderInfo[0]); // c expect(orderInfos[1]).to.eq(oldOrderInfo[1]); // b2 expect(orderInfos[2]).to.eq(oldOrderInfo[4]); // a1 expect(orderInfos[3]).to.eq(oldOrderInfo[2]); // a2 expect(orderInfos[4]).to.eq(oldOrderInfo[3]); // b1 }); it("does not change the order of irrelevant properties when moving to top", async () => { /** Class hierarchy: * A * / \ * B C * Moving a1 to top: * c b2 * b2 a1 * a2 -> c * b1 a2 * a1 b1 */ const c = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "c", classInfo: createTestECClassInfo({ name: "S:C" }) }) }] }); const b2 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b2", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const a2 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a2", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const b1 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b1", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const a1 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a1", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const allFields = [c, b2, a2, b1, a1]; const visibleFields = [c, a2, a1]; // imitating a selection of a class C instance // data of table ECDbMeta.ClassHasAllBaseClasses const classBaseClass = [ { classFullName: "S:A", baseClassFullName: "S:A" }, { classFullName: "S:B", baseClassFullName: "S:B" }, { classFullName: "S:B", baseClassFullName: "S:A" }, { classFullName: "S:C", baseClassFullName: "S:C" }, { classFullName: "S:C", baseClassFullName: "S:A" }, ]; imodelMock.setup((x) => x.query(moq.It.isAnyString(), undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })).returns(() => createAsyncIterator(classBaseClass)); const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); const oldOrderInfo = [...orderInfos]; storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); await manager.changeFieldPriority(imodelMock.object, a1, undefined, visibleFields); expect(orderInfos[0]).to.eq(oldOrderInfo[1]); // b2 expect(orderInfos[1]).to.eq(oldOrderInfo[4]); // a1 expect(orderInfos[2]).to.eq(oldOrderInfo[0]); // c expect(orderInfos[3]).to.eq(oldOrderInfo[2]); // a2 expect(orderInfos[4]).to.eq(oldOrderInfo[3]); // b1 }); it("does not change non-visible primitive field order with respect to visible fields", async () => { /** Class hierarchy: * A * / \ * B C * Moving a after c: * a prim * b1 c * prim -> a * b2 b1 * c b2 * Note: * prim is a primitive field, only visible having selected class B instances */ const a = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const b1 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b1", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const prim = createTestSimpleContentField(); const b2 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b2", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const c = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "c", classInfo: createTestECClassInfo({ name: "S:C" }) }) }] }); const allFields = [a, b1, prim, b2, c]; const visibleFields = [a, c]; // imitating a selection of a class C instance // data of table ECDbMeta.ClassHasAllBaseClasses const classBaseClass = [ { classFullName: "S:A", baseClassFullName: "S:A" }, { classFullName: "S:B", baseClassFullName: "S:B" }, { classFullName: "S:B", baseClassFullName: "S:A" }, { classFullName: "S:C", baseClassFullName: "S:C" }, { classFullName: "S:C", baseClassFullName: "S:A" }, ]; imodelMock.setup((x) => x.query(moq.It.isAnyString(), undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })).returns(() => createAsyncIterator(classBaseClass)); const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); const oldOrderInfo = [...orderInfos]; storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); await manager.changeFieldPriority(imodelMock.object, a, c, visibleFields); expect(orderInfos[0]).to.eq(oldOrderInfo[2]); // prim expect(orderInfos[1]).to.eq(oldOrderInfo[4]); // c expect(orderInfos[2]).to.eq(oldOrderInfo[0]); // a expect(orderInfos[3]).to.eq(oldOrderInfo[1]); // b1 expect(orderInfos[4]).to.eq(oldOrderInfo[3]); // b2 }); it("treats parent class as the primary class", async () => { /** Class hierarchy: * A * / \ * B C * Moving a after C.A.a2: * a1 C.A.a2 * b -> a1 * C.A.a2 b */ const a1 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a1", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const a2 = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "a2", classInfo: createTestECClassInfo({ name: "S:A" }) }) }] }); const b = createTestPropertiesContentField({ properties: [{ property: createTestPropertyInfo({ name: "b", classInfo: createTestECClassInfo({ name: "S:B" }) }) }] }); const caa2 = createTestPropertiesContentField({ properties: a2.properties }); const nestedMiddle = createTestNestedContentField({ pathToPrimaryClass: [createTestRelatedClassInfo({ sourceClassInfo: createTestECClassInfo({ name: "S:A" }), targetClassInfo: createTestECClassInfo({ name: "S:A" }), })], nestedFields: [caa2], }); const nestedTop = createTestNestedContentField({ pathToPrimaryClass: [createTestRelatedClassInfo({ sourceClassInfo: createTestECClassInfo({ name: "S:A" }), targetClassInfo: createTestECClassInfo({ name: "S:C" }), isForwardRelationship: true, })], nestedFields: [nestedMiddle], }); nestedTop.rebuildParentship(); const allFields = [a1, b, caa2]; const visibleFields = [a1, caa2]; // imitating a selection of a class C instance // data of table ECDbMeta.ClassHasAllBaseClasses const classBaseClass = [ { classFullName: "S:A", baseClassFullName: "S:A" }, { classFullName: "S:B", baseClassFullName: "S:B" }, { classFullName: "S:B", baseClassFullName: "S:A" }, { classFullName: "S:C", baseClassFullName: "S:C" }, { classFullName: "S:C", baseClassFullName: "S:A" }, ]; imodelMock.setup((x) => x.query(moq.It.isAnyString(), undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames })).returns(() => createAsyncIterator(classBaseClass)); const fieldInfos = getFieldsInfos(allFields); storageMock.setup(async (x) => x.loadProperties(moq.It.isAny(), moq.It.isAny())).returns(async () => new Set<PropertyFullName>(fieldInfos)); const orderInfos = getFieldsOrderInfos(allFields); const oldOrderInfo = [...orderInfos]; storageMock.setup(async (x) => x.loadPropertiesOrder(moq.It.isAny(), moq.It.isAny())).returns(async () => orderInfos); await manager.initializeConnection(imodelMock.object); await manager.changeFieldPriority(imodelMock.object, a1, caa2, visibleFields); expect(orderInfos[0]).to.eq(oldOrderInfo[2]); // caa2 expect(orderInfos[1]).to.eq(oldOrderInfo[0]); // a1 expect(orderInfos[2]).to.eq(oldOrderInfo[1]); // b }); }); }); async function* createAsyncIterator<T>(list: T[]): AsyncIterableIterator<T> { for (const e of list) yield e; } const getFieldsInfos = (fields: Field[]): PropertyFullName[] => fields.reduce((total: PropertyFullName[], field) => ([...total, ...getFieldInfos(field)]), []); const getFieldsOrderInfos = (fields: Field[]): FavoritePropertiesOrderInfo[] => { const orderInfos = fields.reduce((total: FavoritePropertiesOrderInfo[], field) => ([...total, ...createFieldOrderInfos(field)]), []); let priority = orderInfos.length; orderInfos.forEach((orderInfo) => orderInfo.priority = priority--); return orderInfos; };
the_stack
import path from 'path' import http from 'http' import { fs } from 'saber-utils' import { log, colors, Log } from 'saber-log' import resolveFrom from 'resolve-from' import merge from 'lodash.merge' import getPort from 'get-port' import { Pages, CreatePageInput } from './Pages' import { BrowserApi } from './BrowserApi' import { Transformers } from './Transformers' import configLoader from './utils/configLoader' import resolvePackage from './utils/resolvePackage' import builtinPlugins from './plugins' import { Compiler } from './Compiler' import { WebpackUtils } from './WebpackUtils' import { hooks } from './hooks' import { VueRenderer } from './vue-renderer' import { validateConfig, ValidatedSaberConfig } from './utils/validateConfig' export interface SaberConstructorOptions { cwd?: string verbose?: boolean dev?: boolean inspectWebpack?: boolean } export interface SaberOptions { cwd: string verbose?: boolean dev?: boolean inspectWebpack?: boolean } export interface SiteConfig { /** Apply to <html> tag */ lang: string [k: string]: any } export interface ThemeConfig { [k: string]: any } export interface SaberPlugin { name: string apply: (api: Saber, options: any) => void | Promise<void> filterPlugins?: ( plugins: ResolvedSaberPlugin[], options?: any ) => ResolvedSaberPlugin[] } export interface SaberConfigPlugin { resolve: string options?: { [k: string]: any } } export interface ResolvedSaberPlugin extends SaberPlugin { location: string options?: any } export interface WebpackContext { type: 'client' | 'server' [k: string]: any } export type PageType = 'page' | 'post' export interface Permalinks { /** * Permalink format for normal pages * @default `/:slug.html` */ page?: string /** * Permalink format for posts * @default `/posts/:slug.html` */ post?: string } export interface SaberConfig { /** The path or name of your theme */ theme?: string siteConfig?: SiteConfig themeConfig?: object locales?: { [localePath: string]: { siteConfig?: SiteConfig themeConfig?: ThemeConfig } } /** * Customize permalink format based on page types (page or post) */ permalinks?: Permalinks | ((page: CreatePageInput) => Permalinks) /** Build configurations */ build?: { /** * The path to output generated files * Defaul to `./public` */ outDir?: string /** * The root path where your website is localed * Default to `/` */ publicUrl?: string /** * Extract CSS into standalone files * Default to `false` */ extractCSS?: boolean /** * Toggle sourcemap for CSS * Default to `false` */ cssSourceMap?: boolean /** * Options for CSS loaders */ loaderOptions?: { /** sass-loader */ sass?: any /** less-loader */ less?: any /** stylus-loader */ stylus?: any /** css-loader */ css?: any /** postcss-loader */ postcss?: any } /** * Toggle cache for webpack * Default to `true` */ cache?: boolean /** * Compile pages on demand * @beta */ lazy?: boolean } server?: { host?: string port?: number } plugins?: Array<string | SaberConfigPlugin> markdown?: { /** The path to a module or npm package name that slugifies the markdown headers. */ slugify?: string /** * Options for the internal markdown-it plugin for generating markdown headings and heading anchors. */ headings?: { /** * Inject markdown headings as `page.markdownHeadings` * @default `true` */ markdownHeadings?: boolean /** * Generating permalinks * @default `false` */ permalink?: boolean permalinkComponent?: string /** * Inject permalink before heading text. * @default `true` */ permalinkBefore?: string /** * The permalink symbol. * @default `'#'` */ permalinkSymbol?: string } /** * Show line numbers in code blocks * @default `false` */ lineNumbers?: boolean /** markdown-it plugins */ plugins?: MarkdownPlugin[] /** markdown-it options */ options?: { [k: string]: any } } template?: { /** * Whether to open external links in new tab. * @default `true` */ openLinkInNewTab?: boolean /** * A set of plugins that are used to transform Vue template. */ plugins?: any[] } } export interface MarkdownPlugin { resolve: string options?: { [k: string]: any } } export class Saber { opts: SaberOptions initialConfig: SaberConfig config: ValidatedSaberConfig pages: Pages browserApi: BrowserApi webpackUtils: WebpackUtils log: Log colors: typeof colors utils: typeof import('saber-utils') hooks: typeof hooks transformers: Transformers runtimePolyfills: Set<string> compilers: { [k: string]: Compiler } renderer: VueRenderer pkg: { path?: string data: { [k: string]: any } } configDir?: string configPath?: string theme: string actualServerPort?: number constructor(opts: SaberConstructorOptions = {}, config: SaberConfig = {}) { this.opts = { ...opts, cwd: path.resolve(opts.cwd || '.') } this.initialConfig = config this.pages = new Pages(this) this.browserApi = new BrowserApi(this) this.webpackUtils = new WebpackUtils(this) this.log = log this.colors = colors this.utils = require('saber-utils') this.hooks = hooks this.transformers = new Transformers() this.runtimePolyfills = new Set() this.compilers = { server: new Compiler('server', this), client: new Compiler('client', this) } const hookNames = Object.keys(this.hooks) as Array<keyof typeof hooks> for (const hook of hookNames) { const ignoreNames = ['theme-node-api', 'user-node-api'] this.hooks[hook].intercept({ register(tapInfo) { const { fn, name } = tapInfo tapInfo.fn = (...args: any[]) => { if (!ignoreNames.includes(name)) { const msg = `${hook} ${colors.dim(`(${name})`)}` log.verbose(msg) } return fn(...args) } return tapInfo } }) } if (opts.verbose) { process.env.SABER_LOG_LEVEL = '4' } // Load package.json data const loadedPkg = configLoader.load({ files: ['package.json'], cwd: this.opts.cwd }) this.pkg = { ...loadedPkg, data: loadedPkg.data || {} } // To make TypeScript happy // We actually initialize them in `prepare()` // TODO: find a better way this.configDir = '' this.configPath = '' // Load Saber config const loadedConfig = this.loadConfig() this.config = loadedConfig.config this.configPath = loadedConfig.configPath this.configDir = this.configPath && path.dirname(this.configPath) if (this.configPath) { log.info( `Using config file: ${colors.dim( path.relative(process.cwd(), this.configPath) )}` ) } this.renderer = new VueRenderer() this.renderer.init(this) // Load theme if (this.config.theme) { this.theme = resolvePackage(this.config.theme, { cwd: this.configDir || this.opts.cwd, prefix: 'saber-theme-' }) // When a theme is loaded from `node_modules` and `$theme/dist` directory exists // We use the `dist` directory instead if (this.theme.includes('node_modules')) { const distDir = path.join(this.theme, 'dist') if (fs.existsSync(distDir)) { this.theme = distDir } } log.info(`Using theme: ${colors.dim(this.config.theme)}`) log.verbose(() => `Theme directory: ${colors.dim(this.theme)}`) } else { this.theme = this.renderer.defaultTheme } } loadConfig(configFiles = configLoader.CONFIG_FILES) { const { data, path: configPath } = configLoader.load({ files: configFiles, cwd: this.opts.cwd }) return { config: validateConfig(merge({}, data, this.initialConfig), { dev: this.dev }), configPath } } setConfig(config: ValidatedSaberConfig, configPath?: string) { this.config = config this.configPath = configPath this.configDir = configPath && path.dirname(configPath) } get dev() { return Boolean(this.opts.dev) } get lazy() { return this.dev && this.config.build.lazy } async prepare() { // Load built-in plugins for (const plugin of builtinPlugins) { const resolvedPlugin = require(plugin.resolve) await this.applyPlugin(resolvedPlugin.default || resolvedPlugin) } // Load user plugins await this.hooks.beforePlugins.promise() const userPlugins = this.getUserPlugins() if (userPlugins.length > 0) { log.info( `Using ${userPlugins.length} plugin${ userPlugins.length > 1 ? 's' : '' } from config file` ) } for (const plugin of userPlugins) { await this.applyPlugin(plugin, plugin.options, plugin.location) } await this.hooks.afterPlugins.promise() } async applyPlugin( plugin: SaberPlugin, options?: any, pluginLocation?: string ) { await plugin.apply(this, options) if (!plugin.name.startsWith('builtin:')) { log.verbose( () => `Using plugin "${colors.bold(plugin.name)}" ${ pluginLocation ? colors.dim(pluginLocation) : '' }` ) } } getUserPlugins() { // Plugins that are specified in user config, a.k.a. saber-config.js etc const plugins: ResolvedSaberPlugin[] = this.configDir && this.config.plugins ? this.config.plugins.map(p => { if (typeof p === 'string') { p = { resolve: p } } const location = resolveFrom(this.configDir as string, p.resolve) const resolvedPlugin = { ...require(location), location, options: p.options } return resolvedPlugin }) : [] const applyFilterPlugins = ( plugins: ResolvedSaberPlugin[] ): ResolvedSaberPlugin[] => { type Handler = (plugins: ResolvedSaberPlugin[]) => ResolvedSaberPlugin[] const handlers = new Set<Handler>() for (const plugin of plugins) { const { filterPlugins, options } = plugin if (filterPlugins) { delete plugin.filterPlugins handlers.add(plugins => filterPlugins(plugins, options)) } } if (handlers.size > 0) { for (const handler of handlers) { plugins = handler(plugins) } return applyFilterPlugins(plugins) } return plugins } return applyFilterPlugins(this.hooks.filterPlugins.call(plugins)) } resolveCache(...args: string[]) { return this.resolveCwd('.saber', ...args) } resolveCwd(...args: string[]) { return path.resolve(this.opts.cwd, ...args) } resolveOwnDir(...args: string[]) { return path.join(__dirname, '../', ...args) } resolveOutDir(...args: string[]) { return this.resolveCwd(this.config.build.outDir, ...args) } getWebpackConfig(opts: WebpackContext) { opts = Object.assign({ type: 'client' }, opts) const chain = require('./webpack/webpack.config')(this, opts) this.hooks.chainWebpack.call(chain, opts) const config = this.hooks.getWebpackConfig.call(chain.toConfig(), opts) if (this.opts.inspectWebpack) { require('./utils/inspectWebpack')(config, opts.type) } return config } async run() { // Throw an error if both `public` and `.saber/public` exist // Because they are replaced by `static` and `public` // TODO: remove this error before v1.0 const hasOldPublicFolder = await Promise.all([ fs.pathExists(this.resolveCache('public')), fs.pathExists(this.resolveCwd('public')), fs.pathExists(this.resolveCwd('public/index.html')) ]).then( ([hasOldOutDir, hasPublicDir, hasNewPublicDir]) => hasOldOutDir && hasPublicDir && !hasNewPublicDir ) if (hasOldPublicFolder) { // Prevent from deleting public folder throw new Error( [ `It seems you are using the ${colors.underline( colors.cyan('public') )} folder to store static files,`, ` this behavior has changed and now we use ${colors.underline( colors.cyan('static') )} folder for static files`, ` while ${colors.underline( colors.cyan('public') )} folder is used to output generated files,`, ` to prevent from unexpectedly deleting your ${colors.underline( colors.cyan('public') )} folder, please rename it to ${colors.underline( colors.cyan('static') )} and delete ${colors.underline( colors.cyan('.saber/public') )} folder as well` ].join('') ) } await this.hooks.beforeRun.promise() await this.hooks.emitRoutes.promise() } // Build app in production mode async build(options: { skipCompilation?: boolean } = {}) { const { skipCompilation } = options await this.prepare() await this.run() if (!skipCompilation) { await this.renderer.build() await this.hooks.afterBuild.promise() } await this.renderer.generate() await this.hooks.afterGenerate.promise() } async serve() { await this.prepare() await this.run() const server = http.createServer(this.renderer.getRequestHandler()) // Make sure the port is available const { host, port = 3000 } = this.config.server this.actualServerPort = await getPort({ port: getPort.makeRange(port, port + 1000), host }) server.listen(this.actualServerPort, host) } async serveOutDir() { await this.prepare() return require('./utils/serveDir')({ dir: this.resolveOutDir(), host: this.config.server.host, port: this.config.server.port }) } hasDependency(name: string) { return this.getDependencies().includes(name) } getDependencies() { return [ ...Object.keys(this.pkg.data.dependencies || {}), ...Object.keys(this.pkg.data.devDependencies || {}) ] } localResolve(name: string): string { return require('resolve-from').silent(this.opts.cwd, name) } localRequire(name: string): any { const resolved = this.localResolve(name) return resolved && require(resolved) } } export const createSaber = ( opts: SaberConstructorOptions, config: SaberConfig ) => new Saber(opts, config)
the_stack
import { Lens, Prism, PropExpr } from './../lens' import { structEq, Option } from './../utils' import { Observable, Subscriber, Subscription, BehaviorSubject, combineLatest } from 'rxjs' /** * Read-only atom. * * @template T type of atom values */ export interface ReadOnlyAtom<T> extends Observable<T> { /** * Get the current atom value. * * @example * import { Atom } from '@grammarly/focal' * * const a = Atom.create(5) * a.get() * // => 5 * * a.set(6) * a.get() * // => 6 * @returns current value */ get(): T /** * View this atom as is. * Doesn't seem to make sense, but it is needed to be used from * inheriting atom classes to conveniently go from read/write to * read-only atom. * * @example * import { Atom } from '@grammarly/focal' * * const source = Atom.create(5) * const view = source.view() * * view.get() * // => 5 * * source.set(6) * view.get() * // => 6 * * view.set(7) // compilation error * @returns this atom */ view(): ReadOnlyAtom<T> /** * View this atom through a given mapping. * * @example * import { Atom } from '@grammarly/focal' * * const a = Atom.create(5) * const b = a.view(x => x * 2) * * a.get() * // => 5 * b.get() * // => 10 * * a.set(10) * * a.get() * // => 10 * b.get() * // => 20 * @param getter getter function that defines the view * @returns atom viewed through the given transformation */ view<U>(getter: (x: T) => U): ReadOnlyAtom<U> /** * View this atom through a given lens. * * @param lens lens that defines the view * @returns atom viewed through the given transformation */ view<U>(lens: Lens<T, U>): ReadOnlyAtom<U> /** * View this atom through a given prism. * * @param prism prism that defines the view * @returns atom viewed through the given transformation */ view<U>(prism: Prism<T, U>): ReadOnlyAtom<Option<U>> /** * View this atom at a property of given name. */ view<K extends keyof T>(k: K): ReadOnlyAtom<T[K]> /** * View this atom at a give property path. */ view< K1 extends keyof T, K2 extends keyof T[K1] >(k1: K1, k2: K2): ReadOnlyAtom<T[K1][K2]> /** * View this atom at a give property path. */ view< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2] >(k1: K1, k2: K2, k3: K3): ReadOnlyAtom<T[K1][K2][K3]> /** * View this atom at a give property path. */ view< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3] >(k1: K1, k2: K2, k3: K3, k4: K4): ReadOnlyAtom<T[K1][K2][K3][K4]> /** * View this atom at a give property path. */ view< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4] >(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5): ReadOnlyAtom<T[K1][K2][K3][K4][K5]> } /** * A read/write atom. * * @template T type of atom values */ export interface Atom<T> extends ReadOnlyAtom<T> { /** * Modify atom value. * * The update function should be: * - referentially transparent: return same result for same arguments * - side-effect free: don't perform any mutations (including calling * Atom.set/Atom.modify) and side effects * * @param updateFn value update function */ modify(updateFn: (currentValue: T) => T): void /** * Set new atom value. * * @param newValue new value */ set(newValue: T): void /** * DEPRECATED: please use other overloads instead! * * Create a lensed atom using a property expression, which specifies * a path inside the atom value's data structure. * * The property expression is a limited form of a getter, * with following restrictions: * - should be a pure function * - should be a single-expression function (i.e. return immediately) * - should only access object properties (nested access is OK) * - should not access array items * * @example * const atom = Atom.create({ a: { b: 5 } }) * * atom.lens(x => x.a.b).modify(x => x + 1) * atom.get() * // => { a: { b: 6 } } * @template U destination value type * @param propExpr property expression * @returns a lensed atom */ lens<U>(propExpr: PropExpr<T, U>): Atom<U> /** * Create a lensed atom by supplying a lens. * * @template U destination value type * @param lens a lens * @returns a lensed atom */ lens<U>(lens: Lens<T, U>): Atom<U> /** * Create a lensed atom that's focused on a property of given name. */ lens<K extends keyof T>(k: K): Atom<T[K]> /** * Create a lensed atom that's focused on a given property path. */ lens< K1 extends keyof T, K2 extends keyof T[K1] >(k1: K1, k2: K2): Atom<T[K1][K2]> /** * Create a lensed atom that's focused on a given property path. */ lens< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2] >(k1: K1, k2: K2, k3: K3): Atom<T[K1][K2][K3]> /** * Create a lensed atom that's focused on a given property path. */ lens< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3] >(k1: K1, k2: K2, k3: K3, k4: K4): Atom<T[K1][K2][K3][K4]> /** * Create a lensed atom that's focused on a given property path. */ lens< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4] >(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5): Atom<T[K1][K2][K3][K4][K5]> } export abstract class AbstractReadOnlyAtom<T> extends BehaviorSubject<T> implements ReadOnlyAtom<T> { abstract get(): T view(): ReadOnlyAtom<T> view<U>(getter: (x: T) => U): ReadOnlyAtom<U> view<U>(lens: Lens<T, U>): ReadOnlyAtom<U> view<U>(prism: Prism<T, U>): ReadOnlyAtom<Option<U>> view<K extends keyof T>(k: K): ReadOnlyAtom<T[K]> view<U>(...args: any[]): ReadOnlyAtom<any> { /* eslint-disable @typescript-eslint/no-use-before-define */ return args[0] !== undefined // view(getter) case ? typeof args[0] === 'function' ? new AtomViewImpl<T, U>(this, args[0] as (x: T) => U) // view('key') case : typeof args[0] === 'string' ? new AtomViewImpl<T, U>(this, Lens.compose<T, U>(...args.map(Lens.key())).get) // view(lens) and view(prism) cases // @NOTE single case handles both lens and prism arg : new AtomViewImpl<T, U>(this, x => (args[0] as Lens<T, U>).get(x)) // view() case : this as ReadOnlyAtom<T> /* eslint-enable @typescript-eslint/no-use-before-define */ } } export abstract class AbstractAtom<T> extends AbstractReadOnlyAtom<T> implements Atom<T> { abstract modify(updateFn: (x: T) => T): void set(x: T) { this.modify(() => x) } lens<U>(propExpr: PropExpr<T, U>): Atom<U> lens<U>(lens: Lens<T, U>): Atom<U> lens<K extends keyof T>(k: K): Atom<T[K]> lens<U>(arg1: Lens<T, U> | PropExpr<T, U> | string, ...args: string[]): Atom<any> { /* eslint-disable @typescript-eslint/no-use-before-define */ // lens(prop expr) case return typeof arg1 === 'function' ? new LensedAtom<T, U>(this, Lens.prop(arg1 as (x: T) => U), structEq) // lens('key') case : typeof arg1 === 'string' ? new LensedAtom( this, Lens.compose(Lens.key(arg1), ...args.map(k => Lens.key(k))), structEq) // lens(lens) case : new LensedAtom<T, U>(this, arg1 as Lens<T, U>, structEq) /* eslint-enable @typescript-eslint/no-use-before-define */ } } export class JsonAtom<T> extends AbstractAtom<T> { constructor(initialValue: T) { super(initialValue) } get() { return this.getValue() } modify(updateFn: (x: T) => T) { const prevValue = this.getValue() const next = updateFn(prevValue) if (!structEq(prevValue, next)) this.next(next) } set(x: T) { const prevValue = this.getValue() if (!structEq(prevValue, x)) this.next(x) } } class LensedAtom<TSource, TDest> extends AbstractAtom<TDest> { constructor( private _source: Atom<TSource>, private _lens: Lens<TSource, TDest>, private _eq: (x: TDest, y: TDest) => boolean = structEq ) { // @NOTE this is a major hack to optimize for not calling // _lens.get the extra time here. This makes the underlying // BehaviorSubject to have an `undefined` for it's current value. // // But it works because before somebody subscribes to this // atom, it will subscribe to the _source (which we expect to be a // descendant of BehaviorSubject as well), which will emit a // value right away, triggering our _onSourceValue. super(undefined!) } get() { // Optimization: in case we're already subscribed to the // source atom, the BehaviorSubject.getValue will return // an up-to-date computed lens value. // // This way we don't need to recalculate the lens value // every time. return this._subscription ? this.getValue() : this._lens.get(this._source.get()) } modify(updateFn: (x: TDest) => TDest) { this._source.modify(x => this._lens.modify(updateFn, x)) } set(newValue: TDest) { this._source.modify(x => this._lens.set(newValue, x)) } private _onSourceValue(x: TSource) { const prevValue = this.getValue() const next = this._lens.get(x) if (!this._eq(prevValue, next)) this.next(next) } private _subscription: Subscription | null = null private _refCount = 0 // Rx method overrides _subscribe(subscriber: Subscriber<TDest>) { if (!this._subscription) { this._subscription = this._source.subscribe(x => this._onSourceValue(x)) } this._refCount++ const sub = new Subscription(() => { if (--this._refCount <= 0 && this._subscription) { this._subscription.unsubscribe() this._subscription = null } }) sub.add(super._subscribe(subscriber)) return sub } unsubscribe() { if (this._subscription) { this._subscription.unsubscribe() this._subscription = null } this._refCount = 0 super.unsubscribe() } } class AtomViewImpl<TSource, TDest> extends AbstractReadOnlyAtom<TDest> { constructor( private _source: ReadOnlyAtom<TSource>, private _getter: (x: TSource) => TDest, private _eq: (x: TDest, y: TDest) => boolean = structEq ) { // @NOTE this is a major hack to optimize for not calling // _getter the extra time here. This makes the underlying // BehaviorSubject to have an `undefined` for it's current value. // // But it works because before somebody subscribes to this // atom, it will subscribe to the _source (which we expect to be a // descendant of BehaviorSubject as well), which will emit a // value right away, triggering our _onSourceValue. super(undefined!) } get() { // Optimization: in case we're already subscribed to the // source atom, the BehaviorSubject.getValue will return // an up-to-date computed lens value. // // This way we don't need to recalculate the view value // every time. return this._subscription ? this.getValue() : this._getter(this._source.get()) } private _onSourceValue(x: TSource) { const prevValue = this.getValue() const next = this._getter(x) if (!this._eq(prevValue, next)) this.next(next) } private _subscription: Subscription | null = null private _refCount = 0 // Rx method overrides _subscribe(subscriber: Subscriber<TDest>) { if (!this._subscription) { this._subscription = this._source.subscribe(x => this._onSourceValue(x)) } this._refCount++ const sub = new Subscription(() => { if (--this._refCount <= 0 && this._subscription) { this._subscription.unsubscribe() this._subscription = null } }) sub.add(super._subscribe(subscriber)) return sub } unsubscribe() { if (this._subscription) { this._subscription.unsubscribe() this._subscription = null } this._refCount = 0 super.unsubscribe() } } export class CombinedAtomViewImpl<TResult> extends AbstractReadOnlyAtom<TResult> { constructor( private _sources: ReadOnlyAtom<any>[], private _combineFn: (xs: any[]) => TResult, private _eq: (x: TResult, y: TResult) => boolean = structEq ) { // @NOTE this is a major hack to optimize for not calling // _combineFn and .get for each source the extra time here. // This makes the underlying BehaviorSubject to have an // `undefined` for it's current value. // // But it works because before somebody subscribes to this // atom, it will subscribe to the _source (which we expect to be a // descendant of BehaviorSubject as well), which will emit a // value right away, triggering our _onSourceValue. super(undefined!) } get() { // Optimization: in case we're already subscribed to // source atoms, the BehaviorSubject.getValue will return // an up-to-date computed view value. // // This way we don't need to recalculate the view value // every time. return this._subscription ? this.getValue() : this._combineFn(this._sources.map(x => x.get())) } private _onSourceValues(xs: any[]) { const prevValue = this.getValue() const next = this._combineFn(xs) if (!this._eq(prevValue, next)) this.next(next) } private _subscription: Subscription | null = null private _refCount = 0 // Rx method overrides _subscribe(subscriber: Subscriber<TResult>) { if (!this._subscription) { this._subscription = combineLatest(this._sources) .subscribe(xs => this._onSourceValues(xs)) } this._refCount++ const sub = new Subscription(() => { if (--this._refCount <= 0 && this._subscription) { this._subscription.unsubscribe() this._subscription = null } }) sub.add(super._subscribe(subscriber)) return sub } unsubscribe() { if (this._subscription) { this._subscription.unsubscribe() this._subscription = null } this._refCount = 0 super.unsubscribe() } }
the_stack
import { IButtonStyles, DefaultButton } from "@fluentui/react"; import { Icon, IIconProps } from '@fluentui/react/lib/Icon'; import { Label } from "@fluentui/react/lib/Label"; import { MSGraphClient } from "@microsoft/sp-http"; import { WebPartContext } from "@microsoft/sp-webpart-base"; import * as React from "react"; //React Boot Strap import BootstrapTable from "react-bootstrap-table-next"; import paginationFactory from "react-bootstrap-table2-paginator"; import commonServices from "../Common/CommonServices"; import * as stringsConstants from "../constants/strings"; import styles from "../scss/TOTLeaderBoard.module.scss"; import TOTSidebar from "./TOTSideBar"; //global variables let commonService: commonServices; let allUsersDetails: any = []; const columns = [ { dataField: "Rank", text: "Rank", }, { dataField: "User", text: "User", }, { dataField: "Points", text: "Points", }, ]; const backIcon: IIconProps = { iconName: 'NavigateBack' }; const backBtnStyles: Partial<IButtonStyles> = { root: { borderColor: "#33344A", backgroundColor: "white", marginLeft: "1.5%" }, rootHovered: { borderColor: "#33344A", backgroundColor: "white", color: "#000003" }, rootPressed: { borderColor: "#33344A", backgroundColor: "white", color: "#000003" }, icon: { fontSize: "17px", fontWeight: "bolder", color: "#000003", opacity: 1 }, label: { font: "normal normal bold 14px/24px Segoe UI", letterSpacing: "0px", color: "#000003", opacity: 1, marginTop: "-3px" } }; export interface ITOTLeaderBoardProps { context?: WebPartContext; siteUrl: string; onClickCancel: Function; onClickMyDashboardLink: Function; } interface ITOTLeaderBoardState { showSuccess: Boolean; showError: Boolean; noActiveParticipants: boolean; noActiveTournament: boolean; errorMessage: string; tournamentName: string; tournamentDescription: string; allUserActions: any; isShowLoader: boolean; currentUserDetails: any; userLoaded: string; } export default class TOTLeaderBoard extends React.Component< ITOTLeaderBoardProps, ITOTLeaderBoardState > { constructor(props: ITOTLeaderBoardProps, state: ITOTLeaderBoardState) { super(props); //Set default values this.state = { showSuccess: false, showError: false, noActiveParticipants: false, noActiveTournament: false, errorMessage: "", tournamentName: "", tournamentDescription: "", allUserActions: [], isShowLoader: false, currentUserDetails: [], userLoaded: "", }; //Create object for commonServices class commonService = new commonServices(this.props.context, this.props.siteUrl); } public _graphClient: MSGraphClient; //Get User Actions from list and bind to table public componentDidMount() { this.setState({ isShowLoader: true, }); this.getAllUsers().then((res) => { if (res == "Success") { this.getUserActions(); } }); } //get all users properties and store in array private async getAllUsers(): Promise<any> { return new Promise<any>(async (resolve, reject) => { this._graphClient = await this.props.context.msGraphClientFactory.getClient(); await this._graphClient .api("/users") .get() .then(async (users: any, rawResponse?: any) => { for (let user of users.value) { if (user.mail != null) { allUsersDetails.push({ email: user.mail.toLowerCase(), displayName: user.displayName, }); } } resolve("Success"); }) .catch((err) => { console.error("TOT_TOTLeaderboard_getAllUsers \n", err); this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + " while getting users. Below are the details: \n" + JSON.stringify(err), showSuccess: false, }); reject("Failed"); }); }); } //get all user action for active tournament and bind to table private async getUserActions(): Promise<any> { return new Promise<any>(async (resolve, reject) => { try { //get all users await this.getAllUsers(); //get active tournament details let tournamentDetails = await commonService.getActiveTournamentDetails(); if (tournamentDetails.length != 0) { this.setState({ tournamentName: tournamentDetails[0]["Title"], tournamentDescription: tournamentDetails[0]["Description"], }); //get active tournament's participants await commonService .getUserActions(this.state.tournamentName, allUsersDetails) .then((res) => { if (res.length > 0) { this.setState({ allUserActions: res, isShowLoader: false, userLoaded: "1", }); } else if (res.length == 0) { this.setState({ userLoaded: "0", showError: true, noActiveParticipants: true, errorMessage: stringsConstants.NoActiveParticipantsMessage, isShowLoader: false, }); } else if (res == "Failed") { console.error("TOT_TOTLeaderboard_getUserActions \n"); } }); } else { //no active tournaments this.setState({ userLoaded: "1", showError: true, errorMessage: stringsConstants.NoActiveTournamentMessage, noActiveTournament: true, isShowLoader: false, }); } } catch (error) { console.error("TOT_TOTLeaderboard_getUserActions \n", error); this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + " while getting user actions. Below are the details: \n" + JSON.stringify(error), showSuccess: false, isShowLoader: false, }); } }); } public render(): React.ReactElement<ITOTLeaderBoardProps> { return ( <div> {this.state.isShowLoader && <div className={styles.load}></div>} <div className={styles.container}> <div className={styles.totSideBar}> {this.state.userLoaded != "" && ( <TOTSidebar siteUrl={this.props.siteUrl} context={this.props.context} currentUserDetails={this.state.allUserActions} onClickCancel={() => this.props.onClickCancel()} /> )} <div className={styles.contentTab}> <div className={styles.totLeaderboardPath}> <img src={require("../assets/CMPImages/BackIcon.png")} className={styles.backImg} /> <span className={styles.backLabel} onClick={() => this.props.onClickCancel()} title="Tournament of Teams" > Tournament of Teams </span> <span className={styles.border}></span> <span className={styles.totLeaderboardLabel}>Leader Board</span> </div> {this.state.tournamentName != "" && ( <div className={styles.contentArea}> {this.state.tournamentName != "" && ( <ul className={styles.listArea}> <li className={styles.listVal}> <span className={styles.labelHeading}>Tournament</span>: <span className={styles.labelNormal}> {this.state.tournamentName} </span> </li> {this.state.tournamentDescription && ( <li className={styles.listVal}> <span className={styles.labelHeading}> Description </span> : <span className={styles.labelNormal}> {this.state.tournamentDescription} </span> </li> )} </ul> )} <div className={styles.table}> {this.state.allUserActions.length > 0 ? ( <BootstrapTable table-responsive bordered hover responsive keyField="Rank" data={this.state.allUserActions} columns={columns} pagination={paginationFactory()} headerClasses="header-class" /> ) : <div> {this.state.showError && this.state.noActiveParticipants && ( <Label className={styles.noActvPartErr}> There are no active participants at the moment. Be the first to participate and log an activity from&nbsp; <span className={styles.myDashboardLink} onClick={() => this.props.onClickMyDashboardLink()}> My Dashboard </span>! </Label> )} </div> } </div> </div> )} <div className={styles.contentArea}> {this.state.showError && !this.state.noActiveParticipants && ( <Label className={this.state.noActiveTournament ? styles.noActvTourErr : styles.errorMessage}> {this.state.errorMessage} </Label> )} </div> <div> <DefaultButton text="Back" title="Back" iconProps={backIcon} onClick={() => this.props.onClickCancel()} styles={backBtnStyles}> </DefaultButton> </div> </div> </div> </div> </div> //outer div ); //close return } //end of render }
the_stack
import { Component, Type, ViewChild, Directive } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NxTabGroupComponent } from './tab-group'; import { NxTabsModule } from './tabs.module'; import { NxTabNavBarComponent } from './tab-nav-bar'; import { dispatchFakeEvent } from '../cdk-test-utils'; declare var viewport: any; const THROTTLE_TIME = 200; // For better readablity here, We can safely ignore some conventions in our specs // tslint:disable:component-class-suffix @Directive() abstract class TabHeaderScrollableTest { direction: any; tabs: any; @ViewChild(NxTabGroupComponent) tabGroupInstance!: NxTabGroupComponent; @ViewChild(NxTabNavBarComponent) tabNavBarInstance!: NxTabNavBarComponent; } describe('Scrollable TabHeader', () => { let fixture: ComponentFixture<TabHeaderScrollableTest>; let testInstance: TabHeaderScrollableTest; let tabHeaderNativeElement: HTMLElement; const createTestComponent = (component: Type<TabHeaderScrollableTest>) => { fixture = TestBed.createComponent(component); fixture.detectChanges(); testInstance = fixture.componentInstance; tabHeaderNativeElement = fixture.debugElement.nativeElement.querySelector('nx-tab-header'); }; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ NotScrollableTabGroupTest, ScrollableTabGroupTest ], imports: [ NxTabsModule, BrowserAnimationsModule ] }).compileComponents(); })); function getStartScrollElement(): HTMLElement { return fixture.debugElement.nativeElement.querySelector('nx-tab-scroll-indicator.start-button'); } function getEndScrollElement(): HTMLElement { return fixture.debugElement.nativeElement.querySelector('nx-tab-scroll-indicator.end-button'); } it('does not show scroll buttons if not scrollable', fakeAsync(() => { createTestComponent(NotScrollableTabGroupTest); fixture.detectChanges(); tick(THROTTLE_TIME); expect(tabHeaderNativeElement.classList).not.toContain('scrollable'); expect(getStartScrollElement()).toBeNull(); expect(getEndScrollElement()).toBeNull(); })); describe('scrollable', () => { beforeEach(fakeAsync(() => { createTestComponent(ScrollableTabGroupTest); fixture.detectChanges(); tick(THROTTLE_TIME); fixture.detectChanges(); tick(THROTTLE_TIME); })); it('shows scroll buttons if scrollable', fakeAsync(() => { expect(tabHeaderNativeElement.classList).toContain('scrollable'); expect(getStartScrollElement()).toBeTruthy(); expect(getEndScrollElement()).toBeTruthy(); })); it('updates scrollable on tabs change', fakeAsync(() => { testInstance.tabs = [ { label: 'Tab Label 1', content: 'Content 1' }, { label: 'Tab Label 2', content: 'Content 2' }, { label: 'Tab Label 3', content: 'Content 3' }]; fixture.detectChanges(); tick(THROTTLE_TIME); fixture.detectChanges(); tick(THROTTLE_TIME); expect(tabHeaderNativeElement.classList).not.toContain('scrollable'); })); it('hides scroll-to-start indicator', fakeAsync(() => { expect(tabHeaderNativeElement.querySelector('.nx-tab-header')?.scrollLeft).toBe(0); expect(getStartScrollElement().classList).toContain('is-scrolled-to-start'); })); it('shows scroll-to-start indicator when scrolled', fakeAsync(() => { const scrollableContainer = tabHeaderNativeElement.querySelector('.nx-tab-header'); scrollableContainer!.scrollTo({ left: 50 }); dispatchFakeEvent(scrollableContainer as Node, 'scroll'); fixture.detectChanges(); expect(getStartScrollElement().classList).not.toContain('is-scrolled-to-start'); })); it('shows scroll-to-end indicator', fakeAsync(() => { expect(getEndScrollElement().classList).not.toContain('is-scrolled-to-end'); })); it('hides scroll-to-end indicator when at end', fakeAsync(() => { const scrollableContainer = tabHeaderNativeElement.querySelector('.nx-tab-header'); scrollableContainer!.scrollTo({ left: 1000 }); dispatchFakeEvent(scrollableContainer as Node, 'scroll'); fixture.detectChanges(); expect(getEndScrollElement().classList).toContain('is-scrolled-to-end'); })); }); describe('responsive', () => { beforeEach(fakeAsync(() => { viewport.set('mobile'); createTestComponent(ScrollableTabGroupTest); tick(THROTTLE_TIME); fixture.detectChanges(); tick(THROTTLE_TIME); fixture.detectChanges(); })); it('marks scrollButtons as mobile', fakeAsync(() => { expect(getStartScrollElement().classList).toContain('is-mobile'); expect(getStartScrollElement().classList).not.toContain('is-desktop-button'); })); it('switches from mobile to desktop', fakeAsync(() => { viewport.set('desktop'); window.dispatchEvent(new Event('resize')); tick(THROTTLE_TIME); fixture.detectChanges(); expect(getStartScrollElement().classList).not.toContain('is-mobile'); expect(getStartScrollElement().classList).toContain('is-desktop-button'); })); afterEach(fakeAsync(() => { viewport.reset(); })); }); }); @Directive() abstract class TabNavBarScrollableTest { direction: any; links: any; @ViewChild(NxTabNavBarComponent) tabNavBarInstance!: NxTabNavBarComponent; } describe('Scrollable TabNavBar', () => { let fixture: ComponentFixture<TabNavBarScrollableTest>; let testInstance: TabNavBarScrollableTest; let tabNavBarNativeElement: HTMLElement; const createTestComponent = (component: Type<TabNavBarScrollableTest>) => { fixture = TestBed.createComponent(component); fixture.detectChanges(); testInstance = fixture.componentInstance; tabNavBarNativeElement = fixture.debugElement.query(By.directive(NxTabNavBarComponent)).nativeElement; }; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ NotScrollableTabNavBarTest, ScrollableTabNavBarTest ], imports: [ NxTabsModule, BrowserAnimationsModule ] }).compileComponents(); })); function getStartScrollElement(): HTMLElement { return fixture.debugElement.nativeElement.querySelector('nx-tab-scroll-indicator.start-button'); } function getEndScrollElement(): HTMLElement { return fixture.debugElement.nativeElement.querySelector('nx-tab-scroll-indicator.end-button'); } it('does not show scroll buttons if not scrollable', fakeAsync(() => { createTestComponent(NotScrollableTabNavBarTest); fixture.detectChanges(); tick(THROTTLE_TIME); expect(tabNavBarNativeElement.classList).not.toContain('scrollable'); expect(getStartScrollElement()).toBeNull(); expect(getEndScrollElement()).toBeNull(); })); describe('scrollable', () => { beforeEach(fakeAsync(() => { createTestComponent(ScrollableTabNavBarTest); fixture.detectChanges(); tick(THROTTLE_TIME); fixture.detectChanges(); tick(THROTTLE_TIME); })); it('shows scroll buttons if scrollable', fakeAsync(() => { expect(tabNavBarNativeElement.classList).toContain('scrollable'); expect(getStartScrollElement()).toBeTruthy(); expect(getEndScrollElement()).toBeTruthy(); tick(THROTTLE_TIME); })); it('updates scrollable on tabs change', fakeAsync(() => { testInstance.links = [ { label: 'Tab Label 1', active: true }, { label: 'Tab Label 2', active: false }, { label: 'Tab Label 3', active: false }]; fixture.detectChanges(); tick(THROTTLE_TIME); fixture.detectChanges(); tick(THROTTLE_TIME); expect(tabNavBarNativeElement.classList).not.toContain('scrollable'); })); it('hides scroll-to-start indicator', fakeAsync(() => { expect(tabNavBarNativeElement.querySelector('.nx-tab-nav-bar')!.scrollLeft).toBe(0); expect(getStartScrollElement().classList).toContain('is-scrolled-to-start'); })); it('shows scroll-to-start indicator when scrolled', fakeAsync(() => { const scrollableContainer = tabNavBarNativeElement.querySelector('.nx-tab-nav-bar'); scrollableContainer!.scrollTo({ left: 50 }); dispatchFakeEvent(scrollableContainer!, 'scroll'); fixture.detectChanges(); expect(scrollableContainer!.scrollLeft).toBe(50); expect(getStartScrollElement().classList).not.toContain('is-scrolled-to-start'); })); it('shows scroll-to-end indicator', fakeAsync(() => { expect(getEndScrollElement().classList).not.toContain('is-scrolled-to-end'); })); it('hides scroll-to-end indicator when at end', fakeAsync(() => { const scrollableContainer = tabNavBarNativeElement.querySelector('.nx-tab-nav-bar'); scrollableContainer!.scrollTo({ left: 1000 }); dispatchFakeEvent(scrollableContainer!, 'scroll'); fixture.detectChanges(); expect(getEndScrollElement().classList).toContain('is-scrolled-to-end'); })); }); }); @Component({ template: ` <nx-tab-group mobileAccordion="false"> <nx-tab *ngFor="let tab of tabs" [label]="tab.label"> {{tab.content}} </nx-tab> </nx-tab-group> ` }) class NotScrollableTabGroupTest extends TabHeaderScrollableTest { tabs = [ { label: 'Tab Label 1', content: 'Content 1' }, { label: 'Tab Label 2', content: 'Content 2' }, { label: 'Tab Label 3', content: 'Content 3' } ]; } @Component({ template: ` <div style="max-width: 400px" [dir]="direction"> <nx-tab-group mobileAccordion="false"> <nx-tab *ngFor="let tab of tabs" [label]="tab.label"> {{tab.content}} </nx-tab> </nx-tab-group> </div> ` }) class ScrollableTabGroupTest extends TabHeaderScrollableTest { tabs = [ { label: 'Tab Label 1', content: 'Content 1' }, { label: 'Tab Label 2', content: 'Content 2' }, { label: 'Tab Label 3', content: 'Content 3' }, { label: 'Tab Label 4', content: 'Content 4' }, { label: 'Tab Label 5', content: 'Content 5' } ]; } @Component({ template: ` <nx-tab-nav-bar> <a nxTabLink *ngFor="let link of links" [active]="link.active"> {{link.label}} </a> </nx-tab-nav-bar> ` }) class NotScrollableTabNavBarTest extends TabNavBarScrollableTest { links = [ { label: 'Tab Label 1', active: true }, { label: 'Tab Label 2', active: false }, { label: 'Tab Label 3', active: false } ]; } @Component({ template: ` <div style="max-width: 400px" [dir]="direction"> <nx-tab-nav-bar> <a nxTabLink *ngFor="let link of links" [active]="link.active"> {{link.label}} </a> </nx-tab-nav-bar> </div> ` }) class ScrollableTabNavBarTest extends TabNavBarScrollableTest { links = [ { label: 'Tab Label 1', active: true }, { label: 'Tab Label 2', active: false }, { label: 'Tab Label 3', active: false }, { label: 'Tab Label 4', active: false }, { label: 'Tab Label 5', active: false } ]; }
the_stack
import { BooleanAlgebra } from './BooleanAlgebra' import { Monoid } from './Monoid' import { Ring } from './Ring' import { Semigroup } from './Semigroup' import { Semiring } from './Semiring' // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- /** * @category instances * @since 2.10.0 */ export const getBooleanAlgebra = <B>(B: BooleanAlgebra<B>) => <A = never>(): BooleanAlgebra<(a: A) => B> => ({ meet: (x, y) => (a) => B.meet(x(a), y(a)), join: (x, y) => (a) => B.join(x(a), y(a)), zero: () => B.zero, one: () => B.one, implies: (x, y) => (a) => B.implies(x(a), y(a)), not: (x) => (a) => B.not(x(a)) }) /** * Unary functions form a semigroup as long as you can provide a semigroup for the codomain. * * @example * import { Predicate, getSemigroup } from 'fp-ts/function' * import * as B from 'fp-ts/boolean' * * const f: Predicate<number> = (n) => n <= 2 * const g: Predicate<number> = (n) => n >= 0 * * const S1 = getSemigroup(B.SemigroupAll)<number>() * * assert.deepStrictEqual(S1.concat(f, g)(1), true) * assert.deepStrictEqual(S1.concat(f, g)(3), false) * * const S2 = getSemigroup(B.SemigroupAny)<number>() * * assert.deepStrictEqual(S2.concat(f, g)(1), true) * assert.deepStrictEqual(S2.concat(f, g)(3), true) * * @category instances * @since 2.10.0 */ export const getSemigroup = <S>(S: Semigroup<S>) => <A = never>(): Semigroup<(a: A) => S> => ({ concat: (f, g) => (a) => S.concat(f(a), g(a)) }) /** * Unary functions form a monoid as long as you can provide a monoid for the codomain. * * @example * import { Predicate } from 'fp-ts/Predicate' * import { getMonoid } from 'fp-ts/function' * import * as B from 'fp-ts/boolean' * * const f: Predicate<number> = (n) => n <= 2 * const g: Predicate<number> = (n) => n >= 0 * * const M1 = getMonoid(B.MonoidAll)<number>() * * assert.deepStrictEqual(M1.concat(f, g)(1), true) * assert.deepStrictEqual(M1.concat(f, g)(3), false) * * const M2 = getMonoid(B.MonoidAny)<number>() * * assert.deepStrictEqual(M2.concat(f, g)(1), true) * assert.deepStrictEqual(M2.concat(f, g)(3), true) * * @category instances * @since 2.10.0 */ export const getMonoid = <M>(M: Monoid<M>): (<A = never>() => Monoid<(a: A) => M>) => { const getSemigroupM = getSemigroup(M) return <A>() => ({ concat: getSemigroupM<A>().concat, empty: () => M.empty }) } /** * @category instances * @since 2.10.0 */ export const getSemiring = <A, B>(S: Semiring<B>): Semiring<(a: A) => B> => ({ add: (f, g) => (x) => S.add(f(x), g(x)), zero: () => S.zero, mul: (f, g) => (x) => S.mul(f(x), g(x)), one: () => S.one }) /** * @category instances * @since 2.10.0 */ export const getRing = <A, B>(R: Ring<B>): Ring<(a: A) => B> => { const S = getSemiring<A, B>(R) return { add: S.add, mul: S.mul, one: S.one, zero: S.zero, sub: (f, g) => (x) => R.sub(f(x), g(x)) } } // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- /** * @since 2.11.0 */ export const apply = <A>(a: A) => <B>(f: (a: A) => B): B => f(a) /** * A *thunk* * * @since 2.0.0 */ export interface Lazy<A> { (): A } /** * @example * import { FunctionN } from 'fp-ts/function' * * export const sum: FunctionN<[number, number], number> = (a, b) => a + b * * @since 2.0.0 */ export interface FunctionN<A extends ReadonlyArray<unknown>, B> { (...args: A): B } /** * @since 2.0.0 */ export function identity<A>(a: A): A { return a } /** * @since 2.0.0 */ export const unsafeCoerce: <A, B>(a: A) => B = identity as any /** * @since 2.0.0 */ export function constant<A>(a: A): Lazy<A> { return () => a } /** * A thunk that returns always `true`. * * @since 2.0.0 */ export const constTrue: Lazy<boolean> = /*#__PURE__*/ constant(true) /** * A thunk that returns always `false`. * * @since 2.0.0 */ export const constFalse: Lazy<boolean> = /*#__PURE__*/ constant(false) /** * A thunk that returns always `null`. * * @since 2.0.0 */ export const constNull: Lazy<null> = /*#__PURE__*/ constant(null) /** * A thunk that returns always `undefined`. * * @since 2.0.0 */ export const constUndefined: Lazy<undefined> = /*#__PURE__*/ constant(undefined) /** * A thunk that returns always `void`. * * @since 2.0.0 */ export const constVoid: Lazy<void> = constUndefined /** * Flips the order of the arguments of a function of two arguments. * * @since 2.0.0 */ export function flip<A, B, C>(f: (a: A, b: B) => C): (b: B, a: A) => C { return (b, a) => f(a, b) } /** * Performs left-to-right function composition. The first argument may have any arity, the remaining arguments must be unary. * * See also [`pipe`](#pipe). * * @example * import { flow } from 'fp-ts/function' * * const len = (s: string): number => s.length * const double = (n: number): number => n * 2 * * const f = flow(len, double) * * assert.strictEqual(f('aaa'), 6) * * @since 2.0.0 */ export function flow<A extends ReadonlyArray<unknown>, B>(ab: (...a: A) => B): (...a: A) => B export function flow<A extends ReadonlyArray<unknown>, B, C>(ab: (...a: A) => B, bc: (b: B) => C): (...a: A) => C export function flow<A extends ReadonlyArray<unknown>, B, C, D>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D ): (...a: A) => D export function flow<A extends ReadonlyArray<unknown>, B, C, D, E>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E ): (...a: A) => E export function flow<A extends ReadonlyArray<unknown>, B, C, D, E, F>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F ): (...a: A) => F export function flow<A extends ReadonlyArray<unknown>, B, C, D, E, F, G>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G ): (...a: A) => G export function flow<A extends ReadonlyArray<unknown>, B, C, D, E, F, G, H>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H ): (...a: A) => H export function flow<A extends ReadonlyArray<unknown>, B, C, D, E, F, G, H, I>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I ): (...a: A) => I export function flow<A extends ReadonlyArray<unknown>, B, C, D, E, F, G, H, I, J>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J ): (...a: A) => J export function flow( ab: Function, bc?: Function, cd?: Function, de?: Function, ef?: Function, fg?: Function, gh?: Function, hi?: Function, ij?: Function ): unknown { switch (arguments.length) { case 1: return ab case 2: return function (this: unknown) { return bc!(ab.apply(this, arguments)) } case 3: return function (this: unknown) { return cd!(bc!(ab.apply(this, arguments))) } case 4: return function (this: unknown) { return de!(cd!(bc!(ab.apply(this, arguments)))) } case 5: return function (this: unknown) { return ef!(de!(cd!(bc!(ab.apply(this, arguments))))) } case 6: return function (this: unknown) { return fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments)))))) } case 7: return function (this: unknown) { return gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments))))))) } case 8: return function (this: unknown) { return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments)))))))) } case 9: return function (this: unknown) { return ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments))))))))) } } return } /** * @since 2.0.0 */ export function tuple<T extends ReadonlyArray<any>>(...t: T): T { return t } /** * @since 2.0.0 */ export function increment(n: number): number { return n + 1 } /** * @since 2.0.0 */ export function decrement(n: number): number { return n - 1 } /** * @since 2.0.0 */ export function absurd<A>(_: never): A { throw new Error('Called `absurd` function which should be uncallable') } /** * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument. * * @example * import { tupled } from 'fp-ts/function' * * const add = tupled((x: number, y: number): number => x + y) * * assert.strictEqual(add([1, 2]), 3) * * @since 2.4.0 */ export function tupled<A extends ReadonlyArray<unknown>, B>(f: (...a: A) => B): (a: A) => B { return (a) => f(...a) } /** * Inverse function of `tupled` * * @since 2.4.0 */ export function untupled<A extends ReadonlyArray<unknown>, B>(f: (a: A) => B): (...a: A) => B { return (...a) => f(a) } /** * Pipes the value of an expression into a pipeline of functions. * * See also [`flow`](#flow). * * @example * import { pipe } from 'fp-ts/function' * * const len = (s: string): number => s.length * const double = (n: number): number => n * 2 * * // without pipe * assert.strictEqual(double(len('aaa')), 6) * * // with pipe * assert.strictEqual(pipe('aaa', len, double), 6) * * @since 2.6.3 */ export function pipe<A>(a: A): A export function pipe<A, B>(a: A, ab: (a: A) => B): B export function pipe<A, B, C>(a: A, ab: (a: A) => B, bc: (b: B) => C): C export function pipe<A, B, C, D>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D export function pipe<A, B, C, D, E>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E): E export function pipe<A, B, C, D, E, F>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F ): F export function pipe<A, B, C, D, E, F, G>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G ): G export function pipe<A, B, C, D, E, F, G, H>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H ): H export function pipe<A, B, C, D, E, F, G, H, I>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I ): I export function pipe<A, B, C, D, E, F, G, H, I, J>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J ): J export function pipe<A, B, C, D, E, F, G, H, I, J, K>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K ): K export function pipe<A, B, C, D, E, F, G, H, I, J, K, L>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L ): L export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M ): M export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N ): N export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O ): O export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P ): P export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q ): Q export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R ): R export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R, rs: (r: R) => S ): S export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T>( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R, rs: (r: R) => S, st: (s: S) => T ): T export function pipe( a: unknown, ab?: Function, bc?: Function, cd?: Function, de?: Function, ef?: Function, fg?: Function, gh?: Function, hi?: Function ): unknown { switch (arguments.length) { case 1: return a case 2: return ab!(a) case 3: return bc!(ab!(a)) case 4: return cd!(bc!(ab!(a))) case 5: return de!(cd!(bc!(ab!(a)))) case 6: return ef!(de!(cd!(bc!(ab!(a))))) case 7: return fg!(ef!(de!(cd!(bc!(ab!(a)))))) case 8: return gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))) case 9: return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))) default: let ret = arguments[0] for (let i = 1; i < arguments.length; i++) { ret = arguments[i](ret) } return ret } } /** * Type hole simulation * * @since 2.7.0 */ export const hole: <T>() => T = absurd as any /** * @since 2.11.0 */ export const SK = <A, B>(_: A, b: B): B => b // ------------------------------------------------------------------------------------- // deprecated // ------------------------------------------------------------------------------------- // tslint:disable: deprecation /** * Use `Refinement` module instead. * * @since 2.0.0 * @deprecated */ export interface Refinement<A, B extends A> { (a: A): a is B } /** * Use `Predicate` module instead. * * @since 2.0.0 * @deprecated */ export interface Predicate<A> { (a: A): boolean } /** * Use `Predicate` module instead. * * @since 2.0.0 * @deprecated */ export function not<A>(predicate: Predicate<A>): Predicate<A> { return (a) => !predicate(a) } /** * Use `Endomorphism` module instead. * * @since 2.0.0 * @deprecated */ export interface Endomorphism<A> { (a: A): A } /** * Use `Endomorphism` module instead. * * @category instances * @since 2.10.0 * @deprecated */ export const getEndomorphismMonoid = <A = never>(): Monoid<Endomorphism<A>> => ({ concat: (first, second) => flow(first, second), empty: identity })
the_stack
const recursiveReadDir = require('recursive-readdir'); const fuzzysort = require('fuzzysort'); import { promisify } from 'util'; import { Service } from 'typedi'; import Project from './Project'; import SourceFile, { ParseFailure, ParseResult } from './SourceFile'; import { getFileType } from 'indexer/util'; import ESModuleItem, { Marker } from './ESModuleItem'; import { readFile, Stats, statSync } from 'fs'; import { findAbsoluteFilePathWhichExists } from './fileResolver'; import { dirname, join, relative, isAbsolute, sep } from 'path'; import { WorkerRunner } from './WorkerRunner'; @Service() export default class Indexer { public files: { [path: string]: SourceFile } = {}; public status: 'needs_indexing' | 'indexed' | 'indexing' = 'needs_indexing'; public project: Project | undefined; public totalFiles: number = 0; public indexedFileCount: number = 0; public failures: ParseFailure[] = []; public workerJSFile: string | undefined; public workerRunner: WorkerRunner; constructor() { this.workerRunner = new WorkerRunner(); } public async parse( project: Project, cache?: { [path: string]: ParseResult } ) { this.status = 'indexing'; this.project = project; this.failures = []; const files = await this.readProjectFiles(project.root); let supportedFiles = files.filter( filePath => getFileType(filePath) !== 'UNSUPPORTED' ); if (cache) { supportedFiles = this.getModifiedFilesForIndexing( supportedFiles, cache, project ); } this.totalFiles = supportedFiles.length; this.indexedFileCount = 0; return this.relaxedIndexer(supportedFiles, project); } public getModifiedFilesForIndexing( allSupportedFiles: string[], cache: { [path: string]: ParseResult }, project: Project ) { const fileToIndex: string[] = []; allSupportedFiles.forEach(filePath => { if (cache[filePath]) { const cachedFile = cache[filePath]; const stat = statSync(cachedFile.path); if (!cachedFile.lastIndexedTime) { fileToIndex.push(filePath); } else if (stat.mtimeMs > cachedFile.lastIndexedTime) { fileToIndex.push(filePath); } else { // add cached file to index const fileObj = SourceFile.getFileFromJSON( cachedFile, project.root, project.pathAlias ); this.files[filePath] = fileObj; } } else { fileToIndex.push(filePath); } }); return fileToIndex; } public async relaxedIndexer(filesToIndex: string[], project: Project) { if (filesToIndex.length === 0) { this.status = 'indexed'; return; } if (this.project) { await this.workerRunner.run( { files: filesToIndex, pathAlias: this.project?.pathAlias, root: this.project?.root, }, (file: SourceFile) => { this.indexedFileCount += 1; file.root = project.root; file.pathAliasMap = project.pathAlias; this.files[file.path] = file; }, this.workerJSFile ); this.status = 'indexed'; } } public indexFile(path: string) { if (!this.project) { return; } const sourceFile = new SourceFile( path, this.project.pathAlias, this.project.root ); this.files[path] = sourceFile; sourceFile.parse(); } public search(query: string, queryType: string) { try { let searchTokens = query .split(/(\s+)/) .filter(item => item.trim() !== ''); const searchQuery = searchTokens.length === 1 ? query : searchTokens[0]; const folderQuery = searchTokens.length > 1 ? searchTokens[1] : null; const queryTypes = queryType.split(':'); let results: ESModuleItem[] = []; Object.entries(this.files) .filter(([, file]) => { if (folderQuery === null) { return true; } else { return file.path.includes(folderQuery); } }) .forEach(([, file]) => { file.symbols.forEach(symbol => { if ( queryType === '' || (queryTypes.includes('func') && symbol.kind === 'FunctionDeclaration') || (queryTypes.includes('type') && (symbol.kind === 'TypeAlias' || symbol.kind === 'TSInterfaceDeclaration')) || (queryTypes.includes('var') && symbol.kind === 'VariableDeclaration') || (queryTypes.includes('class') && symbol.kind === 'ClassDeclaration') ) { results.push({ ...symbol, path: file.path, }); } }); }); const filteredResults = fuzzysort.go(searchQuery, results, { key: 'name', limit: 100, }); return filteredResults; } catch (e) { return []; } } public searchFile(query: string) { const filteredResults = fuzzysort.go(query, Object.keys(this.files), { limit: 100, }); return filteredResults; } public getSymbolWithMarkers(path: string, name: string) { const shouldGetDefaultExport = name === '@@DEFAULT_EXPORT@@'; const file = this.files[path]; if (shouldGetDefaultExport) { return file.symbols.find(symbol => symbol.isDefaultExport === true); } const symbol = file.symbols.find(symbol => symbol.name === name); if (!symbol && this.project) { const reExportedSymbol = this.getReExportedSymbol(name, path, file); if (reExportedSymbol) { return reExportedSymbol; } } return symbol; } public getSymbolsForPath(path: string) { const file = this.files[path]; if (!file) { return []; } return file.symbols; } public findReference(name: string, path: string) { const markers: Marker[] = []; Object.values(this.files).forEach(file => { const symbols = file.symbols; symbols.forEach(symbol => { symbol.markers.forEach(marker => { if ( marker.filePath === path && marker.name === name && symbol.location ) { markers.push({ name: symbol.name, filePath: symbol.path, location: symbol.location, }); } }); }); }); return markers; } public async getCode(path: string, name: string) { const shouldGetDefaultExport = name === '@@DEFAULT_EXPORT@@'; const file = this.files[path]; if (file) { let symbol: ESModuleItem | null | undefined; if (shouldGetDefaultExport) { symbol = file.symbols.find( symbol => symbol.isDefaultExport === true ); } if (!symbol) { symbol = file.symbols.find(symbol => symbol.name === name); } if (!symbol || !symbol.location) { symbol = this.getReExportedSymbol(name, path, file); if (!symbol || !symbol.location) { return ''; } } const content = await promisify(readFile)(symbol.path); const code = content.toString(); const lines = code.split('\n'); const { start = { line: 0, column: 0 }, end = { line: 0, column: 0 }, } = symbol.location; const results: string[] = []; lines.forEach((line, index) => { if (index >= start.line - 1 && index <= end.line - 1) { results.push(line); } }); return results.reduce((acc, line) => { return acc + line + '\n'; }, ''); } } public killAllWorkers() { this.workerRunner.kilAll(); setTimeout(() => { this.status = 'needs_indexing'; this.indexedFileCount = 0; this.totalFiles = 0; this.failures = []; }, 1000); } public getCache() { return Object.values(this.files).reduce( (acc: { [path: string]: ParseResult }, file) => { acc[file.path] = file.asJSON(); return acc; }, {} ); } private isChildOf(child: string, parent: string) { if (child === parent) return true; const parentTokens = parent.split(sep).filter(i => i.length); return parentTokens.every((token, index) => { return child.split(sep).filter(t => t.length)[index] === token; }); } private isParentOf(child: string, parent: string) { if (child === parent) return true; const childTokens = child.split(sep).filter(i => i.length); return childTokens.every((token, index) => { return parent.split(sep).filter(t => t.length)[index] === token; }); } private isPathLiesInProvidedDirectories( path: string, stats: Stats, directories: string[] ) { if (stats.isDirectory()) { return directories.some( directory => this.isChildOf(path, directory) || this.isParentOf(path, directory) ); } return directories.some(dir => path.includes(dir)); } public getIgnoreFunc( indexableDirectories: string[], excludedDirectories: string[] ) { return (path: string, stats: Stats) => { // if no directories are configured, just ignore node_modules if ( indexableDirectories.length === 0 && excludedDirectories.length === 0 ) { // if it's a file from node_modules, return true so it will be ignored return path.includes('node_modules'); } // when the directories are provided, still we return true if the file is in node_modules if (path.includes('node_modules')) { return true; } if ( this.isPathLiesInProvidedDirectories( path, stats, indexableDirectories ) ) { // even if the file belongs to a director which should be indexed, it should not belong to a directory which is excluded return this.isPathLiesInProvidedDirectories( path, stats, excludedDirectories ); } return true; }; } private async readProjectFiles(root: string) { if (this.project) { const indexableDirectories = this.project.directories.map( directory => join(this.project?.root || '', directory) ); const excludedDirectories = this.project.excludedDirectories.map( directory => join(this.project?.root || '', directory) ); const ignoreFunc = this.getIgnoreFunc( indexableDirectories, excludedDirectories ); return new Promise<string[]>((resolve, reject) => { recursiveReadDir( root, [ignoreFunc], (err: Error, files: string[]) => { if (err) { reject(err); } else { resolve(files); } } ); }); } return []; } private getReExportedSymbol( name: string, path: string, file: SourceFile ): ESModuleItem | null | undefined { if (!this.project) { return null; } let actualSymbolName = name; const exportStatement = file.exportStatements.find(s => { const specifier = s.specifiers.find( specifier => specifier.exported === name ); if (specifier) { actualSymbolName = specifier?.local; } return specifier; }); if (exportStatement) { const pathOfTheFile = exportStatement.path; const absolutePath = findAbsoluteFilePathWhichExists( this.project?.root, dirname(path), pathOfTheFile, this.project.pathAlias ); const actualFile = this.files[absolutePath]; const symbolFromActualFile = actualFile.symbols.find( symbol => symbol.name === actualSymbolName ); if (symbolFromActualFile) { return symbolFromActualFile; } return this.getReExportedSymbol(name, absolutePath, actualFile); } } }
the_stack
import {CoreGraphNode} from '../../../../core/graph/CoreGraphNode'; import { ConnectionPointTypeMap, ConnectionPointEnumMap, DEFAULT_CONNECTION_POINT_ENUM_MAP, create_connection_point, } from './connections/ConnectionMap'; import {TypedNode} from '../../_Base'; import {ConnectionPointsSpareParamsController} from './ConnectionPointsSpareParamsController'; import {NodeContext, NetworkChildNodeType} from '../../../poly/NodeContext'; type IONameFunction = (index: number) => string; type ExpectedConnectionTypesFunction<NC extends NodeContext> = () => ConnectionPointEnumMap[NC][]; export class ConnectionPointsController<NC extends NodeContext> { private _spare_params_controller: ConnectionPointsSpareParamsController<NC>; private _create_spare_params_from_inputs = true; private _functions_overridden = false; constructor(private node: TypedNode<NC, any>, private _context: NC) { this._spare_params_controller = new ConnectionPointsSpareParamsController(this.node, this._context); } private _input_name_function: IONameFunction = (index: number) => { return `in${index}`; }; private _output_name_function: IONameFunction = (index: number) => { return index == 0 ? 'val' : `val${index}`; }; // private _default_input_type: ConnectionPointType = ConnectionPointType.FLOAT; private _expected_input_types_function: ExpectedConnectionTypesFunction<NC> = () => { const type = this.first_input_connection_type() || this.default_connection_type(); return [type, type]; }; private _expected_output_types_function: ExpectedConnectionTypesFunction<NC> = () => { return [this._expected_input_types_function()[0]]; }; protected default_connection_type(): ConnectionPointEnumMap[NC] { return DEFAULT_CONNECTION_POINT_ENUM_MAP[this._context]; } protected create_connection_point(name: string, type: ConnectionPointEnumMap[NC]): ConnectionPointTypeMap[NC] { return create_connection_point(this._context, name, type) as ConnectionPointTypeMap[NC]; } functions_overridden(): boolean { return this._functions_overridden; } initialized(): boolean { return this._initialized; } set_create_spare_params_from_inputs(state: boolean) { this._create_spare_params_from_inputs = state; } set_input_name_function(func: IONameFunction) { this._initialize_if_required(); this._input_name_function = func; } set_output_name_function(func: IONameFunction) { this._initialize_if_required(); this._output_name_function = func; } // set_default_input_type(type: ConnectionPointType) { // this._default_input_type = type; // } set_expected_input_types_function(func: ExpectedConnectionTypesFunction<NC>) { this._initialize_if_required(); this._functions_overridden = true; this._expected_input_types_function = func; } set_expected_output_types_function(func: ExpectedConnectionTypesFunction<NC>) { this._initialize_if_required(); this._functions_overridden = true; this._expected_output_types_function = func; } input_name(index: number) { return this._wrapped_input_name_function(index); } output_name(index: number) { return this._wrapped_output_name_function(index); } private _update_signature_if_required_bound = this.update_signature_if_required.bind(this); private _initialized: boolean = false; initializeNode() { // I don't want this check here, as I should refactor to have the has_named_inputs // be initialized from here // if (!this.node.io.inputs.hasNamedInputs()) { // return; // } if (this._initialized) { console.warn('already initialized', this.node); return; } this._initialized = true; // hooks this.node.io.inputs.add_on_set_input_hook( '_update_signature_if_required', this._update_signature_if_required_bound ); // this.node.lifecycle.add_on_add_hook(this._update_signature_if_required_bound); this.node.params.addOnSceneLoadHook('_update_signature_if_required', this._update_signature_if_required_bound); this.node.params.onParamsCreated( '_update_signature_if_required_bound', this._update_signature_if_required_bound ); this.node.addPostDirtyHook('_update_signature_if_required', this._update_signature_if_required_bound); if (!this._spare_params_controller.initialized()) { this._spare_params_controller.initializeNode(); } } private _initialize_if_required() { if (!this._initialized) { this.initializeNode(); } } get spare_params() { return this._spare_params_controller; } update_signature_if_required(dirty_trigger?: CoreGraphNode) { if (!this.node.lifecycle.creation_completed || !this._connections_match_inputs()) { this.update_connection_types(); this.node.removeDirtyState(); // no need to update the successors when loading, // since the connection point types are stored in the scene data if (!this.node.scene().loadingController.isLoading()) { this.make_successors_update_signatures(); } } } // used when a node changes its signature, adn the output nodes need to adapt their own signatures private make_successors_update_signatures() { const successors = this.node.graphAllSuccessors(); if (this.node.childrenAllowed()) { const subnet_inputs = this.node.nodesByType(NetworkChildNodeType.INPUT); const subnet_outputs = this.node.nodesByType(NetworkChildNodeType.OUTPUT); for (let subnet_input of subnet_inputs) { successors.push(subnet_input); } for (let subnet_output of subnet_outputs) { successors.push(subnet_output); } } for (let graph_node of successors) { const node = graph_node as TypedNode<NC, any>; // we need to check if node.io exists to be sure it is a node, not just a graph_node if (node.io && node.io.has_connection_points_controller && node.io.connection_points.initialized()) { node.io.connection_points.update_signature_if_required(this.node); } } // we also need to have subnet_output nodes update their parents // if (this.node.type == NetworkChildNodeType.OUTPUT) { // this.node.parent?.io.connection_points.update_signature_if_required(this.node); // } } update_connection_types() { const set_dirty = false; const expected_input_types = this._wrapped_expected_input_types_function(); const expected_output_types = this._wrapped_expected_output_types_function(); const named_input_connection_points: ConnectionPointTypeMap[NC][] = []; for (let i = 0; i < expected_input_types.length; i++) { const type = expected_input_types[i]; const point = this.create_connection_point(this._wrapped_input_name_function(i), type); named_input_connection_points.push(point); } const named_output_connect_points: ConnectionPointTypeMap[NC][] = []; for (let i = 0; i < expected_output_types.length; i++) { const type = expected_output_types[i]; const point = this.create_connection_point(this._wrapped_output_name_function(i), type); named_output_connect_points.push(point); } this.node.io.inputs.setNamedInputConnectionPoints(named_input_connection_points); this.node.io.outputs.setNamedOutputConnectionPoints(named_output_connect_points, set_dirty); if (this._create_spare_params_from_inputs) { this._spare_params_controller.createSpareParameters(); } } protected _connections_match_inputs(): boolean { const current_input_types = this.node.io.inputs.namedInputConnectionPoints().map((c) => c?.type()); const current_output_types = this.node.io.outputs.namedOutputConnectionPoints().map((c) => c?.type()); const expected_input_types = this._wrapped_expected_input_types_function(); const expected_output_types = this._wrapped_expected_output_types_function(); if (expected_input_types.length != current_input_types.length) { return false; } if (expected_output_types.length != current_output_types.length) { return false; } for (let i = 0; i < current_input_types.length; i++) { if (current_input_types[i] != expected_input_types[i]) { return false; } } for (let i = 0; i < current_output_types.length; i++) { if (current_output_types[i] != expected_output_types[i]) { return false; } } return true; } // // // WRAPPPED METHOD // the goal here is to use the types data saved in the scene file // when the scene is loading. That has 2 purposes: // - avoid an update cascade during loading, where nodes with many inputs are updated // several times. // - allow the subnet_input to load with the connection_points it had on save, // which in turn allows connected nodes to not lose their connections. // private _wrapped_expected_input_types_function() { if (this.node.scene().loadingController.isLoading()) { const in_data = this.node.io.saved_connection_points_data.in(); if (in_data) { return in_data.map((d) => d.type as ConnectionPointEnumMap[NC]); } } return this._expected_input_types_function(); } private _wrapped_expected_output_types_function() { if (this.node.scene().loadingController.isLoading()) { const out_data = this.node.io.saved_connection_points_data.out(); if (out_data) { return out_data.map((d) => d.type as ConnectionPointEnumMap[NC]); } } return this._expected_output_types_function(); } private _wrapped_input_name_function(index: number) { if (this.node.scene().loadingController.isLoading()) { const in_data = this.node.io.saved_connection_points_data.in(); if (in_data) { return in_data[index].name; } } return this._input_name_function(index); } private _wrapped_output_name_function(index: number) { if (this.node.scene().loadingController.isLoading()) { const out_data = this.node.io.saved_connection_points_data.out(); if (out_data) { return out_data[index].name; } } return this._output_name_function(index); } // protected input_connection_type() { // return this.first_input_connection_type(); // } // protected output_connection_type() { // return this.first_input_connection_type(); // } first_input_connection_type(): ConnectionPointEnumMap[NC] | undefined { return this.input_connection_type(0); } input_connection_type(index: number): ConnectionPointEnumMap[NC] | undefined { const connections = this.node.io.connections.inputConnections(); if (connections) { const connection = connections[index]; if (connection) { return connection.src_connection_point()!.type() as ConnectionPointEnumMap[NC]; } } } // input_connection_point_from_connection(connection: TypedNodeConnection<NC>): ConnectionPointTypeMap[NC] { // const node_dest = connection.node_dest; // const output_index = connection.output_index; // return node_dest.io.outputs.namedOutputConnectionPoints()[output_index] as ConnectionPointTypeMap[NC]; // } // output_connection_point_from_connection(connection: TypedNodeConnection<NC>): ConnectionPointTypeMap[NC] { // const node_src = connection.node_src; // const output_index = connection.output_index; // return node_src.io.outputs.namedOutputConnectionPoints()[output_index] as ConnectionPointTypeMap[NC]; // } // connection_point_type_from_connection(connection: TypedNodeConnection<NC>): ConnectionPointEnumMap[NC] { // return connection.dest_connection_point()?.type as ConnectionPointEnumMap[NC]; // // const connection_point = this.output_connection_point_from_connection(connection)!; // // return connection_point.type as ConnectionPointEnumMap[NC]; // } // connection_point_name_from_connection(connection: TypedNodeConnection<NC>): string { // return connection.dest_connection_point()!.name // // const connection_point = this.output_connection_point_from_connection(connection)!; // // return connection_point.name; // } }
the_stack
import ifm = require('./interfaces'); import testifm = require('vso-node-api/interfaces/TestInterfaces'); import ccp = require('./codecoveragepublisher'); import utilities = require('./utilities'); import cm = require('./common'); import Q = require('q'); var xmlreader = require('xmlreader'); export class CodeCoverageSummary { results: testifm.CodeCoverageStatistics[]; constructor() { this.results = []; } addResults(res) { this.results = this.results.concat(res); } } export class JacocoSummaryReader implements ccp.ICodeCoverageReader { private command: cm.ITaskCommand; constructor(command: cm.ITaskCommand) { this.command = command; } //----------------------------------------------------- // Get code coverage summary object given a jacoco summary file // - summaryFilePath: string - location of the code coverage summary file //----------------------------------------------------- public getCodeCoverageSummary(summaryFilePath: string): Q.Promise<testifm.CodeCoverageData> { var defer = Q.defer<testifm.CodeCoverageData>(); var _this = this; SummaryReaderUtilities.getXmlContent(summaryFilePath).then(function(xmlContents) { _this.parseJacocoXmlReport(xmlContents).then(function(codeCoverageSummary) { defer.resolve(SummaryReaderUtilities.getCodeCoverageData(codeCoverageSummary)); }).fail(function(err) { defer.reject(err); }); }).fail(function(err) { defer.reject(err); }); return defer.promise; } //----------------------------------------------------- // Parses xmlContent to read jacoco code coverage and returns codeCoverageSummary object // - xmlContent: any - xml content to be parsed //----------------------------------------------------- private parseJacocoXmlReport(xmlContent): Q.Promise<CodeCoverageSummary> { this.command.info("parseJacocoXmlReport: Parsing summary file."); var defer = Q.defer<CodeCoverageSummary>(); if (!xmlContent || !xmlContent.report || !xmlContent.report.at(0) || !xmlContent.report.at(0).counter) { defer.resolve(null); return defer.promise; } try { var coverage = new CodeCoverageSummary(); var reportNode = xmlContent.report.at(0); var nodeLength = reportNode.counter.count(); var coverageStats = []; for (var i = 0; i < nodeLength; i++) { var counterNode = reportNode.counter.at(i); var attributes = counterNode.attributes(); if (attributes && attributes.type && attributes.covered && attributes.missed) { var covered = parseInt(attributes.covered); var missed = parseInt(attributes.missed); if (!isNaN(covered) && !isNaN(missed)) { var total = covered + missed; this.command.info(attributes.type + " : " + covered + "/" + total + " covered."); var coverageStat = SummaryReaderUtilities.getCodeCoverageStatistics(utilities.toTitleCase(attributes.type), covered, total, attributes.type); coverageStats.push(coverageStat); } else { defer.reject(new Error("Unable to retreive value for '" + attributes.type + "' from summary file. Verify the summary file is well formed and try again.")); return defer.promise; } } } coverage.addResults(coverageStats); } catch (error) { defer.reject(error); return defer.promise; } defer.resolve(coverage); return defer.promise; } } export class CoberturaSummaryReader implements ccp.ICodeCoverageReader { public command: cm.ITaskCommand; constructor(command: cm.ITaskCommand) { this.command = command; } //----------------------------------------------------- // Get code coverage summary object given a cobertura summary file // - summaryFilePath: string - location of the code coverage summary file //----------------------------------------------------- public getCodeCoverageSummary(summaryFilePath: string): Q.Promise<testifm.CodeCoverageData> { var defer = Q.defer<testifm.CodeCoverageData>(); var _this = this; SummaryReaderUtilities.getXmlContent(summaryFilePath).then(function(xmlContents) { _this.parseCoberturaXmlReport(xmlContents).then(function(codeCoverageSummary) { defer.resolve(SummaryReaderUtilities.getCodeCoverageData(codeCoverageSummary)); }).fail(function(err) { defer.reject(err); }); }).fail(function(err) { defer.reject(err); }); return defer.promise; } //----------------------------------------------------- // Parses xmlContent to read cobertura code coverage and returns codeCoverageSummary object // - xmlContent: any - xml content to be parsed //----------------------------------------------------- private parseCoberturaXmlReport(xmlContent): Q.Promise<CodeCoverageSummary> { this.command.info("parseCoberturaXmlReport: Parsing summary file."); var defer = Q.defer<CodeCoverageSummary>(); if (!xmlContent || !xmlContent.coverage || !xmlContent.coverage.at(0) || !xmlContent.coverage.at(0).attributes()) { defer.resolve(null); return defer.promise; } var coverageStats = []; var coverage = new CodeCoverageSummary(); try { var coverageNode = xmlContent.coverage.at(0); var attributes = coverageNode.attributes(); if (attributes) { var linesTotal = attributes['lines-valid']; var linesCovered = attributes['lines-covered']; var branchesCovered = attributes['branches-covered']; var branchesTotal = attributes['branches-valid']; if (linesTotal && linesCovered) { linesTotal = parseInt(linesTotal); linesCovered = parseInt(linesCovered); if (!isNaN(linesTotal) && !isNaN(linesCovered)) { this.command.info("Lines : " + linesCovered + "/" + linesTotal + " covered."); var coverageStat = SummaryReaderUtilities.getCodeCoverageStatistics("Lines", linesCovered, linesTotal, "line"); coverageStats.push(coverageStat); } else { defer.reject(new Error("Unable to retreive value for 'lines' from summary file. Verify the summary file is well formed and try again.")); return defer.promise; } } if (branchesCovered && branchesTotal) { branchesCovered = parseInt(branchesCovered); branchesTotal = parseInt(branchesTotal); if (!isNaN(branchesCovered) && !isNaN(branchesTotal)) { this.command.info("Branches : " + branchesCovered + "/" + branchesTotal + " covered."); var coverageStat = SummaryReaderUtilities.getCodeCoverageStatistics("Branches", branchesCovered, branchesTotal, "branch"); coverageStats.push(coverageStat); } else { defer.reject(new Error("Unable to retreive value for 'branches' from summary file. Verify the summary file is well formed and try again.")); return defer.promise; } } coverage.addResults(coverageStats); } } catch (error) { defer.reject(error); return defer.promise; } defer.resolve(coverage); return defer.promise; } } export class SummaryReaderUtilities { //----------------------------------------------------- // reads the file and returns the xml content //----------------------------------------------------- public static getXmlContent(summaryFile: string): Q.Promise<any> { var defer = Q.defer(); utilities.readFileContents(summaryFile, "utf-8").then(function(contents) { xmlreader.read(contents, function(err, res) { if (err) { defer.reject(err); } else { try { defer.resolve(res); } catch (ex) { defer.reject(err); } } }); }).fail(function(err) { defer.reject(err); }); return defer.promise; } //----------------------------------------------------- // returns a CodeCoverageStatistics object // label : name of code coverage statistic // covered : number of units covered // total : total number of units // priorityTag : name required to assign the position to the statistic //----------------------------------------------------- public static getCodeCoverageStatistics(label: string, covered: number, total: number, priorityTag: string): testifm.CodeCoverageStatistics { var coverageStat: testifm.CodeCoverageStatistics = <testifm.CodeCoverageStatistics>{ label: label, covered: covered, total: total, position: SummaryReaderUtilities.getCoveragePriorityOrder(priorityTag) } return coverageStat; } public static getCodeCoverageData(codeCoverageSummary: CodeCoverageSummary): testifm.CodeCoverageData { if (!codeCoverageSummary) { return null; } var codeCoverageData: testifm.CodeCoverageData = <testifm.CodeCoverageData>{ // <todo: Bug 402783> We are currently passing BuildFlavor and BuildPlatform = "" There value are required be passed to commandlet buildFlavor: "", buildPlatform: "", coverageStats: codeCoverageSummary.results } return codeCoverageData; } //----------------------------------------------------- // Returns a priority number based on the label //----------------------------------------------------- public static getCoveragePriorityOrder(label: string): Number { if (label.toLowerCase() == 'instruction') { return 5; } else if (label.toLowerCase() == 'line') { return 4; } else if (label.toLowerCase() == 'method') { return 3; } else if (label.toLowerCase() == 'complexity') { return 2; } else if (label.toLowerCase() == 'class') { return 1; } return 6; } }
the_stack
import process from "process"; import path from "path"; import os from "os"; import fs from "fs-extra"; import execa from "execa"; import archiver from "archiver"; import cryptoRandomString from "crypto-random-string"; import commander from "commander"; import globby from "globby"; import bash from "dedent"; export default async function caxa({ input, output, command, force = true, exclude = [], filter = (() => { const pathsToExclude = globby .sync(exclude, { expandDirectories: false, onlyFiles: false, }) .map((pathToExclude: string) => path.join(pathToExclude)); return (pathToCopy: string) => !pathsToExclude.includes(path.join(pathToCopy)); })(), dedupe = true, prepareCommand, prepare = async (buildDirectory: string) => { if (prepareCommand === undefined) return; await execa.command(prepareCommand, { cwd: buildDirectory, shell: true }); }, includeNode = true, stub = path.join( __dirname, `../stubs/stub--${process.platform}--${process.arch}` ), identifier = path.join( path.basename(path.basename(path.basename(output, ".app"), ".exe"), ".sh"), cryptoRandomString({ length: 10, type: "alphanumeric" }).toLowerCase() ), removeBuildDirectory = true, uncompressionMessage, }: { input: string; output: string; command: string[]; force?: boolean; exclude?: string[]; filter?: fs.CopyFilterSync | fs.CopyFilterAsync; dedupe?: boolean; prepareCommand?: string; prepare?: (buildDirectory: string) => Promise<void>; includeNode?: boolean; stub?: string; identifier?: string; removeBuildDirectory?: boolean; uncompressionMessage?: string; }): Promise<void> { if (!(await fs.pathExists(input)) || !(await fs.lstat(input)).isDirectory()) throw new Error( `The path to your application isn’t a directory: ‘${input}’.` ); if ((await fs.pathExists(output)) && !force) throw new Error(`Output already exists: ‘${output}’.`); if (process.platform === "win32" && !output.endsWith(".exe")) throw new Error("An Windows executable must end in ‘.exe’."); const buildDirectory = path.join( os.tmpdir(), "caxa/builds", cryptoRandomString({ length: 10, type: "alphanumeric" }).toLowerCase() ); await fs.copy(input, buildDirectory, { filter }); if (dedupe) await execa("npm", ["dedupe", "--production"], { cwd: buildDirectory }); await prepare(buildDirectory); if (includeNode) { const node = path.join( buildDirectory, "node_modules/.bin", path.basename(process.execPath) ); await fs.ensureDir(path.dirname(node)); await fs.copyFile(process.execPath, node); } await fs.ensureDir(path.dirname(output)); await fs.remove(output); if (output.endsWith(".app")) { if (process.platform !== "darwin") throw new Error( "macOS Application Bundles (.app) are supported in macOS only." ); await fs.ensureDir(path.join(output, "Contents/Resources")); await fs.move( buildDirectory, path.join(output, "Contents/Resources/application") ); await fs.ensureDir(path.join(output, "Contents/MacOS")); const name = path.basename(output, ".app"); await fs.writeFile( path.join(output, "Contents/MacOS", name), `#!/usr/bin/env sh\nopen "$(dirname "$0")/../Resources/${name}"`, { mode: 0o755 } ); await fs.writeFile( path.join(output, "Contents/Resources", name), `#!/usr/bin/env sh\n${command .map( (part) => `"${part.replace( /\{\{\s*caxa\s*\}\}/g, `$(dirname "$0")/application` )}"` ) .join(" ")}`, { mode: 0o755 } ); } else if (output.endsWith(".sh")) { if (process.platform === "win32") throw new Error("The Shell Stub (.sh) isn’t supported in Windows."); let stub = bash` #!/usr/bin/env sh export CAXA_TEMPORARY_DIRECTORY="$(dirname $(mktemp))/caxa" export CAXA_EXTRACTION_ATTEMPT=-1 while true do export CAXA_EXTRACTION_ATTEMPT=$(( CAXA_EXTRACTION_ATTEMPT + 1 )) export CAXA_LOCK="$CAXA_TEMPORARY_DIRECTORY/locks/${identifier}/$CAXA_EXTRACTION_ATTEMPT" export CAXA_APPLICATION_DIRECTORY="$CAXA_TEMPORARY_DIRECTORY/applications/${identifier}/$CAXA_EXTRACTION_ATTEMPT" if [ -d "$CAXA_APPLICATION_DIRECTORY" ] then if [ -d "$CAXA_LOCK" ] then continue else break fi else ${ uncompressionMessage === undefined ? bash`` : bash`echo "${uncompressionMessage}" >&2` } mkdir -p "$CAXA_LOCK" mkdir -p "$CAXA_APPLICATION_DIRECTORY" tail -n+{{caxa-number-of-lines}} "$0" | tar -xz -C "$CAXA_APPLICATION_DIRECTORY" rmdir "$CAXA_LOCK" break fi done exec ${command .map( (commandPart) => `"${commandPart.replace( /\{\{\s*caxa\s*\}\}/g, `"$CAXA_APPLICATION_DIRECTORY"` )}"` ) .join(" ")} "$@" ` + "\n"; stub = stub.replace( "{{caxa-number-of-lines}}", String(stub.split("\n").length) ); await fs.writeFile(output, stub, { mode: 0o755 }); await appendTarballOfBuildDirectoryToOutput(); } else { if (!(await fs.pathExists(stub))) throw new Error( `Stub not found (your operating system / architecture may be unsupported): ‘${stub}’` ); await fs.copyFile(stub, output); await fs.chmod(output, 0o755); await appendTarballOfBuildDirectoryToOutput(); await fs.appendFile( output, "\n" + JSON.stringify({ identifier, command, uncompressionMessage }) ); } if (removeBuildDirectory) await fs.remove(buildDirectory); async function appendTarballOfBuildDirectoryToOutput(): Promise<void> { const archive = archiver("tar", { gzip: true }); const archiveStream = fs.createWriteStream(output, { flags: "a" }); archive.pipe(archiveStream); archive.directory(buildDirectory, false); await archive.finalize(); // FIXME: Use ‘stream/promises’ when Node.js 16 lands, because then an LTS version will have the feature: await stream.finished(archiveStream); await new Promise((resolve, reject) => { archiveStream.on("finish", resolve); archiveStream.on("error", reject); }); } } if (require.main === module) (async () => { await commander.program .version(require("../package.json").version) .requiredOption("-i, --input <input>", "The input directory to package.") .requiredOption( "-o, --output <output>", "The path where the executable will be produced. On Windows must end in ‘.exe’. In macOS may end in ‘.app’ to generate a macOS Application Bundle. In macOS and Linux, may end in ‘.sh’ to use the Shell Stub, which takes less space, but depends on some tools being installed on the end-user machine, for example, ‘tar’, ‘tail’, and so forth." ) .option("-f, --force", "[Advanced] Overwrite output if it exists.", true) .option("-F, --no-force") .option( "-e, --exclude <path...>", `[Advanced] Paths to exclude from the build. The paths are passed to https://github.com/sindresorhus/globby and paths that match will be excluded. [Super-Advanced, Please don’t use] If you wish to emulate ‘--include’, you may use ‘--exclude "*" ".*" "!path-to-include" ...’. The problem with ‘--include’ is that if you change your project structure but forget to change the caxa invocation, then things will subtly fail only in the packaged version.` ) .option( "-d, --dedupe", "[Advanced] Run ‘npm dedupe --production’ on the build directory.", true ) .option("-D, --no-dedupe") .option( "-p, --prepare-command <command>", "[Advanced] Command to run on the build directory while packaging." ) .option( "-n, --include-node", "[Advanced] Copy the Node.js executable to ‘{{caxa}}/node_modules/.bin/node’.", true ) .option("-N, --no-include-node") .option("-s, --stub <path>", "[Advanced] Path to the stub.") .option( "--identifier <identifier>", "[Advanced] Build identifier, which is the path in which the application will be unpacked." ) .option( "-b, --remove-build-directory", "[Advanced] Remove the build directory after the build.", true ) .option("-B, --no-remove-build-directory") .option( "-m, --uncompression-message <message>", "[Advanced] A message to show when uncompressing, for example, ‘This may take a while to run the first time, please wait...’." ) .arguments("<command...>") .description("Package Node.js applications into executable binaries.", { command: "The command to run and optional arguments to pass to the command every time the executable is called. Paths must be absolute. The ‘{{caxa}}’ placeholder is substituted for the folder from which the package runs. The ‘node’ executable is available at ‘{{caxa}}/node_modules/.bin/node’. Use double quotes to delimit the command and each argument.", }) .addHelpText( "after", ` Examples: Windows: > caxa --input "examples/echo-command-line-parameters" --output "echo-command-line-parameters.exe" -- "{{caxa}}/node_modules/.bin/node" "{{caxa}}/index.js" "some" "embedded arguments" "--an-option-thats-part-of-the-command" macOS/Linux: $ caxa --input "examples/echo-command-line-parameters" --output "echo-command-line-parameters" -- "{{caxa}}/node_modules/.bin/node" "{{caxa}}/index.js" "some" "embedded arguments" "--an-option-thats-part-of-the-command" macOS (Application Bundle): $ caxa --input "examples/echo-command-line-parameters" --output "Echo Command Line Parameters.app" -- "{{caxa}}/node_modules/.bin/node" "{{caxa}}/index.js" "some" "embedded arguments" "--an-option-thats-part-of-the-command" macOS/Linux (Shell Stub): $ caxa --input "examples/echo-command-line-parameters" --output "echo-command-line-parameters.sh" -- "{{caxa}}/node_modules/.bin/node" "{{caxa}}/index.js" "some" "embedded arguments" "--an-option-thats-part-of-the-command" ` ) .action( async ( command: string[], { input, output, force, exclude = [], dedupe, prepareCommand, includeNode, stub, identifier, removeBuildDirectory, uncompressionMessage, }: { input: string; output: string; force?: boolean; exclude?: string[]; dedupe?: boolean; prepareCommand?: string; includeNode?: boolean; stub?: string; identifier?: string; removeBuildDirectory?: boolean; uncompressionMessage?: string; } ) => { try { await caxa({ input, output, command, force, exclude, dedupe, prepareCommand, includeNode, stub, identifier, removeBuildDirectory, uncompressionMessage, }); } catch (error) { console.error(error.message); process.exit(1); } } ) .parseAsync(); })();
the_stack