hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 5, "code_window": [ " this._filter.markFocused(test);\n", " }\n" ], "labels": [ "add", "keep" ], "after_edit": [ " focusedTests.push(test);\n", " }\n" ], "file_path": "utils/testrunner/index.js", "type": "add", "edit_start_line_idx": 88 }
contents of the file
test/assets/file-to-upload.txt
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017252187535632402, 0.00017252187535632402, 0.00017252187535632402, 0.00017252187535632402, 0 ]
{ "id": 5, "code_window": [ " this._filter.markFocused(test);\n", " }\n" ], "labels": [ "add", "keep" ], "after_edit": [ " focusedTests.push(test);\n", " }\n" ], "file_path": "utils/testrunner/index.js", "type": "add", "edit_start_line_idx": 88 }
<div>beforeunload demo.</div> <script> window.addEventListener('beforeunload', event => { // Chromium & WebKit way. event.returnValue = 'Leave?'; // Firefox way. event.preventDefault(); }); </script>
test/assets/beforeunload.html
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017884183034766465, 0.0001732322562020272, 0.00016762269660830498, 0.0001732322562020272, 0.000005609566869679838 ]
{ "id": 6, "code_window": [ " }\n", " }\n", "\n", " repeatAll(repeatCount) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " return focusedTests;\n", " }\n", "\n", " focusMatchingFilePath(filepathRegex) {\n", " const focusedTests = [];\n", " for (const test of this._collector.tests()) {\n", " if (filepathRegex.test(test.location().filePath())) {\n", " this._filter.markFocused(test);\n", " focusedTests.push(test);\n", " }\n", " }\n", " return focusedTests;\n" ], "file_path": "utils/testrunner/index.js", "type": "add", "edit_start_line_idx": 89 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const fs = require('fs'); const readline = require('readline'); const TestRunner = require('../utils/testrunner/'); const {Environment} = require('../utils/testrunner/Test'); function collect(browserNames) { let parallel = 1; if (process.env.PW_PARALLEL_TESTS) parallel = parseInt(process.env.PW_PARALLEL_TESTS.trim(), 10); const parallelArgIndex = process.argv.indexOf('-j'); if (parallelArgIndex !== -1) parallel = parseInt(process.argv[parallelArgIndex + 1], 10); require('events').defaultMaxListeners *= parallel; let timeout = process.env.CI ? 30 * 1000 : 10 * 1000; if (!isNaN(process.env.TIMEOUT)) timeout = parseInt(process.env.TIMEOUT * 1000, 10); const MAJOR_NODEJS_VERSION = parseInt(process.version.substring(1).split('.')[0], 10); if (MAJOR_NODEJS_VERSION >= 8 && require('inspector').url()) { console.log('Detected inspector - disabling timeout to be debugger-friendly'); timeout = 0; } const config = require('./test.config'); const testRunner = new TestRunner({ timeout, totalTimeout: process.env.CI ? 30 * 60 * 1000 : 0, // 30 minutes on CI parallel, breakOnFailure: process.argv.indexOf('--break-on-failure') !== -1, verbose: process.argv.includes('--verbose'), summary: !process.argv.includes('--verbose'), showSlowTests: process.env.CI ? 5 : 0, showMarkedAsFailingTests: 10, }); if (config.setupTestRunner) config.setupTestRunner(testRunner); for (const [key, value] of Object.entries(testRunner.api())) global[key] = value; // TODO: this should be a preinstalled playwright by default. const playwrightPath = config.playwrightPath; const playwright = require(playwrightPath); const playwrightEnvironment = new Environment('Playwright'); playwrightEnvironment.beforeAll(async state => { state.playwright = playwright; global.playwright = playwright; }); playwrightEnvironment.afterAll(async state => { delete state.playwright; delete global.playwright; }); testRunner.collector().useEnvironment(playwrightEnvironment); for (const e of config.globalEnvironments || []) testRunner.collector().useEnvironment(e); for (const browserName of browserNames) { const browserType = playwright[browserName]; const browserTypeEnvironment = new Environment('BrowserType'); browserTypeEnvironment.beforeAll(async state => { state.browserType = browserType; }); browserTypeEnvironment.afterAll(async state => { delete state.browserType; }); // TODO: maybe launch options per browser? const launchOptions = { ...(config.launchOptions || {}), handleSIGINT: false, }; if (launchOptions.executablePath) launchOptions.executablePath = launchOptions.executablePath[browserName]; if (launchOptions.executablePath) { const YELLOW_COLOR = '\x1b[33m'; const RESET_COLOR = '\x1b[0m'; console.warn(`${YELLOW_COLOR}WARN: running ${browserName} tests with ${launchOptions.executablePath}${RESET_COLOR}`); browserType._executablePath = launchOptions.executablePath; delete launchOptions.executablePath; } else { if (!fs.existsSync(browserType.executablePath())) throw new Error(`Browser is not downloaded. Run 'npm install' and try to re-run tests`); } const browserEnvironment = new Environment(browserName); browserEnvironment.beforeAll(async state => { state._logger = null; state.browser = await state.browserType.launch({...launchOptions, logger: { isEnabled: (name, severity) => { return name === 'browser' || (name === 'protocol' && config.dumpProtocolOnFailure); }, log: (name, severity, message, args) => { if (state._logger) state._logger(name, severity, message); } }}); }); browserEnvironment.afterAll(async state => { await state.browser.close(); delete state.browser; delete state._logger; }); browserEnvironment.beforeEach(async(state, testRun) => { state._logger = (name, severity, message) => { if (name === 'browser') { if (severity === 'warning') testRun.log(`\x1b[31m[browser]\x1b[0m ${message}`) else testRun.log(`\x1b[33m[browser]\x1b[0m ${message}`) } else if (name === 'protocol' && config.dumpProtocolOnFailure) { testRun.log(`\x1b[32m[protocol]\x1b[0m ${message}`) } } }); browserEnvironment.afterEach(async (state, testRun) => { state._logger = null; if (config.dumpProtocolOnFailure) { if (testRun.ok()) testRun.output().splice(0); } }); const pageEnvironment = new Environment('Page'); pageEnvironment.beforeEach(async state => { state.context = await state.browser.newContext(); state.page = await state.context.newPage(); }); pageEnvironment.afterEach(async state => { await state.context.close(); state.context = null; state.page = null; }); const suiteName = { 'chromium': 'Chromium', 'firefox': 'Firefox', 'webkit': 'WebKit' }[browserName]; describe(suiteName, () => { // In addition to state, expose these two on global so that describes can access them. global.playwright = playwright; global.browserType = browserType; testRunner.collector().useEnvironment(browserTypeEnvironment); for (const spec of config.specs || []) { const skip = spec.browsers && !spec.browsers.includes(browserName); (skip ? xdescribe : describe)(spec.title || '', () => { for (const e of spec.environments || ['page']) { if (e === 'browser') { testRunner.collector().useEnvironment(browserEnvironment); } else if (e === 'page') { testRunner.collector().useEnvironment(browserEnvironment); testRunner.collector().useEnvironment(pageEnvironment); } else { testRunner.collector().useEnvironment(e); } } for (const file of spec.files || []) { require(file); delete require.cache[require.resolve(file)]; } }); } delete global.browserType; delete global.playwright; }); } for (const [key, value] of Object.entries(testRunner.api())) { // expect is used when running tests, while the rest of api is not. if (key !== 'expect') delete global[key]; } const filterArgIndex = process.argv.indexOf('--filter'); if (filterArgIndex !== -1) { const filter = process.argv[filterArgIndex + 1]; testRunner.focusMatchingTests(new RegExp(filter, 'i')); } const repeatArgIndex = process.argv.indexOf('--repeat'); if (repeatArgIndex !== -1) { const repeat = parseInt(process.argv[repeatArgIndex + 1], 10); if (!isNaN(repeat)) testRunner.repeatAll(repeat); } return testRunner; } module.exports = collect; if (require.main === module) { console.log('Testing on Node', process.version); const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => { return process.env.BROWSER === name || process.env.BROWSER === 'all'; }); const testRunner = collect(browserNames); testRunner.run().then(() => { delete global.expect; }); }
test/test.js
1
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.999257504940033, 0.04597040265798569, 0.00016502704238519073, 0.00016878850874491036, 0.20803140103816986 ]
{ "id": 6, "code_window": [ " }\n", " }\n", "\n", " repeatAll(repeatCount) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " return focusedTests;\n", " }\n", "\n", " focusMatchingFilePath(filepathRegex) {\n", " const focusedTests = [];\n", " for (const test of this._collector.tests()) {\n", " if (filepathRegex.test(test.location().filePath())) {\n", " this._filter.markFocused(test);\n", " focusedTests.push(test);\n", " }\n", " }\n", " return focusedTests;\n" ], "file_path": "utils/testrunner/index.js", "type": "add", "edit_start_line_idx": 89 }
set PATH=%WEBKIT_BUILD_PATH% set WEBKIT_LIBRARIES=%~dp0checkout\WebKitLibraries\win set WEBKIT_OUTPUTDIR=%~dp0checkout\WebKitBuild perl %~dp0checkout\Tools\Scripts\build-webkit --wincairo --release --no-ninja --touch-events --orientation-events --dark-mode-css --generate-project-only %DEVENV% %~dp0checkout\WebKitBuild\Release\WebKit.sln /build "Release|x64"
browser_patches/webkit/buildwin.bat
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.0001657579850871116, 0.0001657579850871116, 0.0001657579850871116, 0.0001657579850871116, 0 ]
{ "id": 6, "code_window": [ " }\n", " }\n", "\n", " repeatAll(repeatCount) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " return focusedTests;\n", " }\n", "\n", " focusMatchingFilePath(filepathRegex) {\n", " const focusedTests = [];\n", " for (const test of this._collector.tests()) {\n", " if (filepathRegex.test(test.location().filePath())) {\n", " this._filter.markFocused(test);\n", " focusedTests.push(test);\n", " }\n", " }\n", " return focusedTests;\n" ], "file_path": "utils/testrunner/index.js", "type": "add", "edit_start_line_idx": 89 }
/** * Copyright 2019 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const Events = { Browser: { Disconnected: 'disconnected' }, BrowserContext: { Close: 'close', Page: 'page', }, BrowserServer: { Close: 'close', }, Page: { Close: 'close', Crash: 'crash', Console: 'console', Dialog: 'dialog', Download: 'download', FileChooser: 'filechooser', DOMContentLoaded: 'domcontentloaded', // Can't use just 'error' due to node.js special treatment of error events. // @see https://nodejs.org/api/events.html#events_error_events PageError: 'pageerror', Request: 'request', Response: 'response', RequestFailed: 'requestfailed', RequestFinished: 'requestfinished', FrameAttached: 'frameattached', FrameDetached: 'framedetached', FrameNavigated: 'framenavigated', Load: 'load', Popup: 'popup', Worker: 'worker', }, Worker: { Close: 'close', }, };
src/events.ts
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017634248069953173, 0.00017070335161406547, 0.00016681812121532857, 0.00016911579587031156, 0.000003913142791134305 ]
{ "id": 6, "code_window": [ " }\n", " }\n", "\n", " repeatAll(repeatCount) {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " return focusedTests;\n", " }\n", "\n", " focusMatchingFilePath(filepathRegex) {\n", " const focusedTests = [];\n", " for (const test of this._collector.tests()) {\n", " if (filepathRegex.test(test.location().filePath())) {\n", " this._filter.markFocused(test);\n", " focusedTests.push(test);\n", " }\n", " }\n", " return focusedTests;\n" ], "file_path": "utils/testrunner/index.js", "type": "add", "edit_start_line_idx": 89 }
#!/bin/bash set -e set +x if [[ ("$1" == "-h") || ("$1" == "--help") ]]; then echo "usage: $(basename $0) [output-absolute-path]" echo echo "Generate distributable .zip archive from ./checkout folder that was previously built." echo exit 0 fi ZIP_PATH=$1 if [[ $ZIP_PATH != /* ]]; then echo "ERROR: path $ZIP_PATH is not absolute" exit 1 fi if [[ $ZIP_PATH != *.zip ]]; then echo "ERROR: path $ZIP_PATH must have .zip extension" exit 1 fi if [[ -f $ZIP_PATH ]]; then echo "ERROR: path $ZIP_PATH exists; can't do anything." exit 1 fi if ! [[ -d $(dirname $ZIP_PATH) ]]; then echo "ERROR: folder for path $($ZIP_PATH) does not exist." exit 1 fi trap "cd $(pwd -P)" EXIT cd "$(dirname $0)" cd checkout OBJ_FOLDER="obj-build-playwright" ./mach package node ../install-preferences.js $PWD/$OBJ_FOLDER/dist/firefox if ! [[ -d $OBJ_FOLDER/dist/firefox ]]; then echo "ERROR: cannot find $OBJ_FOLDER/dist/firefox folder in the checkout/. Did you build?" exit 1; fi # Copy the libstdc++ version we linked against. # TODO(aslushnikov): this won't be needed with official builds. if [[ "$(uname)" == "Linux" ]]; then cp /usr/lib/x86_64-linux-gnu/libstdc++.so.6 $OBJ_FOLDER/dist/firefox/libstdc++.so.6 fi # tar resulting directory and cleanup TMP. cd $OBJ_FOLDER/dist zip -r $ZIP_PATH firefox
browser_patches/firefox/archive.sh
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017601055151317269, 0.00016975478501990438, 0.0001662967260926962, 0.00016898394096642733, 0.000003096039563388331 ]
{ "id": 0, "code_window": [ " * specific language governing permissions and limitations\n", " * under the License.\n", " */\n", "import React, { useState, useEffect } from 'react';\n", "import { useSelector, useDispatch } from 'react-redux';\n", "import {\n", " t,\n", " SupersetTheme,\n", " css,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isEmpty } from 'lodash';\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 20 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { t, SupersetTheme, css, styled, useTheme, FeatureFlag, isFeatureEnabled, getExtensionsRegistry, usePrevious, } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import { Switch } from 'src/components/Switch'; import { AlertObject } from 'src/features/alerts/types'; import { Menu } from 'src/components/Menu'; import Checkbox from 'src/components/Checkbox'; import { noOp } from 'src/utils/common'; import { NoAnimationDropdown } from 'src/components/Dropdown'; import DeleteModal from 'src/components/DeleteModal'; import ReportModal from 'src/components/ReportModal'; import { ChartState } from 'src/explore/types'; import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; import { fetchUISpecificReport, toggleActive, deleteActiveReport, } from 'src/reports/actions/reports'; import { reportSelector } from 'src/views/CRUD/hooks'; import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index'; const extensionsRegistry = getExtensionsRegistry(); const deleteColor = (theme: SupersetTheme) => css` color: ${theme.colors.error.base}; `; const onMenuHover = (theme: SupersetTheme) => css` & .ant-menu-item { padding: 5px 12px; margin-top: 0px; margin-bottom: 4px; :hover { color: ${theme.colors.grayscale.dark1}; } } :hover { background-color: ${theme.colors.secondary.light5}; } `; const onMenuItemHover = (theme: SupersetTheme) => css` &:hover { color: ${theme.colors.grayscale.dark1}; background-color: ${theme.colors.secondary.light5}; } `; const StyledDropdownItemWithIcon = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; > *:first-child { margin-right: ${({ theme }) => theme.gridUnit}px; } `; const DropdownItemExtension = extensionsRegistry.get( 'report-modal.dropdown.item.icon', ); export enum CreationMethod { CHARTS = 'charts', DASHBOARDS = 'dashboards', } export interface HeaderReportProps { dashboardId?: number; chart?: ChartState; useTextMenu?: boolean; setShowReportSubMenu?: (show: boolean) => void; setIsDropdownVisible?: (visible: boolean) => void; isDropdownVisible?: boolean; showReportSubMenu?: boolean; } export default function HeaderReportDropDown({ dashboardId, chart, useTextMenu = false, setShowReportSubMenu, setIsDropdownVisible, isDropdownVisible, }: HeaderReportProps) { const dispatch = useDispatch(); const report = useSelector<any, AlertObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isReportActive: boolean = report?.active || false; const user: UserWithPermissionsAndRoles = useSelector< any, UserWithPermissionsAndRoles >(state => state.user); const canAddReports = () => { if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) { return false; } if (!user?.userId) { // this is in the case that there is an anonymous user. return false; } const roles = Object.keys(user.roles || []); const permissions = roles.map(key => user.roles[key].filter( perms => perms[0] === 'menu_access' && perms[1] === 'Manage', ), ); return permissions.some(permission => permission.length > 0); }; const [currentReportDeleting, setCurrentReportDeleting] = useState<AlertObject | null>(null); const theme = useTheme(); const prevDashboard = usePrevious(dashboardId); const [showModal, setShowModal] = useState<boolean>(false); const toggleActiveKey = async (data: AlertObject, checked: boolean) => { if (data?.id) { dispatch(toggleActive(data, checked)); } }; const handleReportDelete = async (report: AlertObject) => { await dispatch(deleteActiveReport(report)); setCurrentReportDeleting(null); }; const shouldFetch = canAddReports() && !!((dashboardId && prevDashboard !== dashboardId) || chart?.id); useEffect(() => { if (shouldFetch) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: dashboardId ? 'dashboard_id' : 'chart_id', creationMethod: dashboardId ? 'dashboards' : 'charts', resourceId: dashboardId || chart?.id, }), ); } }, []); const showReportSubMenu = report && setShowReportSubMenu && canAddReports(); useEffect(() => { if (showReportSubMenu) { setShowReportSubMenu(true); } else if (!report && setShowReportSubMenu) { setShowReportSubMenu(false); } }, [report]); const handleShowMenu = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setShowModal(true); } }; const handleDeleteMenuClick = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setCurrentReportDeleting(report); } }; const textMenu = () => report ? ( isDropdownVisible && ( <Menu selectable={false} css={{ border: 'none' }}> <Menu.Item css={onMenuItemHover} onClick={() => toggleActiveKey(report, !isReportActive)} > <MenuItemWithCheckboxContainer> <Checkbox checked={isReportActive} onChange={noOp} /> {t('Email reports active')} </MenuItemWithCheckboxContainer> </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleShowMenu}> {t('Edit email report')} </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}> {t('Delete email report')} </Menu.Item> </Menu> ) ) : ( <Menu selectable={false} css={onMenuHover}> <Menu.Item onClick={handleShowMenu}> {DropdownItemExtension ? ( <StyledDropdownItemWithIcon> <div>{t('Set up an email report')}</div> <DropdownItemExtension /> </StyledDropdownItemWithIcon> ) : ( t('Set up an email report') )} </Menu.Item> <Menu.Divider /> </Menu> ); const menu = () => ( <Menu selectable={false} css={{ width: '200px' }}> <Menu.Item> {t('Email reports active')} <Switch data-test="toggle-active" checked={isReportActive} onClick={(checked: boolean) => toggleActiveKey(report, checked)} size="small" css={{ marginLeft: theme.gridUnit * 2 }} /> </Menu.Item> <Menu.Item onClick={() => setShowModal(true)}> {t('Edit email report')} </Menu.Item> <Menu.Item onClick={() => setCurrentReportDeleting(report)} css={deleteColor} > {t('Delete email report')} </Menu.Item> </Menu> ); const iconMenu = () => report ? ( <> <NoAnimationDropdown overlay={menu()} trigger={['click']} getPopupContainer={(triggerNode: any) => triggerNode.closest('.action-button') } > <span role="button" className="action-button action-schedule-report" tabIndex={0} > <Icons.Calendar /> </span> </NoAnimationDropdown> </> ) : ( <span role="button" title={t('Schedule email report')} tabIndex={0} className="action-button action-schedule-report" onClick={() => setShowModal(true)} > <Icons.Calendar /> </span> ); return ( <> {canAddReports() && ( <> <ReportModal userId={user.userId} show={showModal} onHide={() => setShowModal(false)} userEmail={user.email} dashboardId={dashboardId} chart={chart} creationMethod={ dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS } /> {useTextMenu ? textMenu() : iconMenu()} {currentReportDeleting && ( <DeleteModal description={t( 'This action will permanently delete %s.', currentReportDeleting?.name, )} onConfirm={() => { if (currentReportDeleting) { handleReportDelete(currentReportDeleting); } }} onHide={() => setCurrentReportDeleting(null)} open title={t('Delete Report?')} /> )} </> )} </> ); }
superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.003699093358591199, 0.00036702683428302407, 0.0001646165328565985, 0.00017308637325186282, 0.0006741028628312051 ]
{ "id": 0, "code_window": [ " * specific language governing permissions and limitations\n", " * under the License.\n", " */\n", "import React, { useState, useEffect } from 'react';\n", "import { useSelector, useDispatch } from 'react-redux';\n", "import {\n", " t,\n", " SupersetTheme,\n", " css,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isEmpty } from 'lodash';\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 20 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # isort:skip_file import pytest import tests.integration_tests.test_app # pylint: disable=unused-import from superset import db from superset.embedded.dao import EmbeddedDAO from superset.models.dashboard import Dashboard from tests.integration_tests.base_tests import SupersetTestCase from tests.integration_tests.fixtures.world_bank_dashboard import ( load_world_bank_dashboard_with_slices, load_world_bank_data, ) class TestEmbeddedDAO(SupersetTestCase): @pytest.mark.usefixtures("load_world_bank_dashboard_with_slices") def test_upsert(self): dash = db.session.query(Dashboard).filter_by(slug="world_health").first() assert not dash.embedded EmbeddedDAO.upsert(dash, ["test.example.com"]) assert dash.embedded self.assertEqual(dash.embedded[0].allowed_domains, ["test.example.com"]) original_uuid = dash.embedded[0].uuid self.assertIsNotNone(original_uuid) EmbeddedDAO.upsert(dash, []) self.assertEqual(dash.embedded[0].allowed_domains, []) self.assertEqual(dash.embedded[0].uuid, original_uuid) @pytest.mark.usefixtures("load_world_bank_dashboard_with_slices") def test_get_by_uuid(self): dash = db.session.query(Dashboard).filter_by(slug="world_health").first() uuid = str(EmbeddedDAO.upsert(dash, ["test.example.com"]).uuid) db.session.expire_all() embedded = EmbeddedDAO.find_by_id(uuid) self.assertIsNotNone(embedded)
tests/integration_tests/embedded/dao_tests.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017461608513258398, 0.00017077986558433622, 0.0001647343160584569, 0.00017185366596095264, 0.000003594954932850669 ]
{ "id": 0, "code_window": [ " * specific language governing permissions and limitations\n", " * under the License.\n", " */\n", "import React, { useState, useEffect } from 'react';\n", "import { useSelector, useDispatch } from 'react-redux';\n", "import {\n", " t,\n", " SupersetTheme,\n", " css,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isEmpty } from 'lodash';\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 20 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitationsxw * under the License. */ import { PostProcessingContribution } from '@superset-ui/core'; import { PostProcessingFactory } from './types'; /* eslint-disable @typescript-eslint/no-unused-vars */ export const contributionOperator: PostProcessingFactory<PostProcessingContribution> = (formData, queryObject) => { if (formData.contributionMode) { return { operation: 'contribution', options: { orientation: formData.contributionMode, }, }; } return undefined; };
superset-frontend/packages/superset-ui-chart-controls/src/operators/contributionOperator.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017809748533181846, 0.0001747041824273765, 0.0001709849020699039, 0.000174867149326019, 0.000002604324663479929 ]
{ "id": 0, "code_window": [ " * specific language governing permissions and limitations\n", " * under the License.\n", " */\n", "import React, { useState, useEffect } from 'react';\n", "import { useSelector, useDispatch } from 'react-redux';\n", "import {\n", " t,\n", " SupersetTheme,\n", " css,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isEmpty } from 'lodash';\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 20 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { snakeCase, isEqual } from 'lodash'; import PropTypes from 'prop-types'; import React from 'react'; import { SuperChart, logging, Behavior, t, isFeatureEnabled, FeatureFlag, getChartMetadataRegistry, } from '@superset-ui/core'; import { Logger, LOG_ACTIONS_RENDER_CHART } from 'src/logger/LogUtils'; import { EmptyStateBig, EmptyStateSmall } from 'src/components/EmptyState'; import { ChartSource } from 'src/types/ChartSource'; import ChartContextMenu from './ChartContextMenu'; const propTypes = { annotationData: PropTypes.object, actions: PropTypes.object, chartId: PropTypes.number.isRequired, datasource: PropTypes.object, initialValues: PropTypes.object, formData: PropTypes.object.isRequired, latestQueryFormData: PropTypes.object, labelColors: PropTypes.object, sharedLabelColors: PropTypes.object, height: PropTypes.number, width: PropTypes.number, setControlValue: PropTypes.func, vizType: PropTypes.string.isRequired, triggerRender: PropTypes.bool, // state chartAlert: PropTypes.string, chartStatus: PropTypes.string, queriesResponse: PropTypes.arrayOf(PropTypes.object), triggerQuery: PropTypes.bool, chartIsStale: PropTypes.bool, // dashboard callbacks addFilter: PropTypes.func, setDataMask: PropTypes.func, onFilterMenuOpen: PropTypes.func, onFilterMenuClose: PropTypes.func, ownState: PropTypes.object, postTransformProps: PropTypes.func, source: PropTypes.oneOf([ChartSource.Dashboard, ChartSource.Explore]), emitCrossFilters: PropTypes.bool, }; const BLANK = {}; const BIG_NO_RESULT_MIN_WIDTH = 300; const BIG_NO_RESULT_MIN_HEIGHT = 220; const behaviors = [Behavior.INTERACTIVE_CHART]; const defaultProps = { addFilter: () => BLANK, onFilterMenuOpen: () => BLANK, onFilterMenuClose: () => BLANK, initialValues: BLANK, setControlValue() {}, triggerRender: false, }; class ChartRenderer extends React.Component { constructor(props) { super(props); this.state = { showContextMenu: props.source === ChartSource.Dashboard && (isFeatureEnabled(FeatureFlag.DRILL_TO_DETAIL) || isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS)), inContextMenu: false, }; this.hasQueryResponseChange = false; this.contextMenuRef = React.createRef(); this.handleAddFilter = this.handleAddFilter.bind(this); this.handleRenderSuccess = this.handleRenderSuccess.bind(this); this.handleRenderFailure = this.handleRenderFailure.bind(this); this.handleSetControlValue = this.handleSetControlValue.bind(this); this.handleOnContextMenu = this.handleOnContextMenu.bind(this); this.handleContextMenuSelected = this.handleContextMenuSelected.bind(this); this.handleContextMenuClosed = this.handleContextMenuClosed.bind(this); this.onContextMenuFallback = this.onContextMenuFallback.bind(this); this.hooks = { onAddFilter: this.handleAddFilter, onContextMenu: this.state.showContextMenu ? this.handleOnContextMenu : undefined, onError: this.handleRenderFailure, setControlValue: this.handleSetControlValue, onFilterMenuOpen: this.props.onFilterMenuOpen, onFilterMenuClose: this.props.onFilterMenuClose, setDataMask: dataMask => { this.props.actions?.updateDataMask(this.props.chartId, dataMask); }, }; } shouldComponentUpdate(nextProps, nextState) { const resultsReady = nextProps.queriesResponse && ['success', 'rendered'].indexOf(nextProps.chartStatus) > -1 && !nextProps.queriesResponse?.[0]?.error; if (resultsReady) { if (!isEqual(this.state, nextState)) { return true; } this.hasQueryResponseChange = nextProps.queriesResponse !== this.props.queriesResponse; return ( this.hasQueryResponseChange || !isEqual(nextProps.datasource, this.props.datasource) || nextProps.annotationData !== this.props.annotationData || nextProps.ownState !== this.props.ownState || nextProps.filterState !== this.props.filterState || nextProps.height !== this.props.height || nextProps.width !== this.props.width || nextProps.triggerRender || nextProps.labelColors !== this.props.labelColors || nextProps.sharedLabelColors !== this.props.sharedLabelColors || nextProps.formData.color_scheme !== this.props.formData.color_scheme || nextProps.formData.stack !== this.props.formData.stack || nextProps.cacheBusterProp !== this.props.cacheBusterProp || nextProps.emitCrossFilters !== this.props.emitCrossFilters ); } return false; } handleAddFilter(col, vals, merge = true, refresh = true) { this.props.addFilter(col, vals, merge, refresh); } handleRenderSuccess() { const { actions, chartStatus, chartId, vizType } = this.props; if (['loading', 'rendered'].indexOf(chartStatus) < 0) { actions.chartRenderingSucceeded(chartId); } // only log chart render time which is triggered by query results change // currently we don't log chart re-render time, like window resize etc if (this.hasQueryResponseChange) { actions.logEvent(LOG_ACTIONS_RENDER_CHART, { slice_id: chartId, viz_type: vizType, start_offset: this.renderStartTime, ts: new Date().getTime(), duration: Logger.getTimestamp() - this.renderStartTime, }); } } handleRenderFailure(error, info) { const { actions, chartId } = this.props; logging.warn(error); actions.chartRenderingFailed( error.toString(), chartId, info ? info.componentStack : null, ); // only trigger render log when query is changed if (this.hasQueryResponseChange) { actions.logEvent(LOG_ACTIONS_RENDER_CHART, { slice_id: chartId, has_err: true, error_details: error.toString(), start_offset: this.renderStartTime, ts: new Date().getTime(), duration: Logger.getTimestamp() - this.renderStartTime, }); } } handleSetControlValue(...args) { const { setControlValue } = this.props; if (setControlValue) { setControlValue(...args); } } handleOnContextMenu(offsetX, offsetY, filters) { this.contextMenuRef.current.open(offsetX, offsetY, filters); this.setState({ inContextMenu: true }); } handleContextMenuSelected() { this.setState({ inContextMenu: false }); } handleContextMenuClosed() { this.setState({ inContextMenu: false }); } // When viz plugins don't handle `contextmenu` event, fallback handler // calls `handleOnContextMenu` with no `filters` param. onContextMenuFallback(event) { if (!this.state.inContextMenu) { event.preventDefault(); this.handleOnContextMenu(event.clientX, event.clientY); } } render() { const { chartAlert, chartStatus, chartId, emitCrossFilters } = this.props; // Skip chart rendering if (chartStatus === 'loading' || !!chartAlert || chartStatus === null) { return null; } this.renderStartTime = Logger.getTimestamp(); const { width, height, datasource, annotationData, initialValues, ownState, filterState, chartIsStale, formData, latestQueryFormData, queriesResponse, postTransformProps, } = this.props; const currentFormData = chartIsStale && latestQueryFormData ? latestQueryFormData : formData; const vizType = currentFormData.viz_type || this.props.vizType; // It's bad practice to use unprefixed `vizType` as classnames for chart // container. It may cause css conflicts as in the case of legacy table chart. // When migrating charts, we should gradually add a `superset-chart-` prefix // to each one of them. const snakeCaseVizType = snakeCase(vizType); const chartClassName = vizType === 'table' ? `superset-chart-${snakeCaseVizType}` : snakeCaseVizType; const webpackHash = process.env.WEBPACK_MODE === 'development' ? `-${ // eslint-disable-next-line camelcase typeof __webpack_require__ !== 'undefined' && // eslint-disable-next-line camelcase, no-undef typeof __webpack_require__.h === 'function' && // eslint-disable-next-line no-undef __webpack_require__.h() }` : ''; let noResultsComponent; const noResultTitle = t('No results were returned for this query'); const noResultDescription = this.props.source === ChartSource.Explore ? t( 'Make sure that the controls are configured properly and the datasource contains data for the selected time range', ) : undefined; const noResultImage = 'chart.svg'; if (width > BIG_NO_RESULT_MIN_WIDTH && height > BIG_NO_RESULT_MIN_HEIGHT) { noResultsComponent = ( <EmptyStateBig title={noResultTitle} description={noResultDescription} image={noResultImage} /> ); } else { noResultsComponent = ( <EmptyStateSmall title={noResultTitle} image={noResultImage} /> ); } // Check for Behavior.DRILL_TO_DETAIL to tell if chart can receive Drill to // Detail props or if it'll cause side-effects (e.g. excessive re-renders). const drillToDetailProps = getChartMetadataRegistry() .get(formData.viz_type) ?.behaviors.find(behavior => behavior === Behavior.DRILL_TO_DETAIL) ? { inContextMenu: this.state.inContextMenu } : {}; return ( <> {this.state.showContextMenu && ( <ChartContextMenu ref={this.contextMenuRef} id={chartId} formData={currentFormData} onSelection={this.handleContextMenuSelected} onClose={this.handleContextMenuClosed} /> )} <div onContextMenu={ this.state.showContextMenu ? this.onContextMenuFallback : undefined } > <SuperChart disableErrorBoundary key={`${chartId}${webpackHash}`} id={`chart-id-${chartId}`} className={chartClassName} chartType={vizType} width={width} height={height} annotationData={annotationData} datasource={datasource} initialValues={initialValues} formData={currentFormData} ownState={ownState} filterState={filterState} hooks={this.hooks} behaviors={behaviors} queriesData={queriesResponse} onRenderSuccess={this.handleRenderSuccess} onRenderFailure={this.handleRenderFailure} noResults={noResultsComponent} postTransformProps={postTransformProps} emitCrossFilters={emitCrossFilters} {...drillToDetailProps} /> </div> </> ); } } ChartRenderer.propTypes = propTypes; ChartRenderer.defaultProps = defaultProps; export default ChartRenderer;
superset-frontend/src/components/Chart/ChartRenderer.jsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0002287732932018116, 0.0001738670252962038, 0.00016352582315448672, 0.00017318007303401828, 0.000009966445759346243 ]
{ "id": 1, "code_window": [ " setIsDropdownVisible?: (visible: boolean) => void;\n", " isDropdownVisible?: boolean;\n", " showReportSubMenu?: boolean;\n", "}\n", "\n", "export default function HeaderReportDropDown({\n", " dashboardId,\n", " chart,\n", " useTextMenu = false,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Same instance to be used in useEffects\n", "const EMPTY_OBJECT = {};\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 105 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable camelcase */ // eslint-disable-next-line import/no-extraneous-dependencies import { SET_REPORT, ADD_REPORT, EDIT_REPORT } from '../actions/reports'; export default function reportsReducer(state = {}, action) { const actionHandlers = { [SET_REPORT]() { const { report, resourceId, creationMethod, filterField } = action; // For now report count should only be one, but we are checking in case // functionality changes. const reportObject = report.result?.find( report => report[filterField] === resourceId, ); if (reportObject) { return { ...state, [creationMethod]: { ...state[creationMethod], [resourceId]: reportObject, }, }; } if (state?.[creationMethod]?.[resourceId]) { // remove the empty report from state const newState = { ...state }; delete newState[creationMethod][resourceId]; return newState; } return { ...state }; }, [ADD_REPORT]() { const { result, id } = action.json; const report = { ...result, id }; const reportTypeId = report.dashboard || report.chart; // this is the id of either the chart or the dashboard associated with the report. return { ...state, [report.creation_method]: { ...state[report.creation_method], [reportTypeId]: report, }, }; }, [EDIT_REPORT]() { const report = { ...action.json.result, id: action.json.id, }; const reportTypeId = report.dashboard || report.chart; return { ...state, [report.creation_method]: { ...state[report.creation_method], [reportTypeId]: report, }, }; }, }; if (action.type in actionHandlers) { return actionHandlers[action.type](); } return state; }
superset-frontend/src/reports/reducers/reports.js
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0006589931435883045, 0.000257315143244341, 0.00016774340474512428, 0.00017400426440872252, 0.0001669112971285358 ]
{ "id": 1, "code_window": [ " setIsDropdownVisible?: (visible: boolean) => void;\n", " isDropdownVisible?: boolean;\n", " showReportSubMenu?: boolean;\n", "}\n", "\n", "export default function HeaderReportDropDown({\n", " dashboardId,\n", " chart,\n", " useTextMenu = false,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Same instance to be used in useEffects\n", "const EMPTY_OBJECT = {};\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 105 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable no-magic-numbers, sort-keys */ import React from 'react'; import { SuperChart } from '@superset-ui/core'; import WorldMapChartPlugin from '@superset-ui/legacy-plugin-chart-world-map'; import data from './data'; new WorldMapChartPlugin().configure({ key: 'world-map' }).register(); export default { title: 'Legacy Chart Plugins/legacy-plugin-chart-world-map', }; export const basic = () => ( <SuperChart chartType="world-map" width={400} height={400} queriesData={[{ data }]} formData={{ maxBubbleSize: '25', showBubbles: true, colorPicker: {}, }} /> );
superset-frontend/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-world-map/Stories.tsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017675322305876762, 0.00017285383364651352, 0.00016707440954633057, 0.00017387904517818242, 0.000003384077444934519 ]
{ "id": 1, "code_window": [ " setIsDropdownVisible?: (visible: boolean) => void;\n", " isDropdownVisible?: boolean;\n", " showReportSubMenu?: boolean;\n", "}\n", "\n", "export default function HeaderReportDropDown({\n", " dashboardId,\n", " chart,\n", " useTextMenu = false,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Same instance to be used in useEffects\n", "const EMPTY_OBJECT = {};\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 105 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable sort-keys */ /* eslint-disable no-magic-numbers */ import React from 'react'; import { SuperChart } from '@superset-ui/core'; import { HexChartPlugin } from '@superset-ui/legacy-preset-chart-deckgl'; import payload from './payload'; import dummyDatasource from '../../../../shared/dummyDatasource'; new HexChartPlugin().configure({ key: 'deck_hex' }).register(); export default { title: 'Legacy Chart Plugins/legacy-preset-chart-deckgl/HexChartPlugin', }; export const HexChartViz = () => ( <SuperChart chartType="deck_hex" width={400} height={400} datasource={dummyDatasource} queriesData={[payload]} formData={{ datasource: '5__table', viz_type: 'deck_hex', slice_id: 68, url_params: {}, granularity_sqla: 'dttm', time_grain_sqla: null, time_range: '+:+', spatial: { latCol: 'LAT', lonCol: 'LON', type: 'latlong' }, size: 'count', row_limit: 5000, filter_nulls: true, adhoc_filters: [], mapbox_style: 'mapbox://styles/mapbox/streets-v9', viewport: { bearing: -2.3984797349335167, latitude: 37.789795085160335, longitude: -122.40632230075536, pitch: 54.08961642447763, zoom: 13.835465702403654, }, color_picker: { a: 1, b: 0, g: 255, r: 14 }, autozoom: true, grid_size: 40, extruded: true, js_agg_function: 'sum', js_columns: [], js_data_mutator: '', js_tooltip: '', js_onclick_href: '', }} /> );
superset-frontend/packages/superset-ui-demo/storybook/stories/plugins/legacy-preset-chart-deckgl/Hex/Stories.tsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017701582692097872, 0.00017233891412615776, 0.000167799080372788, 0.00017276582366321236, 0.00000285822966361593 ]
{ "id": 1, "code_window": [ " setIsDropdownVisible?: (visible: boolean) => void;\n", " isDropdownVisible?: boolean;\n", " showReportSubMenu?: boolean;\n", "}\n", "\n", "export default function HeaderReportDropDown({\n", " dashboardId,\n", " chart,\n", " useTextMenu = false,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Same instance to be used in useEffects\n", "const EMPTY_OBJECT = {};\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 105 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { QueryObject, SqlaFormData } from '@superset-ui/core'; import { contributionOperator } from '@superset-ui/chart-controls'; const formData: SqlaFormData = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', datasource: 'foo', viz_type: 'table', }; const queryObject: QueryObject = { metrics: [ 'count(*)', { label: 'sum(val)', expressionType: 'SQL', sqlExpression: 'sum(val)' }, ], time_range: '2015 : 2016', granularity: 'month', }; test('should skip contributionOperator', () => { expect(contributionOperator(formData, queryObject)).toEqual(undefined); }); test('should do contributionOperator', () => { expect( contributionOperator({ ...formData, contributionMode: 'row' }, queryObject), ).toEqual({ operation: 'contribution', options: { orientation: 'row', }, }); });
superset-frontend/packages/superset-ui-chart-controls/test/operators/contributionOperator.test.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0001777802244760096, 0.00017479130474384874, 0.00017201808805111796, 0.00017463721451349556, 0.000001858252176134556 ]
{ "id": 2, "code_window": [ " const dispatch = useDispatch();\n", " const report = useSelector<any, AlertObject>(state => {\n", " const resourceType = dashboardId\n", " ? CreationMethod.DASHBOARDS\n", " : CreationMethod.CHARTS;\n", " return reportSelector(state, resourceType, dashboardId || chart?.id);\n", " });\n", "\n", " const isReportActive: boolean = report?.active || false;\n", " const user: UserWithPermissionsAndRoles = useSelector<\n", " any,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return (\n", " reportSelector(state, resourceType, dashboardId || chart?.id) ||\n", " EMPTY_OBJECT\n", " );\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 118 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { t, SupersetTheme, css, styled, useTheme, FeatureFlag, isFeatureEnabled, getExtensionsRegistry, usePrevious, } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import { Switch } from 'src/components/Switch'; import { AlertObject } from 'src/features/alerts/types'; import { Menu } from 'src/components/Menu'; import Checkbox from 'src/components/Checkbox'; import { noOp } from 'src/utils/common'; import { NoAnimationDropdown } from 'src/components/Dropdown'; import DeleteModal from 'src/components/DeleteModal'; import ReportModal from 'src/components/ReportModal'; import { ChartState } from 'src/explore/types'; import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; import { fetchUISpecificReport, toggleActive, deleteActiveReport, } from 'src/reports/actions/reports'; import { reportSelector } from 'src/views/CRUD/hooks'; import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index'; const extensionsRegistry = getExtensionsRegistry(); const deleteColor = (theme: SupersetTheme) => css` color: ${theme.colors.error.base}; `; const onMenuHover = (theme: SupersetTheme) => css` & .ant-menu-item { padding: 5px 12px; margin-top: 0px; margin-bottom: 4px; :hover { color: ${theme.colors.grayscale.dark1}; } } :hover { background-color: ${theme.colors.secondary.light5}; } `; const onMenuItemHover = (theme: SupersetTheme) => css` &:hover { color: ${theme.colors.grayscale.dark1}; background-color: ${theme.colors.secondary.light5}; } `; const StyledDropdownItemWithIcon = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; > *:first-child { margin-right: ${({ theme }) => theme.gridUnit}px; } `; const DropdownItemExtension = extensionsRegistry.get( 'report-modal.dropdown.item.icon', ); export enum CreationMethod { CHARTS = 'charts', DASHBOARDS = 'dashboards', } export interface HeaderReportProps { dashboardId?: number; chart?: ChartState; useTextMenu?: boolean; setShowReportSubMenu?: (show: boolean) => void; setIsDropdownVisible?: (visible: boolean) => void; isDropdownVisible?: boolean; showReportSubMenu?: boolean; } export default function HeaderReportDropDown({ dashboardId, chart, useTextMenu = false, setShowReportSubMenu, setIsDropdownVisible, isDropdownVisible, }: HeaderReportProps) { const dispatch = useDispatch(); const report = useSelector<any, AlertObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isReportActive: boolean = report?.active || false; const user: UserWithPermissionsAndRoles = useSelector< any, UserWithPermissionsAndRoles >(state => state.user); const canAddReports = () => { if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) { return false; } if (!user?.userId) { // this is in the case that there is an anonymous user. return false; } const roles = Object.keys(user.roles || []); const permissions = roles.map(key => user.roles[key].filter( perms => perms[0] === 'menu_access' && perms[1] === 'Manage', ), ); return permissions.some(permission => permission.length > 0); }; const [currentReportDeleting, setCurrentReportDeleting] = useState<AlertObject | null>(null); const theme = useTheme(); const prevDashboard = usePrevious(dashboardId); const [showModal, setShowModal] = useState<boolean>(false); const toggleActiveKey = async (data: AlertObject, checked: boolean) => { if (data?.id) { dispatch(toggleActive(data, checked)); } }; const handleReportDelete = async (report: AlertObject) => { await dispatch(deleteActiveReport(report)); setCurrentReportDeleting(null); }; const shouldFetch = canAddReports() && !!((dashboardId && prevDashboard !== dashboardId) || chart?.id); useEffect(() => { if (shouldFetch) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: dashboardId ? 'dashboard_id' : 'chart_id', creationMethod: dashboardId ? 'dashboards' : 'charts', resourceId: dashboardId || chart?.id, }), ); } }, []); const showReportSubMenu = report && setShowReportSubMenu && canAddReports(); useEffect(() => { if (showReportSubMenu) { setShowReportSubMenu(true); } else if (!report && setShowReportSubMenu) { setShowReportSubMenu(false); } }, [report]); const handleShowMenu = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setShowModal(true); } }; const handleDeleteMenuClick = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setCurrentReportDeleting(report); } }; const textMenu = () => report ? ( isDropdownVisible && ( <Menu selectable={false} css={{ border: 'none' }}> <Menu.Item css={onMenuItemHover} onClick={() => toggleActiveKey(report, !isReportActive)} > <MenuItemWithCheckboxContainer> <Checkbox checked={isReportActive} onChange={noOp} /> {t('Email reports active')} </MenuItemWithCheckboxContainer> </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleShowMenu}> {t('Edit email report')} </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}> {t('Delete email report')} </Menu.Item> </Menu> ) ) : ( <Menu selectable={false} css={onMenuHover}> <Menu.Item onClick={handleShowMenu}> {DropdownItemExtension ? ( <StyledDropdownItemWithIcon> <div>{t('Set up an email report')}</div> <DropdownItemExtension /> </StyledDropdownItemWithIcon> ) : ( t('Set up an email report') )} </Menu.Item> <Menu.Divider /> </Menu> ); const menu = () => ( <Menu selectable={false} css={{ width: '200px' }}> <Menu.Item> {t('Email reports active')} <Switch data-test="toggle-active" checked={isReportActive} onClick={(checked: boolean) => toggleActiveKey(report, checked)} size="small" css={{ marginLeft: theme.gridUnit * 2 }} /> </Menu.Item> <Menu.Item onClick={() => setShowModal(true)}> {t('Edit email report')} </Menu.Item> <Menu.Item onClick={() => setCurrentReportDeleting(report)} css={deleteColor} > {t('Delete email report')} </Menu.Item> </Menu> ); const iconMenu = () => report ? ( <> <NoAnimationDropdown overlay={menu()} trigger={['click']} getPopupContainer={(triggerNode: any) => triggerNode.closest('.action-button') } > <span role="button" className="action-button action-schedule-report" tabIndex={0} > <Icons.Calendar /> </span> </NoAnimationDropdown> </> ) : ( <span role="button" title={t('Schedule email report')} tabIndex={0} className="action-button action-schedule-report" onClick={() => setShowModal(true)} > <Icons.Calendar /> </span> ); return ( <> {canAddReports() && ( <> <ReportModal userId={user.userId} show={showModal} onHide={() => setShowModal(false)} userEmail={user.email} dashboardId={dashboardId} chart={chart} creationMethod={ dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS } /> {useTextMenu ? textMenu() : iconMenu()} {currentReportDeleting && ( <DeleteModal description={t( 'This action will permanently delete %s.', currentReportDeleting?.name, )} onConfirm={() => { if (currentReportDeleting) { handleReportDelete(currentReportDeleting); } }} onHide={() => setCurrentReportDeleting(null)} open title={t('Delete Report?')} /> )} </> )} </> ); }
superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.9983764886856079, 0.23898199200630188, 0.00016847964434418827, 0.00020867626881226897, 0.40569868683815 ]
{ "id": 2, "code_window": [ " const dispatch = useDispatch();\n", " const report = useSelector<any, AlertObject>(state => {\n", " const resourceType = dashboardId\n", " ? CreationMethod.DASHBOARDS\n", " : CreationMethod.CHARTS;\n", " return reportSelector(state, resourceType, dashboardId || chart?.id);\n", " });\n", "\n", " const isReportActive: boolean = report?.active || false;\n", " const user: UserWithPermissionsAndRoles = useSelector<\n", " any,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return (\n", " reportSelector(state, resourceType, dashboardId || chart?.id) ||\n", " EMPTY_OBJECT\n", " );\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 118 }
{ "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "features": [ { "type": "Feature", "properties": { "ISO": "EC-E", "NAME_1": "Esmeraldas" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -78.828684048999946, 1.43431224200009 ], [ -78.769967610999856, 1.394102072000067 ], [ -78.664676879999945, 1.266642151000042 ], [ -78.602148396999951, 1.263644918000111 ], [ -78.570057332999852, 1.19584543900001 ], [ -78.540601766999941, 1.205353902000084 ], [ -78.47812265099995, 1.18711995600006 ], [ -78.495694139073237, 1.171350002100894 ], [ -78.494143846361396, 1.100759996076931 ], [ -78.53062740822827, 1.021384995920812 ], [ -78.534787359948666, 0.964024155690197 ], [ -78.523496059595459, 0.928367417922004 ], [ -78.442105678734094, 0.871936754577575 ], [ -78.450632290447857, 0.789047756049115 ], [ -78.513444993591577, 0.759902249289382 ], [ -78.424225633006529, 0.586217759941633 ], [ -78.426318528976935, 0.558519192206973 ], [ -78.448616908843235, 0.542034410459678 ], [ -78.497399462315343, 0.542137763247183 ], [ -78.539205694986833, 0.51505931223744 ], [ -78.667414923659805, 0.372949124202705 ], [ -78.719608120018734, 0.402714749486108 ], [ -78.859961310665938, 0.422816881493873 ], [ -78.987576260136279, 0.267477524967774 ], [ -79.01070146410126, 0.267425849023709 ], [ -79.040208706066892, 0.295021063970921 ], [ -79.14506018677821, 0.317655341520776 ], [ -79.221877203869838, 0.31558828397209 ], [ -79.3522310053566, 0.231665758467955 ], [ -79.303655158358879, 0.173271389463025 ], [ -79.369878506188115, 0.035967109194701 ], [ -79.450364548585014, -0.000929863822194 ], [ -79.420702276988493, -0.03338266427852 ], [ -79.43315629822456, -0.050125827544889 ], [ -79.492997606254505, -0.025631198920678 ], [ -79.595549486319726, -0.013590589733951 ], [ -79.618416306966992, 0.045372219152569 ], [ -79.567850917685689, 0.116530666856761 ], [ -79.623945686044578, 0.15389272696774 ], [ -79.649938931436509, 0.145676174515813 ], [ -79.659602423812771, 0.175958563736742 ], [ -79.682133347675858, 0.170429185558476 ], [ -79.702106289373717, 0.187430732142559 ], [ -79.652186856138485, 0.259157619728342 ], [ -79.71223486974344, 0.303651028472189 ], [ -79.695595059264576, 0.347110907542344 ], [ -79.717583380768417, 0.370778712967194 ], [ -79.75269751707674, 0.369280097098795 ], [ -79.814580044233651, 0.322667954862197 ], [ -79.889665899661509, 0.318688870295091 ], [ -79.929405076583009, 0.260294501290218 ], [ -79.973975999692641, 0.284272365976904 ], [ -79.999521235313509, 0.345101779873908 ], [ -79.993316209999932, 0.378119208000044 ], [ -80.043568488999938, 0.458929755000042 ], [ -80.043365037999934, 0.501206773000092 ], [ -80.016957160999937, 0.55890534100007 ], [ -80.036366339999915, 0.625230210000041 ], [ -80.090321417999917, 0.652167059000078 ], [ -80.104969855999911, 0.679673570000091 ], [ -80.097279425999943, 0.780340887000079 ], [ -80.046213344999899, 0.839667059000078 ], [ -79.981312628999945, 0.832220770000049 ], [ -79.862172003999945, 0.87641022300005 ], [ -79.765614386999914, 0.955145575000074 ], [ -79.655751105999911, 1.003607489000046 ], [ -79.670074022999927, 0.921616929000038 ], [ -79.614857550999943, 0.845282294000071 ], [ -79.648304816999939, 0.907416083000044 ], [ -79.632679816999939, 0.986029364000046 ], [ -79.614857550999943, 0.996079820000091 ], [ -79.571766730999911, 0.983710028000075 ], [ -79.435047980999911, 1.078029690000051 ], [ -79.364654100999928, 1.072455145000049 ], [ -79.272206183999913, 1.092962958000044 ], [ -79.248158331999946, 1.080267645000049 ], [ -79.165760870999918, 1.099798895000049 ], [ -79.057240363999938, 1.21751536700009 ], [ -79.013050910999937, 1.192775783000059 ], [ -78.991688605999911, 1.119696356000077 ], [ -78.962147589999915, 1.144680080000057 ], [ -78.954579230999911, 1.20734284100007 ], [ -78.928944464999915, 1.243150132000039 ], [ -78.901682094999899, 1.236314195000091 ], [ -78.871693488999938, 1.288967190000051 ], [ -78.812855597999942, 1.277289130000042 ], [ -78.881947394999941, 1.319281317000048 ], [ -78.83234615799995, 1.381333726000094 ], [ -78.828684048999946, 1.43431224200009 ] ] ], [ [ [ -78.901682094999899, 1.374172268000052 ], [ -78.899281378999945, 1.271429755000042 ], [ -78.912505662999934, 1.245266018000052 ], [ -78.936390753999945, 1.256822007000039 ], [ -78.956898566999939, 1.236314195000091 ], [ -78.995432094999899, 1.286810614000046 ], [ -78.901682094999899, 1.374172268000052 ] ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-C", "NAME_1": "Carchi" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -78.47812265099995, 1.18711995600006 ], [ -78.349218099999945, 1.05580230700005 ], [ -78.250154378999923, 1.019628804000121 ], [ -78.077942667999935, 0.900773011000126 ], [ -77.91826249199994, 0.874418030000072 ], [ -77.903224649999856, 0.832095032000069 ], [ -77.847982543999962, 0.809254048000057 ], [ -77.703185180999924, 0.843102112000054 ], [ -77.673316202999899, 0.819641012000076 ], [ -77.666804972999927, 0.747707418000047 ], [ -77.645565959999942, 0.7162881470001 ], [ -77.579833536999899, 0.670916239000078 ], [ -77.514137794999868, 0.660531216000038 ], [ -77.570014207589622, 0.624716702513808 ], [ -77.669543015697627, 0.638669337819692 ], [ -77.673005337226527, 0.616965237155966 ], [ -77.649957647627332, 0.584977524692988 ], [ -77.775143806141728, 0.448293362049014 ], [ -77.791861130986376, 0.370985419441524 ], [ -77.814081997386268, 0.345663966718689 ], [ -78.000453050168119, 0.46865387647523 ], [ -78.130806850755562, 0.505602525436188 ], [ -78.168608161337545, 0.651381741474154 ], [ -78.258421800225904, 0.775405178206427 ], [ -78.360301886722652, 0.852816474500685 ], [ -78.428618129622976, 0.865373846725618 ], [ -78.523496059595459, 0.928367417922004 ], [ -78.53062740822827, 1.021384995920812 ], [ -78.494143846361396, 1.100759996076931 ], [ -78.495694139073237, 1.171350002100894 ], [ -78.47812265099995, 1.18711995600006 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-U", "NAME_1": "Sucumbios" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -77.509346883999939, 0.661201070000033 ], [ -77.468057413999929, 0.650865784000118 ], [ -77.434726115999865, 0.433824769000054 ], [ -77.397467406999851, 0.387626038000093 ], [ -77.206936401999968, 0.334192607000077 ], [ -77.117432820999852, 0.357550354000125 ], [ -77.082861287999947, 0.348868713000073 ], [ -77.04462072799987, 0.305667216000131 ], [ -76.945867065999948, 0.287063701000079 ], [ -76.882460082999927, 0.240141500000036 ], [ -76.797865763999937, 0.249960022000096 ], [ -76.734355427999873, 0.233113505000119 ], [ -76.736887573999866, 0.272904358000034 ], [ -76.724536905999912, 0.277555237000087 ], [ -76.626868448999886, 0.258538310000034 ], [ -76.565425171999976, 0.21606028300009 ], [ -76.425692098999917, 0.242725322000126 ], [ -76.408018757999912, 0.254507548000035 ], [ -76.416390339999879, 0.401888733000078 ], [ -76.365385701999912, 0.406953023000057 ], [ -76.300480102999899, 0.461626689000099 ], [ -76.223740600999946, 0.406746318000089 ], [ -76.136304077999881, 0.396721090000071 ], [ -76.119560913999919, 0.351762594000149 ], [ -76.053466756999882, 0.363544820000058 ], [ -75.951974243999899, 0.203967997000092 ], [ -75.81787390199986, 0.100098369000079 ], [ -75.75384680199997, 0.073019918000028 ], [ -75.626774454999946, 0.078911031000118 ], [ -75.464923868999875, -0.039738056999923 ], [ -75.283487914999881, -0.107020771999899 ], [ -75.330746012999896, -0.144641214999922 ], [ -75.402576253999911, -0.14577809599993 ], [ -75.429499674999931, -0.163658141999889 ], [ -75.539260417999856, -0.120043232999933 ], [ -75.623002075999921, -0.106607360999888 ], [ -75.643207560999912, -0.128828226999929 ], [ -75.619565592999976, -0.180918069999976 ], [ -75.578973754999936, -0.182675068999856 ], [ -75.484767619999872, -0.247684020999912 ], [ -75.452728230999952, -0.360648701999907 ], [ -75.405625162999854, -0.442400817999925 ], [ -75.34735998599993, -0.470926208999884 ], [ -75.290980997999895, -0.527976989999971 ], [ -75.272041584999869, -0.525703225999948 ], [ -75.257029581999888, -0.56198008199992 ], [ -75.257649699999945, -0.633190204999963 ], [ -75.282091843763567, -0.643526299898838 ], [ -75.289739956333904, -0.618359876806892 ], [ -75.382757534332711, -0.601771742272092 ], [ -75.403014695971422, -0.565494886879549 ], [ -75.542411872210096, -0.542343844492848 ], [ -75.574451259717875, -0.49516326327398 ], [ -75.588533088031568, -0.499969171040448 ], [ -75.654368863132504, -0.455010675202516 ], [ -75.69958574138883, -0.464157402741932 ], [ -75.748316617118178, -0.422609551589517 ], [ -75.831644864319003, -0.436665540582226 ], [ -75.886912807679892, -0.413411147206716 ], [ -75.947632615752582, -0.422867934007968 ], [ -75.937193977020399, -0.561670831044012 ], [ -75.994425625142469, -0.553299248961196 ], [ -76.077986416340025, -0.501622816539737 ], [ -76.102842780170135, -0.441936537241418 ], [ -76.274382696704095, -0.443125094747359 ], [ -76.410214200425003, -0.510304456985125 ], [ -76.427396613263056, -0.485706474674089 ], [ -76.502172411227775, -0.473665867285945 ], [ -76.575733812365513, -0.405091241067908 ], [ -76.621855028186985, -0.424883314713213 ], [ -76.714097459829873, -0.341942641140008 ], [ -76.767608404903967, -0.252645766189175 ], [ -76.917547573561649, -0.078599541635526 ], [ -76.945427009348975, -0.065680434204694 ], [ -77.073610398700907, -0.102112319228183 ], [ -77.147249315103807, -0.083043715095357 ], [ -77.19742713075749, -0.090588473978926 ], [ -77.284010993012885, -0.047335299584404 ], [ -77.349975959323046, -0.131619561193816 ], [ -77.374212206428183, -0.141076347995067 ], [ -77.446455857951491, -0.124849948666224 ], [ -77.44392371330872, -0.060409437545502 ], [ -77.46487850603819, -0.023460788584543 ], [ -77.588979458035567, -0.100045260780178 ], [ -77.64086259603198, -0.081028333490792 ], [ -77.758917405913564, -0.075033868218441 ], [ -77.778864509189759, -0.046818535646935 ], [ -77.778942022656224, 0.015813300343552 ], [ -77.845191209806501, 0.035967109194701 ], [ -77.863898077833994, 0.074155992505041 ], [ -77.970429043365641, 0.119734605067947 ], [ -77.835501879008518, 0.26918284731056 ], [ -77.852477587170881, 0.29264394805972 ], [ -77.791861130986376, 0.370985419441524 ], [ -77.783747932221274, 0.43470246015039 ], [ -77.649957647627332, 0.584977524692988 ], [ -77.673005337226527, 0.616965237155966 ], [ -77.669543015697627, 0.638669337819692 ], [ -77.570014207589622, 0.624716702513808 ], [ -77.509346883999939, 0.661201070000033 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-D", "NAME_1": "Orellana" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -75.266641397999877, -0.642698668999941 ], [ -75.293978230999926, -0.667916767999898 ], [ -75.297027139999841, -0.746981709999972 ], [ -75.252068644999923, -0.933430276999943 ], [ -75.227263957999895, -0.969810484999925 ], [ -75.34872941099988, -0.974978128999922 ], [ -75.406400309999952, -0.915136819999873 ], [ -75.41257564299994, -0.92392181299995 ], [ -75.5807400973776, -1.54663979598979 ], [ -75.602330694605882, -1.496187431704641 ], [ -75.702996385175027, -1.445596204900937 ], [ -75.717569139004524, -1.45567311022586 ], [ -75.747541469862938, -1.405288588097847 ], [ -75.833014288978234, -1.383997897684822 ], [ -75.844176398122272, -1.357332858724476 ], [ -75.880246547939805, -1.342863457682427 ], [ -75.878463711231291, -1.328445732584498 ], [ -75.89962521043509, -1.347307631142257 ], [ -75.950190598817073, -1.344517104081092 ], [ -76.004812587930587, -1.310152275706969 ], [ -76.056411505986205, -1.301160576899122 ], [ -76.063542852820376, -1.276149183438065 ], [ -76.105943365593816, -1.273048598014384 ], [ -76.155630255731694, -1.293099054078084 ], [ -76.245263028366026, -1.282143649609736 ], [ -76.284201218711246, -1.311082451693778 ], [ -76.358331060629951, -1.283125501540667 ], [ -76.362749395668061, -1.262661635226323 ], [ -76.463673468655657, -1.251344495552019 ], [ -76.511267462823128, -1.187782484474099 ], [ -76.515065681136264, -1.084377943687173 ], [ -76.545373907879537, -1.05156340892421 ], [ -76.594673225289114, -1.046344089108459 ], [ -76.760942145163881, -1.097865491898915 ], [ -76.810732388089207, -1.089648939446988 ], [ -76.850006477017303, -1.156828301684811 ], [ -77.056221280287843, -1.093524672125909 ], [ -77.074463060321989, -1.039626152524932 ], [ -77.04283708396423, -0.987949721002849 ], [ -77.061879848775959, -0.963713473897712 ], [ -77.036144985802423, -0.925214532224913 ], [ -77.113995530769103, -0.904233901073667 ], [ -77.186885139237745, -0.860360609954171 ], [ -77.196316087617333, -0.835762627643135 ], [ -77.176704881125374, -0.786928399126339 ], [ -77.1186205722816, -0.730342706150964 ], [ -77.124201626403931, -0.707915134176119 ], [ -77.16481930156948, -0.722797947267452 ], [ -77.209545254310001, -0.764707532726447 ], [ -77.254994675663738, -0.833850599725395 ], [ -77.49921749509133, -0.945316664232678 ], [ -77.566164313332365, -0.947177016206354 ], [ -77.579005907296789, -0.931364028027474 ], [ -77.528466356437207, -0.841188653033896 ], [ -77.533272264203617, -0.780778904223041 ], [ -77.496607836082774, -0.69137867558544 ], [ -77.575285204248758, -0.577018731229487 ], [ -77.621716478432745, -0.544772638146753 ], [ -77.566474371694881, -0.49573170315557 ], [ -77.551539882659426, -0.458007907838692 ], [ -77.448006150663332, -0.507823988286418 ], [ -77.404029506756331, -0.504154962081827 ], [ -77.356564703798028, -0.425658461069133 ], [ -77.329047004115921, -0.424056491513909 ], [ -77.32323340509754, -0.387417900915409 ], [ -77.273184780653082, -0.360391126749107 ], [ -77.254374558938707, -0.294865410910006 ], [ -77.259955613960415, -0.246341240755669 ], [ -77.297911953274024, -0.19027231171782 ], [ -77.299410570041744, -0.058549085571826 ], [ -77.284010993012885, -0.047335299584404 ], [ -77.19742713075749, -0.090588473978926 ], [ -77.147249315103807, -0.083043715095357 ], [ -77.073610398700907, -0.102112319228183 ], [ -76.931706916241183, -0.069607842827679 ], [ -76.767608404903967, -0.252645766189175 ], [ -76.714097459829873, -0.341942641140008 ], [ -76.621855028186985, -0.424883314713213 ], [ -76.575733812365513, -0.405091241067908 ], [ -76.502172411227775, -0.473665867285945 ], [ -76.427396613263056, -0.485706474674089 ], [ -76.410214200425003, -0.510304456985125 ], [ -76.274382696704095, -0.443125094747359 ], [ -76.102842780170135, -0.441936537241418 ], [ -76.077986416340025, -0.501622816539737 ], [ -75.994425625142469, -0.553299248961196 ], [ -75.937193977020399, -0.561670831044012 ], [ -75.947632615752582, -0.422867934007968 ], [ -75.886912807679892, -0.413411147206716 ], [ -75.831644864319003, -0.436665540582226 ], [ -75.748316617118178, -0.422609551589517 ], [ -75.69958574138883, -0.464157402741932 ], [ -75.654368863132504, -0.455010675202516 ], [ -75.588533088031568, -0.499969171040448 ], [ -75.574451259717875, -0.49516326327398 ], [ -75.542411872210096, -0.542343844492848 ], [ -75.403014695971422, -0.565494886879549 ], [ -75.382757534332711, -0.601771742272092 ], [ -75.289739956333904, -0.618359876806892 ], [ -75.285140754142503, -0.641355888663327 ], [ -75.266641397999877, -0.642698668999941 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-Y", "NAME_1": "Pastaza" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -75.5807400973776, -1.54663979598979 ], [ -76.091242228999931, -2.12891286199995 ], [ -76.625266479999937, -2.537673441999928 ], [ -76.725905524120606, -2.577051690083465 ], [ -76.831351284034497, -2.529974459853463 ], [ -76.918271043973505, -2.540361422641524 ], [ -76.95904374877, -2.528269137510677 ], [ -77.017128059412414, -2.477212822713625 ], [ -77.034620530612983, -2.430032239696118 ], [ -77.123064744842111, -2.313656914634919 ], [ -77.384263272432065, -2.154338473541713 ], [ -77.710625779755901, -2.02246021866415 ], [ -77.753155483738567, -1.950785007022489 ], [ -77.838318243592028, -1.912751152443718 ], [ -77.914127570331118, -1.668114922765483 ], [ -77.948544073749986, -1.655609225585295 ], [ -78.008979661881881, -1.668114922765483 ], [ -78.078458624765688, -1.506109306499297 ], [ -78.129282395566065, -1.45624155010745 ], [ -78.172561408382251, -1.446991468881208 ], [ -78.116828376128638, -1.357694593930376 ], [ -78.116518316866802, -1.23330942109294 ], [ -77.941955329275004, -1.223852634291632 ], [ -77.897177699691099, -1.23713347692842 ], [ -77.882062344401675, -1.214085789127864 ], [ -77.831109382392071, -1.221837252687067 ], [ -77.695613776354662, -1.151660657813125 ], [ -77.547069871677195, -1.13574431684674 ], [ -77.445525681964625, -1.087323499479908 ], [ -77.373023648022922, -1.079313652602991 ], [ -77.233755662993417, -1.024536634757908 ], [ -77.051647914719467, -1.010377292078374 ], [ -77.074463060321989, -1.039626152524932 ], [ -77.056221280287843, -1.093524672125909 ], [ -76.867938198688933, -1.157396741566401 ], [ -76.850006477017303, -1.156828301684811 ], [ -76.810732388089207, -1.089648939446988 ], [ -76.760942145163881, -1.097865491898915 ], [ -76.594673225289114, -1.046344089108459 ], [ -76.545373907879537, -1.05156340892421 ], [ -76.515065681136264, -1.084377943687173 ], [ -76.511267462823128, -1.187782484474099 ], [ -76.463673468655657, -1.251344495552019 ], [ -76.362749395668061, -1.262661635226323 ], [ -76.358331060629951, -1.283125501540667 ], [ -76.284201218711246, -1.311082451693778 ], [ -76.245263028366026, -1.282143649609736 ], [ -76.155630255731694, -1.293099054078084 ], [ -76.105943365593816, -1.273048598014384 ], [ -76.063542852820376, -1.276149183438065 ], [ -76.056411505986205, -1.301160576899122 ], [ -76.004812587930587, -1.310152275706969 ], [ -75.950190598817073, -1.344517104081092 ], [ -75.89962521043509, -1.347307631142257 ], [ -75.878463711231291, -1.328445732584498 ], [ -75.880246547939805, -1.342863457682427 ], [ -75.844176398122272, -1.357332858724476 ], [ -75.833014288978234, -1.383997897684822 ], [ -75.747541469862938, -1.405288588097847 ], [ -75.717569139004524, -1.45567311022586 ], [ -75.702996385175027, -1.445596204900937 ], [ -75.602330694605882, -1.496187431704641 ], [ -75.5807400973776, -1.54663979598979 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-S", "NAME_1": "Morona Santiago" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -76.669661558234338, -2.564588924739098 ], [ -77.86782629399994, -2.990255634999897 ], [ -77.941465209999961, -3.054541116999957 ], [ -78.042544311999904, -3.189933369999949 ], [ -78.104917765999858, -3.245433857999927 ], [ -78.148170938999925, -3.322431742999939 ], [ -78.196410888999935, -3.363669534999943 ], [ -78.154527140999846, -3.456790465999859 ], [ -78.163725545999938, -3.477254332999919 ], [ -78.226305704999845, -3.507019958999905 ], [ -78.257182372999921, -3.409558206999918 ], [ -78.33397355199989, -3.384546813999918 ], [ -78.36172379599995, -3.408524677999935 ], [ -78.355290079999889, -3.44552500399989 ], [ -78.375871848407087, -3.529348454167859 ], [ -78.645271573424338, -3.539370212165579 ], [ -78.684364794299825, -3.579316094662033 ], [ -78.822185839404938, -3.547018323836596 ], [ -78.864043748919869, -3.497305597075638 ], [ -78.873603889407946, -3.449608250120662 ], [ -78.84939347982521, -3.389146823567046 ], [ -78.938974575616157, -3.3227426076852 ], [ -78.937579311635886, -3.287809339429486 ], [ -78.671652390645306, -3.090767103918722 ], [ -78.656097784884878, -3.008446547070491 ], [ -78.56992733377939, -2.839206231182629 ], [ -78.598685268710142, -2.785927830105265 ], [ -78.566387498784025, -2.720815524516865 ], [ -78.421435105945363, -2.627022800162081 ], [ -78.427842984166375, -2.601494642763555 ], [ -78.472103848014171, -2.568266696850571 ], [ -78.510266892902791, -2.585216566591271 ], [ -78.526364101921729, -2.622837009120701 ], [ -78.550264452242686, -2.612501723175967 ], [ -78.549101732259146, -2.562944024247315 ], [ -78.528043585842795, -2.562220553835516 ], [ -78.490242276160075, -2.505893243278535 ], [ -78.481224738031244, -2.380681248141116 ], [ -78.579900886316864, -2.311538181142168 ], [ -78.544631721276915, -2.286888522887011 ], [ -78.530162320234865, -2.240379733437976 ], [ -78.497812872565987, -2.210510756266387 ], [ -78.500577562104809, -2.127104993800458 ], [ -78.445800544259669, -2.075221855803989 ], [ -78.489544644169996, -1.964840996914461 ], [ -78.415647346248022, -1.854356785237485 ], [ -78.44835852732416, -1.755654798530145 ], [ -78.44758338096824, -1.705993747713308 ], [ -78.359397549157563, -1.621709487003216 ], [ -78.363092413783875, -1.541611015535921 ], [ -78.30653255923022, -1.484560234567198 ], [ -78.218553432994497, -1.482079765868491 ], [ -78.172561408382251, -1.446991468881208 ], [ -78.129282395566065, -1.45624155010745 ], [ -78.069776984320356, -1.520733738071556 ], [ -78.008979661881881, -1.668114922765483 ], [ -77.948544073749986, -1.655609225585295 ], [ -77.914127570331118, -1.668114922765483 ], [ -77.829481574415126, -1.924843437574566 ], [ -77.753155483738567, -1.950785007022489 ], [ -77.710625779755901, -2.02246021866415 ], [ -77.384263272432065, -2.154338473541713 ], [ -77.123064744842111, -2.313656914634919 ], [ -76.992891812307278, -2.506048272010162 ], [ -76.918271043973505, -2.540361422641524 ], [ -76.831351284034497, -2.529974459853463 ], [ -76.725905524120606, -2.577051690083465 ], [ -76.669661558234338, -2.564588924739098 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-Z", "NAME_1": "Zamora Chinchipe" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -78.375871848407087, -3.529348454167859 ], [ -78.402393147999902, -3.594353128999927 ], [ -78.400739501999936, -3.679825947999859 ], [ -78.425854248999968, -3.689437763999962 ], [ -78.419678914999878, -3.791033629999959 ], [ -78.480682942999863, -3.849531351999957 ], [ -78.497632812999967, -3.949576924999946 ], [ -78.562073323999869, -3.979755960999853 ], [ -78.576620239999926, -4.10005869499993 ], [ -78.682427734999891, -4.326918232999972 ], [ -78.673151814999954, -4.401539000999946 ], [ -78.637210855999882, -4.435128681999885 ], [ -78.66979284699994, -4.493419697999911 ], [ -78.68167842699998, -4.567110290999935 ], [ -78.853063314999929, -4.652273049999877 ], [ -78.898641927999932, -4.694234313999885 ], [ -78.928614257999868, -4.74746103899993 ], [ -78.90021805899994, -4.843682555999891 ], [ -78.910811726999924, -4.863526305999883 ], [ -78.980342366999935, -4.873964944999912 ], [ -79.009281168999877, -4.960109557999914 ], [ -79.06392899599993, -5.011372578999939 ], [ -79.104159097999883, -4.980056660999935 ], [ -79.303216715999952, -4.961246438999922 ], [ -79.341043863999914, -4.904247333999933 ], [ -79.378070027999883, -4.884816995999955 ], [ -79.395329956999973, -4.847609964999947 ], [ -79.450572062999896, -4.810196227999882 ], [ -79.460823144172764, -4.770455598247281 ], [ -79.33158627009027, -4.60819386225694 ], [ -79.318357103397602, -4.513419285071961 ], [ -79.29151119728391, -4.482258395808344 ], [ -79.266422288557749, -4.477659193616887 ], [ -79.205056525338364, -4.50298064454114 ], [ -79.156093105612342, -4.469545993952465 ], [ -79.113537564107276, -4.407999362680471 ], [ -79.102633837381688, -4.206047864817094 ], [ -79.154775356897176, -4.138765150691142 ], [ -79.135887620817016, -4.032104993950327 ], [ -79.139608323865048, -3.947303969302766 ], [ -79.119247810338152, -3.883121839701175 ], [ -79.193558519410146, -3.731038100028286 ], [ -79.152863328979436, -3.71010914482116 ], [ -79.143949143638054, -3.676777846120729 ], [ -79.102246262854749, -3.636005140424913 ], [ -79.065478481946343, -3.619417005890114 ], [ -79.046306525026068, -3.474722995469847 ], [ -79.055091519158282, -3.412246189110363 ], [ -78.938974575616157, -3.3227426076852 ], [ -78.84939347982521, -3.389146823567046 ], [ -78.873603889407946, -3.449608250120662 ], [ -78.864043748919869, -3.497305597075638 ], [ -78.822185839404938, -3.547018323836596 ], [ -78.684364794299825, -3.579316094662033 ], [ -78.645271573424338, -3.539370212165579 ], [ -78.375871848407087, -3.529348454167859 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-L", "NAME_1": "Loja" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -80.325505737999919, -4.015412698999938 ], [ -80.259075683999868, -3.943685810999852 ], [ -80.181147623999891, -3.907925719999923 ], [ -80.165073793999909, -3.880695936999885 ], [ -80.01363766134898, -3.86239959096838 ], [ -79.934831101973771, -3.829533380261296 ], [ -79.741328700559052, -3.832840671259987 ], [ -79.606272345892023, -3.751915377492708 ], [ -79.559763557342308, -3.794858493524657 ], [ -79.446385464017908, -3.80514210352527 ], [ -79.415302090019452, -3.793359876756938 ], [ -79.396362677995171, -3.7656096330781 ], [ -79.402538011320132, -3.721839694746109 ], [ -79.366338671192693, -3.653316746270832 ], [ -79.379722866616987, -3.620295505033539 ], [ -79.427988654352873, -3.589444675031757 ], [ -79.485943772886799, -3.628408704697961 ], [ -79.467753668796774, -3.511671644430862 ], [ -79.422769335436442, -3.449349866802947 ], [ -79.456617398074457, -3.415760185684007 ], [ -79.457754278736957, -3.328013603445072 ], [ -79.317866176982477, -3.346772149215326 ], [ -79.281692674377382, -3.449918307583857 ], [ -79.236553311386217, -3.4607703592647 ], [ -79.184902717386478, -3.44206348943851 ], [ -79.130487433847975, -3.537509861091223 ], [ -79.120436366944773, -3.610942071019792 ], [ -79.102246262854749, -3.636005140424913 ], [ -79.143949143638054, -3.676777846120729 ], [ -79.152863328979436, -3.71010914482116 ], [ -79.193558519410146, -3.731038100028286 ], [ -79.119247810338152, -3.883121839701175 ], [ -79.139608323865048, -3.947303969302766 ], [ -79.135887620817016, -4.032104993950327 ], [ -79.154775356897176, -4.138765150691142 ], [ -79.102633837381688, -4.206047864817094 ], [ -79.113537564107276, -4.407999362680471 ], [ -79.156093105612342, -4.469545993952465 ], [ -79.205056525338364, -4.50298064454114 ], [ -79.266422288557749, -4.477659193616887 ], [ -79.29151119728391, -4.482258395808344 ], [ -79.318357103397602, -4.513419285071961 ], [ -79.33158627009027, -4.60819386225694 ], [ -79.460823144172764, -4.770455598247281 ], [ -79.527854166999902, -4.618063252999974 ], [ -79.507209431999883, -4.531556904999974 ], [ -79.557774821999914, -4.516570739999906 ], [ -79.657975422999925, -4.438746031999955 ], [ -79.795744791999965, -4.484738056999944 ], [ -79.832874308999862, -4.478950296999884 ], [ -79.904084431999905, -4.398645120999959 ], [ -79.9820124929999, -4.388619892999941 ], [ -80.079655110999909, -4.309038187999917 ], [ -80.140245727999883, -4.283096617999959 ], [ -80.205047973999882, -4.298186136999959 ], [ -80.255406656999867, -4.386759541999936 ], [ -80.382866577999891, -4.476263121999949 ], [ -80.469967203999971, -4.446084085999942 ], [ -80.4885448819999, -4.395957946999928 ], [ -80.345271972999882, -4.198450621999967 ], [ -80.469605468999958, -4.213230081999882 ], [ -80.512212686999931, -4.064195251999891 ], [ -80.481077636999885, -3.99877288799992 ], [ -80.447694661999918, -3.982753193999955 ], [ -80.407102823999878, -3.982443135999887 ], [ -80.325505737999919, -4.015412698999938 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-O", "NAME_1": "El Oro" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -80.165073793999909, -3.880695936999885 ], [ -80.188769897999862, -3.857696226999892 ], [ -80.226312825999855, -3.749279072999926 ], [ -80.216390950999966, -3.631560159999935 ], [ -80.224995076999903, -3.59187265999995 ], [ -80.249980631999904, -3.577713317999908 ], [ -80.240291300999871, -3.514047952999917 ], [ -80.271633056999889, -3.485522562999961 ], [ -80.265664428999855, -3.426404723999894 ], [ -80.340728666670429, -3.393497653515368 ], [ -80.341053839999915, -3.368584893999923 ], [ -80.30687415299991, -3.320733330999929 ], [ -80.314320441999939, -3.376071872999944 ], [ -80.286447719999899, -3.320733330999929 ], [ -80.259103969999899, -3.348077080999929 ], [ -80.135568813999896, -3.327569268999923 ], [ -80.059885219999899, -3.204034112999921 ], [ -80.037505662999934, -3.20826588299991 ], [ -80.039947068999936, -3.279880466999941 ], [ -80.029204881999931, -3.273532809999949 ], [ -79.953195766999897, -3.197442315999922 ], [ -79.933338995999918, -3.115411065999922 ], [ -79.89589342508755, -3.045437722386621 ], [ -79.760474819956983, -3.06467050483991 ], [ -79.638518438974756, -3.128852633542238 ], [ -79.600432909351298, -3.161718845148584 ], [ -79.594696824698701, -3.204351901918756 ], [ -79.632162237597186, -3.290909925752487 ], [ -79.667767300320634, -3.319848727836529 ], [ -79.614850632650587, -3.329873955418691 ], [ -79.507932095289959, -3.312975762521432 ], [ -79.457754278736957, -3.328013603445072 ], [ -79.456617398074457, -3.415760185684007 ], [ -79.422769335436442, -3.449349866802947 ], [ -79.467753668796774, -3.511671644430862 ], [ -79.48772660959537, -3.618693535478315 ], [ -79.481267056329557, -3.635333346856498 ], [ -79.427988654352873, -3.589444675031757 ], [ -79.373056606876901, -3.628357028753896 ], [ -79.368354050998619, -3.669078056706951 ], [ -79.402538011320132, -3.721839694746109 ], [ -79.40755062466161, -3.785505058611591 ], [ -79.446385464017908, -3.80514210352527 ], [ -79.559763557342308, -3.794858493524657 ], [ -79.606272345892023, -3.751915377492708 ], [ -79.741328700559052, -3.832840671259987 ], [ -79.934831101973771, -3.829533380261296 ], [ -80.01363766134898, -3.86239959096838 ], [ -80.165073793999909, -3.880695936999885 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-G", "NAME_1": "Guayas" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -80.059885219999899, -2.662774346999925 ], [ -80.014515753999945, -2.664239190999922 ], [ -79.902821417999917, -2.717461846999925 ], [ -79.907215949999909, -2.732354424999926 ], [ -79.995187954999949, -2.798028252999927 ], [ -80.131033119999927, -3.020920851999961 ], [ -80.203724738999938, -3.034112237999921 ], [ -80.26593990799995, -3.018487237999921 ], [ -80.262203789999944, -2.840848014999949 ], [ -80.210682745999918, -2.724867445999962 ], [ -80.059885219999899, -2.662774346999925 ] ] ], [ [ [ -79.89589342508755, -3.045437722386621 ], [ -79.874867316999939, -3.005466403999947 ], [ -79.881214972999942, -2.965427341999941 ], [ -79.834584113999938, -2.806817315999922 ], [ -79.776437954999949, -2.65943775799991 ], [ -79.726429816999939, -2.593845309999949 ], [ -79.745025193999936, -2.490166924999926 ], [ -79.789540167999917, -2.481052341999941 ], [ -79.839466925999943, -2.377048434999949 ], [ -79.839833136999914, -2.209567966999941 ], [ -79.868641730999911, -2.160902601999908 ], [ -79.861887173999946, -2.108005466999941 ], [ -79.818348761999914, -2.079847914999959 ], [ -79.765614386999914, -2.004978122999944 ], [ -79.831369594999899, -2.043552341999941 ], [ -79.834584113999938, -2.07000090899993 ], [ -79.874338344999899, -2.075372002999927 ], [ -79.891957160999937, -2.115899346999925 ], [ -79.901844855999911, -2.18482838299991 ], [ -79.863026495999918, -2.297133070999962 ], [ -79.878570115999935, -2.49187590899993 ], [ -79.896107550999943, -2.543389580999929 ], [ -79.933216925999943, -2.580254815999922 ], [ -79.998402472999942, -2.608168226999908 ], [ -80.063588019999941, -2.577243747999944 ], [ -80.068918423999946, -2.560804945999962 ], [ -80.02570553299995, -2.52507903399993 ], [ -80.001779751999948, -2.48015715899993 ], [ -79.97484290299991, -2.477227471999925 ], [ -79.943755662999934, -2.498304945999962 ], [ -79.929676886999914, -2.484144789999959 ], [ -79.936350063999896, -2.462985934999949 ], [ -79.940825975999928, -2.483982028999947 ], [ -79.977935350999928, -2.45671965899993 ], [ -80.034331834999932, -2.47389088299991 ], [ -80.008941209999932, -2.358819268999923 ], [ -79.977935350999928, -2.347426039999959 ], [ -79.950021938999896, -2.307224216999941 ], [ -80.012684699999909, -2.326429945999962 ], [ -80.076039191999939, -2.457696221999925 ], [ -80.175119594999899, -2.586683851999908 ], [ -80.231800910999937, -2.628676039999959 ], [ -80.270008917999917, -2.605075778999947 ], [ -80.27961178299995, -2.61256275799991 ], [ -80.27961178299995, -2.649183851999908 ], [ -80.244252081999946, -2.699476820999962 ], [ -80.255482550999943, -2.730238539999959 ], [ -80.278431769999941, -2.727146091999941 ], [ -80.467884894999941, -2.617933851999908 ], [ -80.542747415450577, -2.52976243927536 ], [ -80.41076665945377, -2.416674574272179 ], [ -80.276516835683424, -2.367938822418751 ], [ -80.232020041891417, -2.299776686444943 ], [ -80.213445776201581, -2.110307938660469 ], [ -80.288407472127119, -2.017346144708824 ], [ -80.478271172476639, -1.931161345819476 ], [ -80.516087613252751, -1.840817559282925 ], [ -80.437539436295936, -1.835701593153999 ], [ -80.396069098609985, -1.746198011728893 ], [ -80.329303148421559, -1.687131850054868 ], [ -80.299744228713166, -1.697622165630435 ], [ -80.221170214234007, -1.680672295889735 ], [ -80.226001960422138, -1.61891895904273 ], [ -80.267911546780454, -1.59519947677444 ], [ -80.283259446965872, -1.567655937771349 ], [ -80.222048713377433, -1.559439386218685 ], [ -80.188174812317698, -1.536546726250435 ], [ -80.201636522107776, -1.480684502787597 ], [ -80.191973028832194, -1.431178480702329 ], [ -80.130891485553605, -1.397743829214335 ], [ -80.124328578601023, -1.333975111662085 ], [ -80.043299933844878, -1.271808362765739 ], [ -79.983742844856408, -1.118432711900141 ], [ -79.975164558097845, -1.138224785545447 ], [ -79.937699144300041, -1.142875664580288 ], [ -79.853053148384049, -1.088305352310158 ], [ -79.712183193799319, -0.872246188610745 ], [ -79.535889045443071, -0.837467949985921 ], [ -79.517078823728696, -0.860463961842356 ], [ -79.53278845912007, -0.959527682856276 ], [ -79.561675585260048, -0.986709485754147 ], [ -79.580950894068508, -1.050633232937344 ], [ -79.673761765592985, -1.114298597702145 ], [ -79.686396653982399, -1.146648043572384 ], [ -79.738305630400532, -1.184836927781987 ], [ -79.748149990829404, -1.235169773066559 ], [ -79.847317063731509, -1.399139093194606 ], [ -79.870545619584675, -1.519028415728826 ], [ -79.859693569702472, -1.633698418447239 ], [ -79.758872850401701, -1.696691989643625 ], [ -79.649525520286545, -1.906549980697037 ], [ -79.523615892259613, -1.885155937496506 ], [ -79.482429776313097, -1.897454929101684 ], [ -79.372953254089396, -1.970111992674333 ], [ -79.285930142262259, -2.107674656260372 ], [ -79.235493944190182, -2.154338473541713 ], [ -79.17164771227209, -2.16198658611205 ], [ -79.139944220649227, -2.146535333139127 ], [ -79.130074021798634, -2.203689466895412 ], [ -79.192008225798986, -2.266941419610816 ], [ -79.352644415607301, -2.303321627790922 ], [ -79.416387294737831, -2.347918388422897 ], [ -79.425146451347644, -2.421815688143511 ], [ -79.514314134189931, -2.495196222127959 ], [ -79.489741991199935, -2.51777882193511 ], [ -79.437393765210061, -2.497056573202315 ], [ -79.419100308332531, -2.545529066513211 ], [ -79.690556606602115, -2.825718682071511 ], [ -79.703579067719772, -2.874966321738384 ], [ -79.69484575133032, -2.957131849854989 ], [ -79.74884762192022, -3.023691094468461 ], [ -79.760474819956983, -3.06467050483991 ], [ -79.89589342508755, -3.045437722386621 ] ] ], [ [ [ -79.819639715999926, -2.485910851999961 ], [ -79.772570694999899, -2.541987347999907 ], [ -79.828701939999917, -2.592050637999932 ], [ -79.833236679999914, -2.636017324999955 ], [ -79.877239380999924, -2.649677722999911 ], [ -79.881801126999903, -2.62693980399996 ], [ -79.819639715999926, -2.485910851999961 ] ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-W", "NAME_1": "GalΓ‘pagos" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -89.661284959999932, -1.340101820999962 ], [ -89.614572719999899, -1.370049737999921 ], [ -89.613270636999914, -1.391696872999944 ], [ -89.67609615799995, -1.397556247999944 ], [ -89.756906704999949, -1.36060963299991 ], [ -89.736398891999897, -1.340101820999962 ], [ -89.661284959999932, -1.340101820999962 ] ] ], [ [ [ -90.380686001999948, -1.254489841999941 ], [ -90.367054816999939, -1.278741143999923 ], [ -90.432118292999917, -1.345961195999962 ], [ -90.475209113999938, -1.342054945999962 ], [ -90.524037238999938, -1.30592213299991 ], [ -90.471913214999915, -1.216729424999926 ], [ -90.380686001999948, -1.254489841999941 ] ] ], [ [ [ -89.308094855999911, -0.685642184999949 ], [ -89.257191535999937, -0.681573174999926 ], [ -89.273182745999918, -0.759942315999922 ], [ -89.331695115999935, -0.819431247999944 ], [ -89.367298956999946, -0.82976653399993 ], [ -89.420033331999946, -0.919366143999923 ], [ -89.544585740999935, -0.956638278999947 ], [ -89.629953579999949, -0.925876559999949 ], [ -89.604603644999941, -0.883070570999962 ], [ -89.55142167899993, -0.853610934999949 ], [ -89.540882941999939, -0.819431247999944 ], [ -89.47720292899993, -0.796807549999926 ], [ -89.413238084999932, -0.713474216999941 ], [ -89.366444464999915, -0.689629815999922 ], [ -89.308094855999911, -0.685642184999949 ] ] ], [ [ [ -90.191965298999946, -0.538262627999927 ], [ -90.180531378999945, -0.54851653399993 ], [ -90.198801235999952, -0.681573174999926 ], [ -90.259510870999918, -0.743340752999927 ], [ -90.313628709999932, -0.74382903399993 ], [ -90.337066209999932, -0.776950778999947 ], [ -90.428863084999932, -0.762465101999908 ], [ -90.48306230399993, -0.702732028999947 ], [ -90.544545050999943, -0.681573174999926 ], [ -90.52757727799991, -0.569919528999947 ], [ -90.460560675999943, -0.513848565999922 ], [ -90.407948370999918, -0.517754815999922 ], [ -90.26398678299995, -0.483005466999941 ], [ -90.24282792899993, -0.497247002999927 ], [ -90.240589972999942, -0.528008721999925 ], [ -90.191965298999946, -0.538262627999927 ] ] ], [ [ [ -91.401112433999913, -0.452894789999959 ], [ -91.507557745999918, -0.490411065999922 ], [ -91.606516079999949, -0.45631275799991 ], [ -91.651966925999943, -0.381117445999962 ], [ -91.668568488999938, -0.284926039999959 ], [ -91.580962693999936, -0.287204684999949 ], [ -91.474191860999895, -0.24928150799991 ], [ -91.455677863999938, -0.257582289999959 ], [ -91.399525519999941, -0.30787525799991 ], [ -91.401112433999913, -0.452894789999959 ] ] ], [ [ [ -90.565012173999946, -0.284926039999959 ], [ -90.551503058999913, -0.292738539999959 ], [ -90.558176235999952, -0.310804945999962 ], [ -90.586781378999945, -0.363702080999929 ], [ -90.604888475999928, -0.369805596999925 ], [ -90.740061001999948, -0.353936455999929 ], [ -90.795887824999909, -0.330661716999941 ], [ -90.818226691999939, -0.339613539999959 ], [ -90.848947719999899, -0.275648695999962 ], [ -90.874134894999941, -0.271254164999959 ], [ -90.831654425999943, -0.212660414999959 ], [ -90.82681230399993, -0.164157809999949 ], [ -90.777251756999931, -0.14771900799991 ], [ -90.632476365999935, -0.201267184999949 ], [ -90.551991339999915, -0.278090101999908 ], [ -90.565012173999946, -0.284926039999959 ] ] ], [ [ [ -90.811431443999936, -0.730645440999922 ], [ -90.791574673999946, -0.754001559999949 ], [ -90.829090949999909, -0.77467213299991 ], [ -90.860463019999941, -0.872653903999947 ], [ -90.858631964999915, -0.915459893999923 ], [ -90.880279100999928, -0.908786716999941 ], [ -90.928700324999909, -0.970310153999947 ], [ -90.993885870999918, -0.963474216999941 ], [ -91.159779425999943, -1.030205987999921 ], [ -91.399728969999899, -1.018487237999921 ], [ -91.43586178299995, -0.997491143999923 ], [ -91.445790167999917, -0.941501559999949 ], [ -91.477406378999945, -0.935479424999926 ], [ -91.502308722999942, -0.896254164999959 ], [ -91.465891079999949, -0.80787525799991 ], [ -91.310454881999931, -0.68328215899993 ], [ -91.234771287999934, -0.661879164999959 ], [ -91.157785610999895, -0.678806247999944 ], [ -91.086781378999945, -0.582452080999929 ], [ -91.106841600999928, -0.558689059999949 ], [ -91.161488410999937, -0.538262627999927 ], [ -91.208892381999931, -0.484633070999962 ], [ -91.238677537999934, -0.376153252999927 ], [ -91.374989386999914, -0.281914971999925 ], [ -91.373768683999913, -0.250176690999922 ], [ -91.40648352799991, -0.216403903999947 ], [ -91.40453040299991, -0.195896091999941 ], [ -91.380604620999918, -0.18873463299991 ], [ -91.405751105999911, -0.148044528999947 ], [ -91.423329230999911, -0.02857838299991 ], [ -91.476429816999939, -0.01108163899994 ], [ -91.563099738999938, -0.051771742999961 ], [ -91.603382941999939, -0.01421477699995 ], [ -91.604359503999945, 0.001450914000088 ], [ -91.504465298999946, 0.066148179000038 ], [ -91.497303839999915, 0.10610586100006 ], [ -91.452748175999943, 0.103745835000041 ], [ -91.368763800999943, 0.150620835000041 ], [ -91.339670376999948, 0.153794664000088 ], [ -91.323638475999928, 0.13930898600006 ], [ -91.28351803299995, 0.033189195000091 ], [ -91.247425910999937, -0.003838799999926 ], [ -91.20929928299995, -0.010674737999921 ], [ -91.173573370999918, -0.228448174999926 ], [ -91.128041144999941, -0.27076588299991 ], [ -91.124134894999941, -0.299574476999908 ], [ -91.005034959999932, -0.373142184999949 ], [ -90.956044074999909, -0.422133070999962 ], [ -90.949208136999914, -0.521416924999926 ], [ -90.990142381999931, -0.579196872999944 ], [ -90.967844204999949, -0.564548434999949 ], [ -90.956044074999909, -0.60711028399993 ], [ -90.892974412999934, -0.625746351999908 ], [ -90.894602016999897, -0.64812590899993 ], [ -90.859730597999942, -0.664157809999949 ], [ -90.859852667999917, -0.689629815999922 ], [ -90.811431443999936, -0.730645440999922 ] ] ], [ [ [ -90.513783331999946, 0.28351471600007 ], [ -90.544545050999943, 0.31085846600007 ], [ -90.542307094999899, 0.333563544000071 ], [ -90.504465298999946, 0.361029364000046 ], [ -90.436431443999936, 0.346625067000048 ], [ -90.407948370999918, 0.31085846600007 ], [ -90.454579230999911, 0.267401434000078 ], [ -90.513783331999946, 0.28351471600007 ] ] ], [ [ [ -90.797759568999936, 0.653509833000044 ], [ -90.756988084999932, 0.630601304000038 ], [ -90.744496222999942, 0.58539459800005 ], [ -90.760568813999896, 0.553697007000039 ], [ -90.805246548999946, 0.571600653000075 ], [ -90.797759568999936, 0.653509833000044 ] ] ], [ [ [ -91.819162563999896, 1.386419989000046 ], [ -91.810943162999934, 1.377183335000041 ], [ -91.817738410999937, 1.368068752000056 ], [ -91.825306769999941, 1.377020575000074 ], [ -91.819162563999896, 1.386419989000046 ] ] ], [ [ [ -91.822010870999918, 1.394476630000042 ], [ -91.817534959999932, 1.394761460000041 ], [ -91.820464647999927, 1.39134349200009 ], [ -91.822010870999918, 1.394476630000042 ] ] ], [ [ [ -92.011586066999939, 1.658636786000045 ], [ -92.00609290299991, 1.66437409100007 ], [ -91.999826626999948, 1.651190497000073 ], [ -92.006662563999896, 1.649603583000044 ], [ -92.011586066999939, 1.658636786000045 ] ] ], [ [ [ -89.957117753210582, 0.341870937337148 ], [ -89.936668733838701, 0.327995159529848 ], [ -89.944702239599451, 0.303895008840129 ], [ -89.952005426654637, 0.317770860016822 ], [ -89.970993712998279, 0.309737474712847 ], [ -89.957117753210582, 0.341870937337148 ] ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-SE", "NAME_1": "Santa Elena" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -80.542747415450577, -2.52976243927536 ], [ -80.656646287999934, -2.415785414999959 ], [ -80.803456183999913, -2.374769789999959 ], [ -80.86392167899993, -2.329278252999927 ], [ -80.913644985999952, -2.318780205999929 ], [ -80.934803839999915, -2.260918877999927 ], [ -81.010894334999932, -2.176690362999921 ], [ -81.001210089999915, -2.164483330999929 ], [ -80.949330206999946, -2.186211846999925 ], [ -80.931286318999923, -2.217333015999941 ], [ -80.906342922999897, -2.216258380999932 ], [ -80.780702356999939, -2.142843412999923 ], [ -80.744979189999924, -2.102914607999935 ], [ -80.737446656999907, -2.043497173999924 ], [ -80.762521938999896, -1.97389088299991 ], [ -80.733185043999924, -1.953769676999912 ], [ -80.733021613999938, -1.90398528399993 ], [ -80.782134568999936, -1.736993096999925 ], [ -80.818164557642575, -1.676979241717978 ], [ -80.624866502586997, -1.655867608003689 ], [ -80.563810797730127, -1.667339775510243 ], [ -80.539807094621722, -1.727387790913838 ], [ -80.561537034606431, -1.816994724227129 ], [ -80.516087613252751, -1.840817559282925 ], [ -80.478271172476639, -1.931161345819476 ], [ -80.288407472127119, -2.017346144708824 ], [ -80.213445776201581, -2.110307938660469 ], [ -80.232020041891417, -2.299776686444943 ], [ -80.276516835683424, -2.367938822418751 ], [ -80.41076665945377, -2.416674574272179 ], [ -80.542747415450577, -2.52976243927536 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-M", "NAME_1": "Manabi" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -80.818164557642575, -1.676979241717978 ], [ -80.855580206999946, -1.588311455999929 ], [ -80.816489555999908, -1.552254752999943 ], [ -80.82054602799991, -1.499932549999926 ], [ -80.770861664999927, -1.477829952999912 ], [ -80.764290159999916, -1.390887025999916 ], [ -80.74266293699992, -1.368161967999924 ], [ -80.744256335999921, -1.343773381999938 ], [ -80.882150844999899, -1.14576588299991 ], [ -80.916180217999909, -1.065524767999932 ], [ -80.909610914999917, -1.044915051999908 ], [ -80.816365198999904, -0.946343556999921 ], [ -80.722245176999934, -0.931125513999916 ], [ -80.690874930999939, -0.949588742999936 ], [ -80.653041719999919, -0.923064662999934 ], [ -80.616320398999903, -0.941408096999908 ], [ -80.569883134999941, -0.912242570999922 ], [ -80.547211961999949, -0.888489750999952 ], [ -80.497561625999936, -0.692437544999962 ], [ -80.448969096999917, -0.60606015299993 ], [ -80.421991646999913, -0.599599732999934 ], [ -80.405824602999928, -0.646034024999949 ], [ -80.37879806299992, -0.657885419999957 ], [ -80.299006949999921, -0.66222862099994 ], [ -80.298996049999914, -0.650355188999924 ], [ -80.391737228999943, -0.625486672999955 ], [ -80.437125419999916, -0.557538114999943 ], [ -80.452056443999936, -0.476739190999922 ], [ -80.496463547999952, -0.381374052999945 ], [ -80.432724739999912, -0.339187023999955 ], [ -80.371232334999945, -0.222830502999955 ], [ -80.349658206999948, -0.215264482999942 ], [ -80.323695251999936, -0.173172607999959 ], [ -80.305350455999928, -0.189366935999942 ], [ -80.231847859999903, -0.139698740999961 ], [ -80.107899542999917, 0.007066148000092 ], [ -80.098784959999932, 0.039211330000057 ], [ -80.066458956999952, 0.052209779000066 ], [ -80.036976691999939, 0.175970770000049 ], [ -80.048491990999935, 0.318304755000042 ], [ -80.036529100999928, 0.357082424000055 ], [ -80.012684699999909, 0.32453034100007 ], [ -79.999521235313509, 0.345101779873908 ], [ -79.961211920993321, 0.266082261886879 ], [ -79.933435838892819, 0.259674384565187 ], [ -79.889665899661509, 0.318688870295091 ], [ -79.814580044233651, 0.322667954862197 ], [ -79.75269751707674, 0.369280097098795 ], [ -79.717583380768417, 0.370778712967194 ], [ -79.695595059264576, 0.347110907542344 ], [ -79.71223486974344, 0.303651028472189 ], [ -79.652186856138485, 0.259157619728342 ], [ -79.702106289373717, 0.187430732142559 ], [ -79.682133347675858, 0.170429185558476 ], [ -79.659602423812771, 0.175958563736742 ], [ -79.649938931436509, 0.145676174515813 ], [ -79.623945686044578, 0.15389272696774 ], [ -79.567850917685689, 0.116530666856761 ], [ -79.619010586169622, 0.042116604097998 ], [ -79.595549486319726, -0.013590589733951 ], [ -79.607305873767018, -0.040824069475264 ], [ -79.598753425430232, -0.07177825316387 ], [ -79.496692470880816, -0.161850273571304 ], [ -79.411426358239851, -0.188101902280948 ], [ -79.410263638256311, -0.398269951696932 ], [ -79.449072639190945, -0.462297051667633 ], [ -79.536044074174697, -0.691016941278804 ], [ -79.578728806888932, -0.723108004730648 ], [ -79.619630702894597, -0.850232028685184 ], [ -79.722363451012427, -0.881237887418592 ], [ -79.841451788769007, -1.074817804098416 ], [ -79.904367844700232, -1.129749850675069 ], [ -79.969738531807764, -1.139775079156607 ], [ -79.977334968434036, -1.114712008852109 ], [ -79.993096279769475, -1.128819674688259 ], [ -80.043299933844878, -1.271808362765739 ], [ -80.124328578601023, -1.333975111662085 ], [ -80.130891485553605, -1.397743829214335 ], [ -80.191973028832194, -1.431178480702329 ], [ -80.201636522107776, -1.480684502787597 ], [ -80.188174812317698, -1.536546726250435 ], [ -80.222048713377433, -1.559439386218685 ], [ -80.283259446965872, -1.567655937771349 ], [ -80.267911546780454, -1.59519947677444 ], [ -80.226001960422138, -1.61891895904273 ], [ -80.221170214234007, -1.680672295889735 ], [ -80.299744228713166, -1.697622165630435 ], [ -80.329303148421559, -1.687131850054868 ], [ -80.396069098609985, -1.746198011728893 ], [ -80.437539436295936, -1.835701593153999 ], [ -80.516087613252751, -1.840817559282925 ], [ -80.552803718217035, -1.828105156527783 ], [ -80.562880621743261, -1.798029472881865 ], [ -80.539807094621722, -1.727387790913838 ], [ -80.577401699628695, -1.65974334068261 ], [ -80.818164557642575, -1.676979241717978 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-A", "NAME_1": "Azuay" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -79.437393765210061, -2.497056573202315 ], [ -79.388120287121524, -2.507753595252211 ], [ -79.349233770921785, -2.569972019193358 ], [ -79.29399166508324, -2.588007093652436 ], [ -79.163612026973453, -2.731667576197708 ], [ -79.142579718978823, -2.728515313031266 ], [ -79.137928839943982, -2.703297213995256 ], [ -79.078707647739748, -2.650845636117197 ], [ -79.060517543649723, -2.654256279903393 ], [ -78.951041022325285, -2.762156670993591 ], [ -78.915151739661042, -2.822514743860324 ], [ -78.816191372333947, -2.822514743860324 ], [ -78.784229499192008, -2.699628187790665 ], [ -78.725576747768685, -2.690998223289398 ], [ -78.638011033582302, -2.644024346746221 ], [ -78.610674201053541, -2.59736052766624 ], [ -78.564423794022844, -2.561600437110485 ], [ -78.549101732259146, -2.562944024247315 ], [ -78.554036831234782, -2.602269789119475 ], [ -78.533314581602667, -2.62392221383908 ], [ -78.480707974093718, -2.568111667219682 ], [ -78.421357590680259, -2.618496188448376 ], [ -78.436783006130838, -2.645264581095546 ], [ -78.557705858338693, -2.709963473735343 ], [ -78.597470872782537, -2.779158216678354 ], [ -78.56992733377939, -2.839206231182629 ], [ -78.656097784884878, -3.008446547070491 ], [ -78.671652390645306, -3.090767103918722 ], [ -78.937579311635886, -3.287809339429486 ], [ -78.938974575616157, -3.3227426076852 ], [ -79.055091519158282, -3.412246189110363 ], [ -79.05023393364911, -3.552134290864842 ], [ -79.065478481946343, -3.619417005890114 ], [ -79.084676276389018, -3.633317966151253 ], [ -79.102246262854749, -3.636005140424913 ], [ -79.120436366944773, -3.610942071019792 ], [ -79.123356086114484, -3.557043551418758 ], [ -79.178779060005581, -3.448161309297006 ], [ -79.236553311386217, -3.4607703592647 ], [ -79.281692674377382, -3.449918307583857 ], [ -79.317866176982477, -3.346772149215326 ], [ -79.43258785744365, -3.338090508769994 ], [ -79.507932095289959, -3.312975762521432 ], [ -79.614850632650587, -3.329873955418691 ], [ -79.667767300320634, -3.319848727836529 ], [ -79.626891241837313, -3.281608167682805 ], [ -79.595161912692106, -3.174999687785373 ], [ -79.638518438974756, -3.128852633542238 ], [ -79.760474819956983, -3.06467050483991 ], [ -79.74884762192022, -3.023691094468461 ], [ -79.69484575133032, -2.957131849854989 ], [ -79.703579067719772, -2.874966321738384 ], [ -79.690556606602115, -2.825718682071511 ], [ -79.424836392085808, -2.555347588520419 ], [ -79.417162441993071, -2.534160250894899 ], [ -79.437393765210061, -2.497056573202315 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-F", "NAME_1": "CaΓ±ar" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -79.1529150049235, -2.735026544039783 ], [ -79.29399166508324, -2.588007093652436 ], [ -79.349233770921785, -2.569972019193358 ], [ -79.388120287121524, -2.507753595252211 ], [ -79.437393765210061, -2.497056573202315 ], [ -79.489741991199935, -2.51777882193511 ], [ -79.512867194265596, -2.508838799970647 ], [ -79.514314134189931, -2.495196222127959 ], [ -79.425146451347644, -2.421815688143511 ], [ -79.425663215285169, -2.360734144864921 ], [ -79.364788377581533, -2.308540947606673 ], [ -79.192008225798986, -2.266941419610816 ], [ -79.130074021798634, -2.203689466895412 ], [ -79.116741503217781, -2.245030612472817 ], [ -79.028374803354495, -2.345127862261052 ], [ -78.945072394575334, -2.397372734564044 ], [ -78.862441779364588, -2.389983005311478 ], [ -78.762034471213838, -2.325955906240097 ], [ -78.598762783975303, -2.302546481435002 ], [ -78.481224738031244, -2.380681248141116 ], [ -78.490242276160075, -2.505893243278535 ], [ -78.517708298998798, -2.549663180711207 ], [ -78.600545619784498, -2.586611829672222 ], [ -78.638011033582302, -2.644024346746221 ], [ -78.725576747768685, -2.690998223289398 ], [ -78.784229499192008, -2.699628187790665 ], [ -78.816191372333947, -2.822514743860324 ], [ -78.930008714330711, -2.817088717570243 ], [ -78.951041022325285, -2.762156670993591 ], [ -79.072041388898981, -2.649967136074451 ], [ -79.132347784922331, -2.696992689461069 ], [ -79.1529150049235, -2.735026544039783 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-N", "NAME_1": "Napo" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -78.391436936665286, -0.963558445166143 ], [ -78.331673143001126, -1.059831638219521 ], [ -78.34508317684714, -1.164269707780818 ], [ -78.291933966979002, -1.140240167150012 ], [ -78.221524828108329, -1.139981784731617 ], [ -78.175791185015157, -1.184165134213572 ], [ -78.119696417555588, -1.200649915960867 ], [ -78.114167040276698, -1.342553398420591 ], [ -78.148170131646225, -1.424357192230673 ], [ -78.201655240097239, -1.474483331040915 ], [ -78.30653255923022, -1.484560234567198 ], [ -78.353377244564172, -1.526366469037328 ], [ -78.36893185122392, -1.493190199068465 ], [ -78.480087857368687, -1.440583590660196 ], [ -78.515434535875102, -1.480116062006687 ], [ -78.619717576704772, -1.489831231226333 ], [ -78.698575812024103, -1.478100681301385 ], [ -78.799964973005103, -1.424357192230673 ], [ -78.880735236242117, -1.459238782743626 ], [ -78.927554084053725, -1.383171074485517 ], [ -78.866239996778404, -1.17832569677347 ], [ -78.76691789424541, -1.131765232279633 ], [ -78.661239590334787, -1.138534844807225 ], [ -78.575120816072797, -1.102774752452888 ], [ -78.553287523300526, -1.060916842937957 ], [ -78.467840541707631, -1.080502211008252 ], [ -78.434380051797916, -1.044432061190662 ], [ -78.419988166021028, -0.988156426577859 ], [ -78.391436936665286, -0.963558445166143 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-T", "NAME_1": "Tungurahua" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -78.338571946737943, -1.164373060568323 ], [ -78.335729742833337, -1.045207207546582 ], [ -78.391436936665286, -0.963558445166143 ], [ -78.441537237953128, -0.938133639655746 ], [ -78.387793748882416, -0.813800143661695 ], [ -78.405053676985574, -0.710240574143199 ], [ -78.396759610167862, -0.684350680639398 ], [ -78.329657762295881, -0.660424492796096 ], [ -78.310873379003226, -0.598464451273401 ], [ -78.262297532904824, -0.531440117767204 ], [ -78.237467006597058, -0.452840263967005 ], [ -78.24565772242596, -0.399923598095597 ], [ -78.187444220574321, -0.296467379565911 ], [ -78.177263964260533, -0.180867200860632 ], [ -78.126801926867415, -0.169395032454815 ], [ -78.095175951409033, -0.184432875177038 ], [ -78.056909552833588, -0.132704765912251 ], [ -78.013139615400917, -0.135960381866141 ], [ -77.980350918160354, -0.100562025617023 ], [ -77.964486254037354, -0.047800387577809 ], [ -77.857025113418217, 0.001395575245567 ], [ -77.832685512626313, 0.031936346884891 ], [ -77.778942022656224, 0.015813300343552 ], [ -77.772120734184512, -0.066197198142163 ], [ -77.740288052251799, -0.078392836060573 ], [ -77.64086259603198, -0.081028333490792 ], [ -77.588979458035567, -0.100045260780178 ], [ -77.46487850603819, -0.023460788584543 ], [ -77.44392371330872, -0.060409437545502 ], [ -77.446455857951491, -0.124849948666224 ], [ -77.391058723381377, -0.139422702495722 ], [ -77.349975959323046, -0.131619561193816 ], [ -77.299410570041744, -0.058549085571826 ], [ -77.297911953274024, -0.19027231171782 ], [ -77.257681850836718, -0.25326588291415 ], [ -77.254503750147933, -0.309438164739504 ], [ -77.273184780653082, -0.360391126749107 ], [ -77.32323340509754, -0.387417900915409 ], [ -77.329047004115921, -0.424056491513909 ], [ -77.356564703798028, -0.425658461069133 ], [ -77.404029506756331, -0.504154962081827 ], [ -77.448006150663332, -0.507823988286418 ], [ -77.551539882659426, -0.458007907838692 ], [ -77.566474371694881, -0.49573170315557 ], [ -77.620166184821585, -0.536607760739571 ], [ -77.618796760162354, -0.552885836911855 ], [ -77.575285204248758, -0.577018731229487 ], [ -77.509707810666896, -0.655721937817191 ], [ -77.496607836082774, -0.69137867558544 ], [ -77.533272264203617, -0.780778904223041 ], [ -77.528466356437207, -0.841188653033896 ], [ -77.579109260084294, -0.940045667573486 ], [ -77.49921749509133, -0.945316664232678 ], [ -77.254994675663738, -0.833850599725395 ], [ -77.209545254310001, -0.764707532726447 ], [ -77.16481930156948, -0.722797947267452 ], [ -77.124201626403931, -0.707915134176119 ], [ -77.1186205722816, -0.730342706150964 ], [ -77.187711962437106, -0.803361504929512 ], [ -77.192466193360133, -0.852247410289749 ], [ -77.113995530769103, -0.904233901073667 ], [ -77.036144985802423, -0.925214532224913 ], [ -77.061879848775959, -0.963713473897712 ], [ -77.04283708396423, -0.987949721002849 ], [ -77.051647914719467, -1.010377292078374 ], [ -77.233755662993417, -1.024536634757908 ], [ -77.373023648022922, -1.079313652602991 ], [ -77.445525681964625, -1.087323499479908 ], [ -77.547069871677195, -1.13574431684674 ], [ -77.695613776354662, -1.151660657813125 ], [ -77.831109382392071, -1.221837252687067 ], [ -77.882062344401675, -1.214085789127864 ], [ -77.897177699691099, -1.23713347692842 ], [ -77.941955329275004, -1.223852634291632 ], [ -78.116518316866802, -1.23330942109294 ], [ -78.126801926867415, -1.194087009008285 ], [ -78.175791185015157, -1.184165134213572 ], [ -78.221524828108329, -1.139981784731617 ], [ -78.291933966979002, -1.140240167150012 ], [ -78.338571946737943, -1.164373060568323 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-H", "NAME_1": "Chimborazo" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -78.922334764237974, -2.40036996809954 ], [ -79.028374803354495, -2.345127862261052 ], [ -79.116741503217781, -2.245030612472817 ], [ -79.130074021798634, -2.203689466895412 ], [ -79.076330532727866, -2.175164075961334 ], [ -79.016360032589432, -2.09878630844139 ], [ -79.02558427629333, -2.046903170444978 ], [ -78.999591030901342, -1.918280530621985 ], [ -79.001709764394093, -1.781854749497086 ], [ -78.975199755064637, -1.760512384039316 ], [ -78.925667893658328, -1.752089125113059 ], [ -78.859754605090927, -1.663929131724046 ], [ -78.852649094879837, -1.540887546023441 ], [ -78.880735236242117, -1.459238782743626 ], [ -78.799964973005103, -1.424357192230673 ], [ -78.698575812024103, -1.478100681301385 ], [ -78.619717576704772, -1.489831231226333 ], [ -78.515434535875102, -1.480116062006687 ], [ -78.480087857368687, -1.440583590660196 ], [ -78.36893185122392, -1.493190199068465 ], [ -78.353377244564172, -1.526366469037328 ], [ -78.36531450096345, -1.549879245730608 ], [ -78.355651007687868, -1.612872816926995 ], [ -78.450167201555075, -1.717310885588915 ], [ -78.415647346248022, -1.854356785237485 ], [ -78.489544644169996, -1.964840996914461 ], [ -78.445800544259669, -2.075221855803989 ], [ -78.500577562104809, -2.127104993800458 ], [ -78.497812872565987, -2.210510756266387 ], [ -78.530162320234865, -2.240379733437976 ], [ -78.544631721276915, -2.286888522887011 ], [ -78.579900886316864, -2.311538181142168 ], [ -78.598762783975303, -2.302546481435002 ], [ -78.762034471213838, -2.325955906240097 ], [ -78.862441779364588, -2.389983005311478 ], [ -78.922334764237974, -2.40036996809954 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-B", "NAME_1": "Bolivar" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -78.866239996778404, -1.17832569677347 ], [ -78.927554084053725, -1.383171074485517 ], [ -78.852649094879837, -1.540887546023441 ], [ -78.859754605090927, -1.663929131724046 ], [ -78.925667893658328, -1.752089125113059 ], [ -78.975199755064637, -1.760512384039316 ], [ -79.001709764394093, -1.781854749497086 ], [ -78.999591030901342, -1.918280530621985 ], [ -79.02558427629333, -2.046903170444978 ], [ -79.016360032589432, -2.09878630844139 ], [ -79.076330532727866, -2.175164075961334 ], [ -79.130074021798634, -2.203689466895412 ], [ -79.139944220649227, -2.146535333139127 ], [ -79.17164771227209, -2.16198658611205 ], [ -79.235493944190182, -2.154338473541713 ], [ -79.205521613331769, -2.065041598590938 ], [ -79.279496425619527, -1.944893893638266 ], [ -79.258515795367657, -1.923086440187092 ], [ -79.22944780117507, -1.822937513555416 ], [ -79.252133754669046, -1.774878432293804 ], [ -79.250376756382195, -1.736172784146675 ], [ -79.299262660843112, -1.659588311051721 ], [ -79.343859423273727, -1.63834929748208 ], [ -79.292415533949736, -1.585277601979783 ], [ -79.266422288557749, -1.585794365917252 ], [ -79.2500925364414, -1.540887546023441 ], [ -79.318512132129172, -1.468023776875839 ], [ -79.318951381700913, -1.359244886642216 ], [ -79.292182989953005, -1.33444019875617 ], [ -79.337348192265267, -1.291135348417583 ], [ -79.377836677120911, -1.325913587941727 ], [ -79.385975715207053, -1.305656427202337 ], [ -79.327839727721255, -1.225196221428462 ], [ -79.137773811212412, -1.156208184060461 ], [ -79.082066617380463, -1.154916273767014 ], [ -78.990909389556691, -1.209279879562814 ], [ -78.951221890377951, -1.203440443921352 ], [ -78.906935187209115, -1.171556085145198 ], [ -78.866239996778404, -1.17832569677347 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-I", "NAME_1": "Imbabura" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -77.814081997386268, 0.345663966718689 ], [ -77.852477587170881, 0.29264394805972 ], [ -77.835501879008518, 0.26918284731056 ], [ -77.94536597396052, 0.161282457119682 ], [ -78.077683478409767, 0.197766018087236 ], [ -78.202172004034765, 0.134720770946785 ], [ -78.254881965230481, 0.142162177042849 ], [ -78.320330165804478, 0.188515936860995 ], [ -78.365366176907514, 0.16665680656638 ], [ -78.360689460350329, 0.217713121363431 ], [ -78.38670854416398, 0.242311102775147 ], [ -78.63106055390142, 0.215025946190451 ], [ -78.778105841811112, 0.239313870138972 ], [ -78.951661139949636, 0.211305243142419 ], [ -78.993854947148066, 0.228875230507469 ], [ -79.01070146410126, 0.267425849023709 ], [ -78.982847866735653, 0.271043199284236 ], [ -78.902465176226883, 0.386695054832899 ], [ -78.859961310665938, 0.422816881493873 ], [ -78.719608120018734, 0.402714749486108 ], [ -78.667414923659805, 0.372949124202705 ], [ -78.539205694986833, 0.51505931223744 ], [ -78.497399462315343, 0.542137763247183 ], [ -78.431176113586787, 0.55133616852936 ], [ -78.424225633006529, 0.586217759941633 ], [ -78.513444993591577, 0.759902249289382 ], [ -78.450632290447857, 0.789047756049115 ], [ -78.442105678734094, 0.871936754577575 ], [ -78.360301886722652, 0.852816474500685 ], [ -78.258421800225904, 0.775405178206427 ], [ -78.168608161337545, 0.651381741474154 ], [ -78.130806850755562, 0.505602525436188 ], [ -78.000453050168119, 0.46865387647523 ], [ -77.814081997386268, 0.345663966718689 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-X", "NAME_1": "Cotopaxi" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -78.396759610167862, -0.684350680639398 ], [ -78.39110103988105, -0.83281707095108 ], [ -78.441537237953128, -0.938133639655746 ], [ -78.391436936665286, -0.963558445166143 ], [ -78.419988166021028, -0.988156426577859 ], [ -78.455438199113587, -1.074766127254975 ], [ -78.492438524018667, -1.082259210194422 ], [ -78.553287523300526, -1.060916842937957 ], [ -78.575120816072797, -1.102774752452888 ], [ -78.661239590334787, -1.138534844807225 ], [ -78.7860381743223, -1.135899346477686 ], [ -78.866239996778404, -1.17832569677347 ], [ -78.906935187209115, -1.171556085145198 ], [ -78.96848181758179, -1.208659762837783 ], [ -79.014783902355191, -1.202665296666112 ], [ -79.082066617380463, -1.154916273767014 ], [ -79.109455125853344, -1.152280775437418 ], [ -79.234537929781595, -1.199564711242431 ], [ -79.280710822446508, -1.202613620722047 ], [ -79.322982144010723, -1.120964857442232 ], [ -79.29071021160695, -0.914000746237434 ], [ -79.180613572658217, -0.785481459202003 ], [ -79.086820848303489, -0.551903984980925 ], [ -79.047236701012935, -0.585080254949844 ], [ -78.990806036769186, -0.531646824241534 ], [ -79.032353888820921, -0.475629571147806 ], [ -79.002691617224343, -0.418682142966532 ], [ -78.927218187269489, -0.347006930425493 ], [ -78.869805671094809, -0.425348402706618 ], [ -78.829446377448335, -0.515678805532445 ], [ -78.751957566788235, -0.572316176250524 ], [ -78.714052904318066, -0.65262135149419 ], [ -78.617986415940322, -0.606732679669449 ], [ -78.589874437055585, -0.621667168704903 ], [ -78.552434861679501, -0.603477064614822 ], [ -78.489854701633135, -0.604355563758247 ], [ -78.396759610167862, -0.684350680639398 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-R", "NAME_1": "Los Rios" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -79.280710822446508, -1.202613620722047 ], [ -79.327839727721255, -1.225196221428462 ], [ -79.388378668640655, -1.31805876979638 ], [ -79.369697639034825, -1.322089532106247 ], [ -79.337348192265267, -1.291135348417583 ], [ -79.292182989953005, -1.33444019875617 ], [ -79.318951381700913, -1.359244886642216 ], [ -79.318512132129172, -1.468023776875839 ], [ -79.2500925364414, -1.540887546023441 ], [ -79.266422288557749, -1.585794365917252 ], [ -79.292415533949736, -1.585277601979783 ], [ -79.343859423273727, -1.63834929748208 ], [ -79.299262660843112, -1.659588311051721 ], [ -79.250376756382195, -1.736172784146675 ], [ -79.252133754669046, -1.774878432293804 ], [ -79.22944780117507, -1.822937513555416 ], [ -79.258515795367657, -1.923086440187092 ], [ -79.279496425619527, -1.944893893638266 ], [ -79.205521613331769, -2.065041598590938 ], [ -79.235493944190182, -2.154338473541713 ], [ -79.285930142262259, -2.107674656260372 ], [ -79.372953254089396, -1.970111992674333 ], [ -79.482429776313097, -1.897454929101684 ], [ -79.523615892259613, -1.885155937496506 ], [ -79.649525520286545, -1.906549980697037 ], [ -79.758872850401701, -1.696691989643625 ], [ -79.862122361557738, -1.624189954802603 ], [ -79.855662808291981, -1.573495375211394 ], [ -79.870545619584675, -1.519028415728826 ], [ -79.847317063731509, -1.399139093194606 ], [ -79.748149990829404, -1.235169773066559 ], [ -79.741406215824213, -1.189126071610929 ], [ -79.686396653982399, -1.146648043572384 ], [ -79.673761765592985, -1.114298597702145 ], [ -79.580950894068508, -1.050633232937344 ], [ -79.561675585260048, -0.986709485754147 ], [ -79.53278845912007, -0.959527682856276 ], [ -79.523073289900367, -0.845271091287827 ], [ -79.619630702894597, -0.850232028685184 ], [ -79.58658362503428, -0.740264580945677 ], [ -79.539067145232536, -0.696753025032081 ], [ -79.479975145136848, -0.543739108473062 ], [ -79.341999071300108, -0.554229424948005 ], [ -79.357269457119742, -0.577173760860376 ], [ -79.34721839111586, -0.622132256698308 ], [ -79.360602587439416, -0.655721937817191 ], [ -79.350758226111225, -0.682490329565042 ], [ -79.316186693061411, -0.695874525888655 ], [ -79.289728359676019, -0.691998793209734 ], [ -79.205469937387704, -0.62931528127524 ], [ -79.13154680014469, -0.555521335241451 ], [ -79.086820848303489, -0.551903984980925 ], [ -79.166014981306319, -0.758919773029106 ], [ -79.281640998433318, -0.899427991508617 ], [ -79.303732672724664, -0.948882337649763 ], [ -79.322982144010723, -1.120964857442232 ], [ -79.280710822446508, -1.202613620722047 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-P", "NAME_1": "Pichincha" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -77.832685512626313, 0.031936346884891 ], [ -77.857025113418217, 0.001395575245567 ], [ -77.964486254037354, -0.047800387577809 ], [ -77.980350918160354, -0.100562025617023 ], [ -78.013139615400917, -0.135960381866141 ], [ -78.056909552833588, -0.132704765912251 ], [ -78.095175951409033, -0.184432875177038 ], [ -78.134682583434483, -0.169395032454815 ], [ -78.183206752689443, -0.18779184301917 ], [ -78.194187994680192, -0.319980157158511 ], [ -78.24565772242596, -0.399923598095597 ], [ -78.237467006597058, -0.452840263967005 ], [ -78.262297532904824, -0.531440117767204 ], [ -78.310873379003226, -0.598464451273401 ], [ -78.329657762295881, -0.660424492796096 ], [ -78.396759610167862, -0.684350680639398 ], [ -78.462078620431953, -0.61541432011478 ], [ -78.527035894590824, -0.602030124690486 ], [ -78.589874437055585, -0.621667168704903 ], [ -78.617986415940322, -0.606732679669449 ], [ -78.70756751173127, -0.65587696654876 ], [ -78.751957566788235, -0.572316176250524 ], [ -78.829446377448335, -0.515678805532445 ], [ -78.921585456303774, -0.345146580250514 ], [ -78.891159546076153, -0.297630224555235 ], [ -78.76438574600536, -0.284952844997804 ], [ -78.745369675769894, -0.215227254734032 ], [ -78.796079195798256, -0.15817904492701 ], [ -78.92285299586905, -0.075776075105807 ], [ -79.100336315968207, -0.082114764884523 ], [ -79.106675005746922, 0.00028820493668 ], [ -79.309513085860203, 0.006626895614716 ], [ -79.363832364072323, 0.046922511864409 ], [ -79.303655158358879, 0.173271389463025 ], [ -79.3522310053566, 0.231665758467955 ], [ -79.221877203869838, 0.31558828397209 ], [ -79.195134649644331, 0.318895574970782 ], [ -79.040208706066892, 0.295021063970921 ], [ -78.993854947148066, 0.228875230507469 ], [ -78.951661139949636, 0.211305243142419 ], [ -78.778105841811112, 0.239313870138972 ], [ -78.63106055390142, 0.215025946190451 ], [ -78.38670854416398, 0.242311102775147 ], [ -78.360689460350329, 0.217713121363431 ], [ -78.365366176907514, 0.16665680656638 ], [ -78.320330165804478, 0.188515936860995 ], [ -78.226769986345801, 0.13327383102245 ], [ -78.175016038659237, 0.140715237118513 ], [ -78.077683478409767, 0.197766018087236 ], [ -77.94536597396052, 0.161282457119682 ], [ -77.970429043365641, 0.115342109350877 ], [ -77.863898077833994, 0.074155992505041 ], [ -77.832685512626313, 0.031936346884891 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "EC-SD", "NAME_1": "Santo Domingo de los TsΓ‘chilas" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -78.921585456303774, -0.345146580250514 ], [ -79.002691617224343, -0.418682142966532 ], [ -79.032353888820921, -0.475629571147806 ], [ -78.990806036769186, -0.531646824241534 ], [ -79.020054898115063, -0.546167901227648 ], [ -79.037030606277426, -0.580842787064967 ], [ -79.061912807629938, -0.582548110307073 ], [ -79.086820848303489, -0.551903984980925 ], [ -79.115449592025016, -0.546839694796063 ], [ -79.289728359676019, -0.691998793209734 ], [ -79.340784675372447, -0.68905323561836 ], [ -79.360602587439416, -0.655721937817191 ], [ -79.34721839111586, -0.622132256698308 ], [ -79.357269457119742, -0.577173760860376 ], [ -79.341999071300108, -0.554229424948005 ], [ -79.479975145136848, -0.543739108473062 ], [ -79.406930507936579, -0.383438815448983 ], [ -79.411426358239851, -0.188101902280948 ], [ -79.496692470880816, -0.161850273571304 ], [ -79.598753425430232, -0.07177825316387 ], [ -79.603430141987474, -0.022530612597677 ], [ -79.575214810315231, -0.012350356283946 ], [ -79.492997606254505, -0.025631198920678 ], [ -79.43315629822456, -0.050125827544889 ], [ -79.420702276988493, -0.03338266427852 ], [ -79.450364548585014, -0.000929863822194 ], [ -79.383546923351844, 0.022479560083639 ], [ -79.363832364072323, 0.046922511864409 ], [ -79.309513085860203, 0.006626895614716 ], [ -79.106675005746922, 0.00028820493668 ], [ -79.100336315968207, -0.082114764884523 ], [ -78.92285299586905, -0.075776075105807 ], [ -78.796079195798256, -0.15817904492701 ], [ -78.745369675769894, -0.215227254734032 ], [ -78.76438574600536, -0.284952844997804 ], [ -78.891159546076153, -0.297630224555235 ], [ -78.921585456303774, -0.345146580250514 ] ] ] } } ] }
superset-frontend/plugins/legacy-plugin-chart-country-map/src/countries/ecuador.geojson
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0016496997559443116, 0.0009065888007171452, 0.00017563920118846, 0.0009005080792121589, 0.0005441310931928456 ]
{ "id": 2, "code_window": [ " const dispatch = useDispatch();\n", " const report = useSelector<any, AlertObject>(state => {\n", " const resourceType = dashboardId\n", " ? CreationMethod.DASHBOARDS\n", " : CreationMethod.CHARTS;\n", " return reportSelector(state, resourceType, dashboardId || chart?.id);\n", " });\n", "\n", " const isReportActive: boolean = report?.active || false;\n", " const user: UserWithPermissionsAndRoles = useSelector<\n", " any,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return (\n", " reportSelector(state, resourceType, dashboardId || chart?.id) ||\n", " EMPTY_OBJECT\n", " );\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 118 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License.
superset/css_templates/__init__.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017935960204340518, 0.0001792424445739016, 0.000179125287104398, 0.0001792424445739016, 1.1715746950358152e-7 ]
{ "id": 2, "code_window": [ " const dispatch = useDispatch();\n", " const report = useSelector<any, AlertObject>(state => {\n", " const resourceType = dashboardId\n", " ? CreationMethod.DASHBOARDS\n", " : CreationMethod.CHARTS;\n", " return reportSelector(state, resourceType, dashboardId || chart?.id);\n", " });\n", "\n", " const isReportActive: boolean = report?.active || false;\n", " const user: UserWithPermissionsAndRoles = useSelector<\n", " any,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return (\n", " reportSelector(state, resourceType, dashboardId || chart?.id) ||\n", " EMPTY_OBJECT\n", " );\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 118 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { t } from '../translation'; /** * formerly called numeric() * @param v */ export default function numeric(v: unknown) { if (v && Number.isNaN(Number(v))) { return t('is expected to be a number'); } return false; }
superset-frontend/packages/superset-ui-core/src/validator/legacyValidateNumber.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.000178826303454116, 0.00017804741219151765, 0.0001773389958543703, 0.00017801215290091932, 5.355277608032338e-7 ]
{ "id": 3, "code_window": [ " // this is in the case that there is an anonymous user.\n", " return false;\n", " }\n", " const roles = Object.keys(user.roles || []);\n", " const permissions = roles.map(key =>\n", " user.roles[key].filter(\n", " perms => perms[0] === 'menu_access' && perms[1] === 'Manage',\n", " ),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " // Cannot add reports if the resource is not saved\n", " if (!(dashboardId || chart?.id)) {\n", " return false;\n", " }\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 135 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable camelcase */ // eslint-disable-next-line import/no-extraneous-dependencies import { SET_REPORT, ADD_REPORT, EDIT_REPORT } from '../actions/reports'; export default function reportsReducer(state = {}, action) { const actionHandlers = { [SET_REPORT]() { const { report, resourceId, creationMethod, filterField } = action; // For now report count should only be one, but we are checking in case // functionality changes. const reportObject = report.result?.find( report => report[filterField] === resourceId, ); if (reportObject) { return { ...state, [creationMethod]: { ...state[creationMethod], [resourceId]: reportObject, }, }; } if (state?.[creationMethod]?.[resourceId]) { // remove the empty report from state const newState = { ...state }; delete newState[creationMethod][resourceId]; return newState; } return { ...state }; }, [ADD_REPORT]() { const { result, id } = action.json; const report = { ...result, id }; const reportTypeId = report.dashboard || report.chart; // this is the id of either the chart or the dashboard associated with the report. return { ...state, [report.creation_method]: { ...state[report.creation_method], [reportTypeId]: report, }, }; }, [EDIT_REPORT]() { const report = { ...action.json.result, id: action.json.id, }; const reportTypeId = report.dashboard || report.chart; return { ...state, [report.creation_method]: { ...state[report.creation_method], [reportTypeId]: report, }, }; }, }; if (action.type in actionHandlers) { return actionHandlers[action.type](); } return state; }
superset-frontend/src/reports/reducers/reports.js
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017545255832374096, 0.00017404671234544367, 0.00017291960830334574, 0.00017379717610310763, 8.941259466155316e-7 ]
{ "id": 3, "code_window": [ " // this is in the case that there is an anonymous user.\n", " return false;\n", " }\n", " const roles = Object.keys(user.roles || []);\n", " const permissions = roles.map(key =>\n", " user.roles[key].filter(\n", " perms => perms[0] === 'menu_access' && perms[1] === 'Manage',\n", " ),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " // Cannot add reports if the resource is not saved\n", " if (!(dashboardId || chart?.id)) {\n", " return false;\n", " }\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 135 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import annotations from typing import Any, Dict, Optional, TYPE_CHECKING from superset.common.chart_data import ChartDataResultType from superset.common.query_object import QueryObject from superset.common.utils.time_range_utils import get_since_until_from_time_range from superset.utils.core import apply_max_row_limit, DatasourceDict, DatasourceType if TYPE_CHECKING: from sqlalchemy.orm import sessionmaker from superset.connectors.base.models import BaseDatasource from superset.datasource.dao import DatasourceDAO class QueryObjectFactory: # pylint: disable=too-few-public-methods _config: Dict[str, Any] _datasource_dao: DatasourceDAO _session_maker: sessionmaker def __init__( self, app_configurations: Dict[str, Any], _datasource_dao: DatasourceDAO, session_maker: sessionmaker, ): self._config = app_configurations self._datasource_dao = _datasource_dao self._session_maker = session_maker def create( # pylint: disable=too-many-arguments self, parent_result_type: ChartDataResultType, datasource: Optional[DatasourceDict] = None, extras: Optional[Dict[str, Any]] = None, row_limit: Optional[int] = None, time_range: Optional[str] = None, time_shift: Optional[str] = None, **kwargs: Any, ) -> QueryObject: datasource_model_instance = None if datasource: datasource_model_instance = self._convert_to_model(datasource) processed_extras = self._process_extras(extras) result_type = kwargs.setdefault("result_type", parent_result_type) row_limit = self._process_row_limit(row_limit, result_type) from_dttm, to_dttm = get_since_until_from_time_range( time_range, time_shift, processed_extras ) kwargs["from_dttm"] = from_dttm kwargs["to_dttm"] = to_dttm return QueryObject( datasource=datasource_model_instance, extras=extras, row_limit=row_limit, time_range=time_range, time_shift=time_shift, **kwargs, ) def _convert_to_model(self, datasource: DatasourceDict) -> BaseDatasource: return self._datasource_dao.get_datasource( datasource_type=DatasourceType(datasource["type"]), datasource_id=int(datasource["id"]), session=self._session_maker(), ) def _process_extras( # pylint: disable=no-self-use self, extras: Optional[Dict[str, Any]], ) -> Dict[str, Any]: extras = extras or {} return extras def _process_row_limit( self, row_limit: Optional[int], result_type: ChartDataResultType ) -> int: default_row_limit = ( self._config["SAMPLES_ROW_LIMIT"] if result_type == ChartDataResultType.SAMPLES else self._config["ROW_LIMIT"] ) return apply_max_row_limit(row_limit or default_row_limit) # light version of the view.utils.core # import view.utils require application context # Todo: move it and the view.utils.core to utils package
superset/common/query_object_factory.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0002274628495797515, 0.00017795040912460536, 0.00016954018792603165, 0.0001731144147925079, 0.000015743973563075997 ]
{ "id": 3, "code_window": [ " // this is in the case that there is an anonymous user.\n", " return false;\n", " }\n", " const roles = Object.keys(user.roles || []);\n", " const permissions = roles.map(key =>\n", " user.roles[key].filter(\n", " perms => perms[0] === 'menu_access' && perms[1] === 'Manage',\n", " ),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " // Cannot add reports if the resource is not saved\n", " if (!(dashboardId || chart?.id)) {\n", " return false;\n", " }\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 135 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { ChartMetadata, ChartPlugin, t } from '@superset-ui/core'; import thumbnail from '../images/thumbnail.png'; import example1 from '../images/example1.jpg'; import example2 from '../images/example2.jpg'; import buildQuery from './buildQuery'; import controlPanel from './controlPanel'; import transformProps from './transformProps'; export default class HandlebarsChartPlugin extends ChartPlugin { /** * The constructor is used to pass relevant metadata and callbacks that get * registered in respective registries that are used throughout the library * and application. A more thorough description of each property is given in * the respective imported file. * * It is worth noting that `buildQuery` and is optional, and only needed for * advanced visualizations that require either post processing operations * (pivoting, rolling aggregations, sorting etc) or submitting multiple queries. */ constructor() { const metadata = new ChartMetadata({ description: t('Write a handlebars template to render the data'), name: t('Handlebars'), thumbnail, exampleGallery: [{ url: example1 }, { url: example2 }], }); super({ buildQuery, controlPanel, loadChart: () => import('../Handlebars'), metadata, transformProps, }); } }
superset-frontend/plugins/plugin-chart-handlebars/src/plugin/index.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017557623505126685, 0.00017188303172588348, 0.000164031473104842, 0.00017305658548139036, 0.0000036609005746868206 ]
{ "id": 3, "code_window": [ " // this is in the case that there is an anonymous user.\n", " return false;\n", " }\n", " const roles = Object.keys(user.roles || []);\n", " const permissions = roles.map(key =>\n", " user.roles[key].filter(\n", " perms => perms[0] === 'menu_access' && perms[1] === 'Manage',\n", " ),\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " // Cannot add reports if the resource is not saved\n", " if (!(dashboardId || chart?.id)) {\n", " return false;\n", " }\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "add", "edit_start_line_idx": 135 }
{# Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #} {% import 'appbuilder/general/lib.html' as lib %} <div class="list-search-container"> <form id="filter_form" class="form-search" method="get"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-filter text-primary" aria-hidden="true"></i> {{_("Filter List")}} </button> <ul class="dropdown-menu"> {% for col in include_cols %} <li><a href="javascript:void(0)" name={{col}} class="filter btn" onclick="return false;"> {{ label_columns[col] }}</a> </li> {% endfor %} </ul> <div class="filters-container"> <table class="table table-responsive table-hover filters"> </table> <div class="filter-action" style="display:none"> <button type="submit" class="btn btn-sm btn-primary" id="search-action"> {{_("Search")}}&nbsp;&nbsp;<i class="fa fa-search"></i> </button> </div> </div> </form> </div> <script> (function($) { function checkSearchButton() { var hasFilter = $('.filters tr').length; if (hasFilter) { $('.filters a.remove-filter').off('click', checkSearchButton); $('.filters a.remove-filter').on('click', checkSearchButton); $('.filter-action').toggle(true); } else { $('.filter-action').toggle(true); $('.filter-action > button').html('{{_("Refresh")}}&nbsp;&nbsp;<i class="fa fa-refresh"></i>'); } } $('a.btn.remove-filter').on('click', checkSearchButton); $(document).ready(function() { checkSearchButton(); }); var filter = new AdminFilters( '#filter_form', {{ label_columns | tojson | safe }}, {{ form_fields | tojson | safe }}, {{ search_filters | tojson | safe }}, {{ active_filters | tojson | safe }} ); })(jQuery); </script>
superset/templates/appbuilder/general/widgets/search.html
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017700131866149604, 0.00017077685333788395, 0.00016570537991356105, 0.00016963794769253582, 0.0000033722035368555225 ]
{ "id": 4, "code_window": [ " setCurrentReportDeleting(report);\n", " }\n", " };\n", "\n", " const textMenu = () =>\n", " report ? (\n", " isDropdownVisible && (\n", " <Menu selectable={false} css={{ border: 'none' }}>\n", " <Menu.Item\n", " css={onMenuItemHover}\n", " onClick={() => toggleActiveKey(report, !isReportActive)}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isEmpty(report) ? (\n", " <Menu selectable={false} css={onMenuHover}>\n", " <Menu.Item onClick={handleShowMenu}>\n", " {DropdownItemExtension ? (\n", " <StyledDropdownItemWithIcon>\n", " <div>{t('Set up an email report')}</div>\n", " <DropdownItemExtension />\n", " </StyledDropdownItemWithIcon>\n", " ) : (\n", " t('Set up an email report')\n", " )}\n", " </Menu.Item>\n", " <Menu.Divider />\n", " </Menu>\n", " ) : (\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 202 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { t, SupersetTheme, css, styled, useTheme, FeatureFlag, isFeatureEnabled, getExtensionsRegistry, usePrevious, } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import { Switch } from 'src/components/Switch'; import { AlertObject } from 'src/features/alerts/types'; import { Menu } from 'src/components/Menu'; import Checkbox from 'src/components/Checkbox'; import { noOp } from 'src/utils/common'; import { NoAnimationDropdown } from 'src/components/Dropdown'; import DeleteModal from 'src/components/DeleteModal'; import ReportModal from 'src/components/ReportModal'; import { ChartState } from 'src/explore/types'; import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; import { fetchUISpecificReport, toggleActive, deleteActiveReport, } from 'src/reports/actions/reports'; import { reportSelector } from 'src/views/CRUD/hooks'; import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index'; const extensionsRegistry = getExtensionsRegistry(); const deleteColor = (theme: SupersetTheme) => css` color: ${theme.colors.error.base}; `; const onMenuHover = (theme: SupersetTheme) => css` & .ant-menu-item { padding: 5px 12px; margin-top: 0px; margin-bottom: 4px; :hover { color: ${theme.colors.grayscale.dark1}; } } :hover { background-color: ${theme.colors.secondary.light5}; } `; const onMenuItemHover = (theme: SupersetTheme) => css` &:hover { color: ${theme.colors.grayscale.dark1}; background-color: ${theme.colors.secondary.light5}; } `; const StyledDropdownItemWithIcon = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; > *:first-child { margin-right: ${({ theme }) => theme.gridUnit}px; } `; const DropdownItemExtension = extensionsRegistry.get( 'report-modal.dropdown.item.icon', ); export enum CreationMethod { CHARTS = 'charts', DASHBOARDS = 'dashboards', } export interface HeaderReportProps { dashboardId?: number; chart?: ChartState; useTextMenu?: boolean; setShowReportSubMenu?: (show: boolean) => void; setIsDropdownVisible?: (visible: boolean) => void; isDropdownVisible?: boolean; showReportSubMenu?: boolean; } export default function HeaderReportDropDown({ dashboardId, chart, useTextMenu = false, setShowReportSubMenu, setIsDropdownVisible, isDropdownVisible, }: HeaderReportProps) { const dispatch = useDispatch(); const report = useSelector<any, AlertObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isReportActive: boolean = report?.active || false; const user: UserWithPermissionsAndRoles = useSelector< any, UserWithPermissionsAndRoles >(state => state.user); const canAddReports = () => { if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) { return false; } if (!user?.userId) { // this is in the case that there is an anonymous user. return false; } const roles = Object.keys(user.roles || []); const permissions = roles.map(key => user.roles[key].filter( perms => perms[0] === 'menu_access' && perms[1] === 'Manage', ), ); return permissions.some(permission => permission.length > 0); }; const [currentReportDeleting, setCurrentReportDeleting] = useState<AlertObject | null>(null); const theme = useTheme(); const prevDashboard = usePrevious(dashboardId); const [showModal, setShowModal] = useState<boolean>(false); const toggleActiveKey = async (data: AlertObject, checked: boolean) => { if (data?.id) { dispatch(toggleActive(data, checked)); } }; const handleReportDelete = async (report: AlertObject) => { await dispatch(deleteActiveReport(report)); setCurrentReportDeleting(null); }; const shouldFetch = canAddReports() && !!((dashboardId && prevDashboard !== dashboardId) || chart?.id); useEffect(() => { if (shouldFetch) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: dashboardId ? 'dashboard_id' : 'chart_id', creationMethod: dashboardId ? 'dashboards' : 'charts', resourceId: dashboardId || chart?.id, }), ); } }, []); const showReportSubMenu = report && setShowReportSubMenu && canAddReports(); useEffect(() => { if (showReportSubMenu) { setShowReportSubMenu(true); } else if (!report && setShowReportSubMenu) { setShowReportSubMenu(false); } }, [report]); const handleShowMenu = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setShowModal(true); } }; const handleDeleteMenuClick = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setCurrentReportDeleting(report); } }; const textMenu = () => report ? ( isDropdownVisible && ( <Menu selectable={false} css={{ border: 'none' }}> <Menu.Item css={onMenuItemHover} onClick={() => toggleActiveKey(report, !isReportActive)} > <MenuItemWithCheckboxContainer> <Checkbox checked={isReportActive} onChange={noOp} /> {t('Email reports active')} </MenuItemWithCheckboxContainer> </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleShowMenu}> {t('Edit email report')} </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}> {t('Delete email report')} </Menu.Item> </Menu> ) ) : ( <Menu selectable={false} css={onMenuHover}> <Menu.Item onClick={handleShowMenu}> {DropdownItemExtension ? ( <StyledDropdownItemWithIcon> <div>{t('Set up an email report')}</div> <DropdownItemExtension /> </StyledDropdownItemWithIcon> ) : ( t('Set up an email report') )} </Menu.Item> <Menu.Divider /> </Menu> ); const menu = () => ( <Menu selectable={false} css={{ width: '200px' }}> <Menu.Item> {t('Email reports active')} <Switch data-test="toggle-active" checked={isReportActive} onClick={(checked: boolean) => toggleActiveKey(report, checked)} size="small" css={{ marginLeft: theme.gridUnit * 2 }} /> </Menu.Item> <Menu.Item onClick={() => setShowModal(true)}> {t('Edit email report')} </Menu.Item> <Menu.Item onClick={() => setCurrentReportDeleting(report)} css={deleteColor} > {t('Delete email report')} </Menu.Item> </Menu> ); const iconMenu = () => report ? ( <> <NoAnimationDropdown overlay={menu()} trigger={['click']} getPopupContainer={(triggerNode: any) => triggerNode.closest('.action-button') } > <span role="button" className="action-button action-schedule-report" tabIndex={0} > <Icons.Calendar /> </span> </NoAnimationDropdown> </> ) : ( <span role="button" title={t('Schedule email report')} tabIndex={0} className="action-button action-schedule-report" onClick={() => setShowModal(true)} > <Icons.Calendar /> </span> ); return ( <> {canAddReports() && ( <> <ReportModal userId={user.userId} show={showModal} onHide={() => setShowModal(false)} userEmail={user.email} dashboardId={dashboardId} chart={chart} creationMethod={ dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS } /> {useTextMenu ? textMenu() : iconMenu()} {currentReportDeleting && ( <DeleteModal description={t( 'This action will permanently delete %s.', currentReportDeleting?.name, )} onConfirm={() => { if (currentReportDeleting) { handleReportDelete(currentReportDeleting); } }} onHide={() => setCurrentReportDeleting(null)} open title={t('Delete Report?')} /> )} </> )} </> ); }
superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.9988721013069153, 0.07149282097816467, 0.00016450011753477156, 0.0014456440694630146, 0.23760752379894257 ]
{ "id": 4, "code_window": [ " setCurrentReportDeleting(report);\n", " }\n", " };\n", "\n", " const textMenu = () =>\n", " report ? (\n", " isDropdownVisible && (\n", " <Menu selectable={false} css={{ border: 'none' }}>\n", " <Menu.Item\n", " css={onMenuItemHover}\n", " onClick={() => toggleActiveKey(report, !isReportActive)}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isEmpty(report) ? (\n", " <Menu selectable={false} css={onMenuHover}>\n", " <Menu.Item onClick={handleShowMenu}>\n", " {DropdownItemExtension ? (\n", " <StyledDropdownItemWithIcon>\n", " <div>{t('Set up an email report')}</div>\n", " <DropdownItemExtension />\n", " </StyledDropdownItemWithIcon>\n", " ) : (\n", " t('Set up an email report')\n", " )}\n", " </Menu.Item>\n", " <Menu.Divider />\n", " </Menu>\n", " ) : (\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 202 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License.
tests/unit_tests/importexport/__init__.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017952728376258165, 0.0001788386289263144, 0.00017814997409004718, 0.0001788386289263144, 6.886548362672329e-7 ]
{ "id": 4, "code_window": [ " setCurrentReportDeleting(report);\n", " }\n", " };\n", "\n", " const textMenu = () =>\n", " report ? (\n", " isDropdownVisible && (\n", " <Menu selectable={false} css={{ border: 'none' }}>\n", " <Menu.Item\n", " css={onMenuItemHover}\n", " onClick={() => toggleActiveKey(report, !isReportActive)}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isEmpty(report) ? (\n", " <Menu selectable={false} css={onMenuHover}>\n", " <Menu.Item onClick={handleShowMenu}>\n", " {DropdownItemExtension ? (\n", " <StyledDropdownItemWithIcon>\n", " <div>{t('Set up an email report')}</div>\n", " <DropdownItemExtension />\n", " </StyledDropdownItemWithIcon>\n", " ) : (\n", " t('Set up an email report')\n", " )}\n", " </Menu.Item>\n", " <Menu.Divider />\n", " </Menu>\n", " ) : (\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 202 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Superset Embedded SDK The Embedded SDK allows you to embed dashboards from Superset into your own app, using your app's authentication. Embedding is done by inserting an iframe, containing a Superset page, into the host application. ## Embedding a Dashboard Using npm: ```sh npm install --save @superset-ui/embedded-sdk ``` ```js import { embedDashboard } from "@superset-ui/embedded-sdk"; embedDashboard({ id: "abc123", // given by the Superset embedding UI supersetDomain: "https://superset.example.com", mountPoint: document.getElementById("my-superset-container"), // any html element that can contain an iframe fetchGuestToken: () => fetchGuestTokenFromBackend(), dashboardUiConfig: { // dashboard UI config: hideTitle, hideTab, hideChartControls, filters.visible, filters.expanded (optional) hideTitle: true, filters: { expanded: true, } }, }); ``` You can also load the Embedded SDK from a CDN. The SDK will be available as `supersetEmbeddedSdk` globally: ```html <script src="https://unpkg.com/@superset-ui/embedded-sdk"></script> <script> supersetEmbeddedSdk.embedDashboard({ // ... here you supply the same parameters as in the example above }); </script> ``` ## Authentication/Authorization with Guest Tokens Embedded resources use a special auth token called a Guest Token to grant Superset access to your users, without requiring your users to log in to Superset directly. Your backend must create a Guest Token by requesting Superset's `POST /security/guest_token` endpoint, and pass that guest token to your frontend. The Embedding SDK takes the guest token and use it to embed a dashboard. ### Creating a Guest Token From the backend, http `POST` to `/security/guest_token` with some parameters to define what the guest token will grant access to. Guest tokens can have Row Level Security rules which filter data for the user carrying the token. The agent making the `POST` request must be authenticated with the `can_grant_guest_token` permission. Example `POST /security/guest_token` payload: ```json { "user": { "username": "stan_lee", "first_name": "Stan", "last_name": "Lee" }, "resources": [{ "type": "dashboard", "id": "abc123" }], "rls": [ { "clause": "publisher = 'Nintendo'" } ] } ```
superset-embedded-sdk/README.md
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00018005631864070892, 0.00017426763952244073, 0.00017061570542864501, 0.0001742750173434615, 0.0000027400637918617576 ]
{ "id": 4, "code_window": [ " setCurrentReportDeleting(report);\n", " }\n", " };\n", "\n", " const textMenu = () =>\n", " report ? (\n", " isDropdownVisible && (\n", " <Menu selectable={false} css={{ border: 'none' }}>\n", " <Menu.Item\n", " css={onMenuItemHover}\n", " onClick={() => toggleActiveKey(report, !isReportActive)}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isEmpty(report) ? (\n", " <Menu selectable={false} css={onMenuHover}>\n", " <Menu.Item onClick={handleShowMenu}>\n", " {DropdownItemExtension ? (\n", " <StyledDropdownItemWithIcon>\n", " <div>{t('Set up an email report')}</div>\n", " <DropdownItemExtension />\n", " </StyledDropdownItemWithIcon>\n", " ) : (\n", " t('Set up an email report')\n", " )}\n", " </Menu.Item>\n", " <Menu.Divider />\n", " </Menu>\n", " ) : (\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 202 }
{ // This file is not used in compilation. It is here just for a nice editor experience. "extends": "@tsconfig/docusaurus/tsconfig.json", "compilerOptions": { "baseUrl": "." } }
docs/tsconfig.json
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017627724446356297, 0.00017627724446356297, 0.00017627724446356297, 0.00017627724446356297, 0 ]
{ "id": 5, "code_window": [ " </Menu.Item>\n", " </Menu>\n", " )\n", " ) : (\n", " <Menu selectable={false} css={onMenuHover}>\n", " <Menu.Item onClick={handleShowMenu}>\n", " {DropdownItemExtension ? (\n", " <StyledDropdownItemWithIcon>\n", " <div>{t('Set up an email report')}</div>\n", " <DropdownItemExtension />\n", " </StyledDropdownItemWithIcon>\n", " ) : (\n", " t('Set up an email report')\n", " )}\n", " </Menu.Item>\n", " <Menu.Divider />\n", " </Menu>\n", " );\n", " const menu = () => (\n", " <Menu selectable={false} css={{ width: '200px' }}>\n", " <Menu.Item>\n", " {t('Email reports active')}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 222 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { t, SupersetTheme, css, styled, useTheme, FeatureFlag, isFeatureEnabled, getExtensionsRegistry, usePrevious, } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import { Switch } from 'src/components/Switch'; import { AlertObject } from 'src/features/alerts/types'; import { Menu } from 'src/components/Menu'; import Checkbox from 'src/components/Checkbox'; import { noOp } from 'src/utils/common'; import { NoAnimationDropdown } from 'src/components/Dropdown'; import DeleteModal from 'src/components/DeleteModal'; import ReportModal from 'src/components/ReportModal'; import { ChartState } from 'src/explore/types'; import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; import { fetchUISpecificReport, toggleActive, deleteActiveReport, } from 'src/reports/actions/reports'; import { reportSelector } from 'src/views/CRUD/hooks'; import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index'; const extensionsRegistry = getExtensionsRegistry(); const deleteColor = (theme: SupersetTheme) => css` color: ${theme.colors.error.base}; `; const onMenuHover = (theme: SupersetTheme) => css` & .ant-menu-item { padding: 5px 12px; margin-top: 0px; margin-bottom: 4px; :hover { color: ${theme.colors.grayscale.dark1}; } } :hover { background-color: ${theme.colors.secondary.light5}; } `; const onMenuItemHover = (theme: SupersetTheme) => css` &:hover { color: ${theme.colors.grayscale.dark1}; background-color: ${theme.colors.secondary.light5}; } `; const StyledDropdownItemWithIcon = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; > *:first-child { margin-right: ${({ theme }) => theme.gridUnit}px; } `; const DropdownItemExtension = extensionsRegistry.get( 'report-modal.dropdown.item.icon', ); export enum CreationMethod { CHARTS = 'charts', DASHBOARDS = 'dashboards', } export interface HeaderReportProps { dashboardId?: number; chart?: ChartState; useTextMenu?: boolean; setShowReportSubMenu?: (show: boolean) => void; setIsDropdownVisible?: (visible: boolean) => void; isDropdownVisible?: boolean; showReportSubMenu?: boolean; } export default function HeaderReportDropDown({ dashboardId, chart, useTextMenu = false, setShowReportSubMenu, setIsDropdownVisible, isDropdownVisible, }: HeaderReportProps) { const dispatch = useDispatch(); const report = useSelector<any, AlertObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isReportActive: boolean = report?.active || false; const user: UserWithPermissionsAndRoles = useSelector< any, UserWithPermissionsAndRoles >(state => state.user); const canAddReports = () => { if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) { return false; } if (!user?.userId) { // this is in the case that there is an anonymous user. return false; } const roles = Object.keys(user.roles || []); const permissions = roles.map(key => user.roles[key].filter( perms => perms[0] === 'menu_access' && perms[1] === 'Manage', ), ); return permissions.some(permission => permission.length > 0); }; const [currentReportDeleting, setCurrentReportDeleting] = useState<AlertObject | null>(null); const theme = useTheme(); const prevDashboard = usePrevious(dashboardId); const [showModal, setShowModal] = useState<boolean>(false); const toggleActiveKey = async (data: AlertObject, checked: boolean) => { if (data?.id) { dispatch(toggleActive(data, checked)); } }; const handleReportDelete = async (report: AlertObject) => { await dispatch(deleteActiveReport(report)); setCurrentReportDeleting(null); }; const shouldFetch = canAddReports() && !!((dashboardId && prevDashboard !== dashboardId) || chart?.id); useEffect(() => { if (shouldFetch) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: dashboardId ? 'dashboard_id' : 'chart_id', creationMethod: dashboardId ? 'dashboards' : 'charts', resourceId: dashboardId || chart?.id, }), ); } }, []); const showReportSubMenu = report && setShowReportSubMenu && canAddReports(); useEffect(() => { if (showReportSubMenu) { setShowReportSubMenu(true); } else if (!report && setShowReportSubMenu) { setShowReportSubMenu(false); } }, [report]); const handleShowMenu = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setShowModal(true); } }; const handleDeleteMenuClick = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setCurrentReportDeleting(report); } }; const textMenu = () => report ? ( isDropdownVisible && ( <Menu selectable={false} css={{ border: 'none' }}> <Menu.Item css={onMenuItemHover} onClick={() => toggleActiveKey(report, !isReportActive)} > <MenuItemWithCheckboxContainer> <Checkbox checked={isReportActive} onChange={noOp} /> {t('Email reports active')} </MenuItemWithCheckboxContainer> </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleShowMenu}> {t('Edit email report')} </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}> {t('Delete email report')} </Menu.Item> </Menu> ) ) : ( <Menu selectable={false} css={onMenuHover}> <Menu.Item onClick={handleShowMenu}> {DropdownItemExtension ? ( <StyledDropdownItemWithIcon> <div>{t('Set up an email report')}</div> <DropdownItemExtension /> </StyledDropdownItemWithIcon> ) : ( t('Set up an email report') )} </Menu.Item> <Menu.Divider /> </Menu> ); const menu = () => ( <Menu selectable={false} css={{ width: '200px' }}> <Menu.Item> {t('Email reports active')} <Switch data-test="toggle-active" checked={isReportActive} onClick={(checked: boolean) => toggleActiveKey(report, checked)} size="small" css={{ marginLeft: theme.gridUnit * 2 }} /> </Menu.Item> <Menu.Item onClick={() => setShowModal(true)}> {t('Edit email report')} </Menu.Item> <Menu.Item onClick={() => setCurrentReportDeleting(report)} css={deleteColor} > {t('Delete email report')} </Menu.Item> </Menu> ); const iconMenu = () => report ? ( <> <NoAnimationDropdown overlay={menu()} trigger={['click']} getPopupContainer={(triggerNode: any) => triggerNode.closest('.action-button') } > <span role="button" className="action-button action-schedule-report" tabIndex={0} > <Icons.Calendar /> </span> </NoAnimationDropdown> </> ) : ( <span role="button" title={t('Schedule email report')} tabIndex={0} className="action-button action-schedule-report" onClick={() => setShowModal(true)} > <Icons.Calendar /> </span> ); return ( <> {canAddReports() && ( <> <ReportModal userId={user.userId} show={showModal} onHide={() => setShowModal(false)} userEmail={user.email} dashboardId={dashboardId} chart={chart} creationMethod={ dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS } /> {useTextMenu ? textMenu() : iconMenu()} {currentReportDeleting && ( <DeleteModal description={t( 'This action will permanently delete %s.', currentReportDeleting?.name, )} onConfirm={() => { if (currentReportDeleting) { handleReportDelete(currentReportDeleting); } }} onHide={() => setCurrentReportDeleting(null)} open title={t('Delete Report?')} /> )} </> )} </> ); }
superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.9970279335975647, 0.0626584067940712, 0.00016226629668381065, 0.00030093692475929856, 0.23646822571754456 ]
{ "id": 5, "code_window": [ " </Menu.Item>\n", " </Menu>\n", " )\n", " ) : (\n", " <Menu selectable={false} css={onMenuHover}>\n", " <Menu.Item onClick={handleShowMenu}>\n", " {DropdownItemExtension ? (\n", " <StyledDropdownItemWithIcon>\n", " <div>{t('Set up an email report')}</div>\n", " <DropdownItemExtension />\n", " </StyledDropdownItemWithIcon>\n", " ) : (\n", " t('Set up an email report')\n", " )}\n", " </Menu.Item>\n", " <Menu.Divider />\n", " </Menu>\n", " );\n", " const menu = () => (\n", " <Menu selectable={false} css={{ width: '200px' }}>\n", " <Menu.Item>\n", " {t('Email reports active')}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 222 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable camelcase */ import React from 'react'; import PropTypes from 'prop-types'; import { isDefined, t, styled, ensureIsArray, DatasourceType, } from '@superset-ui/core'; import Tabs from 'src/components/Tabs'; import Button from 'src/components/Button'; import { Select } from 'src/components'; import { Tooltip } from 'src/components/Tooltip'; import { EmptyStateSmall } from 'src/components/EmptyState'; import { Form, FormItem } from 'src/components/Form'; import { SQLEditor } from 'src/components/AsyncAceEditor'; import sqlKeywords from 'src/SqlLab/utils/sqlKeywords'; import { noOp } from 'src/utils/common'; import { AGGREGATES_OPTIONS, POPOVER_INITIAL_HEIGHT, POPOVER_INITIAL_WIDTH, } from 'src/explore/constants'; import columnType from 'src/explore/components/controls/MetricControl/columnType'; import savedMetricType from 'src/explore/components/controls/MetricControl/savedMetricType'; import AdhocMetric, { EXPRESSION_TYPES, } from 'src/explore/components/controls/MetricControl/AdhocMetric'; import { StyledMetricOption, StyledColumnOption, } from 'src/explore/components/optionRenderers'; const propTypes = { onChange: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, onResize: PropTypes.func.isRequired, getCurrentTab: PropTypes.func, getCurrentLabel: PropTypes.func, adhocMetric: PropTypes.instanceOf(AdhocMetric).isRequired, columns: PropTypes.arrayOf(columnType), savedMetricsOptions: PropTypes.arrayOf(savedMetricType), savedMetric: savedMetricType, datasource: PropTypes.object, isNewMetric: PropTypes.bool, isLabelModified: PropTypes.bool, }; const defaultProps = { columns: [], getCurrentTab: noOp, isNewMetric: false, }; const StyledSelect = styled(Select)` .metric-option { & > svg { min-width: ${({ theme }) => `${theme.gridUnit * 4}px`}; } & > .option-label { overflow: hidden; text-overflow: ellipsis; } } `; export const SAVED_TAB_KEY = 'SAVED'; export default class AdhocMetricEditPopover extends React.PureComponent { // "Saved" is a default tab unless there are no saved metrics for dataset defaultActiveTabKey = this.getDefaultTab(); constructor(props) { super(props); this.onSave = this.onSave.bind(this); this.onResetStateAndClose = this.onResetStateAndClose.bind(this); this.onColumnChange = this.onColumnChange.bind(this); this.onAggregateChange = this.onAggregateChange.bind(this); this.onSavedMetricChange = this.onSavedMetricChange.bind(this); this.onSqlExpressionChange = this.onSqlExpressionChange.bind(this); this.onDragDown = this.onDragDown.bind(this); this.onMouseMove = this.onMouseMove.bind(this); this.onMouseUp = this.onMouseUp.bind(this); this.onTabChange = this.onTabChange.bind(this); this.handleAceEditorRef = this.handleAceEditorRef.bind(this); this.refreshAceEditor = this.refreshAceEditor.bind(this); this.getDefaultTab = this.getDefaultTab.bind(this); this.state = { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, width: POPOVER_INITIAL_WIDTH, height: POPOVER_INITIAL_HEIGHT, }; document.addEventListener('mouseup', this.onMouseUp); } componentDidMount() { this.props.getCurrentTab(this.defaultActiveTabKey); } componentDidUpdate(prevProps, prevState) { if ( prevState.adhocMetric?.sqlExpression !== this.state.adhocMetric?.sqlExpression || prevState.adhocMetric?.aggregate !== this.state.adhocMetric?.aggregate || prevState.adhocMetric?.column?.column_name !== this.state.adhocMetric?.column?.column_name || prevState.savedMetric?.metric_name !== this.state.savedMetric?.metric_name ) { this.props.getCurrentLabel({ savedMetricLabel: this.state.savedMetric?.verbose_name || this.state.savedMetric?.metric_name, adhocMetricLabel: this.state.adhocMetric?.getDefaultLabel(), }); } } componentWillUnmount() { document.removeEventListener('mouseup', this.onMouseUp); document.removeEventListener('mousemove', this.onMouseMove); } getDefaultTab() { const { adhocMetric, savedMetric, savedMetricsOptions, isNewMetric } = this.props; if (isDefined(adhocMetric.column) || isDefined(adhocMetric.sqlExpression)) { return adhocMetric.expressionType; } if ( (isNewMetric || savedMetric.metric_name) && Array.isArray(savedMetricsOptions) && savedMetricsOptions.length > 0 ) { return SAVED_TAB_KEY; } return adhocMetric.expressionType; } onSave() { const { adhocMetric, savedMetric } = this.state; const metric = savedMetric?.metric_name ? savedMetric : adhocMetric; const oldMetric = this.props.savedMetric?.metric_name ? this.props.savedMetric : this.props.adhocMetric; this.props.onChange( { ...metric, }, oldMetric, ); this.props.onClose(); } onResetStateAndClose() { this.setState( { adhocMetric: this.props.adhocMetric, savedMetric: this.props.savedMetric, }, this.props.onClose, ); } onColumnChange(columnName) { const column = this.props.columns.find( column => column.column_name === columnName, ); this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ column, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onAggregateChange(aggregate) { // we construct this object explicitly to overwrite the value in the case aggregate is null this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ aggregate, expressionType: EXPRESSION_TYPES.SIMPLE, }), savedMetric: undefined, })); } onSavedMetricChange(savedMetricName) { const savedMetric = this.props.savedMetricsOptions.find( metric => metric.metric_name === savedMetricName, ); this.setState(prevState => ({ savedMetric, adhocMetric: prevState.adhocMetric.duplicateWith({ column: undefined, aggregate: undefined, sqlExpression: undefined, expressionType: EXPRESSION_TYPES.SIMPLE, }), })); } onSqlExpressionChange(sqlExpression) { this.setState(prevState => ({ adhocMetric: prevState.adhocMetric.duplicateWith({ sqlExpression, expressionType: EXPRESSION_TYPES.SQL, }), savedMetric: undefined, })); } onDragDown(e) { this.dragStartX = e.clientX; this.dragStartY = e.clientY; this.dragStartWidth = this.state.width; this.dragStartHeight = this.state.height; document.addEventListener('mousemove', this.onMouseMove); } onMouseMove(e) { this.props.onResize(); this.setState({ width: Math.max( this.dragStartWidth + (e.clientX - this.dragStartX), POPOVER_INITIAL_WIDTH, ), height: Math.max( this.dragStartHeight + (e.clientY - this.dragStartY) * 2, POPOVER_INITIAL_HEIGHT, ), }); } onMouseUp() { document.removeEventListener('mousemove', this.onMouseMove); } onTabChange(tab) { this.refreshAceEditor(); this.props.getCurrentTab(tab); } handleAceEditorRef(ref) { if (ref) { this.aceEditorRef = ref; } } refreshAceEditor() { setTimeout(() => { if (this.aceEditorRef) { this.aceEditorRef.editor.resize(); } }, 0); } renderColumnOption(option) { const column = { ...option }; if (column.metric_name && !column.verbose_name) { column.verbose_name = column.metric_name; } return <StyledColumnOption column={column} showType />; } renderMetricOption(savedMetric) { return <StyledMetricOption metric={savedMetric} showType />; } render() { const { adhocMetric: propsAdhocMetric, savedMetric: propsSavedMetric, columns, savedMetricsOptions, onChange, onClose, onResize, datasource, isNewMetric, isLabelModified, ...popoverProps } = this.props; const { adhocMetric, savedMetric } = this.state; const keywords = sqlKeywords.concat( columns.map(column => ({ name: column.column_name, value: column.column_name, score: 50, meta: 'column', })), ); const columnValue = (adhocMetric.column && adhocMetric.column.column_name) || adhocMetric.inferSqlExpressionColumn(); // autofocus on column if there's no value in column; otherwise autofocus on aggregate const columnSelectProps = { ariaLabel: t('Select column'), placeholder: t('%s column(s)', columns.length), value: columnValue, onChange: this.onColumnChange, allowClear: true, autoFocus: !columnValue, }; const aggregateSelectProps = { ariaLabel: t('Select aggregate options'), placeholder: t('%s aggregates(s)', AGGREGATES_OPTIONS.length), value: adhocMetric.aggregate || adhocMetric.inferSqlExpressionAggregate(), onChange: this.onAggregateChange, allowClear: true, autoFocus: !!columnValue, }; const savedSelectProps = { ariaLabel: t('Select saved metrics'), placeholder: t('%s saved metric(s)', savedMetricsOptions?.length ?? 0), value: savedMetric?.metric_name, onChange: this.onSavedMetricChange, allowClear: true, autoFocus: true, }; const stateIsValid = adhocMetric.isValid() || savedMetric?.metric_name; const hasUnsavedChanges = isLabelModified || isNewMetric || !adhocMetric.equals(propsAdhocMetric) || (!( typeof savedMetric?.metric_name === 'undefined' && typeof propsSavedMetric?.metric_name === 'undefined' ) && savedMetric?.metric_name !== propsSavedMetric?.metric_name); let extra = {}; if (datasource?.extra) { try { extra = JSON.parse(datasource.extra); } catch {} // eslint-disable-line no-empty } return ( <Form layout="vertical" id="metrics-edit-popover" data-test="metrics-edit-popover" {...popoverProps} > <Tabs id="adhoc-metric-edit-tabs" data-test="adhoc-metric-edit-tabs" defaultActiveKey={this.defaultActiveTabKey} className="adhoc-metric-edit-tabs" style={{ height: this.state.height, width: this.state.width }} onChange={this.onTabChange} allowOverflow > <Tabs.TabPane key={SAVED_TAB_KEY} tab={t('Saved')}> {ensureIsArray(savedMetricsOptions).length > 0 ? ( <FormItem label={t('Saved metric')}> <StyledSelect options={ensureIsArray(savedMetricsOptions).map( savedMetric => ({ value: savedMetric.metric_name, label: savedMetric.metric_name, customLabel: this.renderMetricOption(savedMetric), key: savedMetric.id, }), )} {...savedSelectProps} /> </FormItem> ) : datasource.type === DatasourceType.Table ? ( <EmptyStateSmall image="empty.svg" title={t('No saved metrics found')} description={t( 'Add metrics to dataset in "Edit datasource" modal', )} /> ) : ( <EmptyStateSmall image="empty.svg" title={t('No saved metrics found')} description={ <> <span tabIndex={0} role="button" onClick={() => { this.props.handleDatasetModal(true); this.props.onClose(); }} > {t('Create a dataset')} </span> {t(' to add metrics')} </> } /> )} </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SIMPLE} tab={ extra.disallow_adhoc_metrics ? ( <Tooltip title={t( 'Simple ad-hoc metrics are not enabled for this dataset', )} > {t('Simple')} </Tooltip> ) : ( t('Simple') ) } disabled={extra.disallow_adhoc_metrics} > <FormItem label={t('column')}> <Select options={columns.map(column => ({ value: column.column_name, label: column.verbose_name || column.column_name, key: column.id, customLabel: this.renderColumnOption(column), }))} {...columnSelectProps} /> </FormItem> <FormItem label={t('aggregate')}> <Select options={AGGREGATES_OPTIONS.map(option => ({ value: option, label: option, key: option, }))} {...aggregateSelectProps} /> </FormItem> </Tabs.TabPane> <Tabs.TabPane key={EXPRESSION_TYPES.SQL} tab={ extra.disallow_adhoc_metrics ? ( <Tooltip title={t( 'Custom SQL ad-hoc metrics are not enabled for this dataset', )} > {t('Custom SQL')} </Tooltip> ) : ( t('Custom SQL') ) } data-test="adhoc-metric-edit-tab#custom" disabled={extra.disallow_adhoc_metrics} > <SQLEditor data-test="sql-editor" showLoadingForImport ref={this.handleAceEditorRef} keywords={keywords} height={`${this.state.height - 80}px`} onChange={this.onSqlExpressionChange} width="100%" showGutter={false} value={ adhocMetric.sqlExpression || adhocMetric.translateToSql({ transformCountDistinct: true }) } editorProps={{ $blockScrolling: true }} enableLiveAutocompletion className="filter-sql-editor" wrapEnabled /> </Tabs.TabPane> </Tabs> <div> <Button buttonSize="small" onClick={this.onResetStateAndClose} data-test="AdhocMetricEdit#cancel" cta > {t('Close')} </Button> <Button disabled={!stateIsValid || !hasUnsavedChanges} buttonStyle="primary" buttonSize="small" data-test="AdhocMetricEdit#save" onClick={this.onSave} cta > {t('Save')} </Button> <i role="button" aria-label="Resize" tabIndex={0} onMouseDown={this.onDragDown} className="fa fa-expand edit-popover-resize text-muted" /> </div> </Form> ); } } AdhocMetricEditPopover.propTypes = propTypes; AdhocMetricEditPopover.defaultProps = defaultProps;
superset-frontend/src/explore/components/controls/MetricControl/AdhocMetricEditPopover/index.jsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0014531748602166772, 0.0002351133880438283, 0.00016138552746269852, 0.00016574907931499183, 0.0002270875993417576 ]
{ "id": 5, "code_window": [ " </Menu.Item>\n", " </Menu>\n", " )\n", " ) : (\n", " <Menu selectable={false} css={onMenuHover}>\n", " <Menu.Item onClick={handleShowMenu}>\n", " {DropdownItemExtension ? (\n", " <StyledDropdownItemWithIcon>\n", " <div>{t('Set up an email report')}</div>\n", " <DropdownItemExtension />\n", " </StyledDropdownItemWithIcon>\n", " ) : (\n", " t('Set up an email report')\n", " )}\n", " </Menu.Item>\n", " <Menu.Divider />\n", " </Menu>\n", " );\n", " const menu = () => (\n", " <Menu selectable={false} css={{ width: '200px' }}>\n", " <Menu.Item>\n", " {t('Email reports active')}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 222 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { ReactNode, CSSProperties } from 'react'; import { XAxis, YAxis } from '@data-ui/xy-chart'; import { ChartFrame, Margin, mergeMargin, Dimension } from '@superset-ui/core'; import { ChannelEncoder, PlainObject, Value, XFieldDef, YFieldDef, } from 'encodable'; import createTickComponent from './createTickComponent'; import computeAxisLayout, { AxisLayout } from './computeAxisLayout'; export const DEFAULT_LABEL_ANGLE = 40; // Additional margin to avoid content hidden behind scroll bar const OVERFLOW_MARGIN = 8; export interface XYChartLayoutConfig< XOutput extends Value, YOutput extends Value, > { width: number; height: number; minContentWidth?: number; minContentHeight?: number; margin: Margin; xEncoder: ChannelEncoder<XFieldDef<XOutput>, XOutput>; xTickSize?: number; xTickTextStyle?: CSSProperties; autoAdjustXMargin?: boolean; yEncoder: ChannelEncoder<YFieldDef<YOutput>, YOutput>; yTickSize?: number; yTickTextStyle?: CSSProperties; autoAdjustYMargin?: boolean; } export default class XYChartLayout< XOutput extends Value, YOutput extends Value, > { chartWidth: number; chartHeight: number; containerWidth: number; containerHeight: number; margin: Margin; xEncoder: ChannelEncoder<XFieldDef<XOutput>, XOutput>; xLayout?: AxisLayout; yEncoder: ChannelEncoder<YFieldDef<YOutput>, YOutput>; yLayout?: AxisLayout; constructor(config: XYChartLayoutConfig<XOutput, YOutput>) { const { width, height, minContentWidth = 0, minContentHeight = 0, margin, xEncoder, xTickSize, xTickTextStyle, autoAdjustXMargin = true, yEncoder, yTickSize, yTickTextStyle, autoAdjustYMargin = true, } = config; this.xEncoder = xEncoder; this.yEncoder = yEncoder; if (typeof yEncoder.axis !== 'undefined') { this.yLayout = computeAxisLayout(yEncoder.axis, { axisWidth: Math.max(height - margin.top - margin.bottom), defaultTickSize: yTickSize, tickTextStyle: yTickTextStyle, }); } const secondMargin = this.yLayout && autoAdjustYMargin ? mergeMargin(margin, this.yLayout.minMargin) : margin; const innerWidth = Math.max( width - secondMargin.left - secondMargin.right, minContentWidth, ); if (typeof xEncoder.axis !== 'undefined') { this.xLayout = computeAxisLayout(xEncoder.axis, { axisWidth: innerWidth, defaultTickSize: xTickSize, tickTextStyle: xTickTextStyle, }); } const finalMargin = this.xLayout && autoAdjustXMargin ? mergeMargin(secondMargin, this.xLayout.minMargin) : secondMargin; const innerHeight = Math.max( height - finalMargin.top - finalMargin.bottom, minContentHeight, ); const chartWidth = Math.round( innerWidth + finalMargin.left + finalMargin.right, ); const chartHeight = Math.round( innerHeight + finalMargin.top + finalMargin.bottom, ); const isOverFlowX = chartWidth > width; const isOverFlowY = chartHeight > height; if (isOverFlowX) { finalMargin.bottom += OVERFLOW_MARGIN; } if (isOverFlowY) { finalMargin.right += OVERFLOW_MARGIN; } this.chartWidth = isOverFlowX ? chartWidth + OVERFLOW_MARGIN : chartWidth; this.chartHeight = isOverFlowY ? chartHeight + OVERFLOW_MARGIN : chartHeight; this.containerWidth = width; this.containerHeight = height; this.margin = finalMargin; } renderChartWithFrame(renderChart: (input: Dimension) => ReactNode) { return ( <ChartFrame width={this.containerWidth} height={this.containerHeight} contentWidth={this.chartWidth} contentHeight={this.chartHeight} renderContent={renderChart} /> ); } renderXAxis(props?: PlainObject) { const { axis } = this.xEncoder; return axis && this.xLayout ? ( <XAxis label={axis.getTitle()} labelOffset={this.xLayout.labelOffset} numTicks={axis.config.tickCount} orientation={axis.config.orient} tickComponent={createTickComponent(this.xLayout)} tickFormat={axis.formatValue} {...props} /> ) : null; } renderYAxis(props?: PlainObject) { const { axis } = this.yEncoder; return axis && this.yLayout ? ( <YAxis label={axis.getTitle()} labelOffset={this.yLayout.labelOffset} numTicks={axis.config.tickCount} orientation={axis.config.orient} tickFormat={axis.formatValue} {...props} /> ) : null; } }
superset-frontend/plugins/preset-chart-xy/src/utils/XYChartLayout.tsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.001938489149324596, 0.0002491172344889492, 0.00016117592167574912, 0.0001634011132409796, 0.0003777670790441334 ]
{ "id": 5, "code_window": [ " </Menu.Item>\n", " </Menu>\n", " )\n", " ) : (\n", " <Menu selectable={false} css={onMenuHover}>\n", " <Menu.Item onClick={handleShowMenu}>\n", " {DropdownItemExtension ? (\n", " <StyledDropdownItemWithIcon>\n", " <div>{t('Set up an email report')}</div>\n", " <DropdownItemExtension />\n", " </StyledDropdownItemWithIcon>\n", " ) : (\n", " t('Set up an email report')\n", " )}\n", " </Menu.Item>\n", " <Menu.Divider />\n", " </Menu>\n", " );\n", " const menu = () => (\n", " <Menu selectable={false} css={{ width: '200px' }}>\n", " <Menu.Item>\n", " {t('Email reports active')}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 222 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """security converge queries Revision ID: e37912a26567 Revises: 42b4c9e01447 Create Date: 2020-12-16 12:15:28.291777 """ # revision identifiers, used by Alembic. revision = "e37912a26567" down_revision = "42b4c9e01447" from alembic import op from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session from superset.migrations.shared.security_converge import ( add_pvms, get_reversed_new_pvms, get_reversed_pvm_map, migrate_roles, Pvm, ) NEW_PVMS = {"Query": ("can_read",)} PVM_MAP = { Pvm("QueryView", "can_list"): (Pvm("Query", "can_read"),), Pvm("QueryView", "can_show"): (Pvm("Query", "can_read"),), } def upgrade(): bind = op.get_bind() session = Session(bind=bind) # Add the new permissions on the migration itself add_pvms(session, NEW_PVMS) migrate_roles(session, PVM_MAP) try: session.commit() except SQLAlchemyError as ex: print(f"An error occurred while upgrading permissions: {ex}") session.rollback() def downgrade(): bind = op.get_bind() session = Session(bind=bind) # Add the old permissions on the migration itself add_pvms(session, get_reversed_new_pvms(PVM_MAP)) migrate_roles(session, get_reversed_pvm_map(PVM_MAP)) try: session.commit() except SQLAlchemyError as ex: print(f"An error occurred while downgrading permissions: {ex}") session.rollback() pass
superset/migrations/versions/2020-12-16_12-15_e37912a26567_security_converge_queries.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0001756936399033293, 0.0001649785554036498, 0.00016102859808597714, 0.0001633106148801744, 0.000004433564299688442 ]
{ "id": 6, "code_window": [ " </Menu>\n", " );\n", "\n", " const iconMenu = () =>\n", " report ? (\n", " <>\n", " <NoAnimationDropdown\n", " overlay={menu()}\n", " trigger={['click']}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " isEmpty(report) ? (\n", " <span\n", " role=\"button\"\n", " title={t('Schedule email report')}\n", " tabIndex={0}\n", " className=\"action-button action-schedule-report\"\n", " onClick={() => setShowModal(true)}\n", " >\n", " <Icons.Calendar />\n", " </span>\n", " ) : (\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 262 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { t, SupersetTheme, css, styled, useTheme, FeatureFlag, isFeatureEnabled, getExtensionsRegistry, usePrevious, } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import { Switch } from 'src/components/Switch'; import { AlertObject } from 'src/features/alerts/types'; import { Menu } from 'src/components/Menu'; import Checkbox from 'src/components/Checkbox'; import { noOp } from 'src/utils/common'; import { NoAnimationDropdown } from 'src/components/Dropdown'; import DeleteModal from 'src/components/DeleteModal'; import ReportModal from 'src/components/ReportModal'; import { ChartState } from 'src/explore/types'; import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; import { fetchUISpecificReport, toggleActive, deleteActiveReport, } from 'src/reports/actions/reports'; import { reportSelector } from 'src/views/CRUD/hooks'; import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index'; const extensionsRegistry = getExtensionsRegistry(); const deleteColor = (theme: SupersetTheme) => css` color: ${theme.colors.error.base}; `; const onMenuHover = (theme: SupersetTheme) => css` & .ant-menu-item { padding: 5px 12px; margin-top: 0px; margin-bottom: 4px; :hover { color: ${theme.colors.grayscale.dark1}; } } :hover { background-color: ${theme.colors.secondary.light5}; } `; const onMenuItemHover = (theme: SupersetTheme) => css` &:hover { color: ${theme.colors.grayscale.dark1}; background-color: ${theme.colors.secondary.light5}; } `; const StyledDropdownItemWithIcon = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; > *:first-child { margin-right: ${({ theme }) => theme.gridUnit}px; } `; const DropdownItemExtension = extensionsRegistry.get( 'report-modal.dropdown.item.icon', ); export enum CreationMethod { CHARTS = 'charts', DASHBOARDS = 'dashboards', } export interface HeaderReportProps { dashboardId?: number; chart?: ChartState; useTextMenu?: boolean; setShowReportSubMenu?: (show: boolean) => void; setIsDropdownVisible?: (visible: boolean) => void; isDropdownVisible?: boolean; showReportSubMenu?: boolean; } export default function HeaderReportDropDown({ dashboardId, chart, useTextMenu = false, setShowReportSubMenu, setIsDropdownVisible, isDropdownVisible, }: HeaderReportProps) { const dispatch = useDispatch(); const report = useSelector<any, AlertObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isReportActive: boolean = report?.active || false; const user: UserWithPermissionsAndRoles = useSelector< any, UserWithPermissionsAndRoles >(state => state.user); const canAddReports = () => { if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) { return false; } if (!user?.userId) { // this is in the case that there is an anonymous user. return false; } const roles = Object.keys(user.roles || []); const permissions = roles.map(key => user.roles[key].filter( perms => perms[0] === 'menu_access' && perms[1] === 'Manage', ), ); return permissions.some(permission => permission.length > 0); }; const [currentReportDeleting, setCurrentReportDeleting] = useState<AlertObject | null>(null); const theme = useTheme(); const prevDashboard = usePrevious(dashboardId); const [showModal, setShowModal] = useState<boolean>(false); const toggleActiveKey = async (data: AlertObject, checked: boolean) => { if (data?.id) { dispatch(toggleActive(data, checked)); } }; const handleReportDelete = async (report: AlertObject) => { await dispatch(deleteActiveReport(report)); setCurrentReportDeleting(null); }; const shouldFetch = canAddReports() && !!((dashboardId && prevDashboard !== dashboardId) || chart?.id); useEffect(() => { if (shouldFetch) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: dashboardId ? 'dashboard_id' : 'chart_id', creationMethod: dashboardId ? 'dashboards' : 'charts', resourceId: dashboardId || chart?.id, }), ); } }, []); const showReportSubMenu = report && setShowReportSubMenu && canAddReports(); useEffect(() => { if (showReportSubMenu) { setShowReportSubMenu(true); } else if (!report && setShowReportSubMenu) { setShowReportSubMenu(false); } }, [report]); const handleShowMenu = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setShowModal(true); } }; const handleDeleteMenuClick = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setCurrentReportDeleting(report); } }; const textMenu = () => report ? ( isDropdownVisible && ( <Menu selectable={false} css={{ border: 'none' }}> <Menu.Item css={onMenuItemHover} onClick={() => toggleActiveKey(report, !isReportActive)} > <MenuItemWithCheckboxContainer> <Checkbox checked={isReportActive} onChange={noOp} /> {t('Email reports active')} </MenuItemWithCheckboxContainer> </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleShowMenu}> {t('Edit email report')} </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}> {t('Delete email report')} </Menu.Item> </Menu> ) ) : ( <Menu selectable={false} css={onMenuHover}> <Menu.Item onClick={handleShowMenu}> {DropdownItemExtension ? ( <StyledDropdownItemWithIcon> <div>{t('Set up an email report')}</div> <DropdownItemExtension /> </StyledDropdownItemWithIcon> ) : ( t('Set up an email report') )} </Menu.Item> <Menu.Divider /> </Menu> ); const menu = () => ( <Menu selectable={false} css={{ width: '200px' }}> <Menu.Item> {t('Email reports active')} <Switch data-test="toggle-active" checked={isReportActive} onClick={(checked: boolean) => toggleActiveKey(report, checked)} size="small" css={{ marginLeft: theme.gridUnit * 2 }} /> </Menu.Item> <Menu.Item onClick={() => setShowModal(true)}> {t('Edit email report')} </Menu.Item> <Menu.Item onClick={() => setCurrentReportDeleting(report)} css={deleteColor} > {t('Delete email report')} </Menu.Item> </Menu> ); const iconMenu = () => report ? ( <> <NoAnimationDropdown overlay={menu()} trigger={['click']} getPopupContainer={(triggerNode: any) => triggerNode.closest('.action-button') } > <span role="button" className="action-button action-schedule-report" tabIndex={0} > <Icons.Calendar /> </span> </NoAnimationDropdown> </> ) : ( <span role="button" title={t('Schedule email report')} tabIndex={0} className="action-button action-schedule-report" onClick={() => setShowModal(true)} > <Icons.Calendar /> </span> ); return ( <> {canAddReports() && ( <> <ReportModal userId={user.userId} show={showModal} onHide={() => setShowModal(false)} userEmail={user.email} dashboardId={dashboardId} chart={chart} creationMethod={ dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS } /> {useTextMenu ? textMenu() : iconMenu()} {currentReportDeleting && ( <DeleteModal description={t( 'This action will permanently delete %s.', currentReportDeleting?.name, )} onConfirm={() => { if (currentReportDeleting) { handleReportDelete(currentReportDeleting); } }} onHide={() => setCurrentReportDeleting(null)} open title={t('Delete Report?')} /> )} </> )} </> ); }
superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.9988037347793579, 0.061709944158792496, 0.00016515816969331354, 0.0005154997925274074, 0.23793376982212067 ]
{ "id": 6, "code_window": [ " </Menu>\n", " );\n", "\n", " const iconMenu = () =>\n", " report ? (\n", " <>\n", " <NoAnimationDropdown\n", " overlay={menu()}\n", " trigger={['click']}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " isEmpty(report) ? (\n", " <span\n", " role=\"button\"\n", " title={t('Schedule email report')}\n", " tabIndex={0}\n", " className=\"action-button action-schedule-report\"\n", " onClick={() => setShowModal(true)}\n", " >\n", " <Icons.Calendar />\n", " </span>\n", " ) : (\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 262 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import annotations import json from typing import Any, Dict, Generator, List, TYPE_CHECKING import pytest from superset import db, security_manager as sm from superset.dashboards.filter_sets.consts import ( DESCRIPTION_FIELD, JSON_METADATA_FIELD, NAME_FIELD, OWNER_ID_FIELD, OWNER_TYPE_FIELD, USER_OWNER_TYPE, ) from superset.models.dashboard import Dashboard from superset.models.filter_set import FilterSet from tests.integration_tests.dashboards.filter_sets.consts import ( ADMIN_USERNAME_FOR_TEST, DASHBOARD_OWNER_USERNAME, FILTER_SET_OWNER_USERNAME, REGULAR_USER, ) from tests.integration_tests.dashboards.superset_factory_util import ( create_dashboard, create_database, create_datasource_table, create_slice, ) from tests.integration_tests.test_app import app if TYPE_CHECKING: from flask.ctx import AppContext from flask.testing import FlaskClient from flask_appbuilder.security.manager import BaseSecurityManager from flask_appbuilder.security.sqla.models import ( PermissionView, Role, User, ViewMenu, ) from sqlalchemy.orm import Session from superset.connectors.sqla.models import SqlaTable from superset.models.core import Database from superset.models.slice import Slice security_manager: BaseSecurityManager = sm @pytest.fixture(autouse=True, scope="module") def test_users() -> Generator[Dict[str, int], None, None]: usernames = [ ADMIN_USERNAME_FOR_TEST, DASHBOARD_OWNER_USERNAME, FILTER_SET_OWNER_USERNAME, REGULAR_USER, ] with app.app_context(): filter_set_role = build_filter_set_role() admin_role: Role = security_manager.find_role("Admin") usernames_to_ids = create_test_users(admin_role, filter_set_role, usernames) yield usernames_to_ids delete_users(usernames_to_ids) def delete_users(usernames_to_ids: Dict[str, int]) -> None: for username in usernames_to_ids.keys(): db.session.delete(security_manager.find_user(username)) db.session.commit() def create_test_users( admin_role: Role, filter_set_role: Role, usernames: List[str] ) -> Dict[str, int]: users: List[User] = [] for username in usernames: user = build_user(username, filter_set_role, admin_role) users.append(user) return {user.username: user.id for user in users} def build_user(username: str, filter_set_role: Role, admin_role: Role) -> User: roles_to_add = ( [admin_role] if username == ADMIN_USERNAME_FOR_TEST else [filter_set_role] ) user: User = security_manager.add_user( username, "test", "test", username, roles_to_add, password="general" ) if not user: user = security_manager.find_user(username) if user is None: raise Exception("Failed to build the user {}".format(username)) return user def build_filter_set_role() -> Role: filter_set_role: Role = security_manager.add_role("filter_set_role") filterset_view_name: ViewMenu = security_manager.find_view_menu("FilterSets") all_datasource_view_name: ViewMenu = security_manager.find_view_menu( "all_datasource_access" ) pvms: List[PermissionView] = security_manager.find_permissions_view_menu( filterset_view_name ) + security_manager.find_permissions_view_menu(all_datasource_view_name) for pvm in pvms: security_manager.add_permission_role(filter_set_role, pvm) return filter_set_role @pytest.fixture def client() -> Generator[FlaskClient[Any], None, None]: with app.test_client() as client: yield client @pytest.fixture def dashboard(app_context) -> Generator[Dashboard, None, None]: dashboard_owner_user = security_manager.find_user(DASHBOARD_OWNER_USERNAME) database = create_database("test_database_filter_sets") datasource = create_datasource_table( name="test_datasource", database=database, owners=[dashboard_owner_user] ) slice_ = create_slice( datasource=datasource, name="test_slice", owners=[dashboard_owner_user] ) dashboard = create_dashboard( dashboard_title="test_dashboard", published=True, slices=[slice_], owners=[dashboard_owner_user], ) db.session.add(dashboard) db.session.commit() yield dashboard db.session.delete(dashboard) db.session.delete(slice_) db.session.delete(datasource) db.session.delete(database) db.session.commit() @pytest.fixture def dashboard_id(dashboard: Dashboard) -> Generator[int, None, None]: yield dashboard.id @pytest.fixture def filtersets( dashboard_id: int, test_users: Dict[str, int], dumped_valid_json_metadata: str ) -> Generator[Dict[str, List[FilterSet]], None, None]: first_filter_set = FilterSet( name="filter_set_1_of_" + str(dashboard_id), dashboard_id=dashboard_id, json_metadata=dumped_valid_json_metadata, owner_id=dashboard_id, owner_type="Dashboard", ) second_filter_set = FilterSet( name="filter_set_2_of_" + str(dashboard_id), json_metadata=dumped_valid_json_metadata, dashboard_id=dashboard_id, owner_id=dashboard_id, owner_type="Dashboard", ) third_filter_set = FilterSet( name="filter_set_3_of_" + str(dashboard_id), json_metadata=dumped_valid_json_metadata, dashboard_id=dashboard_id, owner_id=test_users[FILTER_SET_OWNER_USERNAME], owner_type="User", ) fourth_filter_set = FilterSet( name="filter_set_4_of_" + str(dashboard_id), json_metadata=dumped_valid_json_metadata, dashboard_id=dashboard_id, owner_id=test_users[FILTER_SET_OWNER_USERNAME], owner_type="User", ) db.session.add(first_filter_set) db.session.add(second_filter_set) db.session.add(third_filter_set) db.session.add(fourth_filter_set) db.session.commit() yield { "Dashboard": [first_filter_set, second_filter_set], FILTER_SET_OWNER_USERNAME: [third_filter_set, fourth_filter_set], } db.session.delete(first_filter_set) db.session.delete(second_filter_set) db.session.delete(third_filter_set) db.session.delete(fourth_filter_set) db.session.commit() @pytest.fixture def filterset_id(filtersets: Dict[str, List[FilterSet]]) -> int: return filtersets["Dashboard"][0].id @pytest.fixture def valid_json_metadata() -> Dict[str, Any]: return {"nativeFilters": {}} @pytest.fixture def dumped_valid_json_metadata(valid_json_metadata: Dict[str, Any]) -> str: return json.dumps(valid_json_metadata) @pytest.fixture def exists_user_id() -> int: return 1 @pytest.fixture def valid_filter_set_data_for_create( dashboard_id: int, dumped_valid_json_metadata: str, exists_user_id: int ) -> Dict[str, Any]: name = "test_filter_set_of_dashboard_" + str(dashboard_id) return { NAME_FIELD: name, DESCRIPTION_FIELD: "description of " + name, JSON_METADATA_FIELD: dumped_valid_json_metadata, OWNER_TYPE_FIELD: USER_OWNER_TYPE, OWNER_ID_FIELD: exists_user_id, } @pytest.fixture def valid_filter_set_data_for_update( dashboard_id: int, dumped_valid_json_metadata: str, exists_user_id: int ) -> Dict[str, Any]: name = "name_changed_test_filter_set_of_dashboard_" + str(dashboard_id) return { NAME_FIELD: name, DESCRIPTION_FIELD: "changed description of " + name, JSON_METADATA_FIELD: dumped_valid_json_metadata, } @pytest.fixture def not_exists_dashboard_id(dashboard_id: int) -> Generator[int, None, None]: yield dashboard_id + 1 @pytest.fixture def not_exists_user_id() -> int: return 99999 @pytest.fixture() def dashboard_based_filter_set_dict( filtersets: Dict[str, List[FilterSet]] ) -> Dict[str, Any]: return filtersets["Dashboard"][0].to_dict() @pytest.fixture() def user_based_filter_set_dict( filtersets: Dict[str, List[FilterSet]] ) -> Dict[str, Any]: return filtersets[FILTER_SET_OWNER_USERNAME][0].to_dict()
tests/integration_tests/dashboards/filter_sets/conftest.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0006926340865902603, 0.0001905880926642567, 0.00016538746422156692, 0.00017284163914155215, 0.00009493453399045393 ]
{ "id": 6, "code_window": [ " </Menu>\n", " );\n", "\n", " const iconMenu = () =>\n", " report ? (\n", " <>\n", " <NoAnimationDropdown\n", " overlay={menu()}\n", " trigger={['click']}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " isEmpty(report) ? (\n", " <span\n", " role=\"button\"\n", " title={t('Schedule email report')}\n", " tabIndex={0}\n", " className=\"action-button action-schedule-report\"\n", " onClick={() => setShowModal(true)}\n", " >\n", " <Icons.Calendar />\n", " </span>\n", " ) : (\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 262 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """${message} Revision ID: ${up_revision} Revises: ${down_revision} Create Date: ${create_date} """ # revision identifiers, used by Alembic. revision = ${repr(up_revision)} down_revision = ${repr(down_revision)} from alembic import op import sqlalchemy as sa ${imports if imports else ""} def upgrade(): ${upgrades if upgrades else "pass"} def downgrade(): ${downgrades if downgrades else "pass"}
superset/migrations/script.py.mako
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0001772570249158889, 0.00017491498147137463, 0.00017177188419736922, 0.0001753155083861202, 0.0000021904809273110004 ]
{ "id": 6, "code_window": [ " </Menu>\n", " );\n", "\n", " const iconMenu = () =>\n", " report ? (\n", " <>\n", " <NoAnimationDropdown\n", " overlay={menu()}\n", " trigger={['click']}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " isEmpty(report) ? (\n", " <span\n", " role=\"button\"\n", " title={t('Schedule email report')}\n", " tabIndex={0}\n", " className=\"action-button action-schedule-report\"\n", " onClick={() => setShowModal(true)}\n", " >\n", " <Icons.Calendar />\n", " </span>\n", " ) : (\n" ], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 262 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { updateDataMask } from 'src/dataMask/actions'; import DashboardHeader from 'src/dashboard/components/Header'; import isDashboardLoading from 'src/dashboard/util/isDashboardLoading'; import { dashboardInfoChanged } from 'src/dashboard/actions/dashboardInfo'; import { setEditMode, showBuilderPane, fetchFaveStar, saveFaveStar, savePublished, setColorScheme, setUnsavedChanges, fetchCharts, updateCss, onChange, saveDashboardRequest, setMaxUndoHistoryExceeded, maxUndoHistoryToast, setRefreshFrequency, onRefresh, } from 'src/dashboard/actions/dashboardState'; import { undoLayoutAction, redoLayoutAction, updateDashboardTitle, dashboardTitleChanged, } from 'src/dashboard/actions/dashboardLayout'; import { addSuccessToast, addDangerToast, addWarningToast, } from 'src/components/MessageToasts/actions'; import { logEvent } from 'src/logger/actions'; import { DASHBOARD_HEADER_ID } from 'src/dashboard/util/constants'; import { fetchUISpecificReport } from 'src/reports/actions/reports'; function mapStateToProps({ dashboardLayout: undoableLayout, dashboardState, reports, dashboardInfo, charts, dataMask, user, }) { return { dashboardInfo, undoLength: undoableLayout.past.length, redoLength: undoableLayout.future.length, layout: undoableLayout.present, dashboardTitle: ( (undoableLayout.present[DASHBOARD_HEADER_ID] || {}).meta || {} ).text, expandedSlices: dashboardState.expandedSlices, refreshFrequency: dashboardState.refreshFrequency, shouldPersistRefreshFrequency: !!dashboardState.shouldPersistRefreshFrequency, customCss: dashboardState.css, colorNamespace: dashboardState.colorNamespace, colorScheme: dashboardState.colorScheme, charts, dataMask, user, isStarred: !!dashboardState.isStarred, isPublished: !!dashboardState.isPublished, isLoading: isDashboardLoading(charts), hasUnsavedChanges: !!dashboardState.hasUnsavedChanges, maxUndoHistoryExceeded: !!dashboardState.maxUndoHistoryExceeded, lastModifiedTime: Math.max( dashboardState.lastModifiedTime, dashboardInfo.last_modified_time, ), editMode: !!dashboardState.editMode, slug: dashboardInfo.slug, metadata: dashboardInfo.metadata, reports, }; } function mapDispatchToProps(dispatch) { return bindActionCreators( { addSuccessToast, addDangerToast, addWarningToast, onUndo: undoLayoutAction, onRedo: redoLayoutAction, setEditMode, showBuilderPane, setColorScheme, setUnsavedChanges, fetchFaveStar, saveFaveStar, savePublished, fetchCharts, updateDashboardTitle, updateCss, onChange, onSave: saveDashboardRequest, setMaxUndoHistoryExceeded, maxUndoHistoryToast, logEvent, setRefreshFrequency, onRefresh, dashboardInfoChanged, dashboardTitleChanged, updateDataMask, fetchUISpecificReport, }, dispatch, ); } export default connect(mapStateToProps, mapDispatchToProps)(DashboardHeader);
superset-frontend/src/dashboard/containers/DashboardHeader.jsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0002570880460552871, 0.00017814684542827308, 0.0001648862671572715, 0.00017408697749488056, 0.000022223139239940792 ]
{ "id": 7, "code_window": [ " <Icons.Calendar />\n", " </span>\n", " </NoAnimationDropdown>\n", " </>\n", " ) : (\n", " <span\n", " role=\"button\"\n", " title={t('Schedule email report')}\n", " tabIndex={0}\n", " className=\"action-button action-schedule-report\"\n", " onClick={() => setShowModal(true)}\n", " >\n", " <Icons.Calendar />\n", " </span>\n", " );\n", "\n", " return (\n", " <>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 280 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { t, SupersetTheme, css, styled, useTheme, FeatureFlag, isFeatureEnabled, getExtensionsRegistry, usePrevious, } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import { Switch } from 'src/components/Switch'; import { AlertObject } from 'src/features/alerts/types'; import { Menu } from 'src/components/Menu'; import Checkbox from 'src/components/Checkbox'; import { noOp } from 'src/utils/common'; import { NoAnimationDropdown } from 'src/components/Dropdown'; import DeleteModal from 'src/components/DeleteModal'; import ReportModal from 'src/components/ReportModal'; import { ChartState } from 'src/explore/types'; import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; import { fetchUISpecificReport, toggleActive, deleteActiveReport, } from 'src/reports/actions/reports'; import { reportSelector } from 'src/views/CRUD/hooks'; import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index'; const extensionsRegistry = getExtensionsRegistry(); const deleteColor = (theme: SupersetTheme) => css` color: ${theme.colors.error.base}; `; const onMenuHover = (theme: SupersetTheme) => css` & .ant-menu-item { padding: 5px 12px; margin-top: 0px; margin-bottom: 4px; :hover { color: ${theme.colors.grayscale.dark1}; } } :hover { background-color: ${theme.colors.secondary.light5}; } `; const onMenuItemHover = (theme: SupersetTheme) => css` &:hover { color: ${theme.colors.grayscale.dark1}; background-color: ${theme.colors.secondary.light5}; } `; const StyledDropdownItemWithIcon = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; > *:first-child { margin-right: ${({ theme }) => theme.gridUnit}px; } `; const DropdownItemExtension = extensionsRegistry.get( 'report-modal.dropdown.item.icon', ); export enum CreationMethod { CHARTS = 'charts', DASHBOARDS = 'dashboards', } export interface HeaderReportProps { dashboardId?: number; chart?: ChartState; useTextMenu?: boolean; setShowReportSubMenu?: (show: boolean) => void; setIsDropdownVisible?: (visible: boolean) => void; isDropdownVisible?: boolean; showReportSubMenu?: boolean; } export default function HeaderReportDropDown({ dashboardId, chart, useTextMenu = false, setShowReportSubMenu, setIsDropdownVisible, isDropdownVisible, }: HeaderReportProps) { const dispatch = useDispatch(); const report = useSelector<any, AlertObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isReportActive: boolean = report?.active || false; const user: UserWithPermissionsAndRoles = useSelector< any, UserWithPermissionsAndRoles >(state => state.user); const canAddReports = () => { if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) { return false; } if (!user?.userId) { // this is in the case that there is an anonymous user. return false; } const roles = Object.keys(user.roles || []); const permissions = roles.map(key => user.roles[key].filter( perms => perms[0] === 'menu_access' && perms[1] === 'Manage', ), ); return permissions.some(permission => permission.length > 0); }; const [currentReportDeleting, setCurrentReportDeleting] = useState<AlertObject | null>(null); const theme = useTheme(); const prevDashboard = usePrevious(dashboardId); const [showModal, setShowModal] = useState<boolean>(false); const toggleActiveKey = async (data: AlertObject, checked: boolean) => { if (data?.id) { dispatch(toggleActive(data, checked)); } }; const handleReportDelete = async (report: AlertObject) => { await dispatch(deleteActiveReport(report)); setCurrentReportDeleting(null); }; const shouldFetch = canAddReports() && !!((dashboardId && prevDashboard !== dashboardId) || chart?.id); useEffect(() => { if (shouldFetch) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: dashboardId ? 'dashboard_id' : 'chart_id', creationMethod: dashboardId ? 'dashboards' : 'charts', resourceId: dashboardId || chart?.id, }), ); } }, []); const showReportSubMenu = report && setShowReportSubMenu && canAddReports(); useEffect(() => { if (showReportSubMenu) { setShowReportSubMenu(true); } else if (!report && setShowReportSubMenu) { setShowReportSubMenu(false); } }, [report]); const handleShowMenu = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setShowModal(true); } }; const handleDeleteMenuClick = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setCurrentReportDeleting(report); } }; const textMenu = () => report ? ( isDropdownVisible && ( <Menu selectable={false} css={{ border: 'none' }}> <Menu.Item css={onMenuItemHover} onClick={() => toggleActiveKey(report, !isReportActive)} > <MenuItemWithCheckboxContainer> <Checkbox checked={isReportActive} onChange={noOp} /> {t('Email reports active')} </MenuItemWithCheckboxContainer> </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleShowMenu}> {t('Edit email report')} </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}> {t('Delete email report')} </Menu.Item> </Menu> ) ) : ( <Menu selectable={false} css={onMenuHover}> <Menu.Item onClick={handleShowMenu}> {DropdownItemExtension ? ( <StyledDropdownItemWithIcon> <div>{t('Set up an email report')}</div> <DropdownItemExtension /> </StyledDropdownItemWithIcon> ) : ( t('Set up an email report') )} </Menu.Item> <Menu.Divider /> </Menu> ); const menu = () => ( <Menu selectable={false} css={{ width: '200px' }}> <Menu.Item> {t('Email reports active')} <Switch data-test="toggle-active" checked={isReportActive} onClick={(checked: boolean) => toggleActiveKey(report, checked)} size="small" css={{ marginLeft: theme.gridUnit * 2 }} /> </Menu.Item> <Menu.Item onClick={() => setShowModal(true)}> {t('Edit email report')} </Menu.Item> <Menu.Item onClick={() => setCurrentReportDeleting(report)} css={deleteColor} > {t('Delete email report')} </Menu.Item> </Menu> ); const iconMenu = () => report ? ( <> <NoAnimationDropdown overlay={menu()} trigger={['click']} getPopupContainer={(triggerNode: any) => triggerNode.closest('.action-button') } > <span role="button" className="action-button action-schedule-report" tabIndex={0} > <Icons.Calendar /> </span> </NoAnimationDropdown> </> ) : ( <span role="button" title={t('Schedule email report')} tabIndex={0} className="action-button action-schedule-report" onClick={() => setShowModal(true)} > <Icons.Calendar /> </span> ); return ( <> {canAddReports() && ( <> <ReportModal userId={user.userId} show={showModal} onHide={() => setShowModal(false)} userEmail={user.email} dashboardId={dashboardId} chart={chart} creationMethod={ dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS } /> {useTextMenu ? textMenu() : iconMenu()} {currentReportDeleting && ( <DeleteModal description={t( 'This action will permanently delete %s.', currentReportDeleting?.name, )} onConfirm={() => { if (currentReportDeleting) { handleReportDelete(currentReportDeleting); } }} onHide={() => setCurrentReportDeleting(null)} open title={t('Delete Report?')} /> )} </> )} </> ); }
superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.8224305510520935, 0.026578186079859734, 0.00016474624862894416, 0.0001778789155650884, 0.14082665741443634 ]
{ "id": 7, "code_window": [ " <Icons.Calendar />\n", " </span>\n", " </NoAnimationDropdown>\n", " </>\n", " ) : (\n", " <span\n", " role=\"button\"\n", " title={t('Schedule email report')}\n", " tabIndex={0}\n", " className=\"action-button action-schedule-report\"\n", " onClick={() => setShowModal(true)}\n", " >\n", " <Icons.Calendar />\n", " </span>\n", " );\n", "\n", " return (\n", " <>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 280 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { ControlStateMapping } from '@superset-ui/chart-controls'; import { ChartState, ExplorePageInitialData, ExplorePageState, } from 'src/explore/types'; import { getChartKey } from 'src/explore/exploreUtils'; import { getControlsState } from 'src/explore/store'; import { Dispatch } from 'redux'; import { ensureIsArray, getCategoricalSchemeRegistry, getColumnLabel, getSequentialSchemeRegistry, hasGenericChartAxes, NO_TIME_RANGE, QueryFormColumn, } from '@superset-ui/core'; import { getFormDataFromControls, applyMapStateToPropsToControl, } from 'src/explore/controlUtils'; import { getDatasourceUid } from 'src/utils/getDatasourceUid'; import { getUrlParam } from 'src/utils/urlUtils'; import { URL_PARAMS } from 'src/constants'; import { findPermission } from 'src/utils/findPermission'; enum ColorSchemeType { CATEGORICAL = 'CATEGORICAL', SEQUENTIAL = 'SEQUENTIAL', } export const HYDRATE_EXPLORE = 'HYDRATE_EXPLORE'; export const hydrateExplore = ({ form_data, slice, dataset, metadata, saveAction = null, }: ExplorePageInitialData) => (dispatch: Dispatch, getState: () => ExplorePageState) => { const { user, datasources, charts, sliceEntities, common, explore } = getState(); const sliceId = getUrlParam(URL_PARAMS.sliceId); const dashboardId = getUrlParam(URL_PARAMS.dashboardId); const fallbackSlice = sliceId ? sliceEntities?.slices?.[sliceId] : null; const initialSlice = slice ?? fallbackSlice; const initialFormData = form_data ?? initialSlice?.form_data; if (!initialFormData.viz_type) { const defaultVizType = common?.conf.DEFAULT_VIZ_TYPE || 'table'; initialFormData.viz_type = getUrlParam(URL_PARAMS.vizType) || defaultVizType; } if (!initialFormData.time_range) { initialFormData.time_range = common?.conf?.DEFAULT_TIME_FILTER || NO_TIME_RANGE; } if ( hasGenericChartAxes && initialFormData.include_time && initialFormData.granularity_sqla && !initialFormData.groupby?.some( (col: QueryFormColumn) => getColumnLabel(col) === getColumnLabel(initialFormData.granularity_sqla!), ) ) { initialFormData.groupby = [ initialFormData.granularity_sqla, ...ensureIsArray(initialFormData.groupby), ]; initialFormData.granularity_sqla = undefined; } if (dashboardId) { initialFormData.dashboardId = dashboardId; } const initialDatasource = dataset; const initialExploreState = { form_data: initialFormData, slice: initialSlice, datasource: initialDatasource, }; const initialControls = getControlsState( initialExploreState, initialFormData, ) as ControlStateMapping; const colorSchemeKey = initialControls.color_scheme && 'color_scheme'; const linearColorSchemeKey = initialControls.linear_color_scheme && 'linear_color_scheme'; // if the selected color scheme does not exist anymore // fallbacks and selects the available default one const verifyColorScheme = (type: ColorSchemeType) => { const schemes = type === 'CATEGORICAL' ? getCategoricalSchemeRegistry() : getSequentialSchemeRegistry(); const key = type === 'CATEGORICAL' ? colorSchemeKey : linearColorSchemeKey; const registryDefaultScheme = schemes.defaultKey; const defaultScheme = type === 'CATEGORICAL' ? 'supersetColors' : 'superset_seq_1'; const currentScheme = initialFormData[key]; const colorSchemeExists = !!schemes.get(currentScheme, true); if (currentScheme && !colorSchemeExists) { initialControls[key].value = registryDefaultScheme || defaultScheme; } }; if (colorSchemeKey) verifyColorScheme(ColorSchemeType.CATEGORICAL); if (linearColorSchemeKey) verifyColorScheme(ColorSchemeType.SEQUENTIAL); const exploreState = { // note this will add `form_data` to state, // which will be manipulable by future reducers. can_add: findPermission('can_write', 'Chart', user?.roles), can_download: findPermission('can_csv', 'Superset', user?.roles), can_overwrite: ensureIsArray(slice?.owners).includes( user?.userId as number, ), isDatasourceMetaLoading: false, isStarred: false, triggerRender: false, // duplicate datasource in exploreState - it's needed by getControlsState datasource: initialDatasource, // Initial control state will skip `control.mapStateToProps` // because `bootstrapData.controls` is undefined. controls: initialControls, form_data: initialFormData, slice: initialSlice, controlsTransferred: explore.controlsTransferred, standalone: getUrlParam(URL_PARAMS.standalone), force: getUrlParam(URL_PARAMS.force), metadata, saveAction, common, }; // apply initial mapStateToProps for all controls, must execute AFTER // bootstrapState has initialized `controls`. Order of execution is not // guaranteed, so controls shouldn't rely on each other's mapped state. Object.entries(exploreState.controls).forEach(([key, controlState]) => { exploreState.controls[key] = applyMapStateToPropsToControl( controlState, exploreState, ); }); const sliceFormData = initialSlice ? getFormDataFromControls(initialControls) : null; const chartKey: number = getChartKey(initialExploreState); const chart: ChartState = { id: chartKey, chartAlert: null, chartStatus: null, chartStackTrace: null, chartUpdateEndTime: null, chartUpdateStartTime: 0, latestQueryFormData: getFormDataFromControls(exploreState.controls), sliceFormData, queryController: null, queriesResponse: null, triggerQuery: false, lastRendered: 0, }; return dispatch({ type: HYDRATE_EXPLORE, data: { charts: { ...charts, [chartKey]: chart, }, datasources: { ...datasources, [getDatasourceUid(initialDatasource)]: initialDatasource, }, saveModal: { dashboards: [], saveModalAlert: null, isVisible: false, }, explore: exploreState, }, }); }; export type HydrateExplore = { type: typeof HYDRATE_EXPLORE; data: ExplorePageState; };
superset-frontend/src/explore/actions/hydrateExplore.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0001778790756361559, 0.00017235515406355262, 0.00016292862710542977, 0.00017275623395107687, 0.000002940965714515187 ]
{ "id": 7, "code_window": [ " <Icons.Calendar />\n", " </span>\n", " </NoAnimationDropdown>\n", " </>\n", " ) : (\n", " <span\n", " role=\"button\"\n", " title={t('Schedule email report')}\n", " tabIndex={0}\n", " className=\"action-button action-schedule-report\"\n", " onClick={() => setShowModal(true)}\n", " >\n", " <Icons.Calendar />\n", " </span>\n", " );\n", "\n", " return (\n", " <>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 280 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """position_json Revision ID: 1a1d627ebd8e Revises: 0c5070e96b57 Create Date: 2018-08-13 11:30:07.101702 """ import sqlalchemy as sa from alembic import op from superset.utils.core import MediumText # revision identifiers, used by Alembic. revision = "1a1d627ebd8e" down_revision = "0c5070e96b57" def upgrade(): with op.batch_alter_table("dashboards") as batch_op: batch_op.alter_column( "position_json", existing_type=sa.Text(), type_=MediumText(), existing_nullable=True, ) def downgrade(): with op.batch_alter_table("dashboards") as batch_op: batch_op.alter_column( "position_json", existing_type=MediumText(), type_=sa.Text(), existing_nullable=True, )
superset/migrations/versions/2018-08-13_11-30_1a1d627ebd8e_position_json.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017813943850342184, 0.00017147343896795064, 0.00016672175843268633, 0.00017124408623203635, 0.000003801749471676885 ]
{ "id": 7, "code_window": [ " <Icons.Calendar />\n", " </span>\n", " </NoAnimationDropdown>\n", " </>\n", " ) : (\n", " <span\n", " role=\"button\"\n", " title={t('Schedule email report')}\n", " tabIndex={0}\n", " className=\"action-button action-schedule-report\"\n", " onClick={() => setShowModal(true)}\n", " >\n", " <Icons.Calendar />\n", " </span>\n", " );\n", "\n", " return (\n", " <>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx", "type": "replace", "edit_start_line_idx": 280 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ export * from './useChangeEffect';
superset-frontend/packages/superset-ui-core/src/hooks/useChangeEffect/index.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0001778789155650884, 0.00017342060164082795, 0.00016651394253131002, 0.00017586894682608545, 0.0000049522013796376996 ]
{ "id": 8, "code_window": [ " * Is submitting changes to the backend.\n", " */\n", " isSubmitting?: boolean;\n", "};\n", "\n", "function ReportModal({\n", " onHide,\n", " show = false,\n", " dashboardId,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Same instance to be used in useEffects\n", "const EMPTY_OBJECT = {};\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/index.tsx", "type": "add", "edit_start_line_idx": 95 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { t, SupersetTheme, css, styled, useTheme, FeatureFlag, isFeatureEnabled, getExtensionsRegistry, usePrevious, } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import { Switch } from 'src/components/Switch'; import { AlertObject } from 'src/features/alerts/types'; import { Menu } from 'src/components/Menu'; import Checkbox from 'src/components/Checkbox'; import { noOp } from 'src/utils/common'; import { NoAnimationDropdown } from 'src/components/Dropdown'; import DeleteModal from 'src/components/DeleteModal'; import ReportModal from 'src/components/ReportModal'; import { ChartState } from 'src/explore/types'; import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; import { fetchUISpecificReport, toggleActive, deleteActiveReport, } from 'src/reports/actions/reports'; import { reportSelector } from 'src/views/CRUD/hooks'; import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index'; const extensionsRegistry = getExtensionsRegistry(); const deleteColor = (theme: SupersetTheme) => css` color: ${theme.colors.error.base}; `; const onMenuHover = (theme: SupersetTheme) => css` & .ant-menu-item { padding: 5px 12px; margin-top: 0px; margin-bottom: 4px; :hover { color: ${theme.colors.grayscale.dark1}; } } :hover { background-color: ${theme.colors.secondary.light5}; } `; const onMenuItemHover = (theme: SupersetTheme) => css` &:hover { color: ${theme.colors.grayscale.dark1}; background-color: ${theme.colors.secondary.light5}; } `; const StyledDropdownItemWithIcon = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; > *:first-child { margin-right: ${({ theme }) => theme.gridUnit}px; } `; const DropdownItemExtension = extensionsRegistry.get( 'report-modal.dropdown.item.icon', ); export enum CreationMethod { CHARTS = 'charts', DASHBOARDS = 'dashboards', } export interface HeaderReportProps { dashboardId?: number; chart?: ChartState; useTextMenu?: boolean; setShowReportSubMenu?: (show: boolean) => void; setIsDropdownVisible?: (visible: boolean) => void; isDropdownVisible?: boolean; showReportSubMenu?: boolean; } export default function HeaderReportDropDown({ dashboardId, chart, useTextMenu = false, setShowReportSubMenu, setIsDropdownVisible, isDropdownVisible, }: HeaderReportProps) { const dispatch = useDispatch(); const report = useSelector<any, AlertObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isReportActive: boolean = report?.active || false; const user: UserWithPermissionsAndRoles = useSelector< any, UserWithPermissionsAndRoles >(state => state.user); const canAddReports = () => { if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) { return false; } if (!user?.userId) { // this is in the case that there is an anonymous user. return false; } const roles = Object.keys(user.roles || []); const permissions = roles.map(key => user.roles[key].filter( perms => perms[0] === 'menu_access' && perms[1] === 'Manage', ), ); return permissions.some(permission => permission.length > 0); }; const [currentReportDeleting, setCurrentReportDeleting] = useState<AlertObject | null>(null); const theme = useTheme(); const prevDashboard = usePrevious(dashboardId); const [showModal, setShowModal] = useState<boolean>(false); const toggleActiveKey = async (data: AlertObject, checked: boolean) => { if (data?.id) { dispatch(toggleActive(data, checked)); } }; const handleReportDelete = async (report: AlertObject) => { await dispatch(deleteActiveReport(report)); setCurrentReportDeleting(null); }; const shouldFetch = canAddReports() && !!((dashboardId && prevDashboard !== dashboardId) || chart?.id); useEffect(() => { if (shouldFetch) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: dashboardId ? 'dashboard_id' : 'chart_id', creationMethod: dashboardId ? 'dashboards' : 'charts', resourceId: dashboardId || chart?.id, }), ); } }, []); const showReportSubMenu = report && setShowReportSubMenu && canAddReports(); useEffect(() => { if (showReportSubMenu) { setShowReportSubMenu(true); } else if (!report && setShowReportSubMenu) { setShowReportSubMenu(false); } }, [report]); const handleShowMenu = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setShowModal(true); } }; const handleDeleteMenuClick = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setCurrentReportDeleting(report); } }; const textMenu = () => report ? ( isDropdownVisible && ( <Menu selectable={false} css={{ border: 'none' }}> <Menu.Item css={onMenuItemHover} onClick={() => toggleActiveKey(report, !isReportActive)} > <MenuItemWithCheckboxContainer> <Checkbox checked={isReportActive} onChange={noOp} /> {t('Email reports active')} </MenuItemWithCheckboxContainer> </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleShowMenu}> {t('Edit email report')} </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}> {t('Delete email report')} </Menu.Item> </Menu> ) ) : ( <Menu selectable={false} css={onMenuHover}> <Menu.Item onClick={handleShowMenu}> {DropdownItemExtension ? ( <StyledDropdownItemWithIcon> <div>{t('Set up an email report')}</div> <DropdownItemExtension /> </StyledDropdownItemWithIcon> ) : ( t('Set up an email report') )} </Menu.Item> <Menu.Divider /> </Menu> ); const menu = () => ( <Menu selectable={false} css={{ width: '200px' }}> <Menu.Item> {t('Email reports active')} <Switch data-test="toggle-active" checked={isReportActive} onClick={(checked: boolean) => toggleActiveKey(report, checked)} size="small" css={{ marginLeft: theme.gridUnit * 2 }} /> </Menu.Item> <Menu.Item onClick={() => setShowModal(true)}> {t('Edit email report')} </Menu.Item> <Menu.Item onClick={() => setCurrentReportDeleting(report)} css={deleteColor} > {t('Delete email report')} </Menu.Item> </Menu> ); const iconMenu = () => report ? ( <> <NoAnimationDropdown overlay={menu()} trigger={['click']} getPopupContainer={(triggerNode: any) => triggerNode.closest('.action-button') } > <span role="button" className="action-button action-schedule-report" tabIndex={0} > <Icons.Calendar /> </span> </NoAnimationDropdown> </> ) : ( <span role="button" title={t('Schedule email report')} tabIndex={0} className="action-button action-schedule-report" onClick={() => setShowModal(true)} > <Icons.Calendar /> </span> ); return ( <> {canAddReports() && ( <> <ReportModal userId={user.userId} show={showModal} onHide={() => setShowModal(false)} userEmail={user.email} dashboardId={dashboardId} chart={chart} creationMethod={ dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS } /> {useTextMenu ? textMenu() : iconMenu()} {currentReportDeleting && ( <DeleteModal description={t( 'This action will permanently delete %s.', currentReportDeleting?.name, )} onConfirm={() => { if (currentReportDeleting) { handleReportDelete(currentReportDeleting); } }} onHide={() => setCurrentReportDeleting(null)} open title={t('Delete Report?')} /> )} </> )} </> ); }
superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.9989237189292908, 0.20888365805149078, 0.0001656567183090374, 0.00030421363771893084, 0.40044641494750977 ]
{ "id": 8, "code_window": [ " * Is submitting changes to the backend.\n", " */\n", " isSubmitting?: boolean;\n", "};\n", "\n", "function ReportModal({\n", " onHide,\n", " show = false,\n", " dashboardId,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Same instance to be used in useEffects\n", "const EMPTY_OBJECT = {};\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/index.tsx", "type": "add", "edit_start_line_idx": 95 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { useCallback, useEffect } from 'react'; /* eslint camelcase: 0 */ import URI from 'urijs'; import { buildQueryContext, ensureIsArray, getChartBuildQueryRegistry, getChartMetadataRegistry, SupersetClient, } from '@superset-ui/core'; import { availableDomains } from 'src/utils/hostNamesConfig'; import { safeStringify } from 'src/utils/safeStringify'; import { optionLabel } from 'src/utils/common'; import { URL_PARAMS } from 'src/constants'; import { MULTI_OPERATORS, OPERATOR_ENUM_TO_OPERATOR_TYPE, UNSAVED_CHART_ID, } from 'src/explore/constants'; import { DashboardStandaloneMode } from 'src/dashboard/util/constants'; export function getChartKey(explore) { const { slice, form_data } = explore; return slice?.slice_id ?? form_data?.slice_id ?? UNSAVED_CHART_ID; } let requestCounter = 0; export function getHostName(allowDomainSharding = false) { let currentIndex = 0; if (allowDomainSharding) { currentIndex = requestCounter % availableDomains.length; requestCounter += 1; // if domain sharding is enabled, skip main domain for fetching chart API // leave main domain free for other calls like fav star, save change, etc. // to make dashboard be responsive when it's loading large number of charts if (currentIndex === 0) { currentIndex += 1; requestCounter += 1; } } return availableDomains[currentIndex]; } export function getAnnotationJsonUrl(slice_id, force) { if (slice_id === null || slice_id === undefined) { return null; } const uri = URI(window.location.search); return uri .pathname('/api/v1/chart/data') .search({ form_data: safeStringify({ slice_id }), force, }) .toString(); } export function getURIDirectory(endpointType = 'base') { // Building the directory part of the URI if ( ['full', 'json', 'csv', 'query', 'results', 'samples'].includes( endpointType, ) ) { return '/superset/explore_json/'; } return '/explore/'; } export function mountExploreUrl(endpointType, extraSearch = {}, force = false) { const uri = new URI('/'); const directory = getURIDirectory(endpointType); const search = uri.search(true); Object.keys(extraSearch).forEach(key => { search[key] = extraSearch[key]; }); if (endpointType === URL_PARAMS.standalone.name) { if (force) { search.force = '1'; } search.standalone = DashboardStandaloneMode.HIDE_NAV; } return uri.directory(directory).search(search).toString(); } export function getChartDataUri({ path, qs, allowDomainSharding = false }) { // The search params from the window.location are carried through, // but can be specified with curUrl (used for unit tests to spoof // the window.location). let uri = new URI({ protocol: window.location.protocol.slice(0, -1), hostname: getHostName(allowDomainSharding), port: window.location.port ? window.location.port : '', path, }); if (qs) { uri = uri.search(qs); } return uri; } /** * This gets the minimal url for the given form data. * If there are dashboard overrides present in the form data, * they will not be included in the url. */ export function getExploreUrl({ formData, endpointType = 'base', force = false, curUrl = null, requestParams = {}, allowDomainSharding = false, method = 'POST', }) { if (!formData.datasource) { return null; } // label_colors should not pollute the URL // eslint-disable-next-line no-param-reassign delete formData.label_colors; let uri = getChartDataUri({ path: '/', allowDomainSharding }); if (curUrl) { uri = URI(URI(curUrl).search()); } const directory = getURIDirectory(endpointType); // Building the querystring (search) part of the URI const search = uri.search(true); const { slice_id, extra_filters, adhoc_filters, viz_type } = formData; if (slice_id) { const form_data = { slice_id }; if (method === 'GET') { form_data.viz_type = viz_type; if (extra_filters && extra_filters.length) { form_data.extra_filters = extra_filters; } if (adhoc_filters && adhoc_filters.length) { form_data.adhoc_filters = adhoc_filters; } } search.form_data = safeStringify(form_data); } if (force) { search.force = 'true'; } if (endpointType === 'csv') { search.csv = 'true'; } if (endpointType === URL_PARAMS.standalone.name) { search.standalone = '1'; } if (endpointType === 'query') { search.query = 'true'; } if (endpointType === 'results') { search.results = 'true'; } if (endpointType === 'samples') { search.samples = 'true'; } const paramNames = Object.keys(requestParams); if (paramNames.length) { paramNames.forEach(name => { if (requestParams.hasOwnProperty(name)) { search[name] = requestParams[name]; } }); } return uri.search(search).directory(directory).toString(); } export const shouldUseLegacyApi = formData => { const vizMetadata = getChartMetadataRegistry().get(formData.viz_type); return vizMetadata ? vizMetadata.useLegacyApi : false; }; export const buildV1ChartDataPayload = ({ formData, force, resultFormat, resultType, setDataMask, ownState, }) => { const buildQuery = getChartBuildQueryRegistry().get(formData.viz_type) ?? (buildQueryformData => buildQueryContext(buildQueryformData, baseQueryObject => [ { ...baseQueryObject, }, ])); return buildQuery( { ...formData, force, result_format: resultFormat, result_type: resultType, }, { ownState, hooks: { setDataMask, }, }, ); }; export const getLegacyEndpointType = ({ resultType, resultFormat }) => resultFormat === 'csv' ? resultFormat : resultType; export const exportChart = ({ formData, resultFormat = 'json', resultType = 'full', force = false, ownState = {}, }) => { let url; let payload; if (shouldUseLegacyApi(formData)) { const endpointType = getLegacyEndpointType({ resultFormat, resultType }); url = getExploreUrl({ formData, endpointType, allowDomainSharding: false, }); payload = formData; } else { url = '/api/v1/chart/data'; payload = buildV1ChartDataPayload({ formData, force, resultFormat, resultType, ownState, }); } SupersetClient.postForm(url, { form_data: safeStringify(payload) }); }; export const exploreChart = (formData, requestParams) => { const url = getExploreUrl({ formData, endpointType: 'base', allowDomainSharding: false, requestParams, }); SupersetClient.postForm(url, { form_data: safeStringify(formData) }); }; export const useDebouncedEffect = (effect, delay, deps) => { // eslint-disable-next-line react-hooks/exhaustive-deps const callback = useCallback(effect, deps); useEffect(() => { const handler = setTimeout(() => { callback(); }, delay); return () => { clearTimeout(handler); }; }, [callback, delay]); }; export const getSimpleSQLExpression = (subject, operator, comparator) => { const isMulti = [...MULTI_OPERATORS] .map(op => OPERATOR_ENUM_TO_OPERATOR_TYPE[op].operation) .indexOf(operator) >= 0; let expression = subject ?? ''; if (subject && operator) { expression += ` ${operator}`; const firstValue = isMulti && Array.isArray(comparator) ? comparator[0] : comparator; const comparatorArray = ensureIsArray(comparator); const isString = firstValue !== undefined && Number.isNaN(Number(firstValue)); const quote = isString ? "'" : ''; const [prefix, suffix] = isMulti ? ['(', ')'] : ['', '']; const formattedComparators = comparatorArray .map(val => optionLabel(val)) .map( val => `${quote}${isString ? String(val).replace("'", "''") : val}${quote}`, ); if (comparatorArray.length > 0) { expression += ` ${prefix}${formattedComparators.join(', ')}${suffix}`; } } return expression; }; export function formatSelectOptions(options) { return options.map(opt => [opt, opt.toString()]); }
superset-frontend/src/explore/exploreUtils/index.js
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00026503842673264444, 0.00017619931895751506, 0.00016771189984865487, 0.00017031322931870818, 0.000019105253159068525 ]
{ "id": 8, "code_window": [ " * Is submitting changes to the backend.\n", " */\n", " isSubmitting?: boolean;\n", "};\n", "\n", "function ReportModal({\n", " onHide,\n", " show = false,\n", " dashboardId,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Same instance to be used in useEffects\n", "const EMPTY_OBJECT = {};\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/index.tsx", "type": "add", "edit_start_line_idx": 95 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> ## @superset-ui/legacy-plugin-chart-country-map [![Version](https://img.shields.io/npm/v/@superset-ui/legacy-plugin-chart-country-map.svg?style=flat-square)](https://www.npmjs.com/package/@superset-ui/legacy-plugin-chart-country-map) [![David (path)](https://img.shields.io/david/apache-superset/superset-ui-plugins.svg?path=packages%2Fsuperset-ui-legacy-plugin-chart-country-map&style=flat-square)](https://david-dm.org/apache-superset/superset-ui-plugins?path=packages/superset-ui-legacy-plugin-chart-country-map) This plugin provides Country Map for Superset. ### Usage Configure `key`, which can be any `string`, and register the plugin. This `key` will be used to lookup this chart throughout the app. ```js import CountryMapChartPlugin from '@superset-ui/legacy-plugin-chart-country-map'; new CountryMapChartPlugin().configure({ key: 'country-map' }).register(); ``` Then use it via `SuperChart`. See [storybook](https://apache-superset.github.io/superset-ui-plugins/?selectedKind=plugin-chart-country-map) for more details. ```js <SuperChart chartType="country-map" width={600} height={600} formData={...} queriesData={[{ data: {...}, }]} /> ``` ### Update Map To update the country maps or add a new country, run scripts in the Jupyter notebook `scripts/Country Map GeoJSON Generator.ipynb`. ```bash pip install jupyter notebook jupyter notebook ```
superset-frontend/plugins/legacy-plugin-chart-country-map/README.md
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017736015433911234, 0.00017209384532179683, 0.0001619261020096019, 0.0001732860109768808, 0.000004813112354895566 ]
{ "id": 8, "code_window": [ " * Is submitting changes to the backend.\n", " */\n", " isSubmitting?: boolean;\n", "};\n", "\n", "function ReportModal({\n", " onHide,\n", " show = false,\n", " dashboardId,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Same instance to be used in useEffects\n", "const EMPTY_OBJECT = {};\n", "\n" ], "file_path": "superset-frontend/src/components/ReportModal/index.tsx", "type": "add", "edit_start_line_idx": 95 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from typing import Optional, Type from flask_babel import lazy_gettext as _ from marshmallow import ValidationError from superset import security_manager from superset.databases.commands.exceptions import DatabaseInvalidError from superset.databases.utils import make_url_safe from superset.models.core import Database def sqlalchemy_uri_validator( uri: str, exception: Type[ValidationError] = ValidationError ) -> None: """ Check if a user has submitted a valid SQLAlchemy URI """ try: make_url_safe(uri.strip()) except DatabaseInvalidError as ex: raise exception( [ _( "Invalid connection string, a valid string usually follows:" "'DRIVER://USER:PASSWORD@DB-HOST/DATABASE-NAME'" "<p>" "Example:'postgresql://user:password@your-postgres-db/database'" "</p>" ) ] ) from ex def schema_allows_file_upload(database: Database, schema: Optional[str]) -> bool: if not database.allow_file_upload: return False schemas = database.get_schema_access_for_file_upload() if schemas: return schema in schemas return security_manager.can_access_database(database)
superset/views/database/validators.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017621942970436066, 0.00017221989401150495, 0.00016931789286900312, 0.0001710176293272525, 0.0000027801497708423994 ]
{ "id": 9, "code_window": [ " const resourceType = dashboardId\n", " ? CreationMethod.DASHBOARDS\n", " : CreationMethod.CHARTS;\n", " return reportSelector(state, resourceType, dashboardId || chart?.id);\n", " });\n", " const isEditMode = report && Object.keys(report).length;\n", "\n", " useEffect(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return (\n", " reportSelector(state, resourceType, dashboardId || chart?.id) ||\n", " EMPTY_OBJECT\n", " );\n" ], "file_path": "superset-frontend/src/components/ReportModal/index.tsx", "type": "replace", "edit_start_line_idx": 149 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint-disable camelcase */ // eslint-disable-next-line import/no-extraneous-dependencies import { SET_REPORT, ADD_REPORT, EDIT_REPORT } from '../actions/reports'; export default function reportsReducer(state = {}, action) { const actionHandlers = { [SET_REPORT]() { const { report, resourceId, creationMethod, filterField } = action; // For now report count should only be one, but we are checking in case // functionality changes. const reportObject = report.result?.find( report => report[filterField] === resourceId, ); if (reportObject) { return { ...state, [creationMethod]: { ...state[creationMethod], [resourceId]: reportObject, }, }; } if (state?.[creationMethod]?.[resourceId]) { // remove the empty report from state const newState = { ...state }; delete newState[creationMethod][resourceId]; return newState; } return { ...state }; }, [ADD_REPORT]() { const { result, id } = action.json; const report = { ...result, id }; const reportTypeId = report.dashboard || report.chart; // this is the id of either the chart or the dashboard associated with the report. return { ...state, [report.creation_method]: { ...state[report.creation_method], [reportTypeId]: report, }, }; }, [EDIT_REPORT]() { const report = { ...action.json.result, id: action.json.id, }; const reportTypeId = report.dashboard || report.chart; return { ...state, [report.creation_method]: { ...state[report.creation_method], [reportTypeId]: report, }, }; }, }; if (action.type in actionHandlers) { return actionHandlers[action.type](); } return state; }
superset-frontend/src/reports/reducers/reports.js
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.01575198583304882, 0.003111978294327855, 0.00016995177429635078, 0.0005232360563240945, 0.004825802985578775 ]
{ "id": 9, "code_window": [ " const resourceType = dashboardId\n", " ? CreationMethod.DASHBOARDS\n", " : CreationMethod.CHARTS;\n", " return reportSelector(state, resourceType, dashboardId || chart?.id);\n", " });\n", " const isEditMode = report && Object.keys(report).length;\n", "\n", " useEffect(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return (\n", " reportSelector(state, resourceType, dashboardId || chart?.id) ||\n", " EMPTY_OBJECT\n", " );\n" ], "file_path": "superset-frontend/src/components/ReportModal/index.tsx", "type": "replace", "edit_start_line_idx": 149 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from sqlalchemy import types from superset.db_engine_specs.base import BaseEngineSpec, LimitMethod class OracleEngineSpec(BaseEngineSpec): engine = "oracle" engine_name = "Oracle" limit_method = LimitMethod.WRAP_SQL force_column_alias_quotes = True max_column_name_length = 30 _time_grain_expressions = { None: "{col}", "PT1S": "CAST({col} as DATE)", "PT1M": "TRUNC(CAST({col} as DATE), 'MI')", "PT1H": "TRUNC(CAST({col} as DATE), 'HH')", "P1D": "TRUNC(CAST({col} as DATE), 'DDD')", "P1W": "TRUNC(CAST({col} as DATE), 'WW')", "P1M": "TRUNC(CAST({col} as DATE), 'MONTH')", "P3M": "TRUNC(CAST({col} as DATE), 'Q')", "P1Y": "TRUNC(CAST({col} as DATE), 'YEAR')", } @classmethod def convert_dttm( cls, target_type: str, dttm: datetime, db_extra: Optional[Dict[str, Any]] = None ) -> Optional[str]: sqla_type = cls.get_sqla_column_type(target_type) if isinstance(sqla_type, types.Date): return f"TO_DATE('{dttm.date().isoformat()}', 'YYYY-MM-DD')" if isinstance(sqla_type, types.TIMESTAMP): return f"""TO_TIMESTAMP('{dttm .isoformat(timespec="microseconds")}', 'YYYY-MM-DD"T"HH24:MI:SS.ff6')""" if isinstance(sqla_type, types.DateTime): datetime_formatted = dttm.isoformat(timespec="seconds") return f"""TO_DATE('{datetime_formatted}', 'YYYY-MM-DD"T"HH24:MI:SS')""" return None @classmethod def epoch_to_dttm(cls) -> str: return "TO_DATE('1970-01-01','YYYY-MM-DD')+(1/24/60/60)*{col}" @classmethod def epoch_ms_to_dttm(cls) -> str: return "TO_DATE('1970-01-01','YYYY-MM-DD')+(1/24/60/60/1000)*{col}" @classmethod def fetch_data( cls, cursor: Any, limit: Optional[int] = None ) -> List[Tuple[Any, ...]]: """ :param cursor: Cursor instance :param limit: Maximum number of rows to be returned by the cursor :return: Result of query """ if not cursor.description: return [] return super().fetch_data(cursor, limit)
superset/db_engine_specs/oracle.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0002940715057775378, 0.00019196307403035462, 0.00017532747006043792, 0.00017723269411362708, 0.00003861565710394643 ]
{ "id": 9, "code_window": [ " const resourceType = dashboardId\n", " ? CreationMethod.DASHBOARDS\n", " : CreationMethod.CHARTS;\n", " return reportSelector(state, resourceType, dashboardId || chart?.id);\n", " });\n", " const isEditMode = report && Object.keys(report).length;\n", "\n", " useEffect(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return (\n", " reportSelector(state, resourceType, dashboardId || chart?.id) ||\n", " EMPTY_OBJECT\n", " );\n" ], "file_path": "superset-frontend/src/components/ReportModal/index.tsx", "type": "replace", "edit_start_line_idx": 149 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { buildQueryContext, QueryFormData } from '@superset-ui/core'; export default function buildQuery(formData: QueryFormData) { const { metric, sort_by_metric } = formData; return buildQueryContext(formData, baseQueryObject => [ { ...baseQueryObject, ...(sort_by_metric && { orderby: [[metric, false]] }), }, ]); }
superset-frontend/plugins/plugin-chart-echarts/src/Funnel/buildQuery.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017765008669812232, 0.00017652126553002745, 0.00017495073552709073, 0.00017696300346869975, 0.0000011454160357970977 ]
{ "id": 9, "code_window": [ " const resourceType = dashboardId\n", " ? CreationMethod.DASHBOARDS\n", " : CreationMethod.CHARTS;\n", " return reportSelector(state, resourceType, dashboardId || chart?.id);\n", " });\n", " const isEditMode = report && Object.keys(report).length;\n", "\n", " useEffect(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return (\n", " reportSelector(state, resourceType, dashboardId || chart?.id) ||\n", " EMPTY_OBJECT\n", " );\n" ], "file_path": "superset-frontend/src/components/ReportModal/index.tsx", "type": "replace", "edit_start_line_idx": 149 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { getChartIdAndColumnFromFilterKey } from './getDashboardFilterKey'; export default function getSelectedChartIdForFilterScopeTree({ activeFilterField, checkedFilterFields, }) { // we don't apply filter on filter_box itself, so we will disable // checkbox in filter scope selector. // this function returns chart id based on current filter scope selector local state: // 1. if in single-edit mode, return the chart id for selected filter field. // 2. if in multi-edit mode, if all filter fields are from same chart id, // return the single chart id. // otherwise, there is no chart to disable. if (activeFilterField) { return getChartIdAndColumnFromFilterKey(activeFilterField).chartId; } if (checkedFilterFields.length) { const { chartId } = getChartIdAndColumnFromFilterKey( checkedFilterFields[0], ); if ( checkedFilterFields.some( filterKey => getChartIdAndColumnFromFilterKey(filterKey).chartId !== chartId, ) ) { return null; } return chartId; } return null; }
superset-frontend/src/dashboard/util/getSelectedChartIdForFilterScopeTree.js
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.002257435815408826, 0.0005402882234193385, 0.0001749564107740298, 0.00020188657799735665, 0.00076827104203403 ]
{ "id": 10, "code_window": [ " });\n", " };\n", "}\n", "\n", "export function deleteActiveReport(report) {\n", " return function deleteActiveReportThunk(dispatch) {\n", " return SupersetClient.delete({\n", " endpoint: encodeURI(`/api/v1/report/${report.id}`),\n", " })\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const DELETE_REPORT = 'DELETE_REPORT';\n", "\n" ], "file_path": "superset-frontend/src/reports/actions/reports.js", "type": "add", "edit_start_line_idx": 145 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect, useReducer, useCallback, useMemo, } from 'react'; import { t, SupersetTheme } from '@superset-ui/core'; import { useDispatch, useSelector } from 'react-redux'; import { getClientErrorObject } from 'src/utils/getClientErrorObject'; import { addReport, editReport } from 'src/reports/actions/reports'; import Alert from 'src/components/Alert'; import TimezoneSelector from 'src/components/TimezoneSelector'; import LabeledErrorBoundInput from 'src/components/Form/LabeledErrorBoundInput'; import Icons from 'src/components/Icons'; import { CronError } from 'src/components/CronPicker'; import { RadioChangeEvent } from 'src/components'; import withToasts from 'src/components/MessageToasts/withToasts'; import { ChartState } from 'src/explore/types'; import { ReportCreationMethod, ReportObject, NOTIFICATION_FORMATS, } from 'src/reports/types'; import { reportSelector } from 'src/views/CRUD/hooks'; import { CreationMethod } from './HeaderReportDropdown'; import { antDErrorAlertStyles, StyledModal, StyledTopSection, StyledBottomSection, StyledIconWrapper, StyledScheduleTitle, StyledCronPicker, StyledCronError, noBottomMargin, StyledFooterButton, TimezoneHeaderStyle, SectionHeaderStyle, StyledMessageContentTitle, StyledRadio, StyledRadioGroup, } from './styles'; interface ReportProps { onHide: () => {}; addDangerToast: (msg: string) => void; show: boolean; userId: number; userEmail: string; chart?: ChartState; chartName?: string; dashboardId?: number; dashboardName?: string; creationMethod: ReportCreationMethod; props: any; } const TEXT_BASED_VISUALIZATION_TYPES = [ 'pivot_table', 'pivot_table_v2', 'table', 'paired_ttest', ]; const INITIAL_STATE = { crontab: '0 12 * * 1', }; type ReportObjectState = Partial<ReportObject> & { error?: string; /** * Is submitting changes to the backend. */ isSubmitting?: boolean; }; function ReportModal({ onHide, show = false, dashboardId, chart, userId, userEmail, creationMethod, dashboardName, chartName, }: ReportProps) { const vizType = chart?.sliceFormData?.viz_type; const isChart = !!chart; const isTextBasedChart = isChart && vizType && TEXT_BASED_VISUALIZATION_TYPES.includes(vizType); const defaultNotificationFormat = isTextBasedChart ? NOTIFICATION_FORMATS.TEXT : NOTIFICATION_FORMATS.PNG; const entityName = dashboardName || chartName; const initialState: ReportObjectState = useMemo( () => ({ ...INITIAL_STATE, name: entityName ? t('Weekly Report for %s', entityName) : t('Weekly Report'), }), [entityName], ); const reportReducer = useCallback( (state: ReportObjectState | null, action: 'reset' | ReportObjectState) => { if (action === 'reset') { return initialState; } return { ...state, ...action, }; }, [initialState], ); const [currentReport, setCurrentReport] = useReducer( reportReducer, initialState, ); const [cronError, setCronError] = useState<CronError>(); const dispatch = useDispatch(); // Report fetch logic const report = useSelector<any, ReportObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isEditMode = report && Object.keys(report).length; useEffect(() => { if (isEditMode) { setCurrentReport(report); } else { setCurrentReport('reset'); } }, [isEditMode, report]); const onSave = async () => { // Create new Report const newReportValues: Partial<ReportObject> = { type: 'Report', active: true, force_screenshot: false, creation_method: creationMethod, dashboard: dashboardId, chart: chart?.id, owners: [userId], recipients: [ { recipient_config_json: { target: userEmail }, type: 'Email', }, ], name: currentReport.name, description: currentReport.description, crontab: currentReport.crontab, report_format: currentReport.report_format || defaultNotificationFormat, timezone: currentReport.timezone, }; setCurrentReport({ isSubmitting: true, error: undefined }); try { if (isEditMode) { await dispatch( editReport(currentReport.id, newReportValues as ReportObject), ); } else { await dispatch(addReport(newReportValues as ReportObject)); } onHide(); } catch (e) { const { error } = await getClientErrorObject(e); setCurrentReport({ error }); } setCurrentReport({ isSubmitting: false }); }; const wrappedTitle = ( <StyledIconWrapper> <Icons.Calendar /> <span className="text"> {isEditMode ? t('Edit email report') : t('Schedule a new email report')} </span> </StyledIconWrapper> ); const renderModalFooter = ( <> <StyledFooterButton key="back" onClick={onHide}> {t('Cancel')} </StyledFooterButton> <StyledFooterButton key="submit" buttonStyle="primary" onClick={onSave} disabled={!currentReport.name} loading={currentReport.isSubmitting} > {isEditMode ? t('Save') : t('Add')} </StyledFooterButton> </> ); const renderMessageContentSection = ( <> <StyledMessageContentTitle> <h4>{t('Message content')}</h4> </StyledMessageContentTitle> <div className="inline-container"> <StyledRadioGroup onChange={(event: RadioChangeEvent) => { setCurrentReport({ report_format: event.target.value }); }} value={currentReport.report_format || defaultNotificationFormat} > {isTextBasedChart && ( <StyledRadio value={NOTIFICATION_FORMATS.TEXT}> {t('Text embedded in email')} </StyledRadio> )} <StyledRadio value={NOTIFICATION_FORMATS.PNG}> {t('Image (PNG) embedded in email')} </StyledRadio> <StyledRadio value={NOTIFICATION_FORMATS.CSV}> {t('Formatted CSV attached in email')} </StyledRadio> </StyledRadioGroup> </div> </> ); return ( <StyledModal show={show} onHide={onHide} title={wrappedTitle} footer={renderModalFooter} width="432" centered > <StyledTopSection> <LabeledErrorBoundInput id="name" name="name" value={currentReport.name || ''} placeholder={initialState.name} required validationMethods={{ onChange: ({ target }: { target: HTMLInputElement }) => setCurrentReport({ name: target.value }), }} label={t('Report Name')} data-test="report-name-test" /> <LabeledErrorBoundInput id="description" name="description" value={currentReport?.description || ''} validationMethods={{ onChange: ({ target }: { target: HTMLInputElement }) => { setCurrentReport({ description: target.value }); }, }} label={t('Description')} placeholder={t( 'Include a description that will be sent with your report', )} css={noBottomMargin} data-test="report-description-test" /> </StyledTopSection> <StyledBottomSection> <StyledScheduleTitle> <h4 css={(theme: SupersetTheme) => SectionHeaderStyle(theme)}> {t('Schedule')} </h4> <p> {t('A screenshot of the dashboard will be sent to your email at')} </p> </StyledScheduleTitle> <StyledCronPicker clearButton={false} value={currentReport.crontab || '0 12 * * 1'} setValue={(newValue: string) => { setCurrentReport({ crontab: newValue }); }} onError={setCronError} /> <StyledCronError>{cronError}</StyledCronError> <div className="control-label" css={(theme: SupersetTheme) => TimezoneHeaderStyle(theme)} > {t('Timezone')} </div> <TimezoneSelector timezone={currentReport.timezone} onTimezoneChange={value => { setCurrentReport({ timezone: value }); }} /> {isChart && renderMessageContentSection} </StyledBottomSection> {currentReport.error && ( <Alert type="error" css={(theme: SupersetTheme) => antDErrorAlertStyles(theme)} message={ isEditMode ? t('Failed to update report') : t('Failed to create report') } description={currentReport.error} /> )} </StyledModal> ); } export default withToasts(ReportModal);
superset-frontend/src/components/ReportModal/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0019258876563981175, 0.0002684603678062558, 0.00016384061018470675, 0.0001696330145932734, 0.0003705446142703295 ]
{ "id": 10, "code_window": [ " });\n", " };\n", "}\n", "\n", "export function deleteActiveReport(report) {\n", " return function deleteActiveReportThunk(dispatch) {\n", " return SupersetClient.delete({\n", " endpoint: encodeURI(`/api/v1/report/${report.id}`),\n", " })\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const DELETE_REPORT = 'DELETE_REPORT';\n", "\n" ], "file_path": "superset-frontend/src/reports/actions/reports.js", "type": "add", "edit_start_line_idx": 145 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { extent as d3Extent } from 'd3-array'; import { Point, Range } from '../types'; const LAT_LIMIT: Range = [-90, 90]; const LNG_LIMIT: Range = [-180, 180]; /** * Expand a coordinate range by `padding` and within limits, if needed */ function expandIfNeeded( [curMin, curMax]: Range, [minBound, maxBound]: Range, padding = 0.25, ) { return curMin < curMax ? [curMin, curMax] : [ Math.max(minBound, curMin - padding), Math.min(maxBound, curMax + padding), ]; } export default function computeBoundsFromPoints( points: Point[], ): [Point, Point] { const latBounds = expandIfNeeded( d3Extent(points, (x: Point) => x[1]) as Range, LAT_LIMIT, ); const lngBounds = expandIfNeeded( d3Extent(points, (x: Point) => x[0]) as Range, LNG_LIMIT, ); return [ [lngBounds[0], latBounds[0]], [lngBounds[1], latBounds[1]], ]; }
superset-frontend/plugins/legacy-preset-chart-deckgl/src/utils/computeBoundsFromPoints.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.000176409404957667, 0.00017418863717466593, 0.0001690478529781103, 0.00017494839266873896, 0.0000024415880943706725 ]
{ "id": 10, "code_window": [ " });\n", " };\n", "}\n", "\n", "export function deleteActiveReport(report) {\n", " return function deleteActiveReportThunk(dispatch) {\n", " return SupersetClient.delete({\n", " endpoint: encodeURI(`/api/v1/report/${report.id}`),\n", " })\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const DELETE_REPORT = 'DELETE_REPORT';\n", "\n" ], "file_path": "superset-frontend/src/reports/actions/reports.js", "type": "add", "edit_start_line_idx": 145 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from typing import Any, Dict from unittest.mock import Mock def get_column_mock(params: Dict[str, Any]) -> Mock: mock = Mock() mock.id = params["id"] mock.column_name = params["column_name"] mock.verbose_name = params["verbose_name"] mock.description = params["description"] mock.expression = params["expression"] mock.filterable = params["filterable"] mock.groupby = params["groupby"] mock.is_dttm = params["is_dttm"] mock.type = params["type"] return mock def get_metric_mock(params: Dict[str, Any]) -> Mock: mock = Mock() mock.id = params["id"] mock.metric_name = params["metric_name"] mock.metric_name = params["verbose_name"] mock.description = params["description"] mock.expression = params["expression"] mock.warning_text = params["warning_text"] mock.d3format = params["d3format"] return mock def get_dataset_mock() -> Mock: mock = Mock() mock.id = None mock.column_formats = {"ratio": ".2%"} mock.database = {"id": 1} mock.description = "Adding a DESCRip" mock.default_endpoint = "" mock.filter_select_enabled = True mock.name = "birth_names" mock.table_name = "birth_names" mock.datasource_name = "birth_names" mock.type = "table" mock.schema = None mock.offset = 66 mock.cache_timeout = 55 mock.sql = "" mock.columns = [ get_column_mock( { "id": 504, "column_name": "ds", "verbose_name": "", "description": None, "expression": "", "filterable": True, "groupby": True, "is_dttm": True, "type": "DATETIME", } ), get_column_mock( { "id": 505, "column_name": "gender", "verbose_name": None, "description": None, "expression": "", "filterable": True, "groupby": True, "is_dttm": False, "type": "VARCHAR(16)", } ), get_column_mock( { "id": 506, "column_name": "name", "verbose_name": None, "description": None, "expression": None, "filterable": True, "groupby": True, "is_dttm": None, "type": "VARCHAR(255)", } ), get_column_mock( { "id": 508, "column_name": "state", "verbose_name": None, "description": None, "expression": None, "filterable": True, "groupby": True, "is_dttm": None, "type": "VARCHAR(10)", } ), get_column_mock( { "id": 509, "column_name": "num_boys", "verbose_name": None, "description": None, "expression": None, "filterable": True, "groupby": True, "is_dttm": None, "type": "BIGINT(20)", } ), get_column_mock( { "id": 510, "column_name": "num_girls", "verbose_name": None, "description": None, "expression": "", "filterable": False, "groupby": False, "is_dttm": False, "type": "BIGINT(20)", } ), get_column_mock( { "id": 532, "column_name": "num", "verbose_name": None, "description": None, "expression": None, "filterable": True, "groupby": True, "is_dttm": None, "type": "BIGINT(20)", } ), get_column_mock( { "id": 522, "column_name": "num_california", "verbose_name": None, "description": None, "expression": "CASE WHEN state = 'CA' THEN num ELSE 0 END", "filterable": False, "groupby": False, "is_dttm": False, "type": "NUMBER", } ), ] mock.metrics = ( [ get_metric_mock( { "id": 824, "metric_name": "sum__num", "verbose_name": "Babies", "description": "", "expression": "SUM(num)", "warning_text": "", "d3format": "", } ), get_metric_mock( { "id": 836, "metric_name": "count", "verbose_name": "", "description": None, "expression": "count(1)", "warning_text": None, "d3format": None, } ), get_metric_mock( { "id": 843, "metric_name": "ratio", "verbose_name": "Ratio Boys/Girls", "description": "This represents the ratio of boys/girls", "expression": "sum(num_boys) / sum(num_girls)", "warning_text": "no warning", "d3format": ".2%", } ), ], ) return mock
tests/unit_tests/fixtures/datasets.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017889673472382128, 0.00017500959802418947, 0.00017067362205125391, 0.00017488135199528188, 0.0000021544506125792395 ]
{ "id": 10, "code_window": [ " });\n", " };\n", "}\n", "\n", "export function deleteActiveReport(report) {\n", " return function deleteActiveReportThunk(dispatch) {\n", " return SupersetClient.delete({\n", " endpoint: encodeURI(`/api/v1/report/${report.id}`),\n", " })\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const DELETE_REPORT = 'DELETE_REPORT';\n", "\n" ], "file_path": "superset-frontend/src/reports/actions/reports.js", "type": "add", "edit_start_line_idx": 145 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging import re import time from datetime import datetime from typing import Any, Dict, List, Optional from flask import current_app from sqlalchemy import types from sqlalchemy.engine.reflection import Inspector from sqlalchemy.orm import Session from superset.constants import QUERY_EARLY_CANCEL_KEY from superset.db_engine_specs.base import BaseEngineSpec from superset.models.sql_lab import Query logger = logging.getLogger(__name__) # Query 5543ffdf692b7d02:f78a944000000000: 3% Complete (17 out of 547) QUERY_PROGRESS_REGEX = re.compile(r"Query.*: (?P<query_progress>[0-9]+)%") class ImpalaEngineSpec(BaseEngineSpec): """Engine spec for Cloudera's Impala""" engine = "impala" engine_name = "Apache Impala" _time_grain_expressions = { None: "{col}", "PT1M": "TRUNC({col}, 'MI')", "PT1H": "TRUNC({col}, 'HH')", "P1D": "TRUNC({col}, 'DD')", "P1W": "TRUNC({col}, 'WW')", "P1M": "TRUNC({col}, 'MONTH')", "P3M": "TRUNC({col}, 'Q')", "P1Y": "TRUNC({col}, 'YYYY')", } @classmethod def epoch_to_dttm(cls) -> str: return "from_unixtime({col})" @classmethod def convert_dttm( cls, target_type: str, dttm: datetime, db_extra: Optional[Dict[str, Any]] = None ) -> Optional[str]: sqla_type = cls.get_sqla_column_type(target_type) if isinstance(sqla_type, types.Date): return f"CAST('{dttm.date().isoformat()}' AS DATE)" if isinstance(sqla_type, types.TIMESTAMP): return f"""CAST('{dttm.isoformat(timespec="microseconds")}' AS TIMESTAMP)""" return None @classmethod def get_schema_names(cls, inspector: Inspector) -> List[str]: schemas = [ row[0] for row in inspector.engine.execute("SHOW SCHEMAS") if not row[0].startswith("_") ] return schemas @classmethod def has_implicit_cancel(cls) -> bool: """ Return True if the live cursor handles the implicit cancelation of the query, False otherwise. :return: Whether the live cursor implicitly cancels the query :see: handle_cursor """ return True @classmethod def execute( cls, cursor: Any, query: str, **kwargs: Any, ) -> None: try: cursor.execute_async(query) except Exception as ex: raise cls.get_dbapi_mapped_exception(ex) @classmethod def handle_cursor(cls, cursor: Any, query: Query, session: Session) -> None: """Stop query and updates progress information""" query_id = query.id unfinished_states = ( "INITIALIZED_STATE", "RUNNING_STATE", ) try: status = cursor.status() while status in unfinished_states: session.refresh(query) query = session.query(Query).filter_by(id=query_id).one() # if query cancelation was requested prior to the handle_cursor call, but # the query was still executed # modified in stop_query in views / core.py is reflected here. # stop query if query.extra.get(QUERY_EARLY_CANCEL_KEY): cursor.cancel_operation() cursor.close_operation() cursor.close() break # updates progress info by log try: log = cursor.get_log() or "" except Exception: # pylint: disable=broad-except logger.warning("Call to GetLog() failed") log = "" if log: match = QUERY_PROGRESS_REGEX.match(log) if match: progress = int(match.groupdict()["query_progress"]) logger.debug( "Query %s: Progress total: %s", str(query_id), str(progress) ) needs_commit = False if progress > query.progress: query.progress = progress needs_commit = True if needs_commit: session.commit() sleep_interval = current_app.config["DB_POLL_INTERVAL_SECONDS"].get( cls.engine, 5 ) time.sleep(sleep_interval) status = cursor.status() except Exception: # pylint: disable=broad-except logger.debug("Call to status() failed ") return
superset/db_engine_specs/impala.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017729063984006643, 0.00017220537120010704, 0.0001656429813010618, 0.00017252846737392247, 0.0000034552560919109965 ]
{ "id": 11, "code_window": [ " dispatch(addDangerToast(t('Your report could not be deleted')));\n", " })\n", " .finally(() => {\n", " dispatch(structureFetchAction);\n", " dispatch(addSuccessToast(t('Deleted: %s', report.name)));\n", " });\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " dispatch({ type: DELETE_REPORT, report });\n" ], "file_path": "superset-frontend/src/reports/actions/reports.js", "type": "replace", "edit_start_line_idx": 154 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { t, SupersetTheme, css, styled, useTheme, FeatureFlag, isFeatureEnabled, getExtensionsRegistry, usePrevious, } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import { Switch } from 'src/components/Switch'; import { AlertObject } from 'src/features/alerts/types'; import { Menu } from 'src/components/Menu'; import Checkbox from 'src/components/Checkbox'; import { noOp } from 'src/utils/common'; import { NoAnimationDropdown } from 'src/components/Dropdown'; import DeleteModal from 'src/components/DeleteModal'; import ReportModal from 'src/components/ReportModal'; import { ChartState } from 'src/explore/types'; import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; import { fetchUISpecificReport, toggleActive, deleteActiveReport, } from 'src/reports/actions/reports'; import { reportSelector } from 'src/views/CRUD/hooks'; import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index'; const extensionsRegistry = getExtensionsRegistry(); const deleteColor = (theme: SupersetTheme) => css` color: ${theme.colors.error.base}; `; const onMenuHover = (theme: SupersetTheme) => css` & .ant-menu-item { padding: 5px 12px; margin-top: 0px; margin-bottom: 4px; :hover { color: ${theme.colors.grayscale.dark1}; } } :hover { background-color: ${theme.colors.secondary.light5}; } `; const onMenuItemHover = (theme: SupersetTheme) => css` &:hover { color: ${theme.colors.grayscale.dark1}; background-color: ${theme.colors.secondary.light5}; } `; const StyledDropdownItemWithIcon = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; > *:first-child { margin-right: ${({ theme }) => theme.gridUnit}px; } `; const DropdownItemExtension = extensionsRegistry.get( 'report-modal.dropdown.item.icon', ); export enum CreationMethod { CHARTS = 'charts', DASHBOARDS = 'dashboards', } export interface HeaderReportProps { dashboardId?: number; chart?: ChartState; useTextMenu?: boolean; setShowReportSubMenu?: (show: boolean) => void; setIsDropdownVisible?: (visible: boolean) => void; isDropdownVisible?: boolean; showReportSubMenu?: boolean; } export default function HeaderReportDropDown({ dashboardId, chart, useTextMenu = false, setShowReportSubMenu, setIsDropdownVisible, isDropdownVisible, }: HeaderReportProps) { const dispatch = useDispatch(); const report = useSelector<any, AlertObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isReportActive: boolean = report?.active || false; const user: UserWithPermissionsAndRoles = useSelector< any, UserWithPermissionsAndRoles >(state => state.user); const canAddReports = () => { if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) { return false; } if (!user?.userId) { // this is in the case that there is an anonymous user. return false; } const roles = Object.keys(user.roles || []); const permissions = roles.map(key => user.roles[key].filter( perms => perms[0] === 'menu_access' && perms[1] === 'Manage', ), ); return permissions.some(permission => permission.length > 0); }; const [currentReportDeleting, setCurrentReportDeleting] = useState<AlertObject | null>(null); const theme = useTheme(); const prevDashboard = usePrevious(dashboardId); const [showModal, setShowModal] = useState<boolean>(false); const toggleActiveKey = async (data: AlertObject, checked: boolean) => { if (data?.id) { dispatch(toggleActive(data, checked)); } }; const handleReportDelete = async (report: AlertObject) => { await dispatch(deleteActiveReport(report)); setCurrentReportDeleting(null); }; const shouldFetch = canAddReports() && !!((dashboardId && prevDashboard !== dashboardId) || chart?.id); useEffect(() => { if (shouldFetch) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: dashboardId ? 'dashboard_id' : 'chart_id', creationMethod: dashboardId ? 'dashboards' : 'charts', resourceId: dashboardId || chart?.id, }), ); } }, []); const showReportSubMenu = report && setShowReportSubMenu && canAddReports(); useEffect(() => { if (showReportSubMenu) { setShowReportSubMenu(true); } else if (!report && setShowReportSubMenu) { setShowReportSubMenu(false); } }, [report]); const handleShowMenu = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setShowModal(true); } }; const handleDeleteMenuClick = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setCurrentReportDeleting(report); } }; const textMenu = () => report ? ( isDropdownVisible && ( <Menu selectable={false} css={{ border: 'none' }}> <Menu.Item css={onMenuItemHover} onClick={() => toggleActiveKey(report, !isReportActive)} > <MenuItemWithCheckboxContainer> <Checkbox checked={isReportActive} onChange={noOp} /> {t('Email reports active')} </MenuItemWithCheckboxContainer> </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleShowMenu}> {t('Edit email report')} </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}> {t('Delete email report')} </Menu.Item> </Menu> ) ) : ( <Menu selectable={false} css={onMenuHover}> <Menu.Item onClick={handleShowMenu}> {DropdownItemExtension ? ( <StyledDropdownItemWithIcon> <div>{t('Set up an email report')}</div> <DropdownItemExtension /> </StyledDropdownItemWithIcon> ) : ( t('Set up an email report') )} </Menu.Item> <Menu.Divider /> </Menu> ); const menu = () => ( <Menu selectable={false} css={{ width: '200px' }}> <Menu.Item> {t('Email reports active')} <Switch data-test="toggle-active" checked={isReportActive} onClick={(checked: boolean) => toggleActiveKey(report, checked)} size="small" css={{ marginLeft: theme.gridUnit * 2 }} /> </Menu.Item> <Menu.Item onClick={() => setShowModal(true)}> {t('Edit email report')} </Menu.Item> <Menu.Item onClick={() => setCurrentReportDeleting(report)} css={deleteColor} > {t('Delete email report')} </Menu.Item> </Menu> ); const iconMenu = () => report ? ( <> <NoAnimationDropdown overlay={menu()} trigger={['click']} getPopupContainer={(triggerNode: any) => triggerNode.closest('.action-button') } > <span role="button" className="action-button action-schedule-report" tabIndex={0} > <Icons.Calendar /> </span> </NoAnimationDropdown> </> ) : ( <span role="button" title={t('Schedule email report')} tabIndex={0} className="action-button action-schedule-report" onClick={() => setShowModal(true)} > <Icons.Calendar /> </span> ); return ( <> {canAddReports() && ( <> <ReportModal userId={user.userId} show={showModal} onHide={() => setShowModal(false)} userEmail={user.email} dashboardId={dashboardId} chart={chart} creationMethod={ dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS } /> {useTextMenu ? textMenu() : iconMenu()} {currentReportDeleting && ( <DeleteModal description={t( 'This action will permanently delete %s.', currentReportDeleting?.name, )} onConfirm={() => { if (currentReportDeleting) { handleReportDelete(currentReportDeleting); } }} onHide={() => setCurrentReportDeleting(null)} open title={t('Delete Report?')} /> )} </> )} </> ); }
superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0015966515056788921, 0.000293690332910046, 0.0001618265378056094, 0.00017566113092470914, 0.0003398547414690256 ]
{ "id": 11, "code_window": [ " dispatch(addDangerToast(t('Your report could not be deleted')));\n", " })\n", " .finally(() => {\n", " dispatch(structureFetchAction);\n", " dispatch(addSuccessToast(t('Deleted: %s', report.name)));\n", " });\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " dispatch({ type: DELETE_REPORT, report });\n" ], "file_path": "superset-frontend/src/reports/actions/reports.js", "type": "replace", "edit_start_line_idx": 154 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> This data was downloaded from the [World's Health Organization's website](https://datacatalog.worldbank.org/dataset/health-nutrition-and-population-statistics) Here's the script that was used to massage the data: DIR = "" df_country = pd.read_csv(DIR + '/HNP_Country.csv') df_country.columns = ['country_code'] + list(df_country.columns[1:]) df_country = df_country[['country_code', 'Region']] df_country.columns = ['country_code', 'region'] df = pd.read_csv(DIR + '/HNP_Data.csv') del df['Unnamed: 60'] df.columns = ['country_name', 'country_code'] + list(df.columns[2:]) ndf = df.merge(df_country, how='inner') dims = ('country_name', 'country_code', 'region') vv = [str(i) for i in range(1960, 2015)] mdf = pd.melt(ndf, id_vars=dims + ('Indicator Code',), value_vars=vv) mdf['year'] = mdf.variable + '-01-01' dims = dims + ('year',) pdf = mdf.pivot_table(values='value', columns='Indicator Code', index=dims) pdf = pdf.reset_index() pdf.to_csv(DIR + '/countries.csv') pdf.to_json(DIR + '/countries.json', orient='records') Here's the description of the metrics available: Series | Code Indicator Name --- | --- NY.GNP.PCAP.CD | GNI per capita, Atlas method (current US$) SE.ADT.1524.LT.FM.ZS | Literacy rate, youth (ages 15-24), gender parity index (GPI) SE.ADT.1524.LT.MA.ZS | Literacy rate, youth male (% of males ages 15-24) SE.ADT.1524.LT.ZS | Literacy rate, youth total (% of people ages 15-24) SE.ADT.LITR.FE.ZS | Literacy rate, adult female (% of females ages 15 and above) SE.ADT.LITR.MA.ZS | Literacy rate, adult male (% of males ages 15 and above) SE.ADT.LITR.ZS | Literacy rate, adult total (% of people ages 15 and above) SE.ENR.ORPH | Ratio of school attendance of orphans to school attendance of non-orphans ages 10-14 SE.PRM.CMPT.FE.ZS | Primary completion rate, female (% of relevant age group) SE.PRM.CMPT.MA.ZS | Primary completion rate, male (% of relevant age group) SE.PRM.CMPT.ZS | Primary completion rate, total (% of relevant age group) SE.PRM.ENRR | School enrollment, primary (% gross) SE.PRM.ENRR.FE | School enrollment, primary, female (% gross) SE.PRM.ENRR.MA | School enrollment, primary, male (% gross) SE.PRM.NENR | School enrollment, primary (% net) SE.PRM.NENR.FE | School enrollment, primary, female (% net) SE.PRM.NENR.MA | School enrollment, primary, male (% net) SE.SEC.ENRR | School enrollment, secondary (% gross) SE.SEC.ENRR.FE | School enrollment, secondary, female (% gross) SE.SEC.ENRR.MA | School enrollment, secondary, male (% gross) SE.SEC.NENR | School enrollment, secondary (% net) SE.SEC.NENR.FE | School enrollment, secondary, female (% net) SE.SEC.NENR.MA | School enrollment, secondary, male (% net) SE.TER.ENRR | School enrollment, tertiary (% gross) SE.TER.ENRR.FE | School enrollment, tertiary, female (% gross) SE.XPD.TOTL.GD.ZS | Government expenditure on education, total (% of GDP) SH.ANM.CHLD.ZS | Prevalence of anemia among children (% of children under 5) SH.ANM.NPRG.ZS | Prevalence of anemia among non-pregnant women (% of women ages 15-49) SH.CON.1524.FE.ZS | Condom use, population ages 15-24, female (% of females ages 15-24) SH.CON.1524.MA.ZS | Condom use, population ages 15-24, male (% of males ages 15-24) SH.CON.AIDS.FE.ZS | Condom use at last high-risk sex, adult female (% ages 15-49) SH.CON.AIDS.MA.ZS | Condom use at last high-risk sex, adult male (% ages 15-49) SH.DTH.COMM.ZS | Cause of death, by communicable diseases and maternal, prenatal and nutrition conditions (% of total) SH.DTH.IMRT | Number of infant deaths SH.DTH.INJR.ZS | Cause of death, by injury (% of total) SH.DTH.MORT | Number of under-five deaths SH.DTH.NCOM.ZS | Cause of death, by non-communicable diseases (% of total) SH.DTH.NMRT | Number of neonatal deaths SH.DYN.AIDS | Adults (ages 15+) living with HIV SH.DYN.AIDS.DH | AIDS estimated deaths (UNAIDS estimates) SH.DYN.AIDS.FE.ZS | Women's share of population ages 15+ living with HIV (%) SH.DYN.AIDS.ZS | Prevalence of HIV, total (% of population ages 15-49) SH.DYN.MORT | Mortality rate, under-5 (per 1,000 live births) SH.DYN.MORT.FE | Mortality rate, under-5, female (per 1,000 live births) SH.DYN.MORT.MA | Mortality rate, under-5, male (per 1,000 live births) SH.DYN.NMRT | Mortality rate, neonatal (per 1,000 live births) SH.FPL.SATI.ZS | Met need for contraception (% of married women ages 15-49) SH.H2O.SAFE.RU.ZS | Improved water source, rural (% of rural population with access) SH.H2O.SAFE.UR.ZS | Improved water source, urban (% of urban population with access) SH.H2O.SAFE.ZS | Improved water source (% of population with access) SH.HIV.0014 | Children (0-14) living with HIV SH.HIV.1524.FE.ZS | Prevalence of HIV, female (% ages 15-24) SH.HIV.1524.KW.FE.ZS | Comprehensive correct knowledge of HIV/AIDS, ages 15-24, female (2 prevent ways and reject 3 misconceptions) SH.HIV.1524.KW.MA.ZS | Comprehensive correct knowledge of HIV/AIDS, ages 15-24, male (2 prevent ways and reject 3 misconceptions) SH.HIV.1524.MA.ZS | Prevalence of HIV, male (% ages 15-24) SH.HIV.ARTC.ZS | Antiretroviral therapy coverage (% of people living with HIV) SH.HIV.KNOW.FE.ZS | % of females ages 15-49 having comprehensive correct knowledge about HIV (2 prevent ways and reject 3 misconceptions) SH.HIV.KNOW.MA.ZS | % of males ages 15-49 having comprehensive correct knowledge about HIV (2 prevent ways and reject 3 misconceptions) SH.HIV.ORPH | Children orphaned by HIV/AIDS SH.HIV.TOTL | Adults (ages 15+) and children (0-14 years) living with HIV SH.IMM.HEPB | Immunization, HepB3 (% of one-year-old children) SH.IMM.HIB3 | Immunization, Hib3 (% of children ages 12-23 months) SH.IMM.IBCG | Immunization, BCG (% of one-year-old children) SH.IMM.IDPT | Immunization, DPT (% of children ages 12-23 months) SH.IMM.MEAS | Immunization, measles (% of children ages 12-23 months) SH.IMM.POL3 | Immunization, Pol3 (% of one-year-old children) SH.MED.BEDS.ZS | Hospital beds (per 1,000 people) SH.MED.CMHW.P3 | Community health workers (per 1,000 people) SH.MED.NUMW.P3 | Nurses and midwives (per 1,000 people) SH.MED.PHYS.ZS | Physicians (per 1,000 people) SH.MLR.NETS.ZS | Use of insecticide-treated bed nets (% of under-5 population) SH.MLR.PREG.ZS | Use of any antimalarial drug (% of pregnant women) SH.MLR.SPF2.ZS | Use of Intermittent Preventive Treatment of malaria, 2+ doses of SP/Fansidar (% of pregnant women) SH.MLR.TRET.ZS | Children with fever receiving antimalarial drugs (% of children under age 5 with fever) SH.MMR.DTHS | Number of maternal deaths SH.MMR.LEVE | Number of weeks of maternity leave SH.MMR.RISK | Lifetime risk of maternal death (1 in: rate varies by country) SH.MMR.RISK.ZS | Lifetime risk of maternal death (%) SH.MMR.WAGE.ZS | Maternal leave benefits (% of wages paid in covered period) SH.PRG.ANEM | Prevalence of anemia among pregnant women (%) SH.PRG.ARTC.ZS | Antiretroviral therapy coverage (% of pregnant women living with HIV) SH.PRG.SYPH.ZS | Prevalence of syphilis (% of women attending antenatal care) SH.PRV.SMOK.FE | Smoking prevalence, females (% of adults) SH.PRV.SMOK.MA | Smoking prevalence, males (% of adults) SH.STA.ACSN | Improved sanitation facilities (% of population with access) SH.STA.ACSN.RU | Improved sanitation facilities, rural (% of rural population with access) SH.STA.ACSN.UR | Improved sanitation facilities, urban (% of urban population with access) SH.STA.ANV4.ZS | Pregnant women receiving prenatal care of at least four visits (% of pregnant women) SH.STA.ANVC.ZS | Pregnant women receiving prenatal care (%) SH.STA.ARIC.ZS | ARI treatment (% of children under 5 taken to a health provider) SH.STA.BFED.ZS | Exclusive breastfeeding (% of children under 6 months) SH.STA.BRTC.ZS | Births attended by skilled health staff (% of total) SH.STA.BRTW.ZS | Low-birthweight babies (% of births) SH.STA.DIAB.ZS | Diabetes prevalence (% of population ages 20 to 79) SH.STA.IYCF.ZS | Infant and young child feeding practices, all 3 IYCF (% children ages 6-23 months) SH.STA.MALN.FE.ZS | Prevalence of underweight, weight for age, female (% of children under 5) SH.STA.MALN.MA.ZS | Prevalence of underweight, weight for age, male (% of children under 5) SH.STA.MALN.ZS | Prevalence of underweight, weight for age (% of children under 5) SH.STA.MALR | Malaria cases reported SH.STA.MMRT | Maternal mortality ratio (modeled estimate, per 100,000 live births) SH.STA.MMRT.NE | Maternal mortality ratio (national estimate, per 100,000 live births) SH.STA.ORCF.ZS | Diarrhea treatment (% of children under 5 receiving oral rehydration and continued feeding) SH.STA.ORTH | Diarrhea treatment (% of children under 5 who received ORS packet) SH.STA.OW15.FE.ZS | Prevalence of overweight, female (% of female adults) SH.STA.OW15.MA.ZS | Prevalence of overweight, male (% of male adults) SH.STA.OW15.ZS | Prevalence of overweight (% of adults) SH.STA.OWGH.FE.ZS | Prevalence of overweight, weight for height, female (% of children under 5) SH.STA.OWGH.MA.ZS | Prevalence of overweight, weight for height, male (% of children under 5) SH.STA.OWGH.ZS | Prevalence of overweight, weight for height (% of children under 5) SH.STA.PNVC.ZS | Postnatal care coverage (% mothers) SH.STA.STNT.FE.ZS | Prevalence of stunting, height for age, female (% of children under 5) SH.STA.STNT.MA.ZS | Prevalence of stunting, height for age, male (% of children under 5) SH.STA.STNT.ZS | Prevalence of stunting, height for age (% of children under 5) SH.STA.WAST.FE.ZS | Prevalence of wasting, weight for height, female (% of children under 5) SH.STA.WAST.MA.ZS | Prevalence of wasting, weight for height, male (% of children under 5) SH.STA.WAST.ZS | Prevalence of wasting, weight for height (% of children under 5) SH.SVR.WAST.FE.ZS | Prevalence of severe wasting, weight for height, female (% of children under 5) SH.SVR.WAST.MA.ZS | Prevalence of severe wasting, weight for height, male (% of children under 5) SH.SVR.WAST.ZS | Prevalence of severe wasting, weight for height (% of children under 5) SH.TBS.CURE.ZS | Tuberculosis treatment success rate (% of new cases) SH.TBS.DTEC.ZS | Tuberculosis case detection rate (%, all forms) SH.TBS.INCD | Incidence of tuberculosis (per 100,000 people) SH.TBS.MORT | Tuberculosis death rate (per 100,000 people) SH.TBS.PREV | Prevalence of tuberculosis (per 100,000 population) SH.VAC.TTNS.ZS | Newborns protected against tetanus (%) SH.XPD.EXTR.ZS | External resources for health (% of total expenditure on health) SH.XPD.OOPC.TO.ZS | Out-of-pocket health expenditure (% of total expenditure on health) SH.XPD.OOPC.ZS | Out-of-pocket health expenditure (% of private expenditure on health) SH.XPD.PCAP | Health expenditure per capita (current US$) SH.XPD.PCAP.PP.KD | Health expenditure per capita, PPP (constant 2011 international $) SH.XPD.PRIV | Health expenditure, private (% of total health expenditure) SH.XPD.PRIV.ZS | Health expenditure, private (% of GDP) SH.XPD.PUBL | Health expenditure, public (% of total health expenditure) SH.XPD.PUBL.GX.ZS | Health expenditure, public (% of government expenditure) SH.XPD.PUBL.ZS | Health expenditure, public (% of GDP) SH.XPD.TOTL.CD | Health expenditure, total (current US$) SH.XPD.TOTL.ZS | Health expenditure, total (% of GDP) SI.POV.NAHC | Poverty headcount ratio at national poverty lines (% of population) SI.POV.RUHC | Rural poverty headcount ratio at national poverty lines (% of rural population) SI.POV.URHC | Urban poverty headcount ratio at national poverty lines (% of urban population) SL.EMP.INSV.FE.ZS | Share of women in wage employment in the nonagricultural sector (% of total nonagricultural employment) SL.TLF.TOTL.FE.ZS | Labor force, female (% of total labor force) SL.TLF.TOTL.IN | Labor force, total SL.UEM.TOTL.FE.ZS | Unemployment, female (% of female labor force) (modeled ILO estimate) SL.UEM.TOTL.MA.ZS | Unemployment, male (% of male labor force) (modeled ILO estimate) SL.UEM.TOTL.ZS | Unemployment, total (% of total labor force) (modeled ILO estimate) SM.POP.NETM | Net migration SN.ITK.DEFC | Number of people who are undernourished SN.ITK.DEFC.ZS | Prevalence of undernourishment (% of population) SN.ITK.SALT.ZS | Consumption of iodized salt (% of households) SN.ITK.VITA.ZS | Vitamin A supplementation coverage rate (% of children ages 6-59 months) SP.ADO.TFRT | Adolescent fertility rate (births per 1,000 women ages 15-19) SP.DYN.AMRT.FE | Mortality rate, adult, female (per 1,000 female adults) SP.DYN.AMRT.MA | Mortality rate, adult, male (per 1,000 male adults) SP.DYN.CBRT.IN | Birth rate, crude (per 1,000 people) SP.DYN.CDRT.IN | Death rate, crude (per 1,000 people) SP.DYN.CONU.ZS | Contraceptive prevalence (% of women ages 15-49) SP.DYN.IMRT.FE.IN | Mortality rate, infant, female (per 1,000 live births) SP.DYN.IMRT.IN | Mortality rate, infant (per 1,000 live births) SP.DYN.IMRT.MA.IN | Mortality rate, infant, male (per 1,000 live births) SP.DYN.LE00.FE.IN | Life expectancy at birth, female (years) SP.DYN.LE00.IN | Life expectancy at birth, total (years) SP.DYN.LE00.MA.IN | Life expectancy at birth, male (years) SP.DYN.SMAM.FE | Mean age at first marriage, female SP.DYN.SMAM.MA | Mean age at first marriage, male SP.DYN.TFRT.IN | Fertility rate, total (births per woman) SP.DYN.TO65.FE.ZS | Survival to age 65, female (% of cohort) SP.DYN.TO65.MA.ZS | Survival to age 65, male (% of cohort) SP.DYN.WFRT | Wanted fertility rate (births per woman) SP.HOU.FEMA.ZS | Female headed households (% of households with a female head) SP.MTR.1519.ZS | Teenage mothers (% of women ages 15-19 who have had children or are currently pregnant) SP.POP.0004.FE | Population ages 0-4, female SP.POP.0004.FE.5Y | Population ages 0-4, female (% of female population) SP.POP.0004.MA | Population ages 0-4, male SP.POP.0004.MA.5Y | Population ages 0-4, male (% of male population) SP.POP.0014.FE.ZS | Population ages 0-14, female (% of total) SP.POP.0014.MA.ZS | Population ages 0-14, male (% of total) SP.POP.0014.TO | Population ages 0-14, total SP.POP.0014.TO.ZS | Population ages 0-14 (% of total) SP.POP.0509.FE | Population ages 5-9, female SP.POP.0509.FE.5Y | Population ages 5-9, female (% of female population) SP.POP.0509.MA | Population ages 5-9, male SP.POP.0509.MA.5Y | Population ages 5-9, male (% of male population) SP.POP.1014.FE | Population ages 10-14, female SP.POP.1014.FE.5Y | Population ages 10-14, female (% of female population) SP.POP.1014.MA | Population ages 10-14, male SP.POP.1014.MA.5Y | Population ages 10-14, male (% of male population) SP.POP.1519.FE | Population ages 15-19, female SP.POP.1519.FE.5Y | Population ages 15-19, female (% of female population) SP.POP.1519.MA | Population ages 15-19, male SP.POP.1519.MA.5Y | Population ages 15-19, male (% of male population) SP.POP.1564.FE.ZS | Population ages 15-64, female (% of total) SP.POP.1564.MA.ZS | Population ages 15-64, male (% of total) SP.POP.1564.TO | Population ages 15-64, total SP.POP.1564.TO.ZS | Population ages 15-64 (% of total) SP.POP.2024.FE | Population ages 20-24, female SP.POP.2024.FE.5Y | Population ages 20-24, female (% of female population) SP.POP.2024.MA | Population ages 20-24, male SP.POP.2024.MA.5Y | Population ages 20-24, male (% of male population) SP.POP.2529.FE | Population ages 25-29, female SP.POP.2529.FE.5Y | Population ages 25-29, female (% of female population) SP.POP.2529.MA | Population ages 25-29, male SP.POP.2529.MA.5Y | Population ages 25-29, male (% of male population) SP.POP.3034.FE | Population ages 30-34, female SP.POP.3034.FE.5Y | Population ages 30-34, female (% of female population) SP.POP.3034.MA | Population ages 30-34, male SP.POP.3034.MA.5Y | Population ages 30-34, male (% of male population) SP.POP.3539.FE | Population ages 35-39, female SP.POP.3539.FE.5Y | Population ages 35-39, female (% of female population) SP.POP.3539.MA | Population ages 35-39, male SP.POP.3539.MA.5Y | Population ages 35-39, male (% of male population) SP.POP.4044.FE | Population ages 40-44, female SP.POP.4044.FE.5Y | Population ages 40-44, female (% of female population) SP.POP.4044.MA | Population ages 40-44, male SP.POP.4044.MA.5Y | Population ages 40-44, male (% of male population) SP.POP.4549.FE | Population ages 45-49, female SP.POP.4549.FE.5Y | Population ages 45-49, female (% of female population) SP.POP.4549.MA | Population ages 45-49, male SP.POP.4549.MA.5Y | Population ages 45-49, male (% of male population) SP.POP.5054.FE | Population ages 50-54, female SP.POP.5054.FE.5Y | Population ages 50-54, female (% of female population) SP.POP.5054.MA | Population ages 50-54, male SP.POP.5054.MA.5Y | Population ages 50-54, male (% of male population) SP.POP.5559.FE | Population ages 55-59, female SP.POP.5559.FE.5Y | Population ages 55-59, female (% of female population) SP.POP.5559.MA | Population ages 55-59, male SP.POP.5559.MA.5Y | Population ages 55-59, male (% of male population) SP.POP.6064.FE | Population ages 60-64, female SP.POP.6064.FE.5Y | Population ages 60-64, female (% of female population) SP.POP.6064.MA | Population ages 60-64, male SP.POP.6064.MA.5Y | Population ages 60-64, male (% of male population) SP.POP.6569.FE | Population ages 65-69, female SP.POP.6569.FE.5Y | Population ages 65-69, female (% of female population) SP.POP.6569.MA | Population ages 65-69, male SP.POP.6569.MA.5Y | Population ages 65-69, male (% of male population) SP.POP.65UP.FE.ZS | Population ages 65 and above, female (% of total) SP.POP.65UP.MA.ZS | Population ages 65 and above, male (% of total) SP.POP.65UP.TO | Population ages 65 and above, total SP.POP.65UP.TO.ZS | Population ages 65 and above (% of total) SP.POP.7074.FE | Population ages 70-74, female SP.POP.7074.FE.5Y | Population ages 70-74, female (% of female population) SP.POP.7074.MA | Population ages 70-74, male SP.POP.7074.MA.5Y | Population ages 70-74, male (% of male population) SP.POP.7579.FE | Population ages 75-79, female SP.POP.7579.FE.5Y | Population ages 75-79, female (% of female population) SP.POP.7579.MA | Population ages 75-79, male SP.POP.7579.MA.5Y | Population ages 75-79, male (% of male population) SP.POP.80UP.FE | Population ages 80 and above, female SP.POP.80UP.FE.5Y | Population ages 80 and above, female (% of female population) SP.POP.80UP.MA | Population ages 80 and above, male SP.POP.80UP.MA.5Y | Population ages 80 and above, male (% of male population) SP.POP.AG00.FE.IN | Age population, age 0, female, interpolated SP.POP.AG00.MA.IN | Age population, age 0, male, interpolated SP.POP.AG01.FE.IN | Age population, age 01, female, interpolated SP.POP.AG01.MA.IN | Age population, age 01, male, interpolated SP.POP.AG02.FE.IN | Age population, age 02, female, interpolated SP.POP.AG02.MA.IN | Age population, age 02, male, interpolated SP.POP.AG03.FE.IN | Age population, age 03, female, interpolated SP.POP.AG03.MA.IN | Age population, age 03, male, interpolated SP.POP.AG04.FE.IN | Age population, age 04, female, interpolated SP.POP.AG04.MA.IN | Age population, age 04, male, interpolated SP.POP.AG05.FE.IN | Age population, age 05, female, interpolated SP.POP.AG05.MA.IN | Age population, age 05, male, interpolated SP.POP.AG06.FE.IN | Age population, age 06, female, interpolated SP.POP.AG06.MA.IN | Age population, age 06, male, interpolated SP.POP.AG07.FE.IN | Age population, age 07, female, interpolated SP.POP.AG07.MA.IN | Age population, age 07, male, interpolated SP.POP.AG08.FE.IN | Age population, age 08, female, interpolated SP.POP.AG08.MA.IN | Age population, age 08, male, interpolated SP.POP.AG09.FE.IN | Age population, age 09, female, interpolated SP.POP.AG09.MA.IN | Age population, age 09, male, interpolated SP.POP.AG10.FE.IN | Age population, age 10, female, interpolated SP.POP.AG10.MA.IN | Age population, age 10, male SP.POP.AG11.FE.IN | Age population, age 11, female, interpolated SP.POP.AG11.MA.IN | Age population, age 11, male SP.POP.AG12.FE.IN | Age population, age 12, female, interpolated SP.POP.AG12.MA.IN | Age population, age 12, male SP.POP.AG13.FE.IN | Age population, age 13, female, interpolated SP.POP.AG13.MA.IN | Age population, age 13, male SP.POP.AG14.FE.IN | Age population, age 14, female, interpolated SP.POP.AG14.MA.IN | Age population, age 14, male SP.POP.AG15.FE.IN | Age population, age 15, female, interpolated SP.POP.AG15.MA.IN | Age population, age 15, male, interpolated SP.POP.AG16.FE.IN | Age population, age 16, female, interpolated SP.POP.AG16.MA.IN | Age population, age 16, male, interpolated SP.POP.AG17.FE.IN | Age population, age 17, female, interpolated SP.POP.AG17.MA.IN | Age population, age 17, male, interpolated SP.POP.AG18.FE.IN | Age population, age 18, female, interpolated SP.POP.AG18.MA.IN | Age population, age 18, male, interpolated SP.POP.AG19.FE.IN | Age population, age 19, female, interpolated SP.POP.AG19.MA.IN | Age population, age 19, male, interpolated SP.POP.AG20.FE.IN | Age population, age 20, female, interpolated SP.POP.AG20.MA.IN | Age population, age 20, male, interpolated SP.POP.AG21.FE.IN | Age population, age 21, female, interpolated SP.POP.AG21.MA.IN | Age population, age 21, male, interpolated SP.POP.AG22.FE.IN | Age population, age 22, female, interpolated SP.POP.AG22.MA.IN | Age population, age 22, male, interpolated SP.POP.AG23.FE.IN | Age population, age 23, female, interpolated SP.POP.AG23.MA.IN | Age population, age 23, male, interpolated SP.POP.AG24.FE.IN | Age population, age 24, female, interpolated SP.POP.AG24.MA.IN | Age population, age 24, male, interpolated SP.POP.AG25.FE.IN | Age population, age 25, female, interpolated SP.POP.AG25.MA.IN | Age population, age 25, male, interpolated SP.POP.BRTH.MF | Sex ratio at birth (male births per female births) SP.POP.DPND | Age dependency ratio (% of working-age population) SP.POP.DPND.OL | Age dependency ratio, old (% of working-age population) SP.POP.DPND.YG | Age dependency ratio, young (% of working-age population) SP.POP.GROW | Population growth (annual %) SP.POP.TOTL | Population, total SP.POP.TOTL.FE.IN | Population, female SP.POP.TOTL.FE.ZS | Population, female (% of total) SP.POP.TOTL.MA.IN | Population, male SP.POP.TOTL.MA.ZS | Population, male (% of total) SP.REG.BRTH.RU.ZS | Completeness of birth registration, rural (%) SP.REG.BRTH.UR.ZS | Completeness of birth registration, urban (%) SP.REG.BRTH.ZS | Completeness of birth registration (%) SP.REG.DTHS.ZS | Completeness of death registration with cause-of-death information (%) SP.RUR.TOTL | Rural population SP.RUR.TOTL.ZG | Rural population growth (annual %) SP.RUR.TOTL.ZS | Rural population (% of total population) SP.URB.GROW | Urban population growth (annual %) SP.URB.TOTL | Urban population SP.URB.TOTL.IN.ZS | Urban population (% of total) SP.UWT.TFRT | Unmet need for contraception (% of married women ages 15-49)
superset/examples/countries.md
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.000179243681486696, 0.0001745667541399598, 0.00017041766841430217, 0.0001744759501889348, 0.000002260422888866742 ]
{ "id": 11, "code_window": [ " dispatch(addDangerToast(t('Your report could not be deleted')));\n", " })\n", " .finally(() => {\n", " dispatch(structureFetchAction);\n", " dispatch(addSuccessToast(t('Deleted: %s', report.name)));\n", " });\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " dispatch({ type: DELETE_REPORT, report });\n" ], "file_path": "superset-frontend/src/reports/actions/reports.js", "type": "replace", "edit_start_line_idx": 154 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ export { default as NumberFormats } from './NumberFormats'; export { default as NumberFormatter, PREVIEW_VALUE } from './NumberFormatter'; export { default as getNumberFormatterRegistry, formatNumber, getNumberFormatter, } from './NumberFormatterRegistrySingleton'; export { default as NumberFormatterRegistry } from './NumberFormatterRegistry'; export { default as createD3NumberFormatter } from './factories/createD3NumberFormatter'; export { default as createDurationFormatter } from './factories/createDurationFormatter'; export { default as createSiAtMostNDigitFormatter } from './factories/createSiAtMostNDigitFormatter'; export { default as createSmartNumberFormatter } from './factories/createSmartNumberFormatter';
superset-frontend/packages/superset-ui-core/src/number-format/index.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017794013547245413, 0.00017620131256990135, 0.00017452985048294067, 0.00017616762488614768, 0.0000013008086625632131 ]
{ "id": 11, "code_window": [ " dispatch(addDangerToast(t('Your report could not be deleted')));\n", " })\n", " .finally(() => {\n", " dispatch(structureFetchAction);\n", " dispatch(addSuccessToast(t('Deleted: %s', report.name)));\n", " });\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " dispatch({ type: DELETE_REPORT, report });\n" ], "file_path": "superset-frontend/src/reports/actions/reports.js", "type": "replace", "edit_start_line_idx": 154 }
name: Docker on: push: branches: - 'master' pull_request: types: [synchronize, opened, reopened, ready_for_review] jobs: docker-build: if: github.event.pull_request.draft == false name: docker-build runs-on: ubuntu-latest steps: - name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )" uses: actions/checkout@v2 with: persist-credentials: false - shell: bash env: DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }} DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} run: | .github/workflows/docker_build_push.sh - name: Build ephemeral env image if: github.event_name == 'pull_request' run: | mkdir -p ./build echo ${{ github.sha }} > ./build/SHA echo ${{ github.event.pull_request.number }} > ./build/PR-NUM docker build --target ci -t ${{ github.sha }} -t "pr-${{ github.event.pull_request.number }}" . docker save ${{ github.sha }} | gzip > ./build/${{ github.sha }}.tar.gz - name: Upload build artifacts if: github.event_name == 'pull_request' uses: actions/upload-artifact@v2 with: name: build path: build/
.github/workflows/docker.yml
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017508858582004905, 0.00017019700317177922, 0.00016051827697083354, 0.00017288036178797483, 0.0000053163289521762636 ]
{ "id": 12, "code_window": [ " * under the License.\n", " */\n", "/* eslint-disable camelcase */\n", "// eslint-disable-next-line import/no-extraneous-dependencies\n", "import { SET_REPORT, ADD_REPORT, EDIT_REPORT } from '../actions/reports';\n", "\n", "export default function reportsReducer(state = {}, action) {\n", " const actionHandlers = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { omit } from 'lodash';\n", "import {\n", " SET_REPORT,\n", " ADD_REPORT,\n", " EDIT_REPORT,\n", " DELETE_REPORT,\n", "} from '../actions/reports';\n" ], "file_path": "superset-frontend/src/reports/reducers/reports.js", "type": "replace", "edit_start_line_idx": 20 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { t, SupersetTheme, css, styled, useTheme, FeatureFlag, isFeatureEnabled, getExtensionsRegistry, usePrevious, } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import { Switch } from 'src/components/Switch'; import { AlertObject } from 'src/features/alerts/types'; import { Menu } from 'src/components/Menu'; import Checkbox from 'src/components/Checkbox'; import { noOp } from 'src/utils/common'; import { NoAnimationDropdown } from 'src/components/Dropdown'; import DeleteModal from 'src/components/DeleteModal'; import ReportModal from 'src/components/ReportModal'; import { ChartState } from 'src/explore/types'; import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes'; import { fetchUISpecificReport, toggleActive, deleteActiveReport, } from 'src/reports/actions/reports'; import { reportSelector } from 'src/views/CRUD/hooks'; import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index'; const extensionsRegistry = getExtensionsRegistry(); const deleteColor = (theme: SupersetTheme) => css` color: ${theme.colors.error.base}; `; const onMenuHover = (theme: SupersetTheme) => css` & .ant-menu-item { padding: 5px 12px; margin-top: 0px; margin-bottom: 4px; :hover { color: ${theme.colors.grayscale.dark1}; } } :hover { background-color: ${theme.colors.secondary.light5}; } `; const onMenuItemHover = (theme: SupersetTheme) => css` &:hover { color: ${theme.colors.grayscale.dark1}; background-color: ${theme.colors.secondary.light5}; } `; const StyledDropdownItemWithIcon = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; > *:first-child { margin-right: ${({ theme }) => theme.gridUnit}px; } `; const DropdownItemExtension = extensionsRegistry.get( 'report-modal.dropdown.item.icon', ); export enum CreationMethod { CHARTS = 'charts', DASHBOARDS = 'dashboards', } export interface HeaderReportProps { dashboardId?: number; chart?: ChartState; useTextMenu?: boolean; setShowReportSubMenu?: (show: boolean) => void; setIsDropdownVisible?: (visible: boolean) => void; isDropdownVisible?: boolean; showReportSubMenu?: boolean; } export default function HeaderReportDropDown({ dashboardId, chart, useTextMenu = false, setShowReportSubMenu, setIsDropdownVisible, isDropdownVisible, }: HeaderReportProps) { const dispatch = useDispatch(); const report = useSelector<any, AlertObject>(state => { const resourceType = dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS; return reportSelector(state, resourceType, dashboardId || chart?.id); }); const isReportActive: boolean = report?.active || false; const user: UserWithPermissionsAndRoles = useSelector< any, UserWithPermissionsAndRoles >(state => state.user); const canAddReports = () => { if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) { return false; } if (!user?.userId) { // this is in the case that there is an anonymous user. return false; } const roles = Object.keys(user.roles || []); const permissions = roles.map(key => user.roles[key].filter( perms => perms[0] === 'menu_access' && perms[1] === 'Manage', ), ); return permissions.some(permission => permission.length > 0); }; const [currentReportDeleting, setCurrentReportDeleting] = useState<AlertObject | null>(null); const theme = useTheme(); const prevDashboard = usePrevious(dashboardId); const [showModal, setShowModal] = useState<boolean>(false); const toggleActiveKey = async (data: AlertObject, checked: boolean) => { if (data?.id) { dispatch(toggleActive(data, checked)); } }; const handleReportDelete = async (report: AlertObject) => { await dispatch(deleteActiveReport(report)); setCurrentReportDeleting(null); }; const shouldFetch = canAddReports() && !!((dashboardId && prevDashboard !== dashboardId) || chart?.id); useEffect(() => { if (shouldFetch) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: dashboardId ? 'dashboard_id' : 'chart_id', creationMethod: dashboardId ? 'dashboards' : 'charts', resourceId: dashboardId || chart?.id, }), ); } }, []); const showReportSubMenu = report && setShowReportSubMenu && canAddReports(); useEffect(() => { if (showReportSubMenu) { setShowReportSubMenu(true); } else if (!report && setShowReportSubMenu) { setShowReportSubMenu(false); } }, [report]); const handleShowMenu = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setShowModal(true); } }; const handleDeleteMenuClick = () => { if (setIsDropdownVisible) { setIsDropdownVisible(false); setCurrentReportDeleting(report); } }; const textMenu = () => report ? ( isDropdownVisible && ( <Menu selectable={false} css={{ border: 'none' }}> <Menu.Item css={onMenuItemHover} onClick={() => toggleActiveKey(report, !isReportActive)} > <MenuItemWithCheckboxContainer> <Checkbox checked={isReportActive} onChange={noOp} /> {t('Email reports active')} </MenuItemWithCheckboxContainer> </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleShowMenu}> {t('Edit email report')} </Menu.Item> <Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}> {t('Delete email report')} </Menu.Item> </Menu> ) ) : ( <Menu selectable={false} css={onMenuHover}> <Menu.Item onClick={handleShowMenu}> {DropdownItemExtension ? ( <StyledDropdownItemWithIcon> <div>{t('Set up an email report')}</div> <DropdownItemExtension /> </StyledDropdownItemWithIcon> ) : ( t('Set up an email report') )} </Menu.Item> <Menu.Divider /> </Menu> ); const menu = () => ( <Menu selectable={false} css={{ width: '200px' }}> <Menu.Item> {t('Email reports active')} <Switch data-test="toggle-active" checked={isReportActive} onClick={(checked: boolean) => toggleActiveKey(report, checked)} size="small" css={{ marginLeft: theme.gridUnit * 2 }} /> </Menu.Item> <Menu.Item onClick={() => setShowModal(true)}> {t('Edit email report')} </Menu.Item> <Menu.Item onClick={() => setCurrentReportDeleting(report)} css={deleteColor} > {t('Delete email report')} </Menu.Item> </Menu> ); const iconMenu = () => report ? ( <> <NoAnimationDropdown overlay={menu()} trigger={['click']} getPopupContainer={(triggerNode: any) => triggerNode.closest('.action-button') } > <span role="button" className="action-button action-schedule-report" tabIndex={0} > <Icons.Calendar /> </span> </NoAnimationDropdown> </> ) : ( <span role="button" title={t('Schedule email report')} tabIndex={0} className="action-button action-schedule-report" onClick={() => setShowModal(true)} > <Icons.Calendar /> </span> ); return ( <> {canAddReports() && ( <> <ReportModal userId={user.userId} show={showModal} onHide={() => setShowModal(false)} userEmail={user.email} dashboardId={dashboardId} chart={chart} creationMethod={ dashboardId ? CreationMethod.DASHBOARDS : CreationMethod.CHARTS } /> {useTextMenu ? textMenu() : iconMenu()} {currentReportDeleting && ( <DeleteModal description={t( 'This action will permanently delete %s.', currentReportDeleting?.name, )} onConfirm={() => { if (currentReportDeleting) { handleReportDelete(currentReportDeleting); } }} onHide={() => setCurrentReportDeleting(null)} open title={t('Delete Report?')} /> )} </> )} </> ); }
superset-frontend/src/components/ReportModal/HeaderReportDropdown/index.tsx
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0010573152685537934, 0.00020016514463350177, 0.00016335547843482345, 0.00017423636745661497, 0.00015169505786616355 ]
{ "id": 12, "code_window": [ " * under the License.\n", " */\n", "/* eslint-disable camelcase */\n", "// eslint-disable-next-line import/no-extraneous-dependencies\n", "import { SET_REPORT, ADD_REPORT, EDIT_REPORT } from '../actions/reports';\n", "\n", "export default function reportsReducer(state = {}, action) {\n", " const actionHandlers = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { omit } from 'lodash';\n", "import {\n", " SET_REPORT,\n", " ADD_REPORT,\n", " EDIT_REPORT,\n", " DELETE_REPORT,\n", "} from '../actions/reports';\n" ], "file_path": "superset-frontend/src/reports/reducers/reports.js", "type": "replace", "edit_start_line_idx": 20 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """a collection of Annotation-related models""" from typing import Any, Dict from flask_appbuilder import Model from sqlalchemy import Column, DateTime, ForeignKey, Index, Integer, String, Text from sqlalchemy.orm import relationship from superset.models.helpers import AuditMixinNullable class AnnotationLayer(Model, AuditMixinNullable): """A logical namespace for a set of annotations""" __tablename__ = "annotation_layer" id = Column(Integer, primary_key=True) name = Column(String(250)) descr = Column(Text) def __repr__(self) -> str: return str(self.name) class Annotation(Model, AuditMixinNullable): """Time-related annotation""" __tablename__ = "annotation" id = Column(Integer, primary_key=True) start_dttm = Column(DateTime) end_dttm = Column(DateTime) layer_id = Column(Integer, ForeignKey("annotation_layer.id"), nullable=False) short_descr = Column(String(500)) long_descr = Column(Text) layer = relationship(AnnotationLayer, backref="annotation") json_metadata = Column(Text) __table_args__ = (Index("ti_dag_state", layer_id, start_dttm, end_dttm),) @property def data(self) -> Dict[str, Any]: return { "layer_id": self.layer_id, "start_dttm": self.start_dttm, "end_dttm": self.end_dttm, "short_descr": self.short_descr, "long_descr": self.long_descr, "layer": self.layer.name if self.layer else None, } def __repr__(self) -> str: return str(self.short_descr)
superset/models/annotations.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.000178946036612615, 0.00017498964734841138, 0.00016775139374658465, 0.00017639494035393, 0.0000035682919587998185 ]
{ "id": 12, "code_window": [ " * under the License.\n", " */\n", "/* eslint-disable camelcase */\n", "// eslint-disable-next-line import/no-extraneous-dependencies\n", "import { SET_REPORT, ADD_REPORT, EDIT_REPORT } from '../actions/reports';\n", "\n", "export default function reportsReducer(state = {}, action) {\n", " const actionHandlers = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { omit } from 'lodash';\n", "import {\n", " SET_REPORT,\n", " ADD_REPORT,\n", " EDIT_REPORT,\n", " DELETE_REPORT,\n", "} from '../actions/reports';\n" ], "file_path": "superset-frontend/src/reports/reducers/reports.js", "type": "replace", "edit_start_line_idx": 20 }
{ "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "features": [ { "type": "Feature", "properties": { "ISO": "RW-02", "NAME_1": "Eastern" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 30.41507328300014, -2.313087665999902 ], [ 30.383447306000051, -2.305542906999946 ], [ 30.378589722000129, -2.303062438999888 ], [ 30.362518351000062, -2.307816670999969 ], [ 30.352751505000128, -2.316911722999933 ], [ 30.348610082000107, -2.322351935999933 ], [ 30.344018189000053, -2.328383890999959 ], [ 30.331150756000056, -2.340269469999981 ], [ 30.316784709000046, -2.34760752299988 ], [ 30.297974487000147, -2.353705341999941 ], [ 30.278854207000052, -2.357632750999912 ], [ 30.262731161000147, -2.358356220999909 ], [ 30.250328816000092, -2.355565693999935 ], [ 30.219116252000106, -2.34037282299991 ], [ 30.207489054000064, -2.339235940999913 ], [ 30.203923381000095, -2.345953877999932 ], [ 30.203406617000041, -2.355358988999896 ], [ 30.201339559000075, -2.362386982999894 ], [ 30.156174357000111, -2.419024352999884 ], [ 30.13912113400005, -2.430806578999892 ], [ 30.116796916000112, -2.431530049999893 ], [ 30.093852580000146, -2.422641702999968 ], [ 30.072975301000099, -2.408792418999909 ], [ 30.056542196000123, -2.394426370999909 ], [ 30.025536336000073, -2.35773610499993 ], [ 30.013340698000093, -2.34833099399988 ], [ 30.001920207000069, -2.344300230999892 ], [ 29.992308390000062, -2.343990172999895 ], [ 29.983885131000079, -2.344816995999921 ], [ 29.976133667000056, -2.343680114999913 ], [ 29.958519715000079, -2.328532809999928 ], [ 29.956781100967021, -2.327037671051698 ], [ 29.959142617238001, -2.324316793784988 ], [ 29.960476970136028, -2.321453493583874 ], [ 29.961623085936651, -2.318994121181731 ], [ 29.964000201847796, -2.299822165160776 ], [ 29.967570917763624, -2.281075905029013 ], [ 29.967927611370158, -2.279203267416847 ], [ 29.968464144204859, -2.277640421068611 ], [ 29.980381630807585, -2.242926412923623 ], [ 29.985911009885172, -2.193833801988376 ], [ 29.984257362587186, -2.160657532918833 ], [ 29.995006060581204, -2.139883606443277 ], [ 30.009888873672537, -2.123605531170313 ], [ 30.016503456569239, -2.111461569196081 ], [ 30.016606810256064, -2.099937724846143 ], [ 30.016658487099505, -2.081799297599503 ], [ 30.017847044605389, -2.072135803424601 ], [ 30.022394570852725, -2.068260071645 ], [ 30.032006387284923, -2.064022604659499 ], [ 30.038207559031605, -2.060611959973983 ], [ 30.043426878847356, -2.055134257739837 ], [ 30.050609903424288, -2.053170553877976 ], [ 30.054227252785495, -2.057459697706918 ], [ 30.058878131820336, -2.063609192610159 ], [ 30.067456418578843, -2.064539368596968 ], [ 30.073605915280723, -2.063764222241048 ], [ 30.076396442341945, -2.062885723097679 ], [ 30.079755410184021, -2.062058899898318 ], [ 30.085698200411628, -2.060922017437179 ], [ 30.092261107364209, -2.059475077512843 ], [ 30.09804886796087, -2.057666403281871 ], [ 30.107040566768717, -2.055754374464811 ], [ 30.115102089589755, -2.055030904952332 ], [ 30.117995970337745, -2.054927552164827 ], [ 30.121406615023261, -2.054307434540476 ], [ 30.123835406878527, -2.050586731492501 ], [ 30.129829873050198, -2.045470764464199 ], [ 30.13680619205212, -2.040354797435953 ], [ 30.14254227580534, -2.037357565699097 ], [ 30.153239296955974, -2.032706686664255 ], [ 30.165383258930262, -2.028417542835371 ], [ 30.177630573691999, -2.031879862565631 ], [ 30.188172565211687, -2.045729147781969 ], [ 30.194942177739279, -2.056116110570031 ], [ 30.202538612566912, -2.065624574214723 ], [ 30.209049843575428, -2.074667949866011 ], [ 30.21581945700234, -2.065056132534494 ], [ 30.223725951091751, -2.046969382131294 ], [ 30.230340533988453, -2.010899232313704 ], [ 30.233337768423269, -1.974829081596852 ], [ 30.233957884248923, -1.963253561302849 ], [ 30.239383909639685, -1.957052389556168 ], [ 30.253801634737613, -1.950954570596991 ], [ 30.267444212580301, -1.944443339588474 ], [ 30.272146767559263, -1.936020081561537 ], [ 30.272508502765163, -1.916383037547178 ], [ 30.270441445216477, -1.900001608587388 ], [ 30.264550332731631, -1.894058817460461 ], [ 30.258349160085629, -1.886462383532205 ], [ 30.259020954553364, -1.872664776058571 ], [ 30.255196897818564, -1.858247050960642 ], [ 30.248375609346851, -1.848531881740939 ], [ 30.247083698154142, -1.843209209137683 ], [ 30.251062783620569, -1.840315329289012 ], [ 30.258142455409995, -1.832822245450302 ], [ 30.266720742168502, -1.826931132965399 ], [ 30.272405149977658, -1.823520488279939 ], [ 30.272095091615142, -1.80827594088197 ], [ 30.2643436262573, -1.777580140511077 ], [ 30.254008340312623, -1.743266988980395 ], [ 30.250442665996218, -1.722286357829148 ], [ 30.254266722731074, -1.711175924629231 ], [ 30.25762569057315, -1.699703757122677 ], [ 30.251734577188984, -1.686267884854999 ], [ 30.237471881721945, -1.670816630982756 ], [ 30.218041543282595, -1.646683737564445 ], [ 30.199903115136635, -1.623119284027723 ], [ 30.186880654918298, -1.60937335249821 ], [ 30.177010456067649, -1.591596659558206 ], [ 30.169310667553248, -1.57123614603131 ], [ 30.165124877411131, -1.54886025089985 ], [ 30.170395873171003, -1.532065410790096 ], [ 30.178354043204536, -1.524934063056548 ], [ 30.178767454354499, -1.520334859965828 ], [ 30.173289753019674, -1.517389303273717 ], [ 30.163522906956587, -1.517389303273717 ], [ 30.151585650557308, -1.521575093415834 ], [ 30.14254227580534, -1.524313944532935 ], [ 30.141818805393541, -1.515115541049397 ], [ 30.13928666075077, -1.499715964020538 ], [ 30.135049192865949, -1.490310853163351 ], [ 30.126419229264002, -1.471500630549656 ], [ 30.117685911975229, -1.455222555276691 ], [ 30.106523802831191, -1.438376037424177 ], [ 30.093914752863554, -1.417292053485482 ], [ 30.087403522754357, -1.412072734569051 ], [ 30.081874144576091, -1.404527975685539 ], [ 30.078721881409706, -1.394347717573112 ], [ 30.073089150443934, -1.389903545012601 ], [ 30.070195270595264, -1.38912839865668 ], [ 30.065984342603315, -1.386944953546788 ], [ 30.095506226000111, -1.371129658999962 ], [ 30.136330607000104, -1.35521331799994 ], [ 30.147182658000077, -1.345084736999894 ], [ 30.15235030100007, -1.329891865999869 ], [ 30.158448120000116, -1.291134541999924 ], [ 30.165579468000146, -1.277491963999921 ], [ 30.173434286000088, -1.272841084999953 ], [ 30.18139245600014, -1.271497497999903 ], [ 30.189350627000124, -1.270877379999931 ], [ 30.196740356000134, -1.26870696999994 ], [ 30.212191610000104, -1.259508564999933 ], [ 30.256685018000098, -1.217237243999946 ], [ 30.269759156000077, -1.200494079999899 ], [ 30.280507853000074, -1.182407327999982 ], [ 30.282419882000113, -1.175792744999896 ], [ 30.284641968000074, -1.161426695999893 ], [ 30.287535848000061, -1.15543222999986 ], [ 30.290949658000102, -1.15262085699996 ], [ 30.294563843000105, -1.149644469999885 ], [ 30.311307007000039, -1.142099710999929 ], [ 30.317404826000086, -1.137035419999961 ], [ 30.322572469000079, -1.121842549999926 ], [ 30.329032023000082, -1.0805014029999 ], [ 30.337455282000064, -1.066238707999929 ], [ 30.352751505000128, -1.06076100699994 ], [ 30.36928796400008, -1.063241474999913 ], [ 30.386341186000038, -1.068202412999952 ], [ 30.403187703000128, -1.070372822999943 ], [ 30.418897339000068, -1.066445413999887 ], [ 30.432023153000046, -1.060554300999883 ], [ 30.445614054000146, -1.058693948999874 ], [ 30.460828622942586, -1.063427549541814 ], [ 30.471785843000134, -1.066836591999916 ], [ 30.463855835000118, -1.075127054999939 ], [ 30.456156047000093, -1.086082457999922 ], [ 30.453003785000135, -1.097347919999976 ], [ 30.456311076000134, -1.108096617999905 ], [ 30.470883829000115, -1.118121845999923 ], [ 30.474191121000104, -1.131764424999929 ], [ 30.472072388000129, -1.137655537999933 ], [ 30.468300008000085, -1.14333994499988 ], [ 30.465612834000069, -1.149334410999899 ], [ 30.467266479000045, -1.155328876999931 ], [ 30.476051473000098, -1.161219990999925 ], [ 30.484009643000093, -1.159979755999899 ], [ 30.49052087400014, -1.156465758999943 ], [ 30.494654989000082, -1.155328876999931 ], [ 30.506953979000116, -1.164217223999941 ], [ 30.511191447000044, -1.170418395999931 ], [ 30.515118856000129, -1.196256611999942 ], [ 30.521216675000062, -1.210829365999913 ], [ 30.539406779000046, -1.241008401999906 ], [ 30.545297892000121, -1.261368915999938 ], [ 30.554599650000057, -1.273461201999922 ], [ 30.556615031000092, -1.281626077999945 ], [ 30.55563317900004, -1.284726663999891 ], [ 30.553359416000035, -1.289067483999872 ], [ 30.550982300000044, -1.294958597999965 ], [ 30.549948771000061, -1.302400003999892 ], [ 30.555323120000139, -1.318419697999943 ], [ 30.568242228000145, -1.328134867999978 ], [ 30.597697795000045, -1.340330504999898 ], [ 30.608239787000116, -1.347771911999914 ], [ 30.623225952000098, -1.362034606999899 ], [ 30.632424357000104, -1.367615660999917 ], [ 30.698466837000126, -1.392110290999966 ], [ 30.718103881000104, -1.394900817999925 ], [ 30.737534220000043, -1.406683043999919 ], [ 30.743218628000079, -1.432831318999931 ], [ 30.741358277000074, -1.458876240999913 ], [ 30.738257690000069, -1.470658467999911 ], [ 30.732935018000035, -1.476446227999887 ], [ 30.738877808000041, -1.489468687999917 ], [ 30.755414266000116, -1.511586201999933 ], [ 30.767816610000068, -1.524815368999924 ], [ 30.772260783000092, -1.532463479999905 ], [ 30.781975952000039, -1.568430276999962 ], [ 30.791587768000056, -1.590961201999988 ], [ 30.807245728000112, -1.60326019299994 ], [ 30.831016887000146, -1.594165139999873 ], [ 30.838303263000057, -1.61535247799992 ], [ 30.837476440000103, -1.641087340999917 ], [ 30.824557333000087, -1.719945576999933 ], [ 30.82424727300014, -1.730694273999873 ], [ 30.826521037000134, -1.735861917999955 ], [ 30.835409383000069, -1.749504495999872 ], [ 30.837889852000046, -1.758702900999964 ], [ 30.826417684000035, -1.786194762999941 ], [ 30.829931681000062, -1.796736754999912 ], [ 30.837889852000046, -1.836837666999898 ], [ 30.832412150000039, -1.853787536999903 ], [ 30.822231893000094, -1.86877370199997 ], [ 30.816599162000045, -1.884173278999867 ], [ 30.82424727300014, -1.902053324999926 ], [ 30.808020874000078, -1.914765725999885 ], [ 30.801923055000145, -1.921276956999947 ], [ 30.796962118000124, -1.929338479999927 ], [ 30.826934449000134, -1.934092711999924 ], [ 30.829931681000062, -1.960551044999917 ], [ 30.816754191000086, -2.01873870799993 ], [ 30.835461059000068, -2.014707946999934 ], [ 30.853496135000057, -2.02369964499988 ], [ 30.868740682000123, -2.038995869999923 ], [ 30.879437703000121, -2.053465270999951 ], [ 30.88780928500006, -2.08250742599995 ], [ 30.853392782000128, -2.193818460999893 ], [ 30.844711141000062, -2.23784678099986 ], [ 30.848948608000114, -2.306266377999947 ], [ 30.844711141000062, -2.326626891999879 ], [ 30.834375855000076, -2.34533375999996 ], [ 30.821353394000141, -2.354738870999924 ], [ 30.804558553000049, -2.362180276999936 ], [ 30.789107300000069, -2.371068623999861 ], [ 30.77515466300008, -2.374479267999973 ], [ 30.767919963000111, -2.378613382999902 ], [ 30.758824910000044, -2.381093851999879 ], [ 30.750660034000134, -2.379130146999941 ], [ 30.698466837000126, -2.353395283999944 ], [ 30.68771813900014, -2.349984638999928 ], [ 30.674799031000134, -2.351741637999908 ], [ 30.663326864000112, -2.360733336999942 ], [ 30.649064168000109, -2.387605081999951 ], [ 30.637850382000067, -2.3970101929999 ], [ 30.616921427000079, -2.398147073999908 ], [ 30.595217325000078, -2.391945901999932 ], [ 30.573926636000124, -2.389258727999987 ], [ 30.554599650000057, -2.400627542999885 ], [ 30.521733440000048, -2.399387308999863 ], [ 30.488453817000106, -2.383781025999909 ], [ 30.434141886000134, -2.339235940999913 ], [ 30.428405802000043, -2.331381123999961 ], [ 30.42323815900005, -2.317325133999944 ], [ 30.418483927000068, -2.311847431999865 ], [ 30.41507328300014, -2.313087665999902 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "RW-05", "NAME_1": "Southern" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 29.956781100967021, -2.327037671051698 ], [ 29.949933716000146, -2.3211491899999 ], [ 29.941923869000107, -2.316601663999947 ], [ 29.931691935000117, -2.316911722999933 ], [ 29.928798055000129, -2.322492776999951 ], [ 29.928901408000058, -2.331794534999887 ], [ 29.922390177000068, -2.382954202999883 ], [ 29.929573202000142, -2.459848733999877 ], [ 29.90792077600014, -2.535399678999909 ], [ 29.903725677797752, -2.637946527810016 ], [ 29.903269898000076, -2.649087828999896 ], [ 29.897895548000122, -2.671101988999879 ], [ 29.888387085000147, -2.692909443999909 ], [ 29.87619144700011, -2.713580016999913 ], [ 29.862858927000104, -2.731666768999929 ], [ 29.842395060000058, -2.752440693999887 ], [ 29.823584839000034, -2.763499450999888 ], [ 29.803379354000128, -2.767323505999926 ], [ 29.778522990000113, -2.766600036999918 ], [ 29.756198771000129, -2.759882099999899 ], [ 29.744726603000117, -2.759985452999928 ], [ 29.737285197000062, -2.769287210999948 ], [ 29.733977905000074, -2.790267841999949 ], [ 29.729637085000093, -2.799569599999884 ], [ 29.719921916000146, -2.805460713999892 ], [ 29.697546021000107, -2.808251240999937 ], [ 29.67868412200005, -2.805357360999949 ], [ 29.637086889000045, -2.791628628999916 ], [ 29.626387573000045, -2.788097431999873 ], [ 29.619256225000129, -2.787684020999947 ], [ 29.589490600000147, -2.798432718999962 ], [ 29.582049194000092, -2.802980244999915 ], [ 29.57409102400004, -2.806080829999942 ], [ 29.563755737000122, -2.805667418999931 ], [ 29.541844930000082, -2.808561298999919 ], [ 29.523138061000111, -2.82044687899986 ], [ 29.504121135000048, -2.826854756999893 ], [ 29.480866740000124, -2.81372894299993 ], [ 29.444674800000087, -2.806989288999972 ], [ 29.425366251000128, -2.803393655999926 ], [ 29.407434530000046, -2.805460713999892 ], [ 29.36428470900006, -2.824167581999873 ], [ 29.339686727000071, -2.826441344999893 ], [ 29.330850057000134, -2.807424417999911 ], [ 29.329661499000053, -2.794918720999917 ], [ 29.320359741000118, -2.774144795999874 ], [ 29.318085978000056, -2.762569274999933 ], [ 29.321496623000087, -2.75213063599989 ], [ 29.335345907000089, -2.735180765999885 ], [ 29.337516316000062, -2.723811949999899 ], [ 29.331418497000129, -2.711409606999922 ], [ 29.309714396000118, -2.691049092999904 ], [ 29.30948054400011, -2.690126857999886 ], [ 29.328380084773073, -2.680160705552112 ], [ 29.333392699013814, -2.678662090583032 ], [ 29.342539426553287, -2.673856181917245 ], [ 29.3566470932887, -2.648689759724618 ], [ 29.359954385186711, -2.612619609907085 ], [ 29.348275511205884, -2.595463034591376 ], [ 29.343262897864406, -2.587969951651985 ], [ 29.341919309828256, -2.580941956705942 ], [ 29.343107868233517, -2.571691874580381 ], [ 29.345019896151257, -2.561925028517237 ], [ 29.340885781953261, -2.555672181725811 ], [ 29.335924843656585, -2.545853658819283 ], [ 29.328380084773073, -2.535880108080505 ], [ 29.322385618601402, -2.523426087743758 ], [ 29.320215208265211, -2.508233216289909 ], [ 29.311946979869219, -2.497122783089992 ], [ 29.298511106702165, -2.490973288186694 ], [ 29.279907590562857, -2.485133851645969 ], [ 29.267815306331329, -2.478570944693331 ], [ 29.266885130344463, -2.471853008109861 ], [ 29.271432656591799, -2.458727194204641 ], [ 29.280114297037187, -2.4460147914495 ], [ 29.301198281875202, -2.434749329517956 ], [ 29.321713825032987, -2.423483867586413 ], [ 29.325796263286918, -2.414388815091741 ], [ 29.322799030650742, -2.403123353160254 ], [ 29.319853473958631, -2.393718242303066 ], [ 29.328276731985568, -2.380230694091267 ], [ 29.338301959567787, -2.364366029069004 ], [ 29.339128782767091, -2.355167623786826 ], [ 29.332307493396058, -2.341214987581623 ], [ 29.325692909600093, -2.324781881778449 ], [ 29.328380084773073, -2.311242656723266 ], [ 29.33850866604206, -2.299150371592361 ], [ 29.353649860652524, -2.291398906234519 ], [ 29.368480996001153, -2.28912514311088 ], [ 29.379746458832017, -2.292535787796396 ], [ 29.392458860687839, -2.286799704043119 ], [ 29.411062376827203, -2.272795390994531 ], [ 29.431267861622473, -2.26948809909652 ], [ 29.448579466569129, -2.2690746879465 ], [ 29.460413369281525, -2.268557923109654 ], [ 29.466511188240702, -2.269436423152399 ], [ 29.481083942070256, -2.254295228541991 ], [ 29.505940305900367, -2.234864889203266 ], [ 29.519272826279916, -2.227423483107259 ], [ 29.530176553005504, -2.217811666675061 ], [ 29.542940631704766, -2.209853496641585 ], [ 29.548728392301427, -2.203755677682409 ], [ 29.55286250560016, -2.197864564298186 ], [ 29.55823685594612, -2.199776592215983 ], [ 29.564541379580987, -2.202205384071249 ], [ 29.571879433788808, -2.199311504222578 ], [ 29.580044310296671, -2.196934388311377 ], [ 29.586917275611768, -2.193058655632456 ], [ 29.597614296762345, -2.18659910056806 ], [ 29.605779173270207, -2.182258281694374 ], [ 29.605417438064308, -2.168564027008244 ], [ 29.601696735016276, -2.154766419534667 ], [ 29.598751178324221, -2.148565247787985 ], [ 29.59983638394192, -2.138384990574878 ], [ 29.608983112380713, -2.121590149565748 ], [ 29.614667520189869, -2.107740866148049 ], [ 29.61471919613399, -2.100299460052042 ], [ 29.618388223237901, -2.093994935517856 ], [ 29.62086869193655, -2.089137350908004 ], [ 29.625777951591147, -2.082109355962018 ], [ 29.632702594649004, -2.071464010755506 ], [ 29.634304564204228, -2.062162252685823 ], [ 29.63513138740359, -2.053480612240492 ], [ 29.636268268965409, -2.045109030157619 ], [ 29.633322712273355, -2.038391093574091 ], [ 29.629808714800333, -2.027177307586669 ], [ 29.630790566731264, -2.00604164770391 ], [ 29.627224893314178, -1.984027486879029 ], [ 29.622729043010906, -1.973950582453426 ], [ 29.632909300224014, -1.973950582453426 ], [ 29.647947142046974, -1.974622376921161 ], [ 29.659522663240296, -1.97095334981725 ], [ 29.668669391679089, -1.962736796466004 ], [ 29.670994830746849, -1.9522464817897 ], [ 29.666550658186281, -1.944081605281895 ], [ 29.662726600552162, -1.932919496137856 ], [ 29.662468219932407, -1.921809062937939 ], [ 29.666343951712008, -1.914057597580097 ], [ 29.671511595583638, -1.901241842936713 ], [ 29.668721067623153, -1.874680156763816 ], [ 29.663966836700126, -1.85008217355346 ], [ 29.664276895062642, -1.837989888422612 ], [ 29.667584186960653, -1.82641436902793 ], [ 29.670323037178377, -1.798560771662267 ], [ 29.666964069336302, -1.764971090543384 ], [ 29.663140014400142, -1.7468326632968 ], [ 29.660246132752832, -1.736704082027757 ], [ 29.65766231126662, -1.733086731767287 ], [ 29.663605100594907, -1.731278056636995 ], [ 29.67502559305666, -1.72967608798109 ], [ 29.686187702200698, -1.731743144630457 ], [ 29.702620808003871, -1.742646872255364 ], [ 29.721379352874806, -1.74951983757046 ], [ 29.733885049155674, -1.7471943985027 ], [ 29.741584837670075, -1.748434632852025 ], [ 29.745150511087218, -1.757684714078323 ], [ 29.755434121087774, -1.773704407832156 ], [ 29.768766640568003, -1.793548156522206 ], [ 29.780548867336336, -1.81173826151155 ], [ 29.794501504440859, -1.824967429103594 ], [ 29.79951411778228, -1.839333475559442 ], [ 29.818479369127544, -1.85142576158961 ], [ 29.845816201656362, -1.860727519659292 ], [ 29.865091509565502, -1.860520814084339 ], [ 29.884935260953512, -1.856903463823812 ], [ 29.902401894631737, -1.857316874973833 ], [ 29.914494179762585, -1.860934225234303 ], [ 29.921367145077681, -1.865895162631659 ], [ 29.929325316010534, -1.870029277728975 ], [ 29.936715046162419, -1.875041891969772 ], [ 29.943019570696606, -1.880984681298003 ], [ 29.951184447204469, -1.889149557805865 ], [ 29.96079626363661, -1.899484843750542 ], [ 29.970511432856313, -1.906099427546565 ], [ 29.978469602889845, -1.907649720258405 ], [ 29.981105101219441, -1.909406718545256 ], [ 29.980588337281915, -1.910698629737965 ], [ 29.982603717987161, -1.914057597580097 ], [ 29.985600950623336, -1.922584209293859 ], [ 29.988288124897053, -1.930180645020755 ], [ 29.990355182445683, -1.933487936918766 ], [ 29.993249063193673, -1.937415345541751 ], [ 29.996246295829849, -1.943616517288433 ], [ 29.999243529365344, -1.951161276171945 ], [ 30.002137409214072, -1.958395976692998 ], [ 30.000432086871285, -1.962788473309388 ], [ 30.000122029408089, -1.964648825283064 ], [ 29.999966998877881, -1.968472881118601 ], [ 29.999243529365344, -1.974829081596852 ], [ 29.997331501447604, -1.981133607030358 ], [ 29.993920856762088, -1.986301250002668 ], [ 30.003377643563397, -2.001184063094058 ], [ 30.009888873672537, -2.016583639223597 ], [ 30.005341348324521, -2.024231751793934 ], [ 30.001827350851556, -2.028055807629414 ], [ 29.993714150287758, -2.031311422684041 ], [ 29.986376096979257, -2.038752828780048 ], [ 29.984464069061517, -2.04841632205563 ], [ 29.990561888020693, -2.060560283130599 ], [ 29.999140175678519, -2.065882955733855 ], [ 30.003480996350902, -2.066503072458829 ], [ 30.009165404160058, -2.068363423533185 ], [ 30.015469928694245, -2.070327129193686 ], [ 30.017847044605389, -2.072135803424601 ], [ 30.016658487099505, -2.081799297599503 ], [ 30.016606810256064, -2.099937724846143 ], [ 30.016503456569239, -2.111461569196081 ], [ 30.009888873672537, -2.123605531170313 ], [ 29.995006060581204, -2.139883606443277 ], [ 29.984257362587186, -2.160657532918833 ], [ 29.985911009885172, -2.193833801988376 ], [ 29.980381630807585, -2.242926412923623 ], [ 29.968464144204859, -2.277640421068611 ], [ 29.967927611370158, -2.279203267416847 ], [ 29.967570917763624, -2.281075905029013 ], [ 29.964000201847796, -2.299822165160776 ], [ 29.961623085936651, -2.318994121181731 ], [ 29.960476970136028, -2.321453493583874 ], [ 29.959142617238001, -2.324316793784988 ], [ 29.956781100967021, -2.327037671051698 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "RW-04", "NAME_1": "Western" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 29.30948054400011, -2.690126857999886 ], [ 29.306045370000106, -2.676579690999873 ], [ 29.30733728000007, -2.664797464999964 ], [ 29.306613810000044, -2.660146585999897 ], [ 29.294418172000064, -2.651051533999933 ], [ 29.276124716000083, -2.640612893999986 ], [ 29.254989054000134, -2.635548603999922 ], [ 29.212769409000089, -2.630277608999975 ], [ 29.190445190000105, -2.623456318999928 ], [ 29.129725383000107, -2.596997985999849 ], [ 29.113447307000087, -2.5946208699999 ], [ 29.055259643000085, -2.598444925999928 ], [ 29.032573690000106, -2.620665791999969 ], [ 29.015365438000117, -2.720711364999957 ], [ 29.00012089000009, -2.703658141999924 ], [ 28.979605347000103, -2.693529560999963 ], [ 28.949736369000107, -2.690325621999904 ], [ 28.936403849000072, -2.685054625999967 ], [ 28.899093465000135, -2.66066335099994 ], [ 28.891342000000122, -2.65270517999997 ], [ 28.898059937000141, -2.57632741299993 ], [ 28.891342000000122, -2.553073017999907 ], [ 28.881058390000135, -2.542634378999963 ], [ 28.869844605000083, -2.537260029999914 ], [ 28.860956258000073, -2.531162210999952 ], [ 28.857235555000074, -2.518346455999961 ], [ 28.860852905000058, -2.505220641999912 ], [ 28.878216187000078, -2.489717711999987 ], [ 28.874702189000118, -2.477522073999879 ], [ 28.864573608000057, -2.459435322999866 ], [ 28.860852905000058, -2.439591572999873 ], [ 28.858837524000108, -2.418197529999958 ], [ 28.866330607000123, -2.391945901999932 ], [ 28.880386596000051, -2.379853616999938 ], [ 28.907258342000063, -2.370551858999917 ], [ 28.928135620000035, -2.364454039999956 ], [ 28.945447225000123, -2.35422210699997 ], [ 28.959658244000082, -2.339752705999942 ], [ 28.971233765000136, -2.321665954999929 ], [ 28.978778524000091, -2.306783141999887 ], [ 28.982189168000104, -2.296034443999872 ], [ 28.983377726000128, -2.287352802999905 ], [ 28.993661336000031, -2.277740986999987 ], [ 29.00213627100004, -2.274743753999886 ], [ 29.03092004400014, -2.275673928999936 ], [ 29.075413452000134, -2.263891702999928 ], [ 29.109829956000084, -2.236709899999951 ], [ 29.134841349000084, -2.197745869999963 ], [ 29.150550984000063, -2.150410257999908 ], [ 29.156338745000141, -2.108655700999861 ], [ 29.154271687000062, -2.072688903999975 ], [ 29.127710001000139, -1.915695901999925 ], [ 29.125539592000081, -1.879108988999889 ], [ 29.130500529000102, -1.84334889699997 ], [ 29.149310750000041, -1.799320575999914 ], [ 29.186640035000039, -1.739618238999896 ], [ 29.212252645000035, -1.698654886999861 ], [ 29.233336629000064, -1.65865732799989 ], [ 29.245428914000058, -1.640983987999974 ], [ 29.293694702000039, -1.600986429999921 ], [ 29.30382328200011, -1.587860615999944 ], [ 29.331211792000147, -1.531429951999925 ], [ 29.342787313000088, -1.516547138999968 ], [ 29.358496948000038, -1.509932555999882 ], [ 29.434926392000136, -1.506831969999936 ], [ 29.437406861000113, -1.506211852999868 ], [ 29.439628947000131, -1.504764912999875 ], [ 29.44169600400005, -1.502594501999894 ], [ 29.445065226000054, -1.497286823999929 ], [ 29.449406289768433, -1.503488343012634 ], [ 29.467286334596622, -1.527827942905276 ], [ 29.491419228914253, -1.556146628264287 ], [ 29.51296830084641, -1.563588033460974 ], [ 29.531881875348233, -1.569582500531965 ], [ 29.540046751856096, -1.569375794956954 ], [ 29.546661334752798, -1.566740296627415 ], [ 29.550640420219224, -1.569169087583361 ], [ 29.555963092822481, -1.570822734881347 ], [ 29.572189492151324, -1.578419170608242 ], [ 29.590741331447248, -1.5876175749911 ], [ 29.610946817141894, -1.58648069252996 ], [ 29.630583861156254, -1.587875956510175 ], [ 29.634717975354249, -1.618158346630423 ], [ 29.63611323933452, -1.659137757901192 ], [ 29.635699828184499, -1.688128235929355 ], [ 29.634459593835174, -1.709935690279906 ], [ 29.646913613272602, -1.724921856158744 ], [ 29.65766231126662, -1.733086731767287 ], [ 29.660246132752832, -1.736704082027757 ], [ 29.663140014400142, -1.7468326632968 ], [ 29.666964069336302, -1.764971090543384 ], [ 29.670323037178377, -1.798560771662267 ], [ 29.667584186960653, -1.82641436902793 ], [ 29.664276895062642, -1.837989888422612 ], [ 29.663966836700126, -1.85008217355346 ], [ 29.668721067623153, -1.874680156763816 ], [ 29.671511595583638, -1.901241842936713 ], [ 29.666343951712008, -1.914057597580097 ], [ 29.662468219932407, -1.921809062937939 ], [ 29.662726600552162, -1.932919496137856 ], [ 29.666550658186281, -1.944081605281895 ], [ 29.670994830746849, -1.9522464817897 ], [ 29.668669391679089, -1.962736796466004 ], [ 29.659522663240296, -1.97095334981725 ], [ 29.647947142046974, -1.974622376921161 ], [ 29.632909300224014, -1.973950582453426 ], [ 29.622729043010906, -1.973950582453426 ], [ 29.627224893314178, -1.984027486879029 ], [ 29.630790566731264, -2.00604164770391 ], [ 29.629808714800333, -2.027177307586669 ], [ 29.633322712273355, -2.038391093574091 ], [ 29.636268268965409, -2.045109030157619 ], [ 29.63513138740359, -2.053480612240492 ], [ 29.634304564204228, -2.062162252685823 ], [ 29.632702594649004, -2.071464010755506 ], [ 29.625777951591147, -2.082109355962018 ], [ 29.62086869193655, -2.089137350908004 ], [ 29.618388223237901, -2.093994935517856 ], [ 29.61471919613399, -2.100299460052042 ], [ 29.614667520189869, -2.107740866148049 ], [ 29.608983112380713, -2.121590149565748 ], [ 29.59983638394192, -2.138384990574878 ], [ 29.598751178324221, -2.148565247787985 ], [ 29.601696735016276, -2.154766419534667 ], [ 29.605417438064308, -2.168564027008244 ], [ 29.605779173270207, -2.182258281694374 ], [ 29.597614296762345, -2.18659910056806 ], [ 29.586917275611768, -2.193058655632456 ], [ 29.580044310296671, -2.196934388311377 ], [ 29.571879433788808, -2.199311504222578 ], [ 29.564541379580987, -2.202205384071249 ], [ 29.55823685594612, -2.199776592215983 ], [ 29.55286250560016, -2.197864564298186 ], [ 29.548728392301427, -2.203755677682409 ], [ 29.542940631704766, -2.209853496641585 ], [ 29.530176553005504, -2.217811666675061 ], [ 29.519272826279916, -2.227423483107259 ], [ 29.505940305900367, -2.234864889203266 ], [ 29.481083942070256, -2.254295228541991 ], [ 29.466511188240702, -2.269436423152399 ], [ 29.460413369281525, -2.268557923109654 ], [ 29.448579466569129, -2.2690746879465 ], [ 29.431267861622473, -2.26948809909652 ], [ 29.411062376827203, -2.272795390994531 ], [ 29.392458860687839, -2.286799704043119 ], [ 29.379746458832017, -2.292535787796396 ], [ 29.368480996001153, -2.28912514311088 ], [ 29.353649860652524, -2.291398906234519 ], [ 29.33850866604206, -2.299150371592361 ], [ 29.328380084773073, -2.311242656723266 ], [ 29.325692909600093, -2.324781881778449 ], [ 29.332307493396058, -2.341214987581623 ], [ 29.339128782767091, -2.355167623786826 ], [ 29.338301959567787, -2.364366029069004 ], [ 29.328276731985568, -2.380230694091267 ], [ 29.319853473958631, -2.393718242303066 ], [ 29.322799030650742, -2.403123353160254 ], [ 29.325796263286918, -2.414388815091741 ], [ 29.321713825032987, -2.423483867586413 ], [ 29.301198281875202, -2.434749329517956 ], [ 29.280114297037187, -2.4460147914495 ], [ 29.271432656591799, -2.458727194204641 ], [ 29.266885130344463, -2.471853008109861 ], [ 29.267815306331329, -2.478570944693331 ], [ 29.279907590562857, -2.485133851645969 ], [ 29.298511106702165, -2.490973288186694 ], [ 29.311946979869219, -2.497122783089992 ], [ 29.320215208265211, -2.508233216289909 ], [ 29.322385618601402, -2.523426087743758 ], [ 29.328380084773073, -2.535880108080505 ], [ 29.335924843656585, -2.545853658819283 ], [ 29.340885781953261, -2.555672181725811 ], [ 29.345019896151257, -2.561925028517237 ], [ 29.343107868233517, -2.571691874580381 ], [ 29.341919309828256, -2.580941956705942 ], [ 29.343262897864406, -2.587969951651985 ], [ 29.348275511205884, -2.595463034591376 ], [ 29.359954385186711, -2.612619609907085 ], [ 29.3566470932887, -2.648689759724618 ], [ 29.342539426553287, -2.673856181917245 ], [ 29.333392699013814, -2.678662090583032 ], [ 29.328380084773073, -2.680160705552112 ], [ 29.30948054400011, -2.690126857999886 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "RW-03", "NAME_1": "Northern" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 29.917429240000047, -1.47520599399985 ], [ 29.938461548000134, -1.47293223099993 ], [ 29.960424032000105, -1.464767353999903 ], [ 30.028326863000075, -1.427146911999984 ], [ 30.03866215000005, -1.424976500999904 ], [ 30.047757202000128, -1.403169046999963 ], [ 30.060779663000062, -1.389733174999918 ], [ 30.065984342603315, -1.386944953546788 ], [ 30.070195270595264, -1.38912839865668 ], [ 30.073089150443934, -1.389903545012601 ], [ 30.078721881409706, -1.394347717573112 ], [ 30.081874144576091, -1.404527975685539 ], [ 30.087403522754357, -1.412072734569051 ], [ 30.093914752863554, -1.417292053485482 ], [ 30.106523802831191, -1.438376037424177 ], [ 30.117685911975229, -1.455222555276691 ], [ 30.126419229264002, -1.471500630549656 ], [ 30.135049192865949, -1.490310853163351 ], [ 30.13928666075077, -1.499715964020538 ], [ 30.141818805393541, -1.515115541049397 ], [ 30.14254227580534, -1.524313944532935 ], [ 30.151585650557308, -1.521575093415834 ], [ 30.163522906956587, -1.517389303273717 ], [ 30.173289753019674, -1.517389303273717 ], [ 30.178767454354499, -1.520334859965828 ], [ 30.178354043204536, -1.524934063056548 ], [ 30.170395873171003, -1.532065410790096 ], [ 30.165124877411131, -1.54886025089985 ], [ 30.169310667553248, -1.57123614603131 ], [ 30.177010456067649, -1.591596659558206 ], [ 30.186880654918298, -1.60937335249821 ], [ 30.199903115136635, -1.623119284027723 ], [ 30.218041543282595, -1.646683737564445 ], [ 30.237471881721945, -1.670816630982756 ], [ 30.251734577188984, -1.686267884854999 ], [ 30.25762569057315, -1.699703757122677 ], [ 30.254266722731074, -1.711175924629231 ], [ 30.250442665996218, -1.722286357829148 ], [ 30.254008340312623, -1.743266988980395 ], [ 30.2643436262573, -1.777580140511077 ], [ 30.272095091615142, -1.80827594088197 ], [ 30.272405149977658, -1.823520488279939 ], [ 30.266720742168502, -1.826931132965399 ], [ 30.258142455409995, -1.832822245450302 ], [ 30.251062783620569, -1.840315329289012 ], [ 30.247083698154142, -1.843209209137683 ], [ 30.239745644845641, -1.842124003519984 ], [ 30.223364215885852, -1.836697979028543 ], [ 30.192151650678113, -1.814528788572716 ], [ 30.159182087183581, -1.792617981434717 ], [ 30.142645628592845, -1.782902813114333 ], [ 30.134842487290939, -1.779388815641312 ], [ 30.129778197106077, -1.79246295270309 ], [ 30.122853554947596, -1.80946449928723 ], [ 30.117375853612714, -1.816492494233216 ], [ 30.107867389968078, -1.815045552510242 ], [ 30.083372760444547, -1.819386374081887 ], [ 30.063115599705156, -1.828481425677239 ], [ 30.057534544683449, -1.835819479885117 ], [ 30.046682493901926, -1.848325176165929 ], [ 30.033556679996764, -1.856076640624451 ], [ 30.021257689290906, -1.84780841042982 ], [ 30.007925169810733, -1.839126770883752 ], [ 29.998313353378535, -1.842434062781763 ], [ 29.990716917651582, -1.854526347912611 ], [ 29.982500365199655, -1.868168925755356 ], [ 29.978056191739824, -1.878297507024342 ], [ 29.983533893974027, -1.893490377578871 ], [ 29.987461302597012, -1.905479309922214 ], [ 29.983740600448357, -1.908373190670204 ], [ 29.981105101219441, -1.909406718545256 ], [ 29.978469602889845, -1.907649720258405 ], [ 29.970511432856313, -1.906099427546565 ], [ 29.96079626363661, -1.899484843750542 ], [ 29.951184447204469, -1.889149557805865 ], [ 29.943019570696606, -1.880984681298003 ], [ 29.936715046162419, -1.875041891969772 ], [ 29.929325316010534, -1.870029277728975 ], [ 29.921367145077681, -1.865895162631659 ], [ 29.914494179762585, -1.860934225234303 ], [ 29.902401894631737, -1.857316874973833 ], [ 29.884935260953512, -1.856903463823812 ], [ 29.865091509565502, -1.860520814084339 ], [ 29.845816201656362, -1.860727519659292 ], [ 29.818479369127544, -1.85142576158961 ], [ 29.79951411778228, -1.839333475559442 ], [ 29.794501504440859, -1.824967429103594 ], [ 29.780548867336336, -1.81173826151155 ], [ 29.768766640568003, -1.793548156522206 ], [ 29.755434121087774, -1.773704407832156 ], [ 29.745150511087218, -1.757684714078323 ], [ 29.741584837670075, -1.748434632852025 ], [ 29.733885049155674, -1.7471943985027 ], [ 29.721379352874806, -1.74951983757046 ], [ 29.702620808003871, -1.742646872255364 ], [ 29.686187702200698, -1.731743144630457 ], [ 29.67502559305666, -1.72967608798109 ], [ 29.663605100594907, -1.731278056636995 ], [ 29.65766231126662, -1.733086731767287 ], [ 29.646913613272602, -1.724921856158744 ], [ 29.634459593835174, -1.709935690279906 ], [ 29.635699828184499, -1.688128235929355 ], [ 29.63611323933452, -1.659137757901192 ], [ 29.634717975354249, -1.618158346630423 ], [ 29.630583861156254, -1.587875956510175 ], [ 29.610946817141894, -1.58648069252996 ], [ 29.590741331447248, -1.5876175749911 ], [ 29.572189492151324, -1.578419170608242 ], [ 29.555963092822481, -1.570822734881347 ], [ 29.550640420219224, -1.569169087583361 ], [ 29.546661334752798, -1.566740296627415 ], [ 29.540046751856096, -1.569375794956954 ], [ 29.531881875348233, -1.569582500531965 ], [ 29.51296830084641, -1.563588033460974 ], [ 29.491419228914253, -1.556146628264287 ], [ 29.467286334596622, -1.527827942905276 ], [ 29.449406289768433, -1.503488343012634 ], [ 29.445065226000054, -1.497286823999929 ], [ 29.464330282000105, -1.466937764999898 ], [ 29.498746785000094, -1.431074319999951 ], [ 29.538640991000079, -1.402342223999938 ], [ 29.577915080000082, -1.388389587999953 ], [ 29.618119344000092, -1.39055999699994 ], [ 29.639099976000125, -1.389009703999918 ], [ 29.657703491000063, -1.383945413999939 ], [ 29.678322388000083, -1.372369892999899 ], [ 29.693773641000064, -1.361207783999873 ], [ 29.710516805000111, -1.352526142999906 ], [ 29.734804728000086, -1.348185322999925 ], [ 29.746690308000041, -1.350872496999955 ], [ 29.767980997000109, -1.36379160499996 ], [ 29.77490563900011, -1.366272073999937 ], [ 29.783173869000052, -1.361414488999927 ], [ 29.789168335000056, -1.341674092999952 ], [ 29.798211711000135, -1.330925394999937 ], [ 29.80746179200014, -1.325137633999873 ], [ 29.816143432000104, -1.322553812999956 ], [ 29.825024114000087, -1.323880810999896 ], [ 29.825135132000071, -1.323897399999936 ], [ 29.836090536000142, -1.329478454999943 ], [ 29.864202514000056, -1.370302835999937 ], [ 29.868646688000069, -1.391283466999937 ], [ 29.871023804000117, -1.432417906999916 ], [ 29.880738973000064, -1.453605244999963 ], [ 29.897895548000122, -1.469624938999928 ], [ 29.917429240000047, -1.47520599399985 ] ] ] } }, { "type": "Feature", "properties": { "ISO": "RW-01", "NAME_1": "Kigali City" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 30.017847044605389, -2.072135803424601 ], [ 30.015469928694245, -2.070327129193686 ], [ 30.009165404160058, -2.068363423533185 ], [ 30.003480996350902, -2.066503072458829 ], [ 29.999140175678519, -2.065882955733855 ], [ 29.990561888020693, -2.060560283130599 ], [ 29.984464069061517, -2.04841632205563 ], [ 29.986376096979257, -2.038752828780048 ], [ 29.993714150287758, -2.031311422684041 ], [ 30.001827350851556, -2.028055807629414 ], [ 30.005341348324521, -2.024231751793934 ], [ 30.009888873672537, -2.016583639223597 ], [ 30.003377643563397, -2.001184063094058 ], [ 29.993920856762088, -1.986301250002668 ], [ 29.997331501447604, -1.981133607030358 ], [ 29.999243529365344, -1.974829081596852 ], [ 29.999966998877881, -1.968472881118601 ], [ 30.000122029408089, -1.964648825283064 ], [ 30.000432086871285, -1.962788473309388 ], [ 30.002137409214072, -1.958395976692998 ], [ 29.999243529365344, -1.951161276171945 ], [ 29.996246295829849, -1.943616517288433 ], [ 29.993249063193673, -1.937415345541751 ], [ 29.990355182445683, -1.933487936918766 ], [ 29.988288124897053, -1.930180645020755 ], [ 29.985600950623336, -1.922584209293859 ], [ 29.982603717987161, -1.914057597580097 ], [ 29.980588337281915, -1.910698629737965 ], [ 29.981105101219441, -1.909406718545256 ], [ 29.983740600448357, -1.908373190670204 ], [ 29.987461302597012, -1.905479309922214 ], [ 29.983533893974027, -1.893490377578871 ], [ 29.978056191739824, -1.878297507024342 ], [ 29.982500365199655, -1.868168925755356 ], [ 29.990716917651582, -1.854526347912611 ], [ 29.998313353378535, -1.842434062781763 ], [ 30.007925169810733, -1.839126770883752 ], [ 30.021257689290906, -1.84780841042982 ], [ 30.033556679996764, -1.856076640624451 ], [ 30.046682493901926, -1.848325176165929 ], [ 30.057534544683449, -1.835819479885117 ], [ 30.063115599705156, -1.828481425677239 ], [ 30.083372760444547, -1.819386374081887 ], [ 30.107867389968078, -1.815045552510242 ], [ 30.117375853612714, -1.816492494233216 ], [ 30.122853554947596, -1.80946449928723 ], [ 30.129778197106077, -1.79246295270309 ], [ 30.134842487290939, -1.779388815641312 ], [ 30.142645628592845, -1.782902813114333 ], [ 30.159182087183581, -1.792617981434717 ], [ 30.192151650678113, -1.814528788572716 ], [ 30.223364215885852, -1.836697979028543 ], [ 30.239745644845641, -1.842124003519984 ], [ 30.247083698154142, -1.843209209137683 ], [ 30.248375609346851, -1.848531881740939 ], [ 30.255196897818564, -1.858247050960642 ], [ 30.259020954553364, -1.872664776058571 ], [ 30.258349160085629, -1.886462383532205 ], [ 30.264550332731631, -1.894058817460461 ], [ 30.270441445216477, -1.900001608587388 ], [ 30.272508502765163, -1.916383037547178 ], [ 30.272146767559263, -1.936020081561537 ], [ 30.267444212580301, -1.944443339588474 ], [ 30.253801634737613, -1.950954570596991 ], [ 30.239383909639685, -1.957052389556168 ], [ 30.233957884248923, -1.963253561302849 ], [ 30.233337768423269, -1.974829081596852 ], [ 30.230340533988453, -2.010899232313704 ], [ 30.223725951091751, -2.046969382131294 ], [ 30.21581945700234, -2.065056132534494 ], [ 30.209049843575428, -2.074667949866011 ], [ 30.202538612566912, -2.065624574214723 ], [ 30.194942177739279, -2.056116110570031 ], [ 30.188172565211687, -2.045729147781969 ], [ 30.177630573691999, -2.031879862565631 ], [ 30.165383258930262, -2.028417542835371 ], [ 30.153239296955974, -2.032706686664255 ], [ 30.14254227580534, -2.037357565699097 ], [ 30.13680619205212, -2.040354797435953 ], [ 30.129829873050198, -2.045470764464199 ], [ 30.123835406878527, -2.050586731492501 ], [ 30.121406615023261, -2.054307434540476 ], [ 30.117995970337745, -2.054927552164827 ], [ 30.115102089589755, -2.055030904952332 ], [ 30.107040566768717, -2.055754374464811 ], [ 30.09804886796087, -2.057666403281871 ], [ 30.092261107364209, -2.059475077512843 ], [ 30.085698200411628, -2.060922017437179 ], [ 30.079755410184021, -2.062058899898318 ], [ 30.076396442341945, -2.062885723097679 ], [ 30.073605915280723, -2.063764222241048 ], [ 30.067456418578843, -2.064539368596968 ], [ 30.058878131820336, -2.063609192610159 ], [ 30.054227252785495, -2.057459697706918 ], [ 30.050609903424288, -2.053170553877976 ], [ 30.043426878847356, -2.055134257739837 ], [ 30.038207559031605, -2.060611959973983 ], [ 30.032006387284923, -2.064022604659499 ], [ 30.022394570852725, -2.068260071645 ], [ 30.017847044605389, -2.072135803424601 ] ] ] } } ] }
superset-frontend/plugins/legacy-plugin-chart-country-map/src/countries/rwanda.geojson
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00026593523216433823, 0.00022270352928899229, 0.00017947182641364634, 0.00022270352928899229, 0.000043231702875345945 ]
{ "id": 12, "code_window": [ " * under the License.\n", " */\n", "/* eslint-disable camelcase */\n", "// eslint-disable-next-line import/no-extraneous-dependencies\n", "import { SET_REPORT, ADD_REPORT, EDIT_REPORT } from '../actions/reports';\n", "\n", "export default function reportsReducer(state = {}, action) {\n", " const actionHandlers = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { omit } from 'lodash';\n", "import {\n", " SET_REPORT,\n", " ADD_REPORT,\n", " EDIT_REPORT,\n", " DELETE_REPORT,\n", "} from '../actions/reports';\n" ], "file_path": "superset-frontend/src/reports/reducers/reports.js", "type": "replace", "edit_start_line_idx": 20 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { t, validateNonEmpty } from '@superset-ui/core'; import { sections } from '@superset-ui/chart-controls'; import { viewport, mapboxStyle } from '../utilities/Shared_DeckGL'; export default { controlPanelSections: [ sections.legacyRegularTime, { label: t('Map'), expanded: true, controlSetRows: [ [mapboxStyle, viewport], [ { name: 'deck_slices', config: { type: 'SelectAsyncControl', multi: true, label: t('deck.gl charts'), validators: [validateNonEmpty], default: [], description: t( 'Pick a set of deck.gl charts to layer on top of one another', ), dataEndpoint: '/sliceasync/api/read?_flt_0_viz_type=deck_&_flt_7_viz_type=deck_multi', placeholder: t('Select charts'), onAsyncErrorMessage: t('Error while fetching charts'), mutator: data => { if (!data || !data.result) { return []; } return data.result.map(o => ({ value: o.id, label: o.slice_name, })); }, }, }, null, ], ], }, { label: t('Query'), expanded: true, controlSetRows: [['adhoc_filters']], }, ], };
superset-frontend/plugins/legacy-preset-chart-deckgl/src/Multi/controlPanel.js
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017943007696885616, 0.00017462062533013523, 0.00016664847498759627, 0.00017564640438649803, 0.0000036534215723804664 ]
{ "id": 13, "code_window": [ " ...state[report.creation_method],\n", " [reportTypeId]: report,\n", " },\n", " };\n", " },\n", " };\n", "\n", " if (action.type in actionHandlers) {\n", " return actionHandlers[action.type]();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " [DELETE_REPORT]() {\n", " const { report } = action;\n", " const reportTypeId = report.dashboard || report.chart;\n", " return {\n", " ...state,\n", " [report.creation_method]: {\n", " ...omit(state[report.creation_method], reportTypeId),\n", " },\n", " };\n", " },\n" ], "file_path": "superset-frontend/src/reports/reducers/reports.js", "type": "add", "edit_start_line_idx": 80 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint camelcase: 0 */ import { t, SupersetClient } from '@superset-ui/core'; import rison from 'rison'; import { addDangerToast, addSuccessToast, } from 'src/components/MessageToasts/actions'; import { isEmpty } from 'lodash'; export const SET_REPORT = 'SET_REPORT'; export function setReport(report, resourceId, creationMethod, filterField) { return { type: SET_REPORT, report, resourceId, creationMethod, filterField }; } export function fetchUISpecificReport({ userId, filterField, creationMethod, resourceId, }) { const queryParams = rison.encode({ filters: [ { col: filterField, opr: 'eq', value: resourceId, }, { col: 'creation_method', opr: 'eq', value: creationMethod, }, { col: 'created_by', opr: 'rel_o_m', value: userId, }, ], }); return function fetchUISpecificReportThunk(dispatch) { return SupersetClient.get({ endpoint: `/api/v1/report/?q=${queryParams}`, }) .then(({ json }) => { dispatch(setReport(json, resourceId, creationMethod, filterField)); }) .catch(() => dispatch( addDangerToast( t( 'There was an issue fetching reports attached to this dashboard.', ), ), ), ); }; } const structureFetchAction = (dispatch, getState) => { const state = getState(); const { user, dashboardInfo, charts, explore } = state; if (!isEmpty(dashboardInfo)) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: 'dashboard_id', creationMethod: 'dashboards', resourceId: dashboardInfo.id, }), ); } else { const [chartArr] = Object.keys(charts); dispatch( fetchUISpecificReport({ userId: explore.user?.userId || user?.userId, filterField: 'chart_id', creationMethod: 'charts', resourceId: charts[chartArr].id, }), ); } }; export const ADD_REPORT = 'ADD_REPORT'; export const addReport = report => dispatch => SupersetClient.post({ endpoint: `/api/v1/report/`, jsonPayload: report, }).then(({ json }) => { dispatch({ type: ADD_REPORT, json }); dispatch(addSuccessToast(t('The report has been created'))); }); export const EDIT_REPORT = 'EDIT_REPORT'; export const editReport = (id, report) => dispatch => SupersetClient.put({ endpoint: `/api/v1/report/${id}`, jsonPayload: report, }).then(({ json }) => { dispatch({ type: EDIT_REPORT, json }); dispatch(addSuccessToast(t('Report updated'))); }); export function toggleActive(report, isActive) { return function toggleActiveThunk(dispatch) { return SupersetClient.put({ endpoint: encodeURI(`/api/v1/report/${report.id}`), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ active: isActive, }), }) .catch(() => { dispatch( addDangerToast( t('We were unable to active or deactivate this report.'), ), ); }) .finally(() => { dispatch(structureFetchAction); }); }; } export function deleteActiveReport(report) { return function deleteActiveReportThunk(dispatch) { return SupersetClient.delete({ endpoint: encodeURI(`/api/v1/report/${report.id}`), }) .catch(() => { dispatch(addDangerToast(t('Your report could not be deleted'))); }) .finally(() => { dispatch(structureFetchAction); dispatch(addSuccessToast(t('Deleted: %s', report.name))); }); }; }
superset-frontend/src/reports/actions/reports.js
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0018036196706816554, 0.0004585675778798759, 0.00016563777171541005, 0.00017426378326490521, 0.00044741592137143016 ]
{ "id": 13, "code_window": [ " ...state[report.creation_method],\n", " [reportTypeId]: report,\n", " },\n", " };\n", " },\n", " };\n", "\n", " if (action.type in actionHandlers) {\n", " return actionHandlers[action.type]();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " [DELETE_REPORT]() {\n", " const { report } = action;\n", " const reportTypeId = report.dashboard || report.chart;\n", " return {\n", " ...state,\n", " [report.creation_method]: {\n", " ...omit(state[report.creation_method], reportTypeId),\n", " },\n", " };\n", " },\n" ], "file_path": "superset-frontend/src/reports/reducers/reports.js", "type": "add", "edit_start_line_idx": 80 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React, { useCallback, useState } from 'react'; import { css, t, getChartMetadataRegistry, styled, SupersetTheme, } from '@superset-ui/core'; import { usePluginContext } from 'src/components/DynamicPlugins'; import Modal from 'src/components/Modal'; import { noOp } from 'src/utils/common'; import getBootstrapData from 'src/utils/getBootstrapData'; import VizTypeGallery, { MAX_ADVISABLE_VIZ_GALLERY_WIDTH, } from './VizTypeGallery'; import { FastVizSwitcher } from './FastVizSwitcher'; interface VizTypeControlProps { description?: string; label?: string; name: string; onChange: (vizType: string | null) => void; value: string | null; isModalOpenInit?: boolean; } const bootstrapData = getBootstrapData(); const denyList: string[] = bootstrapData.common.conf.VIZ_TYPE_DENYLIST || []; const metadataRegistry = getChartMetadataRegistry(); export const VIZ_TYPE_CONTROL_TEST_ID = 'viz-type-control'; function VizSupportValidation({ vizType }: { vizType: string }) { const state = usePluginContext(); if (state.loading || metadataRegistry.has(vizType)) { return null; } return ( <div className="text-danger" css={(theme: SupersetTheme) => css` margin-top: ${theme.gridUnit}px; `} > <i className="fa fa-exclamation-circle text-danger" />{' '} <small>{t('This visualization type is not supported.')}</small> </div> ); } const UnpaddedModal = styled(Modal)` .ant-modal-body { padding: 0; } `; /** Manages the viz type and the viz picker modal */ const VizTypeControl = ({ value: initialValue, onChange = noOp, isModalOpenInit, }: VizTypeControlProps) => { const [showModal, setShowModal] = useState(!!isModalOpenInit); // a trick to force re-initialization of the gallery each time the modal opens, // ensuring that the modal always opens to the correct category. const [modalKey, setModalKey] = useState(0); const [selectedViz, setSelectedViz] = useState<string | null>(initialValue); const openModal = useCallback(() => { setShowModal(true); }, []); const onSubmit = useCallback(() => { onChange(selectedViz); setShowModal(false); }, [selectedViz, onChange]); const onCancel = useCallback(() => { setShowModal(false); setModalKey(key => key + 1); // make sure the modal re-opens to the last submitted viz setSelectedViz(initialValue); }, [initialValue]); return ( <> <div css={(theme: SupersetTheme) => css` min-width: ${theme.gridUnit * 72}px; max-width: fit-content; `} > <FastVizSwitcher onChange={onChange} currentSelection={initialValue} /> {initialValue && <VizSupportValidation vizType={initialValue} />} </div> <div css={(theme: SupersetTheme) => css` display: flex; justify-content: flex-end; margin-top: ${theme.gridUnit * 3}px; color: ${theme.colors.grayscale.base}; text-decoration: underline; `} > <span role="button" tabIndex={0} onClick={openModal}> {t('View all charts')} </span> </div> <UnpaddedModal show={showModal} onHide={onCancel} title={t('Select a visualization type')} primaryButtonName={t('Select')} disablePrimaryButton={!selectedViz} onHandledPrimaryAction={onSubmit} maxWidth={`${MAX_ADVISABLE_VIZ_GALLERY_WIDTH}px`} responsive > {/* When the key increments, it forces react to re-init the gallery component */} <VizTypeGallery key={modalKey} selectedViz={selectedViz} onChange={setSelectedViz} onDoubleClick={onSubmit} denyList={denyList} /> </UnpaddedModal> </> ); }; export default VizTypeControl;
superset-frontend/src/explore/components/controls/VizTypeControl/index.tsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0013862254563719034, 0.0002482047420926392, 0.00016662846610415727, 0.00017249373195227236, 0.00029385118978098035 ]
{ "id": 13, "code_window": [ " ...state[report.creation_method],\n", " [reportTypeId]: report,\n", " },\n", " };\n", " },\n", " };\n", "\n", " if (action.type in actionHandlers) {\n", " return actionHandlers[action.type]();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " [DELETE_REPORT]() {\n", " const { report } = action;\n", " const reportTypeId = report.dashboard || report.chart;\n", " return {\n", " ...state,\n", " [report.creation_method]: {\n", " ...omit(state[report.creation_method], reportTypeId),\n", " },\n", " };\n", " },\n" ], "file_path": "superset-frontend/src/reports/reducers/reports.js", "type": "add", "edit_start_line_idx": 80 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { t } from '@superset-ui/core'; import { sections } from '@superset-ui/chart-controls'; export default { controlPanelSections: [ sections.legacyTimeseriesTime, { label: t('Filters configuration'), expanded: true, controlSetRows: [ [ { name: 'filter_configs', config: { type: 'CollectionControl', label: t('Filters'), description: t('Filter configuration for the filter box'), validators: [], controlName: 'FilterBoxItemControl', mapStateToProps: ({ datasource }) => ({ datasource }), }, }, ], [<hr />], [ { name: 'date_filter', config: { type: 'CheckboxControl', label: t('Date filter'), default: true, description: t('Whether to include a time filter'), }, }, ], [ { name: 'instant_filtering', config: { type: 'CheckboxControl', label: t('Instant filtering'), renderTrigger: true, default: false, description: t( 'Check to apply filters instantly as they change instead of displaying [Apply] button', ), }, }, ], [ { name: 'show_sqla_time_granularity', config: { type: 'CheckboxControl', label: t('Show time grain dropdown'), default: false, description: t('Check to include time grain dropdown'), }, }, ], [ { name: 'show_sqla_time_column', config: { type: 'CheckboxControl', label: t('Show time column'), default: false, description: t('Check to include time column dropdown'), }, }, ], ['adhoc_filters'], ], }, ], controlOverrides: { adhoc_filters: { label: t('Limit selector values'), description: t( 'These filters apply to the values available in the dropdowns', ), }, }, };
superset-frontend/src/visualizations/FilterBox/controlPanel.jsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017511445912532508, 0.0001713663514237851, 0.00016779298312030733, 0.0001716004917398095, 0.0000023419167973770527 ]
{ "id": 13, "code_window": [ " ...state[report.creation_method],\n", " [reportTypeId]: report,\n", " },\n", " };\n", " },\n", " };\n", "\n", " if (action.type in actionHandlers) {\n", " return actionHandlers[action.type]();\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " [DELETE_REPORT]() {\n", " const { report } = action;\n", " const reportTypeId = report.dashboard || report.chart;\n", " return {\n", " ...state,\n", " [report.creation_method]: {\n", " ...omit(state[report.creation_method], reportTypeId),\n", " },\n", " };\n", " },\n" ], "file_path": "superset-frontend/src/reports/reducers/reports.js", "type": "add", "edit_start_line_idx": 80 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import URI from 'urijs'; import { Provider } from 'react-redux'; import { shallow, mount } from 'enzyme'; import { fireEvent, render, waitFor } from 'spec/helpers/testing-library'; import sinon from 'sinon'; import { act } from 'react-dom/test-utils'; import fetchMock from 'fetch-mock'; import { supersetTheme, ThemeProvider } from '@superset-ui/core'; import { EditableTabs } from 'src/components/Tabs'; import TabbedSqlEditors from 'src/SqlLab/components/TabbedSqlEditors'; import SqlEditor from 'src/SqlLab/components/SqlEditor'; import { initialState } from 'src/SqlLab/fixtures'; import { newQueryTabName } from 'src/SqlLab/utils/newQueryTabName'; import QueryProvider from 'src/views/QueryProvider'; fetchMock.get('glob:*/api/v1/database/*', {}); fetchMock.get('glob:*/savedqueryviewapi/api/get/*', {}); fetchMock.get('glob:*/kv/*', {}); describe('TabbedSqlEditors', () => { const middlewares = [thunk]; const mockStore = configureStore(middlewares); const store = mockStore(initialState); const queryEditors = [ { autorun: false, dbId: 1, id: 'newEditorId', latestQueryId: 'B1-VQU1zW', schema: null, selectedText: null, sql: 'SELECT ds...', name: 'Untitled Query', }, ]; const mockedProps = { actions: {}, databases: {}, tables: [], queries: {}, queryEditors: initialState.sqlLab.queryEditors, tabHistory: initialState.sqlLab.tabHistory, editorHeight: '', getHeight: () => '100px', database: {}, defaultQueryLimit: 1000, maxRow: 100000, }; const getWrapper = () => shallow(<TabbedSqlEditors store={store} {...mockedProps} />) .dive() .dive(); const mountWithAct = async () => act(async () => { mount( <QueryProvider> <Provider store={store}> <TabbedSqlEditors {...mockedProps} /> </Provider> </QueryProvider>, { wrappingComponent: ThemeProvider, wrappingComponentProps: { theme: supersetTheme }, }, ); }); const setup = (props = {}, overridesStore) => render(<TabbedSqlEditors {...props} />, { useRedux: true, store: overridesStore || store, }); let wrapper; it('is valid', () => { expect(React.isValidElement(<TabbedSqlEditors {...mockedProps} />)).toBe( true, ); }); describe('componentDidMount', () => { let uriStub; beforeEach(() => { sinon.stub(window.history, 'replaceState'); uriStub = sinon.stub(URI.prototype, 'search'); }); afterEach(() => { window.history.replaceState.restore(); uriStub.restore(); }); it('should handle id', async () => { uriStub.returns({ id: 1 }); await mountWithAct(); expect(window.history.replaceState.getCall(0).args[2]).toBe( '/superset/sqllab', ); }); it('should handle savedQueryId', async () => { uriStub.returns({ savedQueryId: 1 }); await mountWithAct(); expect(window.history.replaceState.getCall(0).args[2]).toBe( '/superset/sqllab', ); }); it('should handle sql', async () => { uriStub.returns({ sql: 1, dbid: 1 }); await mountWithAct(); expect(window.history.replaceState.getCall(0).args[2]).toBe( '/superset/sqllab', ); }); }); it('should removeQueryEditor', () => { wrapper = getWrapper(); sinon.stub(wrapper.instance().props.actions, 'removeQueryEditor'); wrapper.instance().removeQueryEditor(queryEditors[0]); expect( wrapper.instance().props.actions.removeQueryEditor.getCall(0).args[0], ).toBe(queryEditors[0]); }); it('should add new query editor', async () => { const { getAllByLabelText } = setup(mockedProps); fireEvent.click(getAllByLabelText('Add tab')[0]); const actions = store.getActions(); await waitFor(() => expect(actions).toContainEqual({ type: 'ADD_QUERY_EDITOR', queryEditor: expect.objectContaining({ name: expect.stringMatching(/Untitled Query (\d+)+/), }), }), ); }); it('should properly increment query tab name', async () => { const { getAllByLabelText } = setup(mockedProps); const newTitle = newQueryTabName(store.getState().sqlLab.queryEditors); fireEvent.click(getAllByLabelText('Add tab')[0]); const actions = store.getActions(); await waitFor(() => expect(actions).toContainEqual({ type: 'ADD_QUERY_EDITOR', queryEditor: expect.objectContaining({ name: newTitle, }), }), ); }); it('should duplicate query editor', () => { wrapper = getWrapper(); sinon.stub(wrapper.instance().props.actions, 'cloneQueryToNewTab'); wrapper.instance().duplicateQueryEditor(queryEditors[0]); expect( wrapper.instance().props.actions.cloneQueryToNewTab.getCall(0).args[0], ).toBe(queryEditors[0]); }); it('should handle select', () => { const mockEvent = { target: { getAttribute: () => null, }, }; wrapper = getWrapper(); sinon.stub(wrapper.instance().props.actions, 'switchQueryEditor'); // cannot switch to current tab, switchQueryEditor never gets called wrapper.instance().handleSelect('dfsadfs', mockEvent); expect( wrapper.instance().props.actions.switchQueryEditor.callCount, ).toEqual(0); }); it('should handle add tab', () => { wrapper = getWrapper(); sinon.spy(wrapper.instance(), 'newQueryEditor'); wrapper.instance().handleEdit('1', 'add'); expect(wrapper.instance().newQueryEditor.callCount).toBe(1); wrapper.instance().newQueryEditor.restore(); }); it('should render', () => { wrapper = getWrapper(); wrapper.setState({ hideLeftBar: true }); const firstTab = wrapper.find(EditableTabs.TabPane).first(); expect(firstTab.props()['data-key']).toContain( initialState.sqlLab.queryEditors[0].id, ); expect(firstTab.find(SqlEditor)).toHaveLength(1); }); it('should disable new tab when offline', () => { wrapper = getWrapper(); expect(wrapper.find('#a11y-query-editor-tabs').props().hideAdd).toBe(false); wrapper.setProps({ offline: true }); expect(wrapper.find('#a11y-query-editor-tabs').props().hideAdd).toBe(true); }); it('should have an empty state when query editors is empty', () => { wrapper = getWrapper(); wrapper.setProps({ queryEditors: [] }); const firstTab = wrapper.find(EditableTabs.TabPane).first(); expect(firstTab.props()['data-key']).toBe(0); }); });
superset-frontend/src/SqlLab/components/TabbedSqlEditors/TabbedSqlEditors.test.jsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00037027959479019046, 0.00018527200154494494, 0.00016726218746043742, 0.00017369163106195629, 0.00004097248529433273 ]
{ "id": 14, "code_window": [ ") => {\n", " if (resourceId) {\n", " return state.reports[resourceType]?.[resourceId];\n", " }\n", " return {};\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return null;\n" ], "file_path": "superset-frontend/src/views/CRUD/hooks.ts", "type": "replace", "edit_start_line_idx": 869 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* eslint camelcase: 0 */ import { t, SupersetClient } from '@superset-ui/core'; import rison from 'rison'; import { addDangerToast, addSuccessToast, } from 'src/components/MessageToasts/actions'; import { isEmpty } from 'lodash'; export const SET_REPORT = 'SET_REPORT'; export function setReport(report, resourceId, creationMethod, filterField) { return { type: SET_REPORT, report, resourceId, creationMethod, filterField }; } export function fetchUISpecificReport({ userId, filterField, creationMethod, resourceId, }) { const queryParams = rison.encode({ filters: [ { col: filterField, opr: 'eq', value: resourceId, }, { col: 'creation_method', opr: 'eq', value: creationMethod, }, { col: 'created_by', opr: 'rel_o_m', value: userId, }, ], }); return function fetchUISpecificReportThunk(dispatch) { return SupersetClient.get({ endpoint: `/api/v1/report/?q=${queryParams}`, }) .then(({ json }) => { dispatch(setReport(json, resourceId, creationMethod, filterField)); }) .catch(() => dispatch( addDangerToast( t( 'There was an issue fetching reports attached to this dashboard.', ), ), ), ); }; } const structureFetchAction = (dispatch, getState) => { const state = getState(); const { user, dashboardInfo, charts, explore } = state; if (!isEmpty(dashboardInfo)) { dispatch( fetchUISpecificReport({ userId: user.userId, filterField: 'dashboard_id', creationMethod: 'dashboards', resourceId: dashboardInfo.id, }), ); } else { const [chartArr] = Object.keys(charts); dispatch( fetchUISpecificReport({ userId: explore.user?.userId || user?.userId, filterField: 'chart_id', creationMethod: 'charts', resourceId: charts[chartArr].id, }), ); } }; export const ADD_REPORT = 'ADD_REPORT'; export const addReport = report => dispatch => SupersetClient.post({ endpoint: `/api/v1/report/`, jsonPayload: report, }).then(({ json }) => { dispatch({ type: ADD_REPORT, json }); dispatch(addSuccessToast(t('The report has been created'))); }); export const EDIT_REPORT = 'EDIT_REPORT'; export const editReport = (id, report) => dispatch => SupersetClient.put({ endpoint: `/api/v1/report/${id}`, jsonPayload: report, }).then(({ json }) => { dispatch({ type: EDIT_REPORT, json }); dispatch(addSuccessToast(t('Report updated'))); }); export function toggleActive(report, isActive) { return function toggleActiveThunk(dispatch) { return SupersetClient.put({ endpoint: encodeURI(`/api/v1/report/${report.id}`), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ active: isActive, }), }) .catch(() => { dispatch( addDangerToast( t('We were unable to active or deactivate this report.'), ), ); }) .finally(() => { dispatch(structureFetchAction); }); }; } export function deleteActiveReport(report) { return function deleteActiveReportThunk(dispatch) { return SupersetClient.delete({ endpoint: encodeURI(`/api/v1/report/${report.id}`), }) .catch(() => { dispatch(addDangerToast(t('Your report could not be deleted'))); }) .finally(() => { dispatch(structureFetchAction); dispatch(addSuccessToast(t('Deleted: %s', report.name))); }); }; }
superset-frontend/src/reports/actions/reports.js
1
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0024992881808429956, 0.00046536195441149175, 0.00016453243733849376, 0.00018065361655317247, 0.0006422849837690592 ]
{ "id": 14, "code_window": [ ") => {\n", " if (resourceId) {\n", " return state.reports[resourceType]?.[resourceId];\n", " }\n", " return {};\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return null;\n" ], "file_path": "superset-frontend/src/views/CRUD/hooks.ts", "type": "replace", "edit_start_line_idx": 869 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { DatasourceType, getChartControlPanelRegistry, t, } from '@superset-ui/core'; import { ControlConfig, ControlPanelState, CustomControlItem, } from '@superset-ui/chart-controls'; import { getControlConfig, getControlState, applyMapStateToPropsToControl, findControlItem, } from 'src/explore/controlUtils'; import { controlPanelSectionsChartOptions, controlPanelSectionsChartOptionsOnlyColorScheme, controlPanelSectionsChartOptionsTable, } from 'src/explore/fixtures'; const getKnownControlConfig = (controlKey: string, vizType: string) => getControlConfig(controlKey, vizType) as ControlConfig; const getKnownControlState = (...args: Parameters<typeof getControlState>) => getControlState(...args) as Exclude<ReturnType<typeof getControlState>, null>; describe('controlUtils', () => { const state: ControlPanelState = { datasource: { id: 1, type: DatasourceType.Table, columns: [{ column_name: 'a' }], metrics: [{ metric_name: 'first' }, { metric_name: 'second' }], column_format: {}, verbose_map: {}, main_dttm_col: '', datasource_name: '1__table', description: null, }, controls: {}, form_data: { datasource: '1__table', viz_type: 'table' }, common: {}, }; beforeAll(() => { getChartControlPanelRegistry() .registerValue('test-chart', { controlPanelSections: controlPanelSectionsChartOptions, }) .registerValue('test-chart-override', { controlPanelSections: controlPanelSectionsChartOptionsOnlyColorScheme, controlOverrides: { color_scheme: { label: t('My beautiful colors'), }, }, }) .registerValue('table', { controlPanelSections: controlPanelSectionsChartOptionsTable, }); }); afterAll(() => { getChartControlPanelRegistry() .remove('test-chart') .remove('test-chart-override'); }); describe('getControlConfig', () => { it('returns a valid spatial controlConfig', () => { const spatialControl = getControlConfig('color_scheme', 'test-chart'); expect(spatialControl?.type).toEqual('ColorSchemeControl'); }); it('overrides according to vizType', () => { let control = getKnownControlConfig('color_scheme', 'test-chart'); expect(control.label).toEqual('Color Scheme'); control = getKnownControlConfig('color_scheme', 'test-chart-override'); expect(control.label).toEqual('My beautiful colors'); }); it( 'returns correct control config when control config is defined ' + 'in the control panel definition', () => { const roseAreaProportionControlConfig = getControlConfig( 'rose_area_proportion', 'test-chart', ); expect(roseAreaProportionControlConfig).toEqual({ type: 'CheckboxControl', label: t('Use Area Proportions'), description: t( 'Check if the Rose Chart should use segment area instead of ' + 'segment radius for proportioning', ), default: false, renderTrigger: true, }); }, ); }); describe('applyMapStateToPropsToControl,', () => { it('applies state to props as expected', () => { let control = getKnownControlConfig('all_columns', 'table'); control = applyMapStateToPropsToControl(control, state); expect(control.options).toEqual([{ column_name: 'a' }]); }); }); describe('getControlState', () => { it('to still have the functions', () => { const control = getKnownControlState('metrics', 'table', state, 'a'); expect(typeof control.mapStateToProps).toBe('function'); expect(typeof control.validators?.[0]).toBe('function'); }); it('to make sure value is array', () => { const control = getKnownControlState('all_columns', 'table', state, 'a'); expect(control.value).toEqual(['a']); }); it('removes missing/invalid choice', () => { let control = getControlState( 'stacked_style', 'test-chart', state, 'stack', ); expect(control?.value).toBe('stack'); control = getControlState('stacked_style', 'test-chart', state, 'FOO'); expect(control?.value).toBeNull(); }); it('returns null for non-existent field', () => { const control = getControlState('NON_EXISTENT', 'table', state); expect(control).toBeNull(); }); it('metrics control should be empty by default', () => { const control = getControlState('metrics', 'table', state); expect(control?.default).toBeUndefined(); }); it('metric control should be empty by default', () => { const control = getControlState('metric', 'table', state); expect(control?.default).toBeUndefined(); }); it('should not apply mapStateToProps when initializing', () => { const control = getControlState('metrics', 'table', { ...state, controls: undefined, }); expect(control?.value).toBe(undefined); }); }); describe('validateControl', () => { it('validates the control, returns an error if empty', () => { const control = getControlState('metric', 'table', state, null); expect(control?.validationErrors).toEqual(['cannot be empty']); }); it('should not validate if control panel is initializing', () => { const control = getControlState( 'metric', 'table', { ...state, controls: undefined }, undefined, ); expect(control?.validationErrors).toBeUndefined(); }); }); describe('findControlItem', () => { it('find control as a string', () => { const controlItem = findControlItem( controlPanelSectionsChartOptions, 'color_scheme', ); expect(controlItem).toEqual('color_scheme'); }); it('find control as a control object', () => { let controlItem = findControlItem( controlPanelSectionsChartOptions, 'rose_area_proportion', ) as CustomControlItem; expect(controlItem.name).toEqual('rose_area_proportion'); expect(controlItem).toHaveProperty('config'); controlItem = findControlItem( controlPanelSectionsChartOptions, 'stacked_style', ) as CustomControlItem; expect(controlItem.name).toEqual('stacked_style'); expect(controlItem).toHaveProperty('config'); }); it('returns null when key is not found', () => { const controlItem = findControlItem( controlPanelSectionsChartOptions, 'non_existing_key', ); expect(controlItem).toBeNull(); }); }); });
superset-frontend/src/explore/controlUtils/controlUtils.test.tsx
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.0017041251994669437, 0.0002549359924159944, 0.00016670807963237166, 0.00017545800074003637, 0.00030399125535041094 ]
{ "id": 14, "code_window": [ ") => {\n", " if (resourceId) {\n", " return state.reports[resourceType]?.[resourceId];\n", " }\n", " return {};\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return null;\n" ], "file_path": "superset-frontend/src/views/CRUD/hooks.ts", "type": "replace", "edit_start_line_idx": 869 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """add key-value store Revision ID: 6766938c6065 Revises: 7293b0ca7944 Create Date: 2022-03-04 09:59:26.922329 """ # revision identifiers, used by Alembic. revision = "6766938c6065" down_revision = "7293b0ca7944" from uuid import uuid4 import sqlalchemy as sa from alembic import op from sqlalchemy_utils import UUIDType def upgrade(): op.create_table( "key_value", sa.Column("id", sa.Integer(), nullable=False), sa.Column("resource", sa.String(32), nullable=False), sa.Column("value", sa.LargeBinary(length=2**31), nullable=False), sa.Column("uuid", UUIDType(binary=True), default=uuid4), sa.Column("created_on", sa.DateTime(), nullable=True), sa.Column("created_by_fk", sa.Integer(), nullable=True), sa.Column("changed_on", sa.DateTime(), nullable=True), sa.Column("changed_by_fk", sa.Integer(), nullable=True), sa.Column("expires_on", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(["created_by_fk"], ["ab_user.id"]), sa.ForeignKeyConstraint(["changed_by_fk"], ["ab_user.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_index(op.f("ix_key_value_uuid"), "key_value", ["uuid"], unique=True) op.create_index( op.f("ix_key_value_expires_on"), "key_value", ["expires_on"], unique=False ) def downgrade(): op.drop_index(op.f("ix_key_value_expires_on"), table_name="key_value") op.drop_index(op.f("ix_key_value_uuid"), table_name="key_value") op.drop_table("key_value")
superset/migrations/versions/2022-03-04_09-59_6766938c6065_add_key_value_store.py
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00017912442854139954, 0.0001744152104947716, 0.00017018464859575033, 0.00017385567480232567, 0.000003143119783999282 ]
{ "id": 14, "code_window": [ ") => {\n", " if (resourceId) {\n", " return state.reports[resourceType]?.[resourceId];\n", " }\n", " return {};\n", "};" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " return null;\n" ], "file_path": "superset-frontend/src/views/CRUD/hooks.ts", "type": "replace", "edit_start_line_idx": 869 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { ComponentType } from 'react'; import { isRequired, Plugin, QueryFormData } from '../..'; import ChartMetadata from './ChartMetadata'; import getChartMetadataRegistry from '../registries/ChartMetadataRegistrySingleton'; import getChartBuildQueryRegistry from '../registries/ChartBuildQueryRegistrySingleton'; import getChartComponentRegistry from '../registries/ChartComponentRegistrySingleton'; import getChartControlPanelRegistry from '../registries/ChartControlPanelRegistrySingleton'; import getChartTransformPropsRegistry from '../registries/ChartTransformPropsRegistrySingleton'; import { BuildQueryFunction, TransformProps } from '../types/TransformFunction'; import { ChartControlPanel } from './ChartControlPanel'; import { ChartProps } from '..'; function IDENTITY<T>(x: T) { return x; } const EMPTY = {}; export type PromiseOrValue<T> = Promise<T> | T; export type PromiseOrValueLoader<T> = () => PromiseOrValue<T>; export type ChartType = ComponentType<any>; type ValueOrModuleWithValue<T> = T | { default: T }; interface ChartPluginConfig< FormData extends QueryFormData = QueryFormData, Props extends ChartProps = ChartProps, > { metadata: ChartMetadata; /** Use buildQuery for immediate value. For lazy-loading, use loadBuildQuery. */ buildQuery?: BuildQueryFunction<FormData>; /** Use loadBuildQuery for dynamic import (lazy-loading) */ loadBuildQuery?: PromiseOrValueLoader< ValueOrModuleWithValue<BuildQueryFunction<FormData>> >; /** Use transformProps for immediate value. For lazy-loading, use loadTransformProps. */ transformProps?: TransformProps<Props>; /** Use loadTransformProps for dynamic import (lazy-loading) */ loadTransformProps?: PromiseOrValueLoader< ValueOrModuleWithValue<TransformProps<Props>> >; /** Use Chart for immediate value. For lazy-loading, use loadChart. */ Chart?: ChartType; /** Use loadChart for dynamic import (lazy-loading) */ loadChart?: PromiseOrValueLoader<ValueOrModuleWithValue<ChartType>>; /** Control panel configuration object */ controlPanel?: ChartControlPanel; } /** * Loaders of the form `() => import('foo')` may return esmodules * which require the value to be extracted as `module.default` * */ function sanitizeLoader<T>( loader: PromiseOrValueLoader<ValueOrModuleWithValue<T>>, ): PromiseOrValueLoader<T> { return () => { const loaded = loader(); return loaded instanceof Promise ? (loaded.then( module => ('default' in module && module.default) || module, ) as Promise<T>) : (loaded as T); }; } export default class ChartPlugin< FormData extends QueryFormData = QueryFormData, Props extends ChartProps = ChartProps, > extends Plugin { controlPanel: ChartControlPanel; metadata: ChartMetadata; loadBuildQuery?: PromiseOrValueLoader<BuildQueryFunction<FormData>>; loadTransformProps: PromiseOrValueLoader<TransformProps<Props>>; loadChart: PromiseOrValueLoader<ChartType>; constructor(config: ChartPluginConfig<FormData, Props>) { super(); const { metadata, buildQuery, loadBuildQuery, transformProps = IDENTITY, loadTransformProps, Chart, loadChart, controlPanel = EMPTY, } = config; this.controlPanel = controlPanel; this.metadata = metadata; this.loadBuildQuery = (loadBuildQuery && sanitizeLoader(loadBuildQuery)) || (buildQuery && sanitizeLoader(() => buildQuery)) || undefined; this.loadTransformProps = sanitizeLoader( loadTransformProps ?? (() => transformProps), ); if (loadChart) { this.loadChart = sanitizeLoader<ChartType>(loadChart); } else if (Chart) { this.loadChart = () => Chart; } else { throw new Error('Chart or loadChart is required'); } } register() { const key: string = this.config.key || isRequired('config.key'); getChartMetadataRegistry().registerValue(key, this.metadata); getChartComponentRegistry().registerLoader(key, this.loadChart); getChartControlPanelRegistry().registerValue(key, this.controlPanel); getChartTransformPropsRegistry().registerLoader( key, this.loadTransformProps, ); if (this.loadBuildQuery) { getChartBuildQueryRegistry().registerLoader(key, this.loadBuildQuery); } return this; } unregister() { const key: string = this.config.key || isRequired('config.key'); getChartMetadataRegistry().remove(key); getChartComponentRegistry().remove(key); getChartControlPanelRegistry().remove(key); getChartTransformPropsRegistry().remove(key); getChartBuildQueryRegistry().remove(key); return this; } configure(config: { [key: string]: unknown }, replace?: boolean) { super.configure(config, replace); return this; } }
superset-frontend/packages/superset-ui-core/src/chart/models/ChartPlugin.ts
0
https://github.com/apache/superset/commit/290920c4fb1fec85bf6f95e23f3c91b2681cfcbe
[ 0.00018002319848164916, 0.0001721551816444844, 0.00016654777573421597, 0.00017144675075542182, 0.0000037162633361731423 ]
{ "id": 0, "code_window": [ "import { resolve } from 'pathe'\n", "import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit'\n", "import defu from 'defu'\n", "import { distDir } from '../dirs'\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 2 }
import { resolve, join } from 'pathe' import { existsSync, readdirSync } from 'node:fs' import defu from 'defu' export default { /** * Vue.js config * @version 2 * @version 3 */ vue: { /** * Properties that will be set directly on `Vue.config` for vue@2. * * @see [vue@2 Documentation](https://v2.vuejs.org/v2/api/#Global-Config) * @type {typeof import('vue/types/vue').VueConfiguration} * @version 2 */ config: { silent: { $resolve: (val, get) => val ?? !get('dev') }, performance: { $resolve: (val, get) => val ?? get('dev') }, }, /** * Options for the Vue compiler that will be passed at build time * @see [documentation](https://vuejs.org/api/application.html#app-config-compileroptions) * @type {typeof import('@vue/compiler-core').CompilerOptions} * @version 3 */ compilerOptions: {} }, /** * Nuxt App configuration. * @version 2 * @version 3 */ app: { /** * The base path of your Nuxt application. * * This can be set at runtime by setting the NUXT_APP_BASE_URL environment variable. * @example * ```bash * NUXT_APP_BASE_URL=/prefix/ node .output/server/index.mjs * ``` */ baseURL: process.env.NUXT_APP_BASE_URL || '/', /** The folder name for the built site assets, relative to `baseURL` (or `cdnURL` if set). This is set at build time and should not be customized at runtime. */ buildAssetsDir: process.env.NUXT_APP_BUILD_ASSETS_DIR || '/_nuxt/', /** * The folder name for the built site assets, relative to `baseURL` (or `cdnURL` if set). * @deprecated - use `buildAssetsDir` instead * @version 2 */ assetsPath: { $resolve: (val, get) => val ?? get('buildAssetsDir') }, /** * An absolute URL to serve the public folder from (production-only). * * This can be set to a different value at runtime by setting the NUXT_APP_CDN_URL environment variable. * @example * ```bash * NUXT_APP_CDN_URL=https://mycdn.org/ node .output/server/index.mjs * ``` */ cdnURL: { $resolve: (val, get) => get('dev') ? '' : (process.env.NUXT_APP_CDN_URL ?? val) || '' }, /** * Set default configuration for `<head>` on every page. * * @example * ```js * app: { * head: { * meta: [ * // <meta name="viewport" content="width=device-width, initial-scale=1"> * { name: 'viewport', content: 'width=device-width, initial-scale=1' } * ], * script: [ * // <script src="https://myawesome-lib.js"></script> * { src: 'https://awesome-lib.js' } * ], * link: [ * // <link rel="stylesheet" href="https://myawesome-lib.css"> * { rel: 'stylesheet', href: 'https://awesome-lib.css' } * ], * // please note that this is an area that is likely to change * style: [ * // <style type="text/css">:root { color: red }</style> * { children: ':root { color: red }', type: 'text/css' } * ], * noscript: [ * // <noscript>Javascript is required</noscript> * { children: 'Javascript is required' } * ] * } * } * ``` * @type {typeof import('../src/types/meta').MetaObject} * @version 3 */ head: { $resolve: (val, get) => { return defu(val, get('meta'), { charset: 'utf-8', viewport: 'width=device-width, initial-scale=1', meta: [], link: [], style: [], script: [], noscript: [] }) } }, }, /** * The path to a templated HTML file for rendering Nuxt responses. * Uses `<srcDir>/app.html` if it exists or the Nuxt default template if not. * * @example * ```html * <!DOCTYPE html> * <html {{ HTML_ATTRS }}> * <head {{ HEAD_ATTRS }}> * {{ HEAD }} * </head> * <body {{ BODY_ATTRS }}> * {{ APP }} * </body> * </html> * ``` * @version 2 */ appTemplatePath: { $resolve: (val, get) => { if (val) { return resolve(get('srcDir'), val) } if (existsSync(join(get('srcDir'), 'app.html'))) { return join(get('srcDir'), 'app.html') } return resolve(get('buildDir'), 'views/app.template.html') } }, /** * Enable or disable vuex store. * * By default it is enabled if there is a `store/` directory * @version 2 */ store: { $resolve: (val, get) => val !== false && existsSync(join(get('srcDir'), get('dir.store'))) && readdirSync(join(get('srcDir'), get('dir.store'))) .find(filename => filename !== 'README.md' && filename[0] !== '.') }, /** * Options to pass directly to `vue-meta`. * * @see [documentation](https://vue-meta.nuxtjs.org/api/#plugin-options). * @type {typeof import('vue-meta').VueMetaOptions} * @version 2 */ vueMeta: null, /** * Set default configuration for `<head>` on every page. * * @see [documentation](https://vue-meta.nuxtjs.org/api/#metainfo-properties) for specifics. * @type {typeof import('vue-meta').MetaInfo} * @version 2 */ head: { /** Each item in the array maps to a newly-created `<meta>` element, where object properties map to attributes. */ meta: [], /** Each item in the array maps to a newly-created `<link>` element, where object properties map to attributes. */ link: [], /** Each item in the array maps to a newly-created `<style>` element, where object properties map to attributes. */ style: [], /** Each item in the array maps to a newly-created `<script>` element, where object properties map to attributes. */ script: [] }, /** * @type {typeof import('../src/types/meta').MetaObject} * @version 3 * @deprecated - use `head` instead */ meta: { meta: [], link: [], style: [], script: [] }, /** * Configuration for the Nuxt `fetch()` hook. * @version 2 */ fetch: { /** Whether to enable `fetch()` on the server. */ server: true, /** Whether to enable `fetch()` on the client. */ client: true }, /** * An array of nuxt app plugins. * * Each plugin can be a string (which can be an absolute or relative path to a file). * If it ends with `.client` or `.server` then it will be automatically loaded only * in the appropriate context. * * It can also be an object with `src` and `mode` keys. * * @example * ```js * plugins: [ * '~/plugins/foo.client.js', // only in client side * '~/plugins/bar.server.js', // only in server side * '~/plugins/baz.js', // both client & server * { src: '~/plugins/both-sides.js' }, * { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side * { src: '~/plugins/server-only.js', mode: 'server' } // only on server side * ] * ``` * @type {(typeof import('../src/types/nuxt').NuxtPlugin | string)[]} * @version 2 */ plugins: [], /** * You may want to extend plugins or change their order. For this, you can pass * a function using `extendPlugins`. It accepts an array of plugin objects and * should return an array of plugin objects. * @type {(plugins: Array<{ src: string, mode?: 'client' | 'server' }>) => Array<{ src: string, mode?: 'client' | 'server' }>} * @version 2 */ extendPlugins: null, /** * You can define the CSS files/modules/libraries you want to set globally * (included in every page). * * Nuxt will automatically guess the file type by its extension and use the * appropriate pre-processor. You will still need to install the required * loader if you need to use them. * * @example * ```js * css: [ * // Load a Node.js module directly (here it's a Sass file) * 'bulma', * // CSS file in the project * '@/assets/css/main.css', * // SCSS file in the project * '@/assets/css/main.scss' * ] * ``` * @type {string[]} * @version 2 * @version 3 */ css: { $resolve: val => (val ?? []).map(c => c.src || c) }, /** * An object where each key name maps to a path to a layout .vue file. * * Normally there is no need to configure this directly. * @type {Record<string, string>} * @version 2 */ layouts: {}, /** * Set a custom error page layout. * * Normally there is no need to configure this directly. * @type {string} * @version 2 */ ErrorPage: null, /** * Configure the Nuxt loading progress bar component that's shown between * routes. Set to `false` to disable. You can also customize it or create * your own component. * @version 2 */ loading: { /** CSS color of the progress bar */ color: 'black', /** * CSS color of the progress bar when an error appended while rendering * the route (if data or fetch sent back an error for example). */ failedColor: 'red', /** Height of the progress bar (used in the style property of the progress bar). */ height: '2px', /** * In ms, wait for the specified time before displaying the progress bar. * Useful for preventing the bar from flashing. */ throttle: 200, /** * In ms, the maximum duration of the progress bar, Nuxt assumes that the * route will be rendered before 5 seconds. */ duration: 5000, /** Keep animating progress bar when loading takes longer than duration. */ continuous: false, /** Set the direction of the progress bar from right to left. */ rtl: false, /** Set to false to remove default progress bar styles (and add your own). */ css: true }, /** * Show a loading spinner while the page is loading (only when `ssr: false`). * * Set to `false` to disable. Alternatively, you can pass a string name or an object for more * configuration. The name can refer to an indicator from [SpinKit](https://tobiasahlin.com/spinkit/) * or a path to an HTML template of the indicator source code (in this case, all the * other options will be passed to the template.) * @version 2 */ loadingIndicator: { $resolve: (val, get) => { val = typeof val === 'string' ? { name: val } : val return defu(val, { name: 'default', color: get('loading.color') || '#D3D3D3', color2: '#F5F5F5', background: (get('manifest') && get('manifest.theme_color')) || 'white', dev: get('dev'), loading: get('messages.loading') }) } }, /** * Used to set the default properties of the page transitions. * * You can either pass a string (the transition name) or an object with properties to bind * to the `<Transition>` component that will wrap your pages. * * @see [vue@2 documentation](https://v2.vuejs.org/v2/guide/transitions.html) * @see [vue@3 documentation](https://vuejs.org/guide/built-ins/transition-group.html#enter-leave-transitions) * @version 2 */ pageTransition: { $resolve: (val, get) => { val = typeof val === 'string' ? { name: val } : val return defu(val, { name: 'page', mode: 'out-in', appear: get('render.ssr') === false || Boolean(val), appearClass: 'appear', appearActiveClass: 'appear-active', appearToClass: 'appear-to' }) } }, /** * Used to set the default properties of the layout transitions. * * You can either pass a string (the transition name) or an object with properties to bind * to the `<Transition>` component that will wrap your layouts. * * @see [vue@2 documentation](https://v2.vuejs.org/v2/guide/transitions.html) * @see [vue@3 documentation](https://vuejs.org/guide/built-ins/transition-group.html#enter-leave-transitions) * @version 2 */ layoutTransition: { $resolve: val => { val = typeof val === 'string' ? { name: val } : val return defu(val, { name: 'layout', mode: 'out-in' }) } }, /** * You can disable specific Nuxt features that you do not want. * @version 2 */ features: { /** Set to false to disable Nuxt vuex integration */ store: true, /** Set to false to disable layouts */ layouts: true, /** Set to false to disable Nuxt integration with `vue-meta` and the `head` property */ meta: true, /** Set to false to disable middleware */ middleware: true, /** Set to false to disable transitions */ transitions: true, /** Set to false to disable support for deprecated features and aliases */ deprecations: true, /** Set to false to disable the Nuxt `validate()` hook */ validate: true, /** Set to false to disable the Nuxt `asyncData()` hook */ useAsyncData: true, /** Set to false to disable the Nuxt `fetch()` hook */ fetch: true, /** Set to false to disable `$nuxt.isOnline` */ clientOnline: true, /** Set to false to disable prefetching behavior in `<NuxtLink>` */ clientPrefetch: true, /** Set to false to disable extra component aliases like `<NLink>` and `<NChild>` */ componentAliases: true, /** Set to false to disable the `<ClientOnly>` component (see [docs](https://github.com/egoist/vue-client-only)) */ componentClientOnly: true } }
packages/schema/src/config/_app.ts
1
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.0012237232876941562, 0.00020840263459831476, 0.0001636108208913356, 0.00016805976338218898, 0.0001643072464503348 ]
{ "id": 0, "code_window": [ "import { resolve } from 'pathe'\n", "import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit'\n", "import defu from 'defu'\n", "import { distDir } from '../dirs'\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 2 }
{ "name": "@nuxt/kit", "version": "3.0.0-rc.6", "repository": "nuxt/framework", "license": "MIT", "type": "module", "main": "./dist/index.mjs", "types": "./dist/index.d.ts", "files": [ "dist" ], "scripts": { "prepack": "unbuild" }, "dependencies": { "@nuxt/schema": "^3.0.0-rc.6", "c12": "^0.2.9", "consola": "^2.15.3", "defu": "^6.0.0", "globby": "^13.1.2", "hash-sum": "^2.0.0", "ignore": "^5.2.0", "jiti": "^1.14.0", "knitwork": "^0.1.2", "lodash.template": "^4.5.0", "mlly": "^0.5.7", "ohash": "^0.1.5", "pathe": "^0.3.3", "pkg-types": "^0.3.3", "scule": "^0.3.2", "semver": "^7.3.7", "unctx": "^2.0.1", "unimport": "^0.6.5", "untyped": "^0.4.5" }, "devDependencies": { "@types/lodash.template": "^4", "@types/semver": "^7", "unbuild": "latest" }, "engines": { "node": "^14.16.0 || ^16.11.0 || ^17.0.0 || ^18.0.0" } }
packages/kit/package.json
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.0001737242710078135, 0.00016686029266566038, 0.00016303615120705217, 0.00016529807180631906, 0.000003828764874924673 ]
{ "id": 0, "code_window": [ "import { resolve } from 'pathe'\n", "import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit'\n", "import defu from 'defu'\n", "import { distDir } from '../dirs'\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 2 }
import { fileURLToPath } from 'node:url' import { dirname, resolve } from 'pathe' let _distDir = dirname(fileURLToPath(import.meta.url)) if (_distDir.endsWith('chunks')) { _distDir = dirname(_distDir) } export const distDir = _distDir export const pkgDir = resolve(distDir, '..') export const runtimeDir = resolve(distDir, 'runtime')
packages/nuxt/src/dirs.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.008391294628381729, 0.008391294628381729, 0.008391294628381729, 0.008391294628381729, 0 ]
{ "id": 0, "code_window": [ "import { resolve } from 'pathe'\n", "import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit'\n", "import defu from 'defu'\n", "import { distDir } from '../dirs'\n" ], "labels": [ "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 2 }
import type { Argv } from 'mri' const _rDefault = r => r.default || r export const commands = { dev: () => import('./dev').then(_rDefault), build: () => import('./build').then(_rDefault), cleanup: () => import('./cleanup').then(_rDefault), clean: () => import('./cleanup').then(_rDefault), preview: () => import('./preview').then(_rDefault), start: () => import('./preview').then(_rDefault), analyze: () => import('./analyze').then(_rDefault), generate: () => import('./generate').then(_rDefault), prepare: () => import('./prepare').then(_rDefault), typecheck: () => import('./typecheck').then(_rDefault), usage: () => import('./usage').then(_rDefault), info: () => import('./info').then(_rDefault), init: () => import('./init').then(_rDefault), create: () => import('./init').then(_rDefault), upgrade: () => import('./upgrade').then(_rDefault), test: () => import('./test').then(_rDefault), add: () => import('./add').then(_rDefault), new: () => import('./add').then(_rDefault) } export type Command = keyof typeof commands export interface NuxtCommandMeta { name: string; usage: string; description: string; [key: string]: any; } export type CLIInvokeResult = void | 'error' | 'wait' export interface NuxtCommand { invoke(args: Argv): Promise<CLIInvokeResult> | CLIInvokeResult meta: NuxtCommandMeta } export function defineNuxtCommand (command: NuxtCommand): NuxtCommand { return command }
packages/nuxi/src/commands/index.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.0032080395612865686, 0.0008056055521592498, 0.0001709920761641115, 0.00018332093895878643, 0.0012021036818623543 ]
{ "id": 1, "code_window": [ "import { distDir } from '../dirs'\n", "import type { MetaObject } from './runtime'\n", "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'meta'\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 4 }
import { resolve } from 'pathe' import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit' import defu from 'defu' import { distDir } from '../dirs' import type { MetaObject } from './runtime' export default defineNuxtModule({ meta: { name: 'meta' }, defaults: { charset: 'utf-8', viewport: 'width=device-width, initial-scale=1' }, setup (options, nuxt) { const runtimeDir = nuxt.options.alias['#head'] || resolve(distDir, 'head/runtime') // Transpile @nuxt/meta and @vueuse/head nuxt.options.build.transpile.push('@vueuse/head') // Add #head alias nuxt.options.alias['#head'] = runtimeDir // Global meta -for Bridge, this is necessary to repeat here // and in packages/schema/src/config/_app.ts const globalMeta: MetaObject = defu(nuxt.options.app.head, { charset: options.charset, viewport: options.viewport }) // Add global meta configuration addTemplate({ filename: 'meta.config.mjs', getContents: () => 'export default ' + JSON.stringify({ globalMeta }) }) // Add generic plugin addPlugin({ src: resolve(runtimeDir, 'plugin') }) // Add library specific plugin addPlugin({ src: resolve(runtimeDir, 'lib/vueuse-head.plugin') }) } })
packages/nuxt/src/head/module.ts
1
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.9780281186103821, 0.19849324226379395, 0.00027452089125290513, 0.004036577884107828, 0.3897811472415924 ]
{ "id": 1, "code_window": [ "import { distDir } from '../dirs'\n", "import type { MetaObject } from './runtime'\n", "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'meta'\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 4 }
{ "extends": "./.nuxt/tsconfig.json" }
examples/routing/nuxt-link/tsconfig.json
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017002325330395252, 0.00017002325330395252, 0.00017002325330395252, 0.00017002325330395252, 0 ]
{ "id": 1, "code_window": [ "import { distDir } from '../dirs'\n", "import type { MetaObject } from './runtime'\n", "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'meta'\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 4 }
<template> <div class="p-4"> Custom layout defined dynamically with the <code>NuxtLayout</code> component <br> <NuxtLayout :name="layout"> Default slot <br> <button class="border p-1 rounded" @click="layout ? layout = null : layout = 'custom'"> Switch layout </button> <template #header> Header slot </template> </NuxtLayout> <br> <NuxtLink to="/"> Back to home </NuxtLink> </div> </template> <script> definePageMeta({ layout: false }) export default { data: () => ({ layout: 'custom' }) } </script>
examples/routing/layouts/pages/dynamic.vue
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.0002182799216825515, 0.00019486542441882193, 0.00016774899268057197, 0.0001967163843801245, 0.000021988473235978745 ]
{ "id": 1, "code_window": [ "import { distDir } from '../dirs'\n", "import type { MetaObject } from './runtime'\n", "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'meta'\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 4 }
{ "private": true, "name": "fixture-bridge", "scripts": { "build": "nuxi build" } }
test/fixtures/basic/package.json
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017326189845334738, 0.00017326189845334738, 0.00017326189845334738, 0.00017326189845334738, 0 ]
{ "id": 2, "code_window": [ "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'meta'\n", " },\n", " defaults: {\n", " charset: 'utf-8',\n", " viewport: 'width=device-width, initial-scale=1'\n", " },\n", " setup (options, nuxt) {\n", " const runtimeDir = nuxt.options.alias['#head'] || resolve(distDir, 'head/runtime')\n", "\n", " // Transpile @nuxt/meta and @vueuse/head\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 10 }
import { resolve } from 'pathe' import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit' import defu from 'defu' import { distDir } from '../dirs' import type { MetaObject } from './runtime' export default defineNuxtModule({ meta: { name: 'meta' }, defaults: { charset: 'utf-8', viewport: 'width=device-width, initial-scale=1' }, setup (options, nuxt) { const runtimeDir = nuxt.options.alias['#head'] || resolve(distDir, 'head/runtime') // Transpile @nuxt/meta and @vueuse/head nuxt.options.build.transpile.push('@vueuse/head') // Add #head alias nuxt.options.alias['#head'] = runtimeDir // Global meta -for Bridge, this is necessary to repeat here // and in packages/schema/src/config/_app.ts const globalMeta: MetaObject = defu(nuxt.options.app.head, { charset: options.charset, viewport: options.viewport }) // Add global meta configuration addTemplate({ filename: 'meta.config.mjs', getContents: () => 'export default ' + JSON.stringify({ globalMeta }) }) // Add generic plugin addPlugin({ src: resolve(runtimeDir, 'plugin') }) // Add library specific plugin addPlugin({ src: resolve(runtimeDir, 'lib/vueuse-head.plugin') }) } })
packages/nuxt/src/head/module.ts
1
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.9992151260375977, 0.8649511337280273, 0.331316739320755, 0.998105525970459, 0.2668176591396332 ]
{ "id": 2, "code_window": [ "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'meta'\n", " },\n", " defaults: {\n", " charset: 'utf-8',\n", " viewport: 'width=device-width, initial-scale=1'\n", " },\n", " setup (options, nuxt) {\n", " const runtimeDir = nuxt.options.alias['#head'] || resolve(distDir, 'head/runtime')\n", "\n", " // Transpile @nuxt/meta and @vueuse/head\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 10 }
export default req => `Hello world (${req.url.substr(1)}) (Generated at ${new Date().toUTCString()})`
examples/composables/use-async-data/server/api/hello.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00016517832409590483, 0.00016517832409590483, 0.00016517832409590483, 0.00016517832409590483, 0 ]
{ "id": 2, "code_window": [ "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'meta'\n", " },\n", " defaults: {\n", " charset: 'utf-8',\n", " viewport: 'width=device-width, initial-scale=1'\n", " },\n", " setup (options, nuxt) {\n", " const runtimeDir = nuxt.options.alias['#head'] || resolve(distDir, 'head/runtime')\n", "\n", " // Transpile @nuxt/meta and @vueuse/head\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 10 }
<template> <NCard class="flex flex-col gap-1 p-4"> <code>nuxt.config.ts</code> can specify other directories like <code class="op50">`other-components-folder/`</code> to import components from and specify prefixes. </NCard> </template>
examples/auto-imports/components/other-components-folder/with-prefix.vue
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00016727237380109727, 0.00016727237380109727, 0.00016727237380109727, 0.00016727237380109727, 0 ]
{ "id": 2, "code_window": [ "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'meta'\n", " },\n", " defaults: {\n", " charset: 'utf-8',\n", " viewport: 'width=device-width, initial-scale=1'\n", " },\n", " setup (options, nuxt) {\n", " const runtimeDir = nuxt.options.alias['#head'] || resolve(distDir, 'head/runtime')\n", "\n", " // Transpile @nuxt/meta and @vueuse/head\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 10 }
export * from './browser' export * from './context' export * from './nuxt' export * from './server' export * from './setup' export * from './run'
packages/test-utils/src/index.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00016631274775136262, 0.00016631274775136262, 0.00016631274775136262, 0.00016631274775136262, 0 ]
{ "id": 3, "code_window": [ " nuxt.options.build.transpile.push('@vueuse/head')\n", "\n", " // Add #head alias\n", " nuxt.options.alias['#head'] = runtimeDir\n", "\n", " // Global meta -for Bridge, this is necessary to repeat here\n", " // and in packages/schema/src/config/_app.ts\n", " const globalMeta: MetaObject = defu(nuxt.options.app.head, {\n", " charset: options.charset,\n", " viewport: options.viewport\n", " })\n", "\n", " // Add global meta configuration\n", " addTemplate({\n", " filename: 'meta.config.mjs',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 23 }
import { resolve } from 'pathe' import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit' import defu from 'defu' import { distDir } from '../dirs' import type { MetaObject } from './runtime' export default defineNuxtModule({ meta: { name: 'meta' }, defaults: { charset: 'utf-8', viewport: 'width=device-width, initial-scale=1' }, setup (options, nuxt) { const runtimeDir = nuxt.options.alias['#head'] || resolve(distDir, 'head/runtime') // Transpile @nuxt/meta and @vueuse/head nuxt.options.build.transpile.push('@vueuse/head') // Add #head alias nuxt.options.alias['#head'] = runtimeDir // Global meta -for Bridge, this is necessary to repeat here // and in packages/schema/src/config/_app.ts const globalMeta: MetaObject = defu(nuxt.options.app.head, { charset: options.charset, viewport: options.viewport }) // Add global meta configuration addTemplate({ filename: 'meta.config.mjs', getContents: () => 'export default ' + JSON.stringify({ globalMeta }) }) // Add generic plugin addPlugin({ src: resolve(runtimeDir, 'plugin') }) // Add library specific plugin addPlugin({ src: resolve(runtimeDir, 'lib/vueuse-head.plugin') }) } })
packages/nuxt/src/head/module.ts
1
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.9990606904029846, 0.4004185199737549, 0.00031438132282346487, 0.0024318844079971313, 0.48851150274276733 ]
{ "id": 3, "code_window": [ " nuxt.options.build.transpile.push('@vueuse/head')\n", "\n", " // Add #head alias\n", " nuxt.options.alias['#head'] = runtimeDir\n", "\n", " // Global meta -for Bridge, this is necessary to repeat here\n", " // and in packages/schema/src/config/_app.ts\n", " const globalMeta: MetaObject = defu(nuxt.options.app.head, {\n", " charset: options.charset,\n", " viewport: options.viewport\n", " })\n", "\n", " // Add global meta configuration\n", " addTemplate({\n", " filename: 'meta.config.mjs',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 23 }
# Dependencies node_modules jspm_packages package-lock.json # */**/yarn.lock # Logs *.log # Temp directories .temp .tmp .cache # Yarn **/.yarn/cache **/.yarn/*state* # Generated dirs dist .nuxt .nuxt-* .output .gen nuxt.d.ts # Junit reports reports # Coverage reports coverage *.lcov .nyc_output # VSCode .vscode # Intellij idea *.iml .idea # OSX .DS_Store .AppleDouble .LSOverride # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk .vercel_build_output .build-* .env .netlify
.gitignore
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.0001749068615026772, 0.00016878126189112663, 0.00016579577641095966, 0.00016751133080106229, 0.0000029212333174655214 ]
{ "id": 3, "code_window": [ " nuxt.options.build.transpile.push('@vueuse/head')\n", "\n", " // Add #head alias\n", " nuxt.options.alias['#head'] = runtimeDir\n", "\n", " // Global meta -for Bridge, this is necessary to repeat here\n", " // and in packages/schema/src/config/_app.ts\n", " const globalMeta: MetaObject = defu(nuxt.options.app.head, {\n", " charset: options.charset,\n", " viewport: options.viewport\n", " })\n", "\n", " // Add global meta configuration\n", " addTemplate({\n", " filename: 'meta.config.mjs',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 23 }
# `useRequestEvent` Nuxt provides composables and utilities for first-class server-side-rendering support. Within your pages, components, and plugins you can use `useRequestEvent` to access the incoming request. ```js // Get underlying request event const event = useRequestEvent() // Get the URL const url = event.req.url ``` ::alert{icon=πŸ‘‰} In the browser, `useRequestEvent` will return `undefined`. ::
docs/content/3.api/1.composables/use-request-event.md
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.0001695364626357332, 0.0001694866077741608, 0.00016943675291258842, 0.0001694866077741608, 4.9854861572384834e-8 ]
{ "id": 3, "code_window": [ " nuxt.options.build.transpile.push('@vueuse/head')\n", "\n", " // Add #head alias\n", " nuxt.options.alias['#head'] = runtimeDir\n", "\n", " // Global meta -for Bridge, this is necessary to repeat here\n", " // and in packages/schema/src/config/_app.ts\n", " const globalMeta: MetaObject = defu(nuxt.options.app.head, {\n", " charset: options.charset,\n", " viewport: options.viewport\n", " })\n", "\n", " // Add global meta configuration\n", " addTemplate({\n", " filename: 'meta.config.mjs',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 23 }
import { defineBuildConfig } from 'unbuild' export default defineBuildConfig({ declaration: true, entries: [ 'src/index', { input: 'src/runtime/', outDir: 'dist/runtime', format: 'esm' } ], dependencies: [ 'vue' ], externals: [ '@nuxt/schema' ] })
packages/vite/build.config.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00020309924730099738, 0.00018441439897287637, 0.00016572955064475536, 0.00018441439897287637, 0.000018684848328121006 ]
{ "id": 4, "code_window": [ " // Add global meta configuration\n", " addTemplate({\n", " filename: 'meta.config.mjs',\n", " getContents: () => 'export default ' + JSON.stringify({ globalMeta })\n", " })\n", "\n", " // Add generic plugin\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " getContents: () => 'export default ' + JSON.stringify({ globalMeta: nuxt.options.app.head })\n" ], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 33 }
import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' // import { isWindows } from 'std-env' import { setup, fetch, $fetch, startServer } from '@nuxt/test-utils' import { expectNoClientErrors } from './utils' await setup({ rootDir: fileURLToPath(new URL('./fixtures/basic', import.meta.url)), server: true, browser: true }) describe('server api', () => { it('should serialize', async () => { expect(await $fetch('/api/hello')).toBe('Hello API') expect(await $fetch('/api/hey')).toEqual({ foo: 'bar', baz: 'qux' }) }) it('should preserve states', async () => { expect(await $fetch('/api/counter')).toEqual({ count: 0 }) expect(await $fetch('/api/counter')).toEqual({ count: 1 }) expect(await $fetch('/api/counter')).toEqual({ count: 2 }) expect(await $fetch('/api/counter')).toEqual({ count: 3 }) }) }) describe('pages', () => { it('render index', async () => { const html = await $fetch('/') // Snapshot // expect(html).toMatchInlineSnapshot() // should render text expect(html).toContain('Hello Nuxt 3!') // should inject runtime config expect(html).toContain('RuntimeConfig | testConfig: 123') // composables auto import expect(html).toContain('Composable | foo: auto imported from ~/components/foo.ts') expect(html).toContain('Composable | bar: auto imported from ~/components/useBar.ts') expect(html).toContain('Composable | template: auto imported from ~/components/template.ts') // should import components expect(html).toContain('This is a custom component with a named export.') // should apply attributes to client-only components expect(html).toContain('<div style="color:red;" class="client-only"></div>') // should register global components automatically expect(html).toContain('global component registered automatically') expect(html).toContain('global component via suffix') await expectNoClientErrors('/') }) it('render 404', async () => { const html = await $fetch('/not-found') // Snapshot // expect(html).toMatchInlineSnapshot() expect(html).toContain('[...slug].vue') expect(html).toContain('404 at not-found') await expectNoClientErrors('/not-found') }) it('preserves query', async () => { const html = await $fetch('/?test=true') // Snapshot // expect(html).toMatchInlineSnapshot() // should render text expect(html).toContain('Path: /?test=true') await expectNoClientErrors('/?test=true') }) it('/nested/[foo]/[bar].vue', async () => { const html = await $fetch('/nested/one/two') // Snapshot // expect(html).toMatchInlineSnapshot() expect(html).toContain('nested/[foo]/[bar].vue') expect(html).toContain('foo: one') expect(html).toContain('bar: two') }) it('/nested/[foo]/index.vue', async () => { const html = await $fetch('/nested/foobar') // TODO: should resolved to same entry // const html2 = await $fetch('/nested/foobar/index') // expect(html).toEqual(html2) // Snapshot // expect(html).toMatchInlineSnapshot() expect(html).toContain('nested/[foo]/index.vue') expect(html).toContain('foo: foobar') await expectNoClientErrors('/nested/foobar') }) it('/nested/[foo]/user-[group].vue', async () => { const html = await $fetch('/nested/foobar/user-admin') // Snapshot // expect(html).toMatchInlineSnapshot() expect(html).toContain('nested/[foo]/user-[group].vue') expect(html).toContain('foo: foobar') expect(html).toContain('group: admin') await expectNoClientErrors('/nested/foobar/user-admin') }) it('/parent', async () => { const html = await $fetch('/parent') expect(html).toContain('parent/index') await expectNoClientErrors('/parent') }) it('/another-parent', async () => { const html = await $fetch('/another-parent') expect(html).toContain('another-parent/index') await expectNoClientErrors('/another-parent') }) }) describe('head tags', () => { it('should render tags', async () => { const headHtml = await $fetch('/head') expect(headHtml).toContain('<title>Using a dynamic component - Title Template Fn Change</title>') expect(headHtml).not.toContain('<meta name="description" content="first">') expect(headHtml).toContain('<meta charset="utf-16">') expect(headHtml).not.toContain('<meta charset="utf-8">') expect(headHtml).toContain('<meta name="description" content="overriding with an inline useHead call">') expect(headHtml).toMatch(/<html[^>]*class="html-attrs-test"/) expect(headHtml).toMatch(/<body[^>]*class="body-attrs-test"/) expect(headHtml).toContain('script>console.log("works with useMeta too")</script>') expect(headHtml).toContain('<script src="https://a-body-appended-script.com" data-meta-body="true"></script></body>') const indexHtml = await $fetch('/') // should render charset by default expect(indexHtml).toContain('<meta charset="utf-8">') // should render <Head> components expect(indexHtml).toContain('<title>Basic fixture</title>') }) // TODO: Doesn't adds header in test environment // it.todo('should render stylesheet link tag (SPA mode)', async () => { // const html = await $fetch('/head', { headers: { 'x-nuxt-no-ssr': '1' } }) // expect(html).toMatch(/<link rel="stylesheet" href="\/_nuxt\/[^>]*.css"/) // }) }) describe('navigate', () => { it('should redirect to index with navigateTo', async () => { const { headers } = await fetch('/navigate-to/', { redirect: 'manual' }) expect(headers.get('location')).toEqual('/') }) }) describe('errors', () => { it('should render a JSON error page', async () => { const res = await fetch('/error', { headers: { accept: 'application/json' } }) expect(res.status).toBe(500) const error = await res.json() delete error.stack expect(error).toMatchObject({ description: process.env.NUXT_TEST_DEV ? expect.stringContaining('<pre>') : '', message: 'This is a custom error', statusCode: 500, statusMessage: 'Internal Server Error', url: '/error' }) }) it('should render a HTML error page', async () => { const res = await fetch('/error') expect(await res.text()).toContain('This is a custom error') }) }) describe('middlewares', () => { it('should redirect to index with global middleware', async () => { const html = await $fetch('/redirect/') // Snapshot // expect(html).toMatchInlineSnapshot() expect(html).toContain('Hello Nuxt 3!') }) it('should inject auth', async () => { const html = await $fetch('/auth') // Snapshot // expect(html).toMatchInlineSnapshot() expect(html).toContain('auth.vue') expect(html).toContain('auth: Injected by injectAuth middleware') }) it('should not inject auth', async () => { const html = await $fetch('/no-auth') // Snapshot // expect(html).toMatchInlineSnapshot() expect(html).toContain('no-auth.vue') expect(html).toContain('auth: ') expect(html).not.toContain('Injected by injectAuth middleware') }) }) describe('plugins', () => { it('basic plugin', async () => { const html = await $fetch('/plugins') expect(html).toContain('myPlugin: Injected by my-plugin') }) it('async plugin', async () => { const html = await $fetch('/plugins') expect(html).toContain('asyncPlugin: Async plugin works! 123') }) }) describe('layouts', () => { it('should apply custom layout', async () => { const html = await $fetch('/with-layout') // Snapshot // expect(html).toMatchInlineSnapshot() expect(html).toContain('with-layout.vue') expect(html).toContain('Custom Layout:') }) }) describe('reactivity transform', () => { it('should works', async () => { const html = await $fetch('/') expect(html).toContain('Sugar Counter 12 x 2 = 24') }) }) describe('server tree shaking', () => { it('should work', async () => { const html = await $fetch('/client') expect(html).toContain('This page should not crash when rendered') }) }) describe('extends support', () => { describe('layouts & pages', () => { it('extends foo/layouts/default & foo/pages/index', async () => { const html = await $fetch('/foo') expect(html).toContain('Extended layout from foo') expect(html).toContain('Extended page from foo') }) it('extends [bar/layouts/override & bar/pages/override] over [foo/layouts/override & foo/pages/override]', async () => { const html = await $fetch('/override') expect(html).toContain('Extended layout from bar') expect(html).toContain('Extended page from bar') }) }) describe('components', () => { it('extends foo/components/ExtendsFoo', async () => { const html = await $fetch('/foo') expect(html).toContain('Extended component from foo') }) it('extends bar/components/ExtendsOverride over foo/components/ExtendsOverride', async () => { const html = await $fetch('/override') expect(html).toContain('Extended component from bar') }) }) describe('middlewares', () => { it('extends foo/middleware/foo', async () => { const html = await $fetch('/foo') expect(html).toContain('Middleware | foo: Injected by extended middleware from foo') }) it('extends bar/middleware/override over foo/middleware/override', async () => { const html = await $fetch('/override') expect(html).toContain('Middleware | override: Injected by extended middleware from bar') }) }) describe('composables', () => { it('extends foo/composables/foo', async () => { const html = await $fetch('/foo') expect(html).toContain('Composable | useExtendsFoo: foo') }) }) describe('plugins', () => { it('extends foo/plugins/foo', async () => { const html = await $fetch('/foo') expect(html).toContain('Plugin | foo: String generated from foo plugin!') }) }) describe('server', () => { it('extends foo/server/api/foo', async () => { expect(await $fetch('/api/foo')).toBe('foo') }) it('extends foo/server/middleware/foo', async () => { const { headers } = await fetch('/') expect(headers.get('injected-header')).toEqual('foo') }) }) describe('app', () => { it('extends foo/app/router.options & bar/app/router.options', async () => { const html: string = await $fetch('/') const routerLinkClasses = html.match(/href="\/" class="([^"]*)"/)[1].split(' ') expect(routerLinkClasses).toContain('foo-active-class') expect(routerLinkClasses).toContain('bar-exact-active-class') }) }) }) describe('automatically keyed composables', () => { it('should automatically generate keys', async () => { const html = await $fetch('/keyed-composables') expect(html).toContain('true') expect(html).not.toContain('false') }) it('should match server-generated keys', async () => { await expectNoClientErrors('/keyed-composables') }) }) describe('dynamic paths', () => { if (process.env.NUXT_TEST_DEV) { // TODO: it.todo('dynamic paths in dev') return } it('should work with no overrides', async () => { const html = await $fetch('/assets') for (const match of html.matchAll(/(href|src)="(.*?)"/g)) { const url = match[2] expect(url.startsWith('/_nuxt/') || url === '/public.svg').toBeTruthy() } }) it('adds relative paths to CSS', async () => { if (process.env.TEST_WITH_WEBPACK) { // Webpack injects CSS differently return } const html = await $fetch('/assets') const urls = Array.from(html.matchAll(/(href|src)="(.*?)"/g)).map(m => m[2]) const cssURL = urls.find(u => /_nuxt\/assets.*\.css$/.test(u)) expect(cssURL).toBeDefined() const css = await $fetch(cssURL) const imageUrls = Array.from(css.matchAll(/url\(([^)]*)\)/g)).map(m => m[1].replace(/[-.][\w]{8}\./g, '.')) expect(imageUrls).toMatchInlineSnapshot(` [ "./logo.svg", "../public.svg", "../public.svg", "../public.svg", ] `) }) it('should allow setting base URL and build assets directory', async () => { process.env.NUXT_APP_BUILD_ASSETS_DIR = '/_other/' process.env.NUXT_APP_BASE_URL = '/foo/' await startServer() const html = await $fetch('/foo/assets') for (const match of html.matchAll(/(href|src)="(.`*?)"/g)) { const url = match[2] expect( url.startsWith('/foo/_other/') || url === '/foo/public.svg' || // TODO: webpack does not yet support dynamic static paths (process.env.TEST_WITH_WEBPACK && url === '/public.svg') ).toBeTruthy() } }) it('should allow setting relative baseURL', async () => { delete process.env.NUXT_APP_BUILD_ASSETS_DIR process.env.NUXT_APP_BASE_URL = './' await startServer() const html = await $fetch('/assets') for (const match of html.matchAll(/(href|src)="(.*?)"/g)) { const url = match[2] expect( url.startsWith('./_nuxt/') || url === './public.svg' || // TODO: webpack does not yet support dynamic static paths (process.env.TEST_WITH_WEBPACK && url === '/public.svg') ).toBeTruthy() expect(url.startsWith('./_nuxt/_nuxt')).toBeFalsy() } }) it('should use baseURL when redirecting', async () => { process.env.NUXT_APP_BUILD_ASSETS_DIR = '/_other/' process.env.NUXT_APP_BASE_URL = '/foo/' await startServer() const { headers } = await fetch('/foo/navigate-to/', { redirect: 'manual' }) expect(headers.get('location')).toEqual('/foo/') }) it('should allow setting CDN URL', async () => { process.env.NUXT_APP_BASE_URL = '/foo/' process.env.NUXT_APP_CDN_URL = 'https://example.com/' process.env.NUXT_APP_BUILD_ASSETS_DIR = '/_cdn/' await startServer() const html = await $fetch('/foo/assets') for (const match of html.matchAll(/(href|src)="(.*?)"/g)) { const url = match[2] expect( url.startsWith('https://example.com/_cdn/') || url === 'https://example.com/public.svg' || // TODO: webpack does not yet support dynamic static paths (process.env.TEST_WITH_WEBPACK && url === '/public.svg') ).toBeTruthy() } }) })
test/basic.test.ts
1
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00025924251531250775, 0.00017448753351345658, 0.00016329069330822676, 0.00017311490955762565, 0.000013122079508320894 ]
{ "id": 4, "code_window": [ " // Add global meta configuration\n", " addTemplate({\n", " filename: 'meta.config.mjs',\n", " getContents: () => 'export default ' + JSON.stringify({ globalMeta })\n", " })\n", "\n", " // Add generic plugin\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " getContents: () => 'export default ' + JSON.stringify({ globalMeta: nuxt.options.app.head })\n" ], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 33 }
import { pathToFileURL } from 'node:url' import { createUnplugin } from 'unplugin' import { isAbsolute, relative } from 'pathe' import { walk } from 'estree-walker' import MagicString from 'magic-string' import { hash } from 'ohash' import type { CallExpression } from 'estree' import { parseURL } from 'ufo' export interface ComposableKeysOptions { sourcemap?: boolean rootDir?: string } const keyedFunctions = [ 'useState', 'useFetch', 'useAsyncData', 'useLazyAsyncData', 'useLazyFetch' ] const KEYED_FUNCTIONS_RE = new RegExp(`(${keyedFunctions.join('|')})`) export const composableKeysPlugin = createUnplugin((options: ComposableKeysOptions = {}) => { return { name: 'nuxt:composable-keys', enforce: 'post', transform (code, id) { const { pathname } = parseURL(decodeURIComponent(pathToFileURL(id).href)) if (!pathname.match(/\.(m?[jt]sx?|vue)/)) { return } if (!KEYED_FUNCTIONS_RE.test(code)) { return } const { 0: script = code, index: codeIndex = 0 } = code.match(/(?<=<script[^>]*>)[\S\s.]*?(?=<\/script>)/) || [] const s = new MagicString(code) // https://github.com/unjs/unplugin/issues/90 let count = 0 const relativeID = isAbsolute(id) ? relative(options.rootDir, id) : id walk(this.parse(script, { sourceType: 'module', ecmaVersion: 'latest' }), { enter (node: CallExpression) { if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier') { return } if (keyedFunctions.includes(node.callee.name) && node.arguments.length < 4) { const end = (node as any).end s.appendLeft( codeIndex + end - 1, (node.arguments.length ? ', ' : '') + "'$" + hash(`${relativeID}-${++count}`) + "'" ) } } }) if (s.hasChanged()) { return { code: s.toString(), map: options.sourcemap && s.generateMap({ source: id, includeContent: true }) } } } } })
packages/vite/src/plugins/composable-keys.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00027850663173012435, 0.0001924386015161872, 0.00017026725981850177, 0.0001735431287670508, 0.00003891478991135955 ]
{ "id": 4, "code_window": [ " // Add global meta configuration\n", " addTemplate({\n", " filename: 'meta.config.mjs',\n", " getContents: () => 'export default ' + JSON.stringify({ globalMeta })\n", " })\n", "\n", " // Add generic plugin\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " getContents: () => 'export default ' + JSON.stringify({ globalMeta: nuxt.options.app.head })\n" ], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 33 }
import { defineNuxtConfig } from 'nuxt' export default defineNuxtConfig({ modules: [ '~/modules/pages', '@nuxt/ui' ] })
examples/advanced/module-extend-pages/nuxt.config.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017003167886286974, 0.00017003167886286974, 0.00017003167886286974, 0.00017003167886286974, 0 ]
{ "id": 4, "code_window": [ " // Add global meta configuration\n", " addTemplate({\n", " filename: 'meta.config.mjs',\n", " getContents: () => 'export default ' + JSON.stringify({ globalMeta })\n", " })\n", "\n", " // Add generic plugin\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " getContents: () => 'export default ' + JSON.stringify({ globalMeta: nuxt.options.app.head })\n" ], "file_path": "packages/nuxt/src/head/module.ts", "type": "replace", "edit_start_line_idx": 33 }
import { existsSync, readdirSync } from 'node:fs' import createTiged from 'tiged' import { relative, resolve } from 'pathe' import superb from 'superb' import consola from 'consola' import { defineNuxtCommand } from './index' const rpath = p => relative(process.cwd(), p) const resolveTemplate = (template) => { if (typeof template === 'boolean') { consola.error('Please specify a template!') process.exit(1) } if (!template) { template = 'v3' } if (template.includes('/')) { return template } return `nuxt/starter#${template}` } export default defineNuxtCommand({ meta: { name: 'init', usage: 'npx nuxi init|create [--verbose|-v] [--template,-t] [dir]', description: 'Initialize a fresh project' }, async invoke (args) { // Clone template const src = resolveTemplate(args.template || args.t) const dstDir = resolve(process.cwd(), args._[0] || 'nuxt-app') const tiged = createTiged(src, { cache: false /* TODO: buggy */, verbose: (args.verbose || args.v) }) if (existsSync(dstDir) && readdirSync(dstDir).length) { consola.error(`Directory ${dstDir} is not empty. Please pick another name or remove it first. Aborting.`) process.exit(1) } const formatArgs = msg => msg.replace('options.', '--') tiged.on('warn', event => consola.warn(formatArgs(event.message))) tiged.on('info', event => consola.info(formatArgs(event.message))) try { await tiged.clone(dstDir) } catch (e) { if (e.toString().includes('could not find commit hash')) { consola.error(`Failed to clone template from \`${src}\`. Please check the repo is valid and that you have installed \`git\` correctly.`) process.exit(1) } throw e } // Show next steps const relativeDist = rpath(dstDir) const nextSteps = [ relativeDist.length > 1 && `πŸ“ \`cd ${relativeDist}\``, 'πŸ’Ώ Install dependencies with `npm install` or `yarn install` or `pnpm install --shamefully-hoist`', 'πŸš€ Start development server with `npm run dev` or `yarn dev` or `pnpm run dev`' ].filter(Boolean) consola.log(`\n ✨ Your ${superb.random()} Nuxt project is just created! Next steps:\n`) for (const step of nextSteps) { consola.log(` ${step}\n`) } } })
packages/nuxi/src/commands/init.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00032016271143220365, 0.00019237004744354635, 0.00016641283582430333, 0.00017163011943921447, 0.000052297105867182836 ]
{ "id": 5, "code_window": [ " * @version 3\n", " */\n", " head: {\n", " $resolve: (val, get) => {\n", " return defu(val, get('meta'), {\n", " charset: 'utf-8',\n", " viewport: 'width=device-width, initial-scale=1',\n", " meta: [],\n", " link: [],\n", " style: [],\n", " script: [],\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const resolved = defu(val, get('meta'), {\n" ], "file_path": "packages/schema/src/config/_app.ts", "type": "replace", "edit_start_line_idx": 107 }
import { resolve, join } from 'pathe' import { existsSync, readdirSync } from 'node:fs' import defu from 'defu' export default { /** * Vue.js config * @version 2 * @version 3 */ vue: { /** * Properties that will be set directly on `Vue.config` for vue@2. * * @see [vue@2 Documentation](https://v2.vuejs.org/v2/api/#Global-Config) * @type {typeof import('vue/types/vue').VueConfiguration} * @version 2 */ config: { silent: { $resolve: (val, get) => val ?? !get('dev') }, performance: { $resolve: (val, get) => val ?? get('dev') }, }, /** * Options for the Vue compiler that will be passed at build time * @see [documentation](https://vuejs.org/api/application.html#app-config-compileroptions) * @type {typeof import('@vue/compiler-core').CompilerOptions} * @version 3 */ compilerOptions: {} }, /** * Nuxt App configuration. * @version 2 * @version 3 */ app: { /** * The base path of your Nuxt application. * * This can be set at runtime by setting the NUXT_APP_BASE_URL environment variable. * @example * ```bash * NUXT_APP_BASE_URL=/prefix/ node .output/server/index.mjs * ``` */ baseURL: process.env.NUXT_APP_BASE_URL || '/', /** The folder name for the built site assets, relative to `baseURL` (or `cdnURL` if set). This is set at build time and should not be customized at runtime. */ buildAssetsDir: process.env.NUXT_APP_BUILD_ASSETS_DIR || '/_nuxt/', /** * The folder name for the built site assets, relative to `baseURL` (or `cdnURL` if set). * @deprecated - use `buildAssetsDir` instead * @version 2 */ assetsPath: { $resolve: (val, get) => val ?? get('buildAssetsDir') }, /** * An absolute URL to serve the public folder from (production-only). * * This can be set to a different value at runtime by setting the NUXT_APP_CDN_URL environment variable. * @example * ```bash * NUXT_APP_CDN_URL=https://mycdn.org/ node .output/server/index.mjs * ``` */ cdnURL: { $resolve: (val, get) => get('dev') ? '' : (process.env.NUXT_APP_CDN_URL ?? val) || '' }, /** * Set default configuration for `<head>` on every page. * * @example * ```js * app: { * head: { * meta: [ * // <meta name="viewport" content="width=device-width, initial-scale=1"> * { name: 'viewport', content: 'width=device-width, initial-scale=1' } * ], * script: [ * // <script src="https://myawesome-lib.js"></script> * { src: 'https://awesome-lib.js' } * ], * link: [ * // <link rel="stylesheet" href="https://myawesome-lib.css"> * { rel: 'stylesheet', href: 'https://awesome-lib.css' } * ], * // please note that this is an area that is likely to change * style: [ * // <style type="text/css">:root { color: red }</style> * { children: ':root { color: red }', type: 'text/css' } * ], * noscript: [ * // <noscript>Javascript is required</noscript> * { children: 'Javascript is required' } * ] * } * } * ``` * @type {typeof import('../src/types/meta').MetaObject} * @version 3 */ head: { $resolve: (val, get) => { return defu(val, get('meta'), { charset: 'utf-8', viewport: 'width=device-width, initial-scale=1', meta: [], link: [], style: [], script: [], noscript: [] }) } }, }, /** * The path to a templated HTML file for rendering Nuxt responses. * Uses `<srcDir>/app.html` if it exists or the Nuxt default template if not. * * @example * ```html * <!DOCTYPE html> * <html {{ HTML_ATTRS }}> * <head {{ HEAD_ATTRS }}> * {{ HEAD }} * </head> * <body {{ BODY_ATTRS }}> * {{ APP }} * </body> * </html> * ``` * @version 2 */ appTemplatePath: { $resolve: (val, get) => { if (val) { return resolve(get('srcDir'), val) } if (existsSync(join(get('srcDir'), 'app.html'))) { return join(get('srcDir'), 'app.html') } return resolve(get('buildDir'), 'views/app.template.html') } }, /** * Enable or disable vuex store. * * By default it is enabled if there is a `store/` directory * @version 2 */ store: { $resolve: (val, get) => val !== false && existsSync(join(get('srcDir'), get('dir.store'))) && readdirSync(join(get('srcDir'), get('dir.store'))) .find(filename => filename !== 'README.md' && filename[0] !== '.') }, /** * Options to pass directly to `vue-meta`. * * @see [documentation](https://vue-meta.nuxtjs.org/api/#plugin-options). * @type {typeof import('vue-meta').VueMetaOptions} * @version 2 */ vueMeta: null, /** * Set default configuration for `<head>` on every page. * * @see [documentation](https://vue-meta.nuxtjs.org/api/#metainfo-properties) for specifics. * @type {typeof import('vue-meta').MetaInfo} * @version 2 */ head: { /** Each item in the array maps to a newly-created `<meta>` element, where object properties map to attributes. */ meta: [], /** Each item in the array maps to a newly-created `<link>` element, where object properties map to attributes. */ link: [], /** Each item in the array maps to a newly-created `<style>` element, where object properties map to attributes. */ style: [], /** Each item in the array maps to a newly-created `<script>` element, where object properties map to attributes. */ script: [] }, /** * @type {typeof import('../src/types/meta').MetaObject} * @version 3 * @deprecated - use `head` instead */ meta: { meta: [], link: [], style: [], script: [] }, /** * Configuration for the Nuxt `fetch()` hook. * @version 2 */ fetch: { /** Whether to enable `fetch()` on the server. */ server: true, /** Whether to enable `fetch()` on the client. */ client: true }, /** * An array of nuxt app plugins. * * Each plugin can be a string (which can be an absolute or relative path to a file). * If it ends with `.client` or `.server` then it will be automatically loaded only * in the appropriate context. * * It can also be an object with `src` and `mode` keys. * * @example * ```js * plugins: [ * '~/plugins/foo.client.js', // only in client side * '~/plugins/bar.server.js', // only in server side * '~/plugins/baz.js', // both client & server * { src: '~/plugins/both-sides.js' }, * { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side * { src: '~/plugins/server-only.js', mode: 'server' } // only on server side * ] * ``` * @type {(typeof import('../src/types/nuxt').NuxtPlugin | string)[]} * @version 2 */ plugins: [], /** * You may want to extend plugins or change their order. For this, you can pass * a function using `extendPlugins`. It accepts an array of plugin objects and * should return an array of plugin objects. * @type {(plugins: Array<{ src: string, mode?: 'client' | 'server' }>) => Array<{ src: string, mode?: 'client' | 'server' }>} * @version 2 */ extendPlugins: null, /** * You can define the CSS files/modules/libraries you want to set globally * (included in every page). * * Nuxt will automatically guess the file type by its extension and use the * appropriate pre-processor. You will still need to install the required * loader if you need to use them. * * @example * ```js * css: [ * // Load a Node.js module directly (here it's a Sass file) * 'bulma', * // CSS file in the project * '@/assets/css/main.css', * // SCSS file in the project * '@/assets/css/main.scss' * ] * ``` * @type {string[]} * @version 2 * @version 3 */ css: { $resolve: val => (val ?? []).map(c => c.src || c) }, /** * An object where each key name maps to a path to a layout .vue file. * * Normally there is no need to configure this directly. * @type {Record<string, string>} * @version 2 */ layouts: {}, /** * Set a custom error page layout. * * Normally there is no need to configure this directly. * @type {string} * @version 2 */ ErrorPage: null, /** * Configure the Nuxt loading progress bar component that's shown between * routes. Set to `false` to disable. You can also customize it or create * your own component. * @version 2 */ loading: { /** CSS color of the progress bar */ color: 'black', /** * CSS color of the progress bar when an error appended while rendering * the route (if data or fetch sent back an error for example). */ failedColor: 'red', /** Height of the progress bar (used in the style property of the progress bar). */ height: '2px', /** * In ms, wait for the specified time before displaying the progress bar. * Useful for preventing the bar from flashing. */ throttle: 200, /** * In ms, the maximum duration of the progress bar, Nuxt assumes that the * route will be rendered before 5 seconds. */ duration: 5000, /** Keep animating progress bar when loading takes longer than duration. */ continuous: false, /** Set the direction of the progress bar from right to left. */ rtl: false, /** Set to false to remove default progress bar styles (and add your own). */ css: true }, /** * Show a loading spinner while the page is loading (only when `ssr: false`). * * Set to `false` to disable. Alternatively, you can pass a string name or an object for more * configuration. The name can refer to an indicator from [SpinKit](https://tobiasahlin.com/spinkit/) * or a path to an HTML template of the indicator source code (in this case, all the * other options will be passed to the template.) * @version 2 */ loadingIndicator: { $resolve: (val, get) => { val = typeof val === 'string' ? { name: val } : val return defu(val, { name: 'default', color: get('loading.color') || '#D3D3D3', color2: '#F5F5F5', background: (get('manifest') && get('manifest.theme_color')) || 'white', dev: get('dev'), loading: get('messages.loading') }) } }, /** * Used to set the default properties of the page transitions. * * You can either pass a string (the transition name) or an object with properties to bind * to the `<Transition>` component that will wrap your pages. * * @see [vue@2 documentation](https://v2.vuejs.org/v2/guide/transitions.html) * @see [vue@3 documentation](https://vuejs.org/guide/built-ins/transition-group.html#enter-leave-transitions) * @version 2 */ pageTransition: { $resolve: (val, get) => { val = typeof val === 'string' ? { name: val } : val return defu(val, { name: 'page', mode: 'out-in', appear: get('render.ssr') === false || Boolean(val), appearClass: 'appear', appearActiveClass: 'appear-active', appearToClass: 'appear-to' }) } }, /** * Used to set the default properties of the layout transitions. * * You can either pass a string (the transition name) or an object with properties to bind * to the `<Transition>` component that will wrap your layouts. * * @see [vue@2 documentation](https://v2.vuejs.org/v2/guide/transitions.html) * @see [vue@3 documentation](https://vuejs.org/guide/built-ins/transition-group.html#enter-leave-transitions) * @version 2 */ layoutTransition: { $resolve: val => { val = typeof val === 'string' ? { name: val } : val return defu(val, { name: 'layout', mode: 'out-in' }) } }, /** * You can disable specific Nuxt features that you do not want. * @version 2 */ features: { /** Set to false to disable Nuxt vuex integration */ store: true, /** Set to false to disable layouts */ layouts: true, /** Set to false to disable Nuxt integration with `vue-meta` and the `head` property */ meta: true, /** Set to false to disable middleware */ middleware: true, /** Set to false to disable transitions */ transitions: true, /** Set to false to disable support for deprecated features and aliases */ deprecations: true, /** Set to false to disable the Nuxt `validate()` hook */ validate: true, /** Set to false to disable the Nuxt `asyncData()` hook */ useAsyncData: true, /** Set to false to disable the Nuxt `fetch()` hook */ fetch: true, /** Set to false to disable `$nuxt.isOnline` */ clientOnline: true, /** Set to false to disable prefetching behavior in `<NuxtLink>` */ clientPrefetch: true, /** Set to false to disable extra component aliases like `<NLink>` and `<NChild>` */ componentAliases: true, /** Set to false to disable the `<ClientOnly>` component (see [docs](https://github.com/egoist/vue-client-only)) */ componentClientOnly: true } }
packages/schema/src/config/_app.ts
1
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.9911243319511414, 0.023486237972974777, 0.00016119728388730437, 0.00017246462812181562, 0.14931149780750275 ]
{ "id": 5, "code_window": [ " * @version 3\n", " */\n", " head: {\n", " $resolve: (val, get) => {\n", " return defu(val, get('meta'), {\n", " charset: 'utf-8',\n", " viewport: 'width=device-width, initial-scale=1',\n", " meta: [],\n", " link: [],\n", " style: [],\n", " script: [],\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const resolved = defu(val, get('meta'), {\n" ], "file_path": "packages/schema/src/config/_app.ts", "type": "replace", "edit_start_line_idx": 107 }
--- icon: IconCloud --- # Render How to deploy Nuxt to [Render](https://render.com/) ## Learn more :ReadMore{link="https://nitro.unjs.io/deploy/providers/render.html" title="the Nitro documentation for Render deployment"}
docs/content/2.guide/5.deploy/providers/render.md
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017246791685465723, 0.00016901020717341453, 0.00016555249749217182, 0.00016901020717341453, 0.0000034577096812427044 ]
{ "id": 5, "code_window": [ " * @version 3\n", " */\n", " head: {\n", " $resolve: (val, get) => {\n", " return defu(val, get('meta'), {\n", " charset: 'utf-8',\n", " viewport: 'width=device-width, initial-scale=1',\n", " meta: [],\n", " link: [],\n", " style: [],\n", " script: [],\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const resolved = defu(val, get('meta'), {\n" ], "file_path": "packages/schema/src/config/_app.ts", "type": "replace", "edit_start_line_idx": 107 }
<template> <NuxtExampleLayout example="routing/layouts"> <template #nav> <nav class="flex align-center gap-4 p-4"> <NuxtLink to="/default"> Default layout </NuxtLink> <NuxtLink to="/custom"> Custom layout </NuxtLink> <NuxtLink to="/dynamic"> Dynamic layout </NuxtLink> </nav> </template> </NuxtExampleLayout> </template>
examples/routing/layouts/pages/index.vue
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.0001717691047815606, 0.00017133764049503952, 0.00017090617620851845, 0.00017133764049503952, 4.3146428652107716e-7 ]
{ "id": 5, "code_window": [ " * @version 3\n", " */\n", " head: {\n", " $resolve: (val, get) => {\n", " return defu(val, get('meta'), {\n", " charset: 'utf-8',\n", " viewport: 'width=device-width, initial-scale=1',\n", " meta: [],\n", " link: [],\n", " style: [],\n", " script: [],\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const resolved = defu(val, get('meta'), {\n" ], "file_path": "packages/schema/src/config/_app.ts", "type": "replace", "edit_start_line_idx": 107 }
# Dependencies node_modules jspm_packages package-lock.json # */**/yarn.lock # Logs *.log # Temp directories .temp .tmp .cache # Yarn **/.yarn/cache **/.yarn/*state* # Generated dirs dist .nuxt .nuxt-* .output .gen nuxt.d.ts # Junit reports reports # Coverage reports coverage *.lcov .nyc_output # VSCode .vscode # Intellij idea *.iml .idea # OSX .DS_Store .AppleDouble .LSOverride # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk .vercel_build_output .build-* .env .netlify
.gitignore
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017578245024196804, 0.00017230950470548123, 0.00016855339345056564, 0.00017106987070292234, 0.0000025586832634871826 ]
{ "id": 6, "code_window": [ " script: [],\n", " noscript: []\n", " })\n", " }\n", " },\n", " },\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " resolved.charset = resolved.charset ?? resolved.meta.find(m => m.charset)?.charset ?? 'utf-8'\n", " resolved.viewport = resolved.viewport ?? resolved.meta.find(m => m.name === 'viewport')?.content ?? 'width=device-width, initial-scale=1'\n", " resolved.meta = resolved.meta.filter(m => m && m.name !== 'viewport' && !m.charset)\n", " resolved.link = resolved.link.filter(Boolean)\n", " resolved.style = resolved.style.filter(Boolean)\n", " resolved.script = resolved.script.filter(Boolean)\n", " resolved.noscript = resolved.noscript.filter(Boolean)\n", "\n", " return resolved\n" ], "file_path": "packages/schema/src/config/_app.ts", "type": "add", "edit_start_line_idx": 116 }
import { resolve, join } from 'pathe' import { existsSync, readdirSync } from 'node:fs' import defu from 'defu' export default { /** * Vue.js config * @version 2 * @version 3 */ vue: { /** * Properties that will be set directly on `Vue.config` for vue@2. * * @see [vue@2 Documentation](https://v2.vuejs.org/v2/api/#Global-Config) * @type {typeof import('vue/types/vue').VueConfiguration} * @version 2 */ config: { silent: { $resolve: (val, get) => val ?? !get('dev') }, performance: { $resolve: (val, get) => val ?? get('dev') }, }, /** * Options for the Vue compiler that will be passed at build time * @see [documentation](https://vuejs.org/api/application.html#app-config-compileroptions) * @type {typeof import('@vue/compiler-core').CompilerOptions} * @version 3 */ compilerOptions: {} }, /** * Nuxt App configuration. * @version 2 * @version 3 */ app: { /** * The base path of your Nuxt application. * * This can be set at runtime by setting the NUXT_APP_BASE_URL environment variable. * @example * ```bash * NUXT_APP_BASE_URL=/prefix/ node .output/server/index.mjs * ``` */ baseURL: process.env.NUXT_APP_BASE_URL || '/', /** The folder name for the built site assets, relative to `baseURL` (or `cdnURL` if set). This is set at build time and should not be customized at runtime. */ buildAssetsDir: process.env.NUXT_APP_BUILD_ASSETS_DIR || '/_nuxt/', /** * The folder name for the built site assets, relative to `baseURL` (or `cdnURL` if set). * @deprecated - use `buildAssetsDir` instead * @version 2 */ assetsPath: { $resolve: (val, get) => val ?? get('buildAssetsDir') }, /** * An absolute URL to serve the public folder from (production-only). * * This can be set to a different value at runtime by setting the NUXT_APP_CDN_URL environment variable. * @example * ```bash * NUXT_APP_CDN_URL=https://mycdn.org/ node .output/server/index.mjs * ``` */ cdnURL: { $resolve: (val, get) => get('dev') ? '' : (process.env.NUXT_APP_CDN_URL ?? val) || '' }, /** * Set default configuration for `<head>` on every page. * * @example * ```js * app: { * head: { * meta: [ * // <meta name="viewport" content="width=device-width, initial-scale=1"> * { name: 'viewport', content: 'width=device-width, initial-scale=1' } * ], * script: [ * // <script src="https://myawesome-lib.js"></script> * { src: 'https://awesome-lib.js' } * ], * link: [ * // <link rel="stylesheet" href="https://myawesome-lib.css"> * { rel: 'stylesheet', href: 'https://awesome-lib.css' } * ], * // please note that this is an area that is likely to change * style: [ * // <style type="text/css">:root { color: red }</style> * { children: ':root { color: red }', type: 'text/css' } * ], * noscript: [ * // <noscript>Javascript is required</noscript> * { children: 'Javascript is required' } * ] * } * } * ``` * @type {typeof import('../src/types/meta').MetaObject} * @version 3 */ head: { $resolve: (val, get) => { return defu(val, get('meta'), { charset: 'utf-8', viewport: 'width=device-width, initial-scale=1', meta: [], link: [], style: [], script: [], noscript: [] }) } }, }, /** * The path to a templated HTML file for rendering Nuxt responses. * Uses `<srcDir>/app.html` if it exists or the Nuxt default template if not. * * @example * ```html * <!DOCTYPE html> * <html {{ HTML_ATTRS }}> * <head {{ HEAD_ATTRS }}> * {{ HEAD }} * </head> * <body {{ BODY_ATTRS }}> * {{ APP }} * </body> * </html> * ``` * @version 2 */ appTemplatePath: { $resolve: (val, get) => { if (val) { return resolve(get('srcDir'), val) } if (existsSync(join(get('srcDir'), 'app.html'))) { return join(get('srcDir'), 'app.html') } return resolve(get('buildDir'), 'views/app.template.html') } }, /** * Enable or disable vuex store. * * By default it is enabled if there is a `store/` directory * @version 2 */ store: { $resolve: (val, get) => val !== false && existsSync(join(get('srcDir'), get('dir.store'))) && readdirSync(join(get('srcDir'), get('dir.store'))) .find(filename => filename !== 'README.md' && filename[0] !== '.') }, /** * Options to pass directly to `vue-meta`. * * @see [documentation](https://vue-meta.nuxtjs.org/api/#plugin-options). * @type {typeof import('vue-meta').VueMetaOptions} * @version 2 */ vueMeta: null, /** * Set default configuration for `<head>` on every page. * * @see [documentation](https://vue-meta.nuxtjs.org/api/#metainfo-properties) for specifics. * @type {typeof import('vue-meta').MetaInfo} * @version 2 */ head: { /** Each item in the array maps to a newly-created `<meta>` element, where object properties map to attributes. */ meta: [], /** Each item in the array maps to a newly-created `<link>` element, where object properties map to attributes. */ link: [], /** Each item in the array maps to a newly-created `<style>` element, where object properties map to attributes. */ style: [], /** Each item in the array maps to a newly-created `<script>` element, where object properties map to attributes. */ script: [] }, /** * @type {typeof import('../src/types/meta').MetaObject} * @version 3 * @deprecated - use `head` instead */ meta: { meta: [], link: [], style: [], script: [] }, /** * Configuration for the Nuxt `fetch()` hook. * @version 2 */ fetch: { /** Whether to enable `fetch()` on the server. */ server: true, /** Whether to enable `fetch()` on the client. */ client: true }, /** * An array of nuxt app plugins. * * Each plugin can be a string (which can be an absolute or relative path to a file). * If it ends with `.client` or `.server` then it will be automatically loaded only * in the appropriate context. * * It can also be an object with `src` and `mode` keys. * * @example * ```js * plugins: [ * '~/plugins/foo.client.js', // only in client side * '~/plugins/bar.server.js', // only in server side * '~/plugins/baz.js', // both client & server * { src: '~/plugins/both-sides.js' }, * { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side * { src: '~/plugins/server-only.js', mode: 'server' } // only on server side * ] * ``` * @type {(typeof import('../src/types/nuxt').NuxtPlugin | string)[]} * @version 2 */ plugins: [], /** * You may want to extend plugins or change their order. For this, you can pass * a function using `extendPlugins`. It accepts an array of plugin objects and * should return an array of plugin objects. * @type {(plugins: Array<{ src: string, mode?: 'client' | 'server' }>) => Array<{ src: string, mode?: 'client' | 'server' }>} * @version 2 */ extendPlugins: null, /** * You can define the CSS files/modules/libraries you want to set globally * (included in every page). * * Nuxt will automatically guess the file type by its extension and use the * appropriate pre-processor. You will still need to install the required * loader if you need to use them. * * @example * ```js * css: [ * // Load a Node.js module directly (here it's a Sass file) * 'bulma', * // CSS file in the project * '@/assets/css/main.css', * // SCSS file in the project * '@/assets/css/main.scss' * ] * ``` * @type {string[]} * @version 2 * @version 3 */ css: { $resolve: val => (val ?? []).map(c => c.src || c) }, /** * An object where each key name maps to a path to a layout .vue file. * * Normally there is no need to configure this directly. * @type {Record<string, string>} * @version 2 */ layouts: {}, /** * Set a custom error page layout. * * Normally there is no need to configure this directly. * @type {string} * @version 2 */ ErrorPage: null, /** * Configure the Nuxt loading progress bar component that's shown between * routes. Set to `false` to disable. You can also customize it or create * your own component. * @version 2 */ loading: { /** CSS color of the progress bar */ color: 'black', /** * CSS color of the progress bar when an error appended while rendering * the route (if data or fetch sent back an error for example). */ failedColor: 'red', /** Height of the progress bar (used in the style property of the progress bar). */ height: '2px', /** * In ms, wait for the specified time before displaying the progress bar. * Useful for preventing the bar from flashing. */ throttle: 200, /** * In ms, the maximum duration of the progress bar, Nuxt assumes that the * route will be rendered before 5 seconds. */ duration: 5000, /** Keep animating progress bar when loading takes longer than duration. */ continuous: false, /** Set the direction of the progress bar from right to left. */ rtl: false, /** Set to false to remove default progress bar styles (and add your own). */ css: true }, /** * Show a loading spinner while the page is loading (only when `ssr: false`). * * Set to `false` to disable. Alternatively, you can pass a string name or an object for more * configuration. The name can refer to an indicator from [SpinKit](https://tobiasahlin.com/spinkit/) * or a path to an HTML template of the indicator source code (in this case, all the * other options will be passed to the template.) * @version 2 */ loadingIndicator: { $resolve: (val, get) => { val = typeof val === 'string' ? { name: val } : val return defu(val, { name: 'default', color: get('loading.color') || '#D3D3D3', color2: '#F5F5F5', background: (get('manifest') && get('manifest.theme_color')) || 'white', dev: get('dev'), loading: get('messages.loading') }) } }, /** * Used to set the default properties of the page transitions. * * You can either pass a string (the transition name) or an object with properties to bind * to the `<Transition>` component that will wrap your pages. * * @see [vue@2 documentation](https://v2.vuejs.org/v2/guide/transitions.html) * @see [vue@3 documentation](https://vuejs.org/guide/built-ins/transition-group.html#enter-leave-transitions) * @version 2 */ pageTransition: { $resolve: (val, get) => { val = typeof val === 'string' ? { name: val } : val return defu(val, { name: 'page', mode: 'out-in', appear: get('render.ssr') === false || Boolean(val), appearClass: 'appear', appearActiveClass: 'appear-active', appearToClass: 'appear-to' }) } }, /** * Used to set the default properties of the layout transitions. * * You can either pass a string (the transition name) or an object with properties to bind * to the `<Transition>` component that will wrap your layouts. * * @see [vue@2 documentation](https://v2.vuejs.org/v2/guide/transitions.html) * @see [vue@3 documentation](https://vuejs.org/guide/built-ins/transition-group.html#enter-leave-transitions) * @version 2 */ layoutTransition: { $resolve: val => { val = typeof val === 'string' ? { name: val } : val return defu(val, { name: 'layout', mode: 'out-in' }) } }, /** * You can disable specific Nuxt features that you do not want. * @version 2 */ features: { /** Set to false to disable Nuxt vuex integration */ store: true, /** Set to false to disable layouts */ layouts: true, /** Set to false to disable Nuxt integration with `vue-meta` and the `head` property */ meta: true, /** Set to false to disable middleware */ middleware: true, /** Set to false to disable transitions */ transitions: true, /** Set to false to disable support for deprecated features and aliases */ deprecations: true, /** Set to false to disable the Nuxt `validate()` hook */ validate: true, /** Set to false to disable the Nuxt `asyncData()` hook */ useAsyncData: true, /** Set to false to disable the Nuxt `fetch()` hook */ fetch: true, /** Set to false to disable `$nuxt.isOnline` */ clientOnline: true, /** Set to false to disable prefetching behavior in `<NuxtLink>` */ clientPrefetch: true, /** Set to false to disable extra component aliases like `<NLink>` and `<NChild>` */ componentAliases: true, /** Set to false to disable the `<ClientOnly>` component (see [docs](https://github.com/egoist/vue-client-only)) */ componentClientOnly: true } }
packages/schema/src/config/_app.ts
1
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.8743835687637329, 0.020540082827210426, 0.00016374191909562796, 0.0001687943295110017, 0.13175101578235626 ]
{ "id": 6, "code_window": [ " script: [],\n", " noscript: []\n", " })\n", " }\n", " },\n", " },\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " resolved.charset = resolved.charset ?? resolved.meta.find(m => m.charset)?.charset ?? 'utf-8'\n", " resolved.viewport = resolved.viewport ?? resolved.meta.find(m => m.name === 'viewport')?.content ?? 'width=device-width, initial-scale=1'\n", " resolved.meta = resolved.meta.filter(m => m && m.name !== 'viewport' && !m.charset)\n", " resolved.link = resolved.link.filter(Boolean)\n", " resolved.style = resolved.style.filter(Boolean)\n", " resolved.script = resolved.script.filter(Boolean)\n", " resolved.noscript = resolved.noscript.filter(Boolean)\n", "\n", " return resolved\n" ], "file_path": "packages/schema/src/config/_app.ts", "type": "add", "edit_start_line_idx": 116 }
<script setup> const a = ref('') useHead({ // title template function example titleTemplate: title => `${title} - Title Template Fn Change`, bodyAttrs: { class: 'body-attrs-test' }, script: [ { src: 'https://a-body-appended-script.com', body: true } ], meta: [{ name: 'description', content: 'first' }] }) useHead({ charset: 'utf-16', meta: [{ name: 'description', content: computed(() => `${a.value} with an inline useHead call`) }] }) useMeta({ script: [{ children: 'console.log("works with useMeta too")' }] }) a.value = 'overriding' </script> <script> export default { head () { return { htmlAttrs: { class: 'html-attrs-test' } } } } </script> <template> <div> <Head> <Title>Using a dynamic component</Title> </Head> </div> </template>
test/fixtures/basic/pages/head.vue
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00021138269221410155, 0.00018615837325342, 0.0001709912612568587, 0.00018293278117198497, 0.000015254589015967213 ]
{ "id": 6, "code_window": [ " script: [],\n", " noscript: []\n", " })\n", " }\n", " },\n", " },\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " resolved.charset = resolved.charset ?? resolved.meta.find(m => m.charset)?.charset ?? 'utf-8'\n", " resolved.viewport = resolved.viewport ?? resolved.meta.find(m => m.name === 'viewport')?.content ?? 'width=device-width, initial-scale=1'\n", " resolved.meta = resolved.meta.filter(m => m && m.name !== 'viewport' && !m.charset)\n", " resolved.link = resolved.link.filter(Boolean)\n", " resolved.style = resolved.style.filter(Boolean)\n", " resolved.script = resolved.script.filter(Boolean)\n", " resolved.noscript = resolved.noscript.filter(Boolean)\n", "\n", " return resolved\n" ], "file_path": "packages/schema/src/config/_app.ts", "type": "add", "edit_start_line_idx": 116 }
export * from './core/nuxt' export * from './core/builder'
packages/nuxt/src/index.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00016870969557203352, 0.00016870969557203352, 0.00016870969557203352, 0.00016870969557203352, 0 ]
{ "id": 6, "code_window": [ " script: [],\n", " noscript: []\n", " })\n", " }\n", " },\n", " },\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " resolved.charset = resolved.charset ?? resolved.meta.find(m => m.charset)?.charset ?? 'utf-8'\n", " resolved.viewport = resolved.viewport ?? resolved.meta.find(m => m.name === 'viewport')?.content ?? 'width=device-width, initial-scale=1'\n", " resolved.meta = resolved.meta.filter(m => m && m.name !== 'viewport' && !m.charset)\n", " resolved.link = resolved.link.filter(Boolean)\n", " resolved.style = resolved.style.filter(Boolean)\n", " resolved.script = resolved.script.filter(Boolean)\n", " resolved.noscript = resolved.noscript.filter(Boolean)\n", "\n", " return resolved\n" ], "file_path": "packages/schema/src/config/_app.ts", "type": "add", "edit_start_line_idx": 116 }
import { promises as fsp, readdirSync, statSync } from 'node:fs' import { hash } from 'ohash' import { join } from 'pathe' export function uniq<T> (arr: T[]): T[] { return Array.from(new Set(arr)) } // Copied from vue-bundle-renderer utils const IS_JS_RE = /\.[cm]?js(\?[^.]+)?$/ const IS_MODULE_RE = /\.mjs(\?[^.]+)?$/ const HAS_EXT_RE = /[^./]+\.[^./]+$/ const IS_CSS_RE = /\.(?:css|scss|sass|postcss|less|stylus|styl)(\?[^.]+)?$/ export function isJS (file: string) { return IS_JS_RE.test(file) || !HAS_EXT_RE.test(file) } export function isModule (file: string) { return IS_MODULE_RE.test(file) || !HAS_EXT_RE.test(file) } export function isCSS (file: string) { return IS_CSS_RE.test(file) } export function hashId (id: string) { return '$id_' + hash(id) } export function readDirRecursively (dir: string) { return readdirSync(dir).reduce((files, file) => { const name = join(dir, file) const isDirectory = statSync(name).isDirectory() return isDirectory ? [...files, ...readDirRecursively(name)] : [...files, name] }, []) } export async function isDirectory (path: string) { try { return (await fsp.stat(path)).isDirectory() } catch (_err) { return false } }
packages/vite/src/utils/index.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.0003169335541315377, 0.00019884486391674727, 0.00016727877664379776, 0.00017047715664375573, 0.00005906552178203128 ]
{ "id": 7, "code_window": [ " it('should render tags', async () => {\n", " const headHtml = await $fetch('/head')\n", " expect(headHtml).toContain('<title>Using a dynamic component - Title Template Fn Change</title>')\n", " expect(headHtml).not.toContain('<meta name=\"description\" content=\"first\">')\n", " expect(headHtml).toContain('<meta charset=\"utf-16\">')\n", " expect(headHtml).not.toContain('<meta charset=\"utf-8\">')\n", " expect(headHtml).toContain('<meta name=\"description\" content=\"overriding with an inline useHead call\">')\n", " expect(headHtml).toMatch(/<html[^>]*class=\"html-attrs-test\"/)\n", " expect(headHtml).toMatch(/<body[^>]*class=\"body-attrs-test\"/)\n", " expect(headHtml).toContain('script>console.log(\"works with useMeta too\")</script>')\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(headHtml.match('meta charset').length).toEqual(1)\n", " expect(headHtml).toContain('<meta name=\"viewport\" content=\"width=1024, initial-scale=1\">')\n", " expect(headHtml.match('meta name=\"viewport\"').length).toEqual(1)\n" ], "file_path": "test/basic.test.ts", "type": "add", "edit_start_line_idx": 140 }
import { resolve } from 'pathe' import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit' import defu from 'defu' import { distDir } from '../dirs' import type { MetaObject } from './runtime' export default defineNuxtModule({ meta: { name: 'meta' }, defaults: { charset: 'utf-8', viewport: 'width=device-width, initial-scale=1' }, setup (options, nuxt) { const runtimeDir = nuxt.options.alias['#head'] || resolve(distDir, 'head/runtime') // Transpile @nuxt/meta and @vueuse/head nuxt.options.build.transpile.push('@vueuse/head') // Add #head alias nuxt.options.alias['#head'] = runtimeDir // Global meta -for Bridge, this is necessary to repeat here // and in packages/schema/src/config/_app.ts const globalMeta: MetaObject = defu(nuxt.options.app.head, { charset: options.charset, viewport: options.viewport }) // Add global meta configuration addTemplate({ filename: 'meta.config.mjs', getContents: () => 'export default ' + JSON.stringify({ globalMeta }) }) // Add generic plugin addPlugin({ src: resolve(runtimeDir, 'plugin') }) // Add library specific plugin addPlugin({ src: resolve(runtimeDir, 'lib/vueuse-head.plugin') }) } })
packages/nuxt/src/head/module.ts
1
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017248158110305667, 0.0001683136506471783, 0.0001647219032747671, 0.00016706946189515293, 0.000002996070179506205 ]
{ "id": 7, "code_window": [ " it('should render tags', async () => {\n", " const headHtml = await $fetch('/head')\n", " expect(headHtml).toContain('<title>Using a dynamic component - Title Template Fn Change</title>')\n", " expect(headHtml).not.toContain('<meta name=\"description\" content=\"first\">')\n", " expect(headHtml).toContain('<meta charset=\"utf-16\">')\n", " expect(headHtml).not.toContain('<meta charset=\"utf-8\">')\n", " expect(headHtml).toContain('<meta name=\"description\" content=\"overriding with an inline useHead call\">')\n", " expect(headHtml).toMatch(/<html[^>]*class=\"html-attrs-test\"/)\n", " expect(headHtml).toMatch(/<body[^>]*class=\"body-attrs-test\"/)\n", " expect(headHtml).toContain('script>console.log(\"works with useMeta too\")</script>')\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(headHtml.match('meta charset').length).toEqual(1)\n", " expect(headHtml).toContain('<meta name=\"viewport\" content=\"width=1024, initial-scale=1\">')\n", " expect(headHtml.match('meta name=\"viewport\"').length).toEqual(1)\n" ], "file_path": "test/basic.test.ts", "type": "add", "edit_start_line_idx": 140 }
MIT License Copyright (c) 2022 - Nuxt Project Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
LICENSE
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017700485477689654, 0.0001719048450468108, 0.00016488219262100756, 0.00017382750229444355, 0.000005132392288942356 ]
{ "id": 7, "code_window": [ " it('should render tags', async () => {\n", " const headHtml = await $fetch('/head')\n", " expect(headHtml).toContain('<title>Using a dynamic component - Title Template Fn Change</title>')\n", " expect(headHtml).not.toContain('<meta name=\"description\" content=\"first\">')\n", " expect(headHtml).toContain('<meta charset=\"utf-16\">')\n", " expect(headHtml).not.toContain('<meta charset=\"utf-8\">')\n", " expect(headHtml).toContain('<meta name=\"description\" content=\"overriding with an inline useHead call\">')\n", " expect(headHtml).toMatch(/<html[^>]*class=\"html-attrs-test\"/)\n", " expect(headHtml).toMatch(/<body[^>]*class=\"body-attrs-test\"/)\n", " expect(headHtml).toContain('script>console.log(\"works with useMeta too\")</script>')\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(headHtml.match('meta charset').length).toEqual(1)\n", " expect(headHtml).toContain('<meta name=\"viewport\" content=\"width=1024, initial-scale=1\">')\n", " expect(headHtml.match('meta name=\"viewport\"').length).toEqual(1)\n" ], "file_path": "test/basic.test.ts", "type": "add", "edit_start_line_idx": 140 }
import type { Nuxt, NuxtModule } from '@nuxt/schema' import { useNuxt } from '../context' import { resolveModule, requireModule, importModule } from '../internal/cjs' import { resolveAlias } from '../resolve' import { useModuleContainer } from './container' /** Installs a module on a Nuxt instance. */ export async function installModule (moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt) { const nuxt = useNuxt() const { nuxtModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions) // Call module await nuxtModule.call(useModuleContainer(), inlineOptions, nuxt) nuxt.options._installedModules = nuxt.options._installedModules || [] nuxt.options._installedModules.push({ meta: await nuxtModule.getMeta?.(), entryPath: typeof moduleToInstall === 'string' ? resolveAlias(moduleToInstall) : undefined }) } // --- Internal --- async function normalizeModule (nuxtModule: string | NuxtModule, inlineOptions?: any) { const nuxt = useNuxt() // Detect if `installModule` used with older signuture (nuxt, nuxtModule) // TODO: Remove in RC // @ts-ignore if (nuxtModule?._version || nuxtModule?.version || nuxtModule?.constructor?.version || '') { [nuxtModule, inlineOptions] = [inlineOptions, {}] console.warn(new Error('`installModule` is being called with old signature!')) } // Import if input is string if (typeof nuxtModule === 'string') { const _src = resolveModule(resolveAlias(nuxtModule), { paths: nuxt.options.modulesDir }) // TODO: also check with type: 'module' in closest `package.json` const isESM = _src.endsWith('.mjs') nuxtModule = isESM ? await importModule(_src) : requireModule(_src) } // Throw error if input is not a function if (typeof nuxtModule !== 'function') { throw new TypeError('Nuxt module should be a function: ' + nuxtModule) } return { nuxtModule, inlineOptions } as { nuxtModule: NuxtModule<any>, inlineOptions: undefined | Record<string, any> } }
packages/kit/src/module/install.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017379534256178886, 0.00017214914259966463, 0.0001686678733676672, 0.0001724978646961972, 0.000001845076553763647 ]
{ "id": 7, "code_window": [ " it('should render tags', async () => {\n", " const headHtml = await $fetch('/head')\n", " expect(headHtml).toContain('<title>Using a dynamic component - Title Template Fn Change</title>')\n", " expect(headHtml).not.toContain('<meta name=\"description\" content=\"first\">')\n", " expect(headHtml).toContain('<meta charset=\"utf-16\">')\n", " expect(headHtml).not.toContain('<meta charset=\"utf-8\">')\n", " expect(headHtml).toContain('<meta name=\"description\" content=\"overriding with an inline useHead call\">')\n", " expect(headHtml).toMatch(/<html[^>]*class=\"html-attrs-test\"/)\n", " expect(headHtml).toMatch(/<body[^>]*class=\"body-attrs-test\"/)\n", " expect(headHtml).toContain('script>console.log(\"works with useMeta too\")</script>')\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(headHtml.match('meta charset').length).toEqual(1)\n", " expect(headHtml).toContain('<meta name=\"viewport\" content=\"width=1024, initial-scale=1\">')\n", " expect(headHtml.match('meta name=\"viewport\"').length).toEqual(1)\n" ], "file_path": "test/basic.test.ts", "type": "add", "edit_start_line_idx": 140 }
import os from 'node:os' import { existsSync, readFileSync } from 'node:fs' import { createRequire } from 'node:module' import { resolve } from 'pathe' import jiti from 'jiti' import destr from 'destr' import { splitByCase } from 'scule' import clipboardy from 'clipboardy' import { getPackageManager, getPackageManagerVersion } from '../utils/packageManagers' import { findup } from '../utils/fs' import { defineNuxtCommand } from './index' export default defineNuxtCommand({ meta: { name: 'info', usage: 'npx nuxi info [rootDir]', description: 'Get information about nuxt project' }, async invoke (args) { // Resolve rootDir const rootDir = resolve(args._[0] || '.') // Load nuxt.config const nuxtConfig = getNuxtConfig(rootDir) // Find nearest package.json const { dependencies = {}, devDependencies = {} } = findPackage(rootDir) // Utils to query a dependency version const getDepVersion = name => getPkg(name, rootDir)?.version || dependencies[name] || devDependencies[name] const listModules = (arr = []) => arr .map(normalizeConfigModule) .filter(Boolean) .map((name) => { const npmName = name.split('/').splice(0, 2).join('/') // @foo/bar/baz => @foo/bar const v = getDepVersion(npmName) return '`' + (v ? `${name}@${v}` : name) + '`' }) .join(', ') // Check nuxt version const nuxtVersion = getDepVersion('nuxt') || getDepVersion('nuxt-edge') || getDepVersion('nuxt3') || '0.0.0' const isNuxt3 = nuxtVersion.startsWith('3') const builder = isNuxt3 ? nuxtConfig.builder /* latest schema */ || (nuxtConfig.vite !== false ? 'vite' : 'webpack') /* previous schema */ : nuxtConfig.bridge?.vite ? 'vite' /* bridge vite implementation */ : (nuxtConfig.buildModules?.includes('nuxt-vite') ? 'vite' /* nuxt-vite */ : 'webpack') let packageManager = getPackageManager(rootDir) if (packageManager) { packageManager += '@' + getPackageManagerVersion(packageManager) } else { packageManager = 'unknown' } const infoObj = { OperatingSystem: os.type(), NodeVersion: process.version, NuxtVersion: nuxtVersion, PackageManager: packageManager, Builder: builder, UserConfig: Object.keys(nuxtConfig).map(key => '`' + key + '`').join(', '), RuntimeModules: listModules(nuxtConfig.modules), BuildModules: listModules(nuxtConfig.buildModules) } console.log('RootDir:', rootDir) let maxLength = 0 const entries = Object.entries(infoObj).map(([key, val]) => { const label = splitByCase(key).join(' ') if (label.length > maxLength) { maxLength = label.length } return [label, val || '-'] }) let infoStr = '' for (const [label, value] of entries) { infoStr += '- ' + (label + ': ').padEnd(maxLength + 2) + (value.includes('`') ? value : '`' + value + '`') + '\n' } const copied = await clipboardy.write(infoStr).then(() => true).catch(() => false) const splitter = '------------------------------' console.log(`Nuxt project info: ${copied ? '(copied to clipboard)' : ''}\n\n${splitter}\n${infoStr}${splitter}\n`) const isNuxt3OrBridge = infoObj.NuxtVersion.startsWith('3') || infoObj.BuildModules.includes('bridge') const repo = isNuxt3OrBridge ? 'nuxt/framework' : 'nuxt/nuxt.js' console.log([ `πŸ‘‰ Report an issue: https://github.com/${repo}/issues/new`, `πŸ‘‰ Suggest an improvement: https://github.com/${repo}/discussions/new`, `πŸ‘‰ Read documentation: ${isNuxt3OrBridge ? 'https://v3.nuxtjs.org' : 'https://nuxtjs.org'}` ].join('\n\n') + '\n') } }) function normalizeConfigModule (module, rootDir) { if (!module) { return null } if (typeof module === 'string') { return module .split(rootDir).pop() // Strip rootDir .split('node_modules').pop() // Strip node_modules .replace(/^\//, '') } if (typeof module === 'function') { return `${module.name}()` } if (Array.isArray(module)) { return normalizeConfigModule(module[0], rootDir) } } function getNuxtConfig (rootDir) { try { return jiti(rootDir, { interopDefault: true, esmResolve: true })('./nuxt.config') } catch (err) { // TODO: Show error as warning if it is not 404 return {} } } function getPkg (name, rootDir) { // Assume it is in {rootDir}/node_modules/${name}/package.json let pkgPath = resolve(rootDir, 'node_modules', name, 'package.json') // Try to resolve for more accuracy const _require = createRequire(rootDir) try { pkgPath = _require.resolve(name + '/package.json') } catch (_err) { // console.log('not found:', name) } return readJSONSync(pkgPath) } function findPackage (rootDir) { return findup(rootDir, (dir) => { const p = resolve(dir, 'package.json') if (existsSync(p)) { return readJSONSync(p) } }) || {} } function readJSONSync (filePath) { try { return destr(readFileSync(filePath, 'utf-8')) } catch (err) { // TODO: Warn error return null } }
packages/nuxi/src/commands/info.ts
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017737621965352446, 0.0001728030911181122, 0.00016622079419903457, 0.0001731270895106718, 0.0000031788138130650623 ]
{ "id": 8, "code_window": [ "import { defineNuxtConfig } from 'nuxt'\n", "import { addComponent } from '@nuxt/kit'\n", "\n", "export default defineNuxtConfig({\n", " buildDir: process.env.NITRO_BUILD_DIR,\n", " builder: process.env.TEST_WITH_WEBPACK ? 'webpack' : 'vite',\n", " extends: [\n", " './extends/bar',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " app: {\n", " head: {\n", " charset: 'utf-8',\n", " link: [undefined],\n", " meta: [{ name: 'viewport', content: 'width=1024, initial-scale=1' }, { charset: 'utf-8' }]\n", " }\n", " },\n" ], "file_path": "test/fixtures/basic/nuxt.config.ts", "type": "add", "edit_start_line_idx": 4 }
import { resolve } from 'pathe' import { addPlugin, addTemplate, defineNuxtModule } from '@nuxt/kit' import defu from 'defu' import { distDir } from '../dirs' import type { MetaObject } from './runtime' export default defineNuxtModule({ meta: { name: 'meta' }, defaults: { charset: 'utf-8', viewport: 'width=device-width, initial-scale=1' }, setup (options, nuxt) { const runtimeDir = nuxt.options.alias['#head'] || resolve(distDir, 'head/runtime') // Transpile @nuxt/meta and @vueuse/head nuxt.options.build.transpile.push('@vueuse/head') // Add #head alias nuxt.options.alias['#head'] = runtimeDir // Global meta -for Bridge, this is necessary to repeat here // and in packages/schema/src/config/_app.ts const globalMeta: MetaObject = defu(nuxt.options.app.head, { charset: options.charset, viewport: options.viewport }) // Add global meta configuration addTemplate({ filename: 'meta.config.mjs', getContents: () => 'export default ' + JSON.stringify({ globalMeta }) }) // Add generic plugin addPlugin({ src: resolve(runtimeDir, 'plugin') }) // Add library specific plugin addPlugin({ src: resolve(runtimeDir, 'lib/vueuse-head.plugin') }) } })
packages/nuxt/src/head/module.ts
1
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.012488341890275478, 0.002653398085385561, 0.00016541506920475513, 0.00020494670025072992, 0.004917535465210676 ]
{ "id": 8, "code_window": [ "import { defineNuxtConfig } from 'nuxt'\n", "import { addComponent } from '@nuxt/kit'\n", "\n", "export default defineNuxtConfig({\n", " buildDir: process.env.NITRO_BUILD_DIR,\n", " builder: process.env.TEST_WITH_WEBPACK ? 'webpack' : 'vite',\n", " extends: [\n", " './extends/bar',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " app: {\n", " head: {\n", " charset: 'utf-8',\n", " link: [undefined],\n", " meta: [{ name: 'viewport', content: 'width=1024, initial-scale=1' }, { charset: 'utf-8' }]\n", " }\n", " },\n" ], "file_path": "test/fixtures/basic/nuxt.config.ts", "type": "add", "edit_start_line_idx": 4 }
<template> <div> Home </div> </template>
examples/routing/middleware/pages/index.vue
0
https://github.com/nuxt/nuxt/commit/fc1d7d9507ace207c8c748642ba389ace54b845f
[ 0.00017377578478772193, 0.00017377578478772193, 0.00017377578478772193, 0.00017377578478772193, 0 ]