hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 9,
"code_window": [
" with page.expect_download() as download_info:\n",
" page.click(\\\"text=Download\\\")\n",
" download = download_info.value`);\n",
"\n",
" expect(sources.get('<async python>').text).toContain(`\n",
" # Click text=Download\n",
" async with page.expect_download() as download_info:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(sources.get('<async python>').text).toContain(`\n",
" context = await browser.new_context(accept_downloads=True)`);\n"
],
"file_path": "tests/inspector/cli-codegen-2.spec.ts",
"type": "add",
"edit_start_line_idx": 271
} | #!/usr/bin/python
import sys
import json
if len(sys.argv) < 2:
print("ERROR: expected arch: 32bit or 64bit")
sys.exit(1)
if str(sys.argv[1]) == "--help" or str(sys.argv[1]) == "-h":
print("Usage: read_files.py [32bit|64bit] <files.cfg path>")
sys.exit(1)
if len(sys.argv) < 3:
print("ERROR: expected FILE.cfg path")
sys.exit(1)
exclude_list = [
# Windows exclude list
"chrome_child.dll",
"gaia1_0.dll",
"gcp_setup.exe",
"icudt.dll",
"interactive_ui_tests.exe",
"*.manifest",
# Linux exclude list
"session",
]
target_arch = sys.argv[1]
file_name = sys.argv[2]
descriptors=[]
if sys.version_info > (3, 0):
exec(open(file_name).read())
descriptors = FILES
else:
variables = {}
execfile(file_name, variables)
descriptors = variables['FILES']
def filter_descriptors(entry):
if 'archive' in entry:
return False
if not 'buildtype' in entry:
return False
if not 'dev' in entry['buildtype']:
return False
if ('arch' in entry) and (entry['arch'] != target_arch):
return False
if entry['filename'] in exclude_list:
return False
return True
for entry in filter(filter_descriptors, descriptors):
print(entry['filename'])
| browser_patches/chromium/compute_files_to_archive.py | 0 | https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0 | [
0.0001778224395820871,
0.00017405953258275986,
0.00016621730173937976,
0.00017507592565380037,
0.000003960691174142994
] |
{
"id": 9,
"code_window": [
" with page.expect_download() as download_info:\n",
" page.click(\\\"text=Download\\\")\n",
" download = download_info.value`);\n",
"\n",
" expect(sources.get('<async python>').text).toContain(`\n",
" # Click text=Download\n",
" async with page.expect_download() as download_info:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(sources.get('<async python>').text).toContain(`\n",
" context = await browser.new_context(accept_downloads=True)`);\n"
],
"file_path": "tests/inspector/cli-codegen-2.spec.ts",
"type": "add",
"edit_start_line_idx": 271
} | /**
* Copyright 2018 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.
*/
import { test as it, expect } from './pageTest';
it.skip(({ isAndroid }) => isAndroid);
it('should work', async ({ page, server, browserName, headless }) => {
it.fail(browserName === 'firefox' && !headless);
await page.setViewportSize({ width: 500, height: 500 });
await page.goto(server.PREFIX + '/grid.html');
const elementHandle = await page.$('.box:nth-of-type(13)');
const box = await elementHandle.boundingBox();
expect(box).toEqual({ x: 100, y: 50, width: 50, height: 50 });
});
it('should handle nested frames', async ({ page, server }) => {
await page.setViewportSize({ width: 500, height: 500 });
await page.goto(server.PREFIX + '/frames/nested-frames.html');
const nestedFrame = page.frames().find(frame => frame.name() === 'dos');
const elementHandle = await nestedFrame.$('div');
const box = await elementHandle.boundingBox();
expect(box).toEqual({ x: 24, y: 224, width: 268, height: 18 });
});
it('should handle scroll offset and click', async ({ page, server }) => {
await page.setContent(`
<style>* { margin: 0; padding: 0; }</style>
<div style="width:8000px; height:8000px;">
<div id=target style="width:20px; height:20px; margin-left:230px; margin-top:340px;"
onclick="window.__clicked = true">
</div>
</div>
`);
const elementHandle = await page.$('#target');
const box1 = await elementHandle.boundingBox();
await page.evaluate(() => window.scrollBy(200, 300));
const box2 = await elementHandle.boundingBox();
expect(box1).toEqual({ x: 230, y: 340, width: 20, height: 20 });
expect(box2).toEqual({ x: 30, y: 40, width: 20, height: 20 });
await page.mouse.click(box2.x + 10, box2.y + 10);
expect(await page.evaluate(() => window['__clicked'])).toBe(true);
});
it('should return null for invisible elements', async ({ page, server }) => {
await page.setContent('<div style="display:none">hi</div>');
const element = await page.$('div');
expect(await element.boundingBox()).toBe(null);
});
it('should force a layout', async ({ page, server }) => {
await page.setViewportSize({ width: 500, height: 500 });
await page.setContent('<div style="width: 100px; height: 100px">hello</div>');
const elementHandle = await page.$('div');
await page.evaluate(element => element.style.height = '200px', elementHandle);
const box = await elementHandle.boundingBox();
expect(box).toEqual({ x: 8, y: 8, width: 100, height: 200 });
});
it('should work with SVG nodes', async ({ page, server }) => {
await page.setContent(`
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
<rect id="theRect" x="30" y="50" width="200" height="300"></rect>
</svg>
`);
const element = await page.$('#therect');
const pwBoundingBox = await element.boundingBox();
const webBoundingBox = await page.evaluate(e => {
const rect = e.getBoundingClientRect();
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
}, element);
expect(pwBoundingBox).toEqual(webBoundingBox);
});
it('should work when inline box child is outside of viewport', async ({ page, server }) => {
await page.setContent(`
<style>
i {
position: absolute;
top: -1000px;
}
body {
margin: 0;
font-size: 12px;
}
</style>
<span><i>woof</i><b>doggo</b></span>
`);
const handle = await page.$('span');
const box = await handle.boundingBox();
const webBoundingBox = await handle.evaluate(e => {
const rect = e.getBoundingClientRect();
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
});
const round = box => ({
x: Math.round(box.x * 100),
y: Math.round(box.y * 100),
width: Math.round(box.width * 100),
height: Math.round(box.height * 100),
});
expect(round(box)).toEqual(round(webBoundingBox));
});
| tests/page/elementhandle-bounding-box.spec.ts | 0 | https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0 | [
0.00025804381584748626,
0.000185743672773242,
0.0001650473423069343,
0.00017571524949744344,
0.000028303165890974924
] |
{
"id": 10,
"code_window": [
" async with page.expect_download() as download_info:\n",
" await page.click(\\\"text=Download\\\")\n",
" download = await download_info.value`);\n",
"\n",
" expect(sources.get('<csharp>').text).toContain(`\n",
" // Click text=Download\n",
" var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(sources.get('<csharp>').text).toContain(`\n",
" var context = await browser.NewContextAsync(new BrowserNewContextOptions\n",
" {\n",
" AcceptDownloads = true,\n",
" });`);\n"
],
"file_path": "tests/inspector/cli-codegen-2.spec.ts",
"type": "add",
"edit_start_line_idx": 277
} | /**
* 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.
*/
import { test, expect } from './inspectorTest';
import * as url from 'url';
test.describe('cli codegen', () => {
test.skip(({ mode }) => mode !== 'default');
test('should contain open page', async ({ openRecorder }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(``);
const sources = await recorder.waitForOutput('<javascript>', `page.goto`);
expect(sources.get('<javascript>').text).toContain(`
// Open new page
const page = await context.newPage();`);
expect(sources.get('<java>').text).toContain(`
// Open new page
Page page = context.newPage();`);
expect(sources.get('<python>').text).toContain(`
# Open new page
page = context.new_page()`);
expect(sources.get('<async python>').text).toContain(`
# Open new page
page = await context.new_page()`);
expect(sources.get('<csharp>').text).toContain(`
// Open new page
var page = await context.NewPageAsync();`);
});
test('should contain second page', async ({ openRecorder, page }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(``);
await page.context().newPage();
const sources = await recorder.waitForOutput('<javascript>', 'page1');
expect(sources.get('<javascript>').text).toContain(`
// Open new page
const page1 = await context.newPage();`);
expect(sources.get('<java>').text).toContain(`
// Open new page
Page page1 = context.newPage();`);
expect(sources.get('<python>').text).toContain(`
# Open new page
page1 = context.new_page()`);
expect(sources.get('<async python>').text).toContain(`
# Open new page
page1 = await context.new_page()`);
expect(sources.get('<csharp>').text).toContain(`
// Open new page
var page1 = await context.NewPageAsync();`);
});
test('should contain close page', async ({ openRecorder, page }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(``);
await page.context().newPage();
await recorder.page.close();
const sources = await recorder.waitForOutput('<javascript>', 'page.close();');
expect(sources.get('<javascript>').text).toContain(`
await page.close();`);
expect(sources.get('<java>').text).toContain(`
page.close();`);
expect(sources.get('<python>').text).toContain(`
page.close()`);
expect(sources.get('<async python>').text).toContain(`
await page.close()`);
expect(sources.get('<csharp>').text).toContain(`
await page.CloseAsync();`);
});
test('should not lead to an error if html gets clicked', async ({ page, openRecorder }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait('');
await page.context().newPage();
const errors: any[] = [];
recorder.page.on('pageerror', e => errors.push(e));
await recorder.page.evaluate(() => document.querySelector('body').remove());
const selector = await recorder.hoverOverElement('html');
expect(selector).toBe('html');
await recorder.page.close();
await recorder.waitForOutput('<javascript>', 'page.close();');
expect(errors.length).toBe(0);
});
test('should upload a single file', async ({ page, openRecorder, browserName, asset }) => {
test.fixme(browserName === 'firefox', 'Hangs');
const recorder = await openRecorder();
await recorder.setContentAndWait(`
<form>
<input type="file">
</form>
`);
await page.focus('input[type=file]');
await page.setInputFiles('input[type=file]', asset('file-to-upload.txt'));
await page.click('input[type=file]');
const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles');
expect(sources.get('<javascript>').text).toContain(`
// Upload file-to-upload.txt
await page.setInputFiles('input[type="file"]', 'file-to-upload.txt');`);
expect(sources.get('<java>').text).toContain(`
// Upload file-to-upload.txt
page.setInputFiles("input[type=\\\"file\\\"]", Paths.get("file-to-upload.txt"));`);
expect(sources.get('<python>').text).toContain(`
# Upload file-to-upload.txt
page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`);
expect(sources.get('<async python>').text).toContain(`
# Upload file-to-upload.txt
await page.set_input_files(\"input[type=\\\"file\\\"]\", \"file-to-upload.txt\")`);
expect(sources.get('<csharp>').text).toContain(`
// Upload file-to-upload.txt
await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\" });`);
});
test('should upload multiple files', async ({ page, openRecorder, browserName, asset }) => {
test.fixme(browserName === 'firefox', 'Hangs');
const recorder = await openRecorder();
await recorder.setContentAndWait(`
<form>
<input type="file" multiple>
</form>
`);
await page.focus('input[type=file]');
await page.setInputFiles('input[type=file]', [asset('file-to-upload.txt'), asset('file-to-upload-2.txt')]);
await page.click('input[type=file]');
const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles');
expect(sources.get('<javascript>').text).toContain(`
// Upload file-to-upload.txt, file-to-upload-2.txt
await page.setInputFiles('input[type=\"file\"]', ['file-to-upload.txt', 'file-to-upload-2.txt']);`);
expect(sources.get('<java>').text).toContain(`
// Upload file-to-upload.txt, file-to-upload-2.txt
page.setInputFiles("input[type=\\\"file\\\"]", new Path[] {Paths.get("file-to-upload.txt"), Paths.get("file-to-upload-2.txt")});`);
expect(sources.get('<python>').text).toContain(`
# Upload file-to-upload.txt, file-to-upload-2.txt
page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`);
expect(sources.get('<async python>').text).toContain(`
# Upload file-to-upload.txt, file-to-upload-2.txt
await page.set_input_files(\"input[type=\\\"file\\\"]\", [\"file-to-upload.txt\", \"file-to-upload-2.txt\"]`);
expect(sources.get('<csharp>').text).toContain(`
// Upload file-to-upload.txt, file-to-upload-2.txt
await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { \"file-to-upload.txt\", \"file-to-upload-2.txt\" });`);
});
test('should clear files', async ({ page, openRecorder, browserName, asset }) => {
test.fixme(browserName === 'firefox', 'Hangs');
const recorder = await openRecorder();
await recorder.setContentAndWait(`
<form>
<input type="file" multiple>
</form>
`);
await page.focus('input[type=file]');
await page.setInputFiles('input[type=file]', asset('file-to-upload.txt'));
await page.setInputFiles('input[type=file]', []);
await page.click('input[type=file]');
const sources = await recorder.waitForOutput('<javascript>', 'setInputFiles');
expect(sources.get('<javascript>').text).toContain(`
// Clear selected files
await page.setInputFiles('input[type=\"file\"]', []);`);
expect(sources.get('<java>').text).toContain(`
// Clear selected files
page.setInputFiles("input[type=\\\"file\\\"]", new Path[0]);`);
expect(sources.get('<python>').text).toContain(`
# Clear selected files
page.set_input_files(\"input[type=\\\"file\\\"]\", []`);
expect(sources.get('<async python>').text).toContain(`
# Clear selected files
await page.set_input_files(\"input[type=\\\"file\\\"]\", []`);
expect(sources.get('<csharp>').text).toContain(`
// Clear selected files
await page.SetInputFilesAsync(\"input[type=\\\"file\\\"]\", new[] { });`);
});
test('should download files', async ({ page, openRecorder, server }) => {
const recorder = await openRecorder();
server.setRoute('/download', (req, res) => {
const pathName = url.parse(req.url!).path;
if (pathName === '/download') {
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment; filename=file.txt');
res.end(`Hello world`);
} else {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end('');
}
});
await recorder.setContentAndWait(`
<a href="${server.PREFIX}/download" download>Download</a>
`, server.PREFIX);
await recorder.hoverOverElement('text=Download');
await Promise.all([
page.waitForEvent('download'),
page.click('text=Download')
]);
const sources = await recorder.waitForOutput('<javascript>', 'waitForEvent');
expect(sources.get('<javascript>').text).toContain(`
// Click text=Download
const [download] = await Promise.all([
page.waitForEvent('download'),
page.click('text=Download')
]);`);
expect(sources.get('<java>').text).toContain(`
// Click text=Download
Download download = page.waitForDownload(() -> {
page.click("text=Download");
});`);
expect(sources.get('<python>').text).toContain(`
# Click text=Download
with page.expect_download() as download_info:
page.click(\"text=Download\")
download = download_info.value`);
expect(sources.get('<async python>').text).toContain(`
# Click text=Download
async with page.expect_download() as download_info:
await page.click(\"text=Download\")
download = await download_info.value`);
expect(sources.get('<csharp>').text).toContain(`
// Click text=Download
var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () =>
{
await page.ClickAsync(\"text=Download\");
});`);
});
test('should handle dialogs', async ({ page, openRecorder }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(`
<button onclick="alert()">click me</button>
`);
await recorder.hoverOverElement('button');
page.once('dialog', async dialog => {
await dialog.dismiss();
});
await page.click('text=click me');
const sources = await recorder.waitForOutput('<javascript>', 'once');
expect(sources.get('<javascript>').text).toContain(`
// Click text=click me
page.once('dialog', dialog => {
console.log(\`Dialog message: \${dialog.message()}\`);
dialog.dismiss().catch(() => {});
});
await page.click('text=click me');`);
expect(sources.get('<java>').text).toContain(`
// Click text=click me
page.onceDialog(dialog -> {
System.out.println(String.format("Dialog message: %s", dialog.message()));
dialog.dismiss();
});
page.click("text=click me");`);
expect(sources.get('<python>').text).toContain(`
# Click text=click me
page.once(\"dialog\", lambda dialog: dialog.dismiss())
page.click(\"text=click me\")`);
expect(sources.get('<async python>').text).toContain(`
# Click text=click me
page.once(\"dialog\", lambda dialog: dialog.dismiss())
await page.click(\"text=click me\")`);
expect(sources.get('<csharp>').text).toContain(`
// Click text=click me
void page_Dialog1_EventHandler(object sender, IDialog dialog)
{
Console.WriteLine($\"Dialog message: {dialog.Message}\");
dialog.DismissAsync();
page.Dialog -= page_Dialog1_EventHandler;
}
page.Dialog += page_Dialog1_EventHandler;
await page.ClickAsync(\"text=click me\");`);
});
test('should handle history.postData', async ({ page, openRecorder, server }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(`
<script>
let seqNum = 0;
function pushState() {
history.pushState({}, 'title', '${server.PREFIX}/#seqNum=' + (++seqNum));
}
</script>`, server.PREFIX);
for (let i = 1; i < 3; ++i) {
await page.evaluate('pushState()');
await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/#seqNum=${i}');`);
}
});
test('should record open in a new tab with url', async ({ page, openRecorder, browserName, platform }) => {
test.fixme(browserName === 'webkit', 'Ctrl+click does not open in new tab on WebKit');
const recorder = await openRecorder();
await recorder.setContentAndWait(`<a href="about:blank?foo">link</a>`);
const selector = await recorder.hoverOverElement('a');
expect(selector).toBe('text=link');
await page.click('a', { modifiers: [ platform === 'darwin' ? 'Meta' : 'Control'] });
const sources = await recorder.waitForOutput('<javascript>', 'page1');
if (browserName === 'chromium') {
expect(sources.get('<javascript>').text).toContain(`
// Open new page
const page1 = await context.newPage();
await page1.goto('about:blank?foo');`);
expect(sources.get('<async python>').text).toContain(`
# Open new page
page1 = await context.new_page()
await page1.goto("about:blank?foo")`);
expect(sources.get('<csharp>').text).toContain(`
// Open new page
var page1 = await context.NewPageAsync();
await page1.GotoAsync("about:blank?foo");`);
} else if (browserName === 'firefox') {
expect(sources.get('<javascript>').text).toContain(`
// Click text=link
const [page1] = await Promise.all([
page.waitForEvent('popup'),
page.click('text=link', {
modifiers: ['${platform === 'darwin' ? 'Meta' : 'Control'}']
})
]);`);
}
});
test('should not clash pages', async ({ page, openRecorder, browserName }) => {
test.fixme(browserName === 'firefox', 'Times out on Firefox, maybe the focus issue');
const recorder = await openRecorder();
const [popup1] = await Promise.all([
page.context().waitForEvent('page'),
page.evaluate(`window.open('about:blank')`)
]);
await recorder.setPageContentAndWait(popup1, '<input id=name>');
const [popup2] = await Promise.all([
page.context().waitForEvent('page'),
page.evaluate(`window.open('about:blank')`)
]);
await recorder.setPageContentAndWait(popup2, '<input id=name>');
await popup1.type('input', 'TextA');
await recorder.waitForOutput('<javascript>', 'TextA');
await popup2.type('input', 'TextB');
await recorder.waitForOutput('<javascript>', 'TextB');
const sources = recorder.sources();
expect(sources.get('<javascript>').text).toContain(`await page1.fill('input', 'TextA');`);
expect(sources.get('<javascript>').text).toContain(`await page2.fill('input', 'TextB');`);
expect(sources.get('<java>').text).toContain(`page1.fill("input", "TextA");`);
expect(sources.get('<java>').text).toContain(`page2.fill("input", "TextB");`);
expect(sources.get('<python>').text).toContain(`page1.fill(\"input\", \"TextA\")`);
expect(sources.get('<python>').text).toContain(`page2.fill(\"input\", \"TextB\")`);
expect(sources.get('<async python>').text).toContain(`await page1.fill(\"input\", \"TextA\")`);
expect(sources.get('<async python>').text).toContain(`await page2.fill(\"input\", \"TextB\")`);
expect(sources.get('<csharp>').text).toContain(`await page1.FillAsync(\"input\", \"TextA\");`);
expect(sources.get('<csharp>').text).toContain(`await page2.FillAsync(\"input\", \"TextB\");`);
});
test('click should emit events in order', async ({ page, openRecorder }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(`
<button id=button>
<script>
button.addEventListener('mousedown', e => console.log(e.type));
button.addEventListener('mouseup', e => console.log(e.type));
button.addEventListener('click', e => console.log(e.type));
</script>
`);
const messages: any[] = [];
page.on('console', message => {
if (message.type() !== 'error')
messages.push(message.text());
});
await Promise.all([
page.click('button'),
recorder.waitForOutput('<javascript>', 'page.click')
]);
expect(messages).toEqual(['mousedown', 'mouseup', 'click']);
});
test('should update hover model on action', async ({ page, openRecorder }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`);
const [ models ] = await Promise.all([
recorder.waitForActionPerformed(),
page.click('input')
]);
expect(models.hovered).toBe('input[name="updated"]');
});
test('should update active model on action', async ({ page, openRecorder, browserName, headless }) => {
test.fixme(browserName === 'webkit' && headless);
test.fixme(browserName === 'firefox' && headless);
const recorder = await openRecorder();
await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name='updated'"></input>`);
const [ models ] = await Promise.all([
recorder.waitForActionPerformed(),
page.click('input')
]);
expect(models.active).toBe('input[name="updated"]');
});
test('should check input with chaning id', async ({ page, openRecorder }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="checkbox.name = 'updated'"></input>`);
await Promise.all([
recorder.waitForActionPerformed(),
page.click('input[id=checkbox]')
]);
});
test('should prefer frame name', async ({ page, openRecorder, server }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(`
<iframe src='./frames/frame.html' name='one'></iframe>
<iframe src='./frames/frame.html' name='two'></iframe>
<iframe src='./frames/frame.html'></iframe>
`, server.EMPTY_PAGE, 4);
const frameOne = page.frame({ name: 'one' });
const frameTwo = page.frame({ name: 'two' });
const otherFrame = page.frames().find(f => f !== page.mainFrame() && !f.name());
let [sources] = await Promise.all([
recorder.waitForOutput('<javascript>', 'one'),
frameOne.click('div'),
]);
expect(sources.get('<javascript>').text).toContain(`
// Click text=Hi, I'm frame
await page.frame({
name: 'one'
}).click('text=Hi, I\\'m frame');`);
expect(sources.get('<java>').text).toContain(`
// Click text=Hi, I'm frame
page.frame("one").click("text=Hi, I'm frame");`);
expect(sources.get('<python>').text).toContain(`
# Click text=Hi, I'm frame
page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`);
expect(sources.get('<async python>').text).toContain(`
# Click text=Hi, I'm frame
await page.frame(name=\"one\").click(\"text=Hi, I'm frame\")`);
expect(sources.get('<csharp>').text).toContain(`
// Click text=Hi, I'm frame
await page.Frame(\"one\").ClickAsync(\"text=Hi, I'm frame\");`);
[sources] = await Promise.all([
recorder.waitForOutput('<javascript>', 'two'),
frameTwo.click('div'),
]);
expect(sources.get('<javascript>').text).toContain(`
// Click text=Hi, I'm frame
await page.frame({
name: 'two'
}).click('text=Hi, I\\'m frame');`);
expect(sources.get('<java>').text).toContain(`
// Click text=Hi, I'm frame
page.frame("two").click("text=Hi, I'm frame");`);
expect(sources.get('<python>').text).toContain(`
# Click text=Hi, I'm frame
page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`);
expect(sources.get('<async python>').text).toContain(`
# Click text=Hi, I'm frame
await page.frame(name=\"two\").click(\"text=Hi, I'm frame\")`);
expect(sources.get('<csharp>').text).toContain(`
// Click text=Hi, I'm frame
await page.Frame(\"two\").ClickAsync(\"text=Hi, I'm frame\");`);
[sources] = await Promise.all([
recorder.waitForOutput('<javascript>', 'url: \''),
otherFrame.click('div'),
]);
expect(sources.get('<javascript>').text).toContain(`
// Click text=Hi, I'm frame
await page.frame({
url: 'http://localhost:${server.PORT}/frames/frame.html'
}).click('text=Hi, I\\'m frame');`);
expect(sources.get('<java>').text).toContain(`
// Click text=Hi, I'm frame
page.frameByUrl("http://localhost:${server.PORT}/frames/frame.html").click("text=Hi, I'm frame");`);
expect(sources.get('<python>').text).toContain(`
# Click text=Hi, I'm frame
page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`);
expect(sources.get('<async python>').text).toContain(`
# Click text=Hi, I'm frame
await page.frame(url=\"http://localhost:${server.PORT}/frames/frame.html\").click(\"text=Hi, I'm frame\")`);
expect(sources.get('<csharp>').text).toContain(`
// Click text=Hi, I'm frame
await page.FrameByUrl(\"http://localhost:${server.PORT}/frames/frame.html\").ClickAsync(\"text=Hi, I'm frame\");`);
});
test('should record navigations after identical pushState', async ({ page, openRecorder, server }) => {
const recorder = await openRecorder();
server.setRoute('/page2.html', (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end('Hello world');
});
await recorder.setContentAndWait(`
<script>
function pushState() {
history.pushState({}, 'title', '${server.PREFIX}');
}
</script>`, server.PREFIX);
for (let i = 1; i < 3; ++i)
await page.evaluate('pushState()');
await page.goto(server.PREFIX + '/page2.html');
await recorder.waitForOutput('<javascript>', `await page.goto('${server.PREFIX}/page2.html');`);
});
test('should record slow navigation signal after mouse move', async ({ page, openRecorder, server }) => {
const recorder = await openRecorder();
await recorder.setContentAndWait(`
<script>
async function onClick() {
await new Promise(f => setTimeout(f, 100));
await window.letTheMouseMove();
window.location = ${JSON.stringify(server.EMPTY_PAGE)};
}
</script>
<button onclick="onClick()">Click me</button>
`);
await page.exposeBinding('letTheMouseMove', async () => {
await page.mouse.move(200, 200);
});
const [, sources] = await Promise.all([
// This will click, finish the click, then mouse move, then navigate.
page.click('button'),
recorder.waitForOutput('<javascript>', 'waitForNavigation'),
]);
expect(sources.get('<javascript>').text).toContain(`page.waitForNavigation(/*{ url: '${server.EMPTY_PAGE}' }*/)`);
});
});
| tests/inspector/cli-codegen-2.spec.ts | 1 | https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0 | [
0.9982656836509705,
0.031590986996889114,
0.00016430213872808963,
0.000989557127468288,
0.16331425309181213
] |
{
"id": 10,
"code_window": [
" async with page.expect_download() as download_info:\n",
" await page.click(\\\"text=Download\\\")\n",
" download = await download_info.value`);\n",
"\n",
" expect(sources.get('<csharp>').text).toContain(`\n",
" // Click text=Download\n",
" var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(sources.get('<csharp>').text).toContain(`\n",
" var context = await browser.NewContextAsync(new BrowserNewContextOptions\n",
" {\n",
" AcceptDownloads = true,\n",
" });`);\n"
],
"file_path": "tests/inspector/cli-codegen-2.spec.ts",
"type": "add",
"edit_start_line_idx": 277
} | /**
* 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.
*/
import { playwrightTest as it, expect } from './config/browserTest';
import fs from 'fs';
import path from 'path';
it.describe('downloads path', () => {
it.beforeEach(async ({server}) => {
server.setRoute('/download', (req, res) => {
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment; filename=file.txt');
res.end(`Hello world`);
});
});
it('should keep downloadsPath folder', async ({browserType, browserOptions, server}, testInfo) => {
const downloadsBrowser = await browserType.launch({ ...browserOptions, downloadsPath: testInfo.outputPath('') });
const page = await downloadsBrowser.newPage();
await page.setContent(`<a href="${server.PREFIX}/download">download</a>`);
const [ download ] = await Promise.all([
page.waitForEvent('download'),
page.click('a')
]);
expect(download.url()).toBe(`${server.PREFIX}/download`);
expect(download.suggestedFilename()).toBe(`file.txt`);
await download.path().catch(e => void 0);
await page.close();
await downloadsBrowser.close();
expect(fs.existsSync(testInfo.outputPath(''))).toBeTruthy();
});
it('should delete downloads when context closes', async ({browserType, browserOptions, server}, testInfo) => {
const downloadsBrowser = await browserType.launch({ ...browserOptions, downloadsPath: testInfo.outputPath('') });
const page = await downloadsBrowser.newPage({ acceptDownloads: true });
await page.setContent(`<a href="${server.PREFIX}/download">download</a>`);
const [ download ] = await Promise.all([
page.waitForEvent('download'),
page.click('a')
]);
const path = await download.path();
expect(fs.existsSync(path)).toBeTruthy();
await page.close();
expect(fs.existsSync(path)).toBeFalsy();
await downloadsBrowser.close();
});
it('should report downloads in downloadsPath folder', async ({browserType, browserOptions, server}, testInfo) => {
const downloadsBrowser = await browserType.launch({ ...browserOptions, downloadsPath: testInfo.outputPath('') });
const page = await downloadsBrowser.newPage({ acceptDownloads: true });
await page.setContent(`<a href="${server.PREFIX}/download">download</a>`);
const [ download ] = await Promise.all([
page.waitForEvent('download'),
page.click('a')
]);
const path = await download.path();
expect(path.startsWith(testInfo.outputPath(''))).toBeTruthy();
await page.close();
await downloadsBrowser.close();
});
it('should report downloads in downloadsPath folder with a relative path', async ({browserType, browserOptions, server}, testInfo) => {
const downloadsBrowser = await browserType.launch({ ...browserOptions, downloadsPath: path.relative(process.cwd(), testInfo.outputPath('')) });
const page = await downloadsBrowser.newPage({ acceptDownloads: true });
await page.setContent(`<a href="${server.PREFIX}/download">download</a>`);
const [ download ] = await Promise.all([
page.waitForEvent('download'),
page.click('a')
]);
const downloadPath = await download.path();
expect(downloadPath.startsWith(testInfo.outputPath(''))).toBeTruthy();
await page.close();
await downloadsBrowser.close();
});
it('should accept downloads in persistent context', async ({launchPersistent, server}, testInfo) => {
const { context, page } = await launchPersistent({ acceptDownloads: true, downloadsPath: testInfo.outputPath('') });
await page.setContent(`<a href="${server.PREFIX}/download">download</a>`);
const [ download ] = await Promise.all([
page.waitForEvent('download'),
page.click('a'),
]);
expect(download.url()).toBe(`${server.PREFIX}/download`);
expect(download.suggestedFilename()).toBe(`file.txt`);
const path = await download.path();
expect(path.startsWith(testInfo.outputPath(''))).toBeTruthy();
await context.close();
});
it('should delete downloads when persistent context closes', async ({launchPersistent, server}, testInfo) => {
const { context, page } = await launchPersistent({ acceptDownloads: true, downloadsPath: testInfo.outputPath('') });
await page.setContent(`<a href="${server.PREFIX}/download">download</a>`);
const [ download ] = await Promise.all([
page.waitForEvent('download'),
page.click('a'),
]);
const path = await download.path();
expect(fs.existsSync(path)).toBeTruthy();
await context.close();
expect(fs.existsSync(path)).toBeFalsy();
});
});
| tests/downloads-path.spec.ts | 0 | https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0 | [
0.009530385956168175,
0.0034983931109309196,
0.00016750110080465674,
0.003512019058689475,
0.0030052363872528076
] |
{
"id": 10,
"code_window": [
" async with page.expect_download() as download_info:\n",
" await page.click(\\\"text=Download\\\")\n",
" download = await download_info.value`);\n",
"\n",
" expect(sources.get('<csharp>').text).toContain(`\n",
" // Click text=Download\n",
" var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(sources.get('<csharp>').text).toContain(`\n",
" var context = await browser.NewContextAsync(new BrowserNewContextOptions\n",
" {\n",
" AcceptDownloads = true,\n",
" });`);\n"
],
"file_path": "tests/inspector/cli-codegen-2.spec.ts",
"type": "add",
"edit_start_line_idx": 277
} | bin
obj
csx
.vs
edge
Publish
*.swp
*.user
*.suo
*.cscfg
*.Cache
project.lock.json
/packages
/TestResults
/tools/NuGet.exe
/App_Data
/secrets
/data
.secrets
appsettings.json
local.settings.json
node_modules
dist
# Local python packages
.python_packages/
# Python Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
| utils/flakiness-dashboard/.gitignore | 0 | https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0 | [
0.0001735378464218229,
0.0001707949850242585,
0.00016792648239061236,
0.00017178009147755802,
0.0000021377261418820126
] |
{
"id": 10,
"code_window": [
" async with page.expect_download() as download_info:\n",
" await page.click(\\\"text=Download\\\")\n",
" download = await download_info.value`);\n",
"\n",
" expect(sources.get('<csharp>').text).toContain(`\n",
" // Click text=Download\n",
" var download1 = await page.RunAndWaitForEventAsync(PageEvent.Download, async () =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(sources.get('<csharp>').text).toContain(`\n",
" var context = await browser.NewContextAsync(new BrowserNewContextOptions\n",
" {\n",
" AcceptDownloads = true,\n",
" });`);\n"
],
"file_path": "tests/inspector/cli-codegen-2.spec.ts",
"type": "add",
"edit_start_line_idx": 277
} | <svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
<style>
@media (prefers-color-scheme: dark) {
* { background-color: blue; }
}
</style>
<circle fill="red" cx="16" cy="16" r="12" />
</svg>
| tests/assets/media-query-prefers-color-scheme.svg | 0 | https://github.com/microsoft/playwright/commit/f529f0a25de1d66068639c59aa9205365e3b0be0 | [
0.00017461007519159466,
0.00017461007519159466,
0.00017461007519159466,
0.00017461007519159466,
0
] |
{
"id": 0,
"code_window": [
"import SeriesModel from '../../model/Series';\n",
"import { Dictionary } from '../../util/types';\n",
"import {\n",
" ModelFinderObject, ParsedModelFinder, ModelFinder,\n",
" parseFinder as modelUtilParseFinder,\n",
" ParsedModelFinderKnown\n",
"} from '../../util/model';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ModelFinderObject, ModelFinder,\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 38
} | /*
* 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 { each, indexOf, curry, assert, map, createHashMap } from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as brushHelper from './brushHelper';
import {
BrushPanelConfig, BrushControllerEvents, BrushType,
BrushAreaRange, BrushDimensionMinMax
} from './BrushController';
import ExtensionAPI from '../../core/ExtensionAPI';
import GridModel from '../../coord/cartesian/GridModel';
import GeoModel from '../../coord/geo/GeoModel';
import { CoordinateSystemMaster } from '../../coord/CoordinateSystem';
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Geo from '../../coord/geo/Geo';
import GlobalModel from '../../model/Global';
import { BrushAreaParam, BrushAreaParamInternal } from '../brush/BrushModel';
import SeriesModel from '../../model/Series';
import { Dictionary } from '../../util/types';
import {
ModelFinderObject, ParsedModelFinder, ModelFinder,
parseFinder as modelUtilParseFinder,
ParsedModelFinderKnown
} from '../../util/model';
const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;
type COORD_CONVERTS_INDEX = 0 | 1;
// FIXME
// how to genarialize to more coordinate systems.
const INCLUDE_FINDER_MAIN_TYPES = [
'grid', 'xAxis', 'yAxis', 'geo', 'graph',
'polar', 'radiusAxis', 'angleAxis', 'bmap'
];
type BrushableCoordinateSystem = Cartesian2D | Geo;
type BrushTargetBuilderKey = 'grid' | 'geo';
/**
* There can be multiple axes in a single targetInfo. Consider the case
* of `grid` component, a targetInfo represents a grid which contains one or more
* cartesian and one or more axes. And consider the case of parallel system,
* which has multiple axes in a coordinate system.
*/
interface BrushTargetInfo {
panelId: string;
coordSysModel: CoordinateSystemMaster['model'];
// Use the first one as the representitive coordSys.
// A representitive cartesian in grid (first cartesian by default).
coordSys: BrushableCoordinateSystem;
// All cartesians.
coordSyses: BrushableCoordinateSystem[];
getPanelRect: GetPanelRect,
}
export interface BrushTargetInfoCartesian2D extends BrushTargetInfo {
gridModel: GridModel;
coordSys: Cartesian2D;
coordSyses: Cartesian2D[];
xAxisDeclared: boolean;
yAxisDeclared: boolean;
}
export interface BrushTargetInfoGeo extends BrushTargetInfo {
geoModel: GeoModel,
coordSysModel: GeoModel,
coordSys: Geo,
coordSyses: Geo[],
}
type GetPanelRect = () => graphic.BoundingRect;
class BrushTargetManager {
private _targetInfoList: BrushTargetInfo[] = [];
/**
* @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
* Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
* @param opt.include include coordinate system types.
*/
constructor(
finder: ModelFinderObject,
ecModel: GlobalModel,
opt?: {include?: BrushTargetBuilderKey[]}
) {
const foundCpts = parseFinder(ecModel, finder);
each(targetInfoBuilders, (builder, type) => {
if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
builder(foundCpts, this._targetInfoList);
}
});
}
setOutputRanges(
areas: BrushControllerEvents['brush']['areas'],
ecModel: GlobalModel
): BrushAreaParam[] {
this.matchOutputRanges(areas, ecModel, function (
area: BrushAreaParam,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem
) {
(area.coordRanges || (area.coordRanges = [])).push(coordRange);
// area.coordRange is the first of area.coordRanges
if (!area.coordRange) {
area.coordRange = coordRange;
// In 'category' axis, coord to pixel is not reversible, so we can not
// rebuild range by coordRange accrately, which may bring trouble when
// brushing only one item. So we use __rangeOffset to rebuilding range
// by coordRange. And this it only used in brush component so it is no
// need to be adapted to coordRanges.
const result = coordConvert[area.brushType](0, coordSys, coordRange);
area.__rangeOffset = {
offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
xyMinMax: result.xyMinMax
};
}
});
return areas;
}
matchOutputRanges<T extends (
Parameters<BrushTargetManager['findTargetInfo']>[0] & {
brushType: BrushType;
range: BrushAreaRange;
}
)>(
areas: T[],
ecModel: GlobalModel,
cb: (
area: T,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem,
ecModel: GlobalModel
) => void
) {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (targetInfo && targetInfo !== true) {
each(
targetInfo.coordSyses,
function (coordSys) {
const result = coordConvert[area.brushType](1, coordSys, area.range, true);
cb(area, result.values, coordSys, ecModel);
}
);
}
}, this);
}
/**
* the `areas` is `BrushModel.areas`.
* Called in layout stage.
* convert `area.coordRange` to global range and set panelId to `area.range`.
*/
setInputRanges(
areas: BrushAreaParamInternal[],
ecModel: GlobalModel
): void {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (__DEV__) {
assert(
!targetInfo || targetInfo === true || area.coordRange,
'coordRange must be specified when coord index specified.'
);
assert(
!targetInfo || targetInfo !== true || area.range,
'range must be specified in global brush.'
);
}
area.range = area.range || [];
// convert coordRange to global range and set panelId.
if (targetInfo && targetInfo !== true) {
area.panelId = targetInfo.panelId;
// (1) area.range shoule always be calculate from coordRange but does
// not keep its original value, for the sake of the dataZoom scenario,
// where area.coordRange remains unchanged but area.range may be changed.
// (2) Only support converting one coordRange to pixel range in brush
// component. So do not consider `coordRanges`.
// (3) About __rangeOffset, see comment above.
const result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
const rangeOffset = area.__rangeOffset;
area.range = rangeOffset
? diffProcessor[area.brushType](
result.values,
rangeOffset.offset,
getScales(result.xyMinMax, rangeOffset.xyMinMax)
)
: result.values;
}
}, this);
}
makePanelOpts(
api: ExtensionAPI,
getDefaultBrushType?: (targetInfo: BrushTargetInfo) => BrushType
): BrushPanelConfig[] {
return map(this._targetInfoList, function (targetInfo) {
const rect = targetInfo.getPanelRect();
return {
panelId: targetInfo.panelId,
defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
clipPath: brushHelper.makeRectPanelClipPath(rect),
isTargetByCursor: brushHelper.makeRectIsTargetByCursor(
rect, api, targetInfo.coordSysModel
),
getLinearBrushOtherExtent: brushHelper.makeLinearBrushOtherExtent(rect)
};
});
}
controlSeries(area: BrushAreaParamInternal, seriesModel: SeriesModel, ecModel: GlobalModel): boolean {
// Check whether area is bound in coord, and series do not belong to that coord.
// If do not do this check, some brush (like lineX) will controll all axes.
const targetInfo = this.findTargetInfo(area, ecModel);
return targetInfo === true || (
targetInfo && indexOf(
targetInfo.coordSyses, seriesModel.coordinateSystem as BrushableCoordinateSystem
) >= 0
);
}
/**
* If return Object, a coord found.
* If reutrn true, global found.
* Otherwise nothing found.
*/
findTargetInfo(
area: ModelFinderObject & {
panelId?: string
},
ecModel: GlobalModel
): BrushTargetInfo | true {
const targetInfoList = this._targetInfoList;
const foundCpts = parseFinder(ecModel, area);
for (let i = 0; i < targetInfoList.length; i++) {
const targetInfo = targetInfoList[i];
const areaPanelId = area.panelId;
if (areaPanelId) {
if (targetInfo.panelId === areaPanelId) {
return targetInfo;
}
}
else {
for (let j = 0; j < targetInfoMatchers.length; j++) {
if (targetInfoMatchers[j](foundCpts, targetInfo)) {
return targetInfo;
}
}
}
}
return true;
}
}
function formatMinMax(minMax: BrushDimensionMinMax): BrushDimensionMinMax {
minMax[0] > minMax[1] && minMax.reverse();
return minMax;
}
function parseFinder(
ecModel: GlobalModel, finder: ModelFinder
): ParsedModelFinderKnown {
return modelUtilParseFinder(
ecModel, finder, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
);
}
type TargetInfoBuilder = (
foundCpts: ParsedModelFinderKnown, targetInfoList: BrushTargetInfo[]
) => void;
const targetInfoBuilders: Record<BrushTargetBuilderKey, TargetInfoBuilder> = {
grid: function (foundCpts, targetInfoList) {
const xAxisModels = foundCpts.xAxisModels;
const yAxisModels = foundCpts.yAxisModels;
const gridModels = foundCpts.gridModels;
// Remove duplicated.
const gridModelMap = createHashMap<GridModel>();
const xAxesHas = {} as Dictionary<boolean>;
const yAxesHas = {} as Dictionary<boolean>;
if (!xAxisModels && !yAxisModels && !gridModels) {
return;
}
each(xAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
});
each(yAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
yAxesHas[gridModel.id] = true;
});
each(gridModels, function (gridModel) {
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
yAxesHas[gridModel.id] = true;
});
gridModelMap.each(function (gridModel) {
const grid = gridModel.coordinateSystem;
const cartesians = [] as Cartesian2D[];
each(grid.getCartesians(), function (cartesian, index) {
if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0
|| indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0
) {
cartesians.push(cartesian);
}
});
targetInfoList.push({
panelId: 'grid--' + gridModel.id,
gridModel: gridModel,
coordSysModel: gridModel,
// Use the first one as the representitive coordSys.
coordSys: cartesians[0],
coordSyses: cartesians,
getPanelRect: panelRectBuilders.grid,
xAxisDeclared: xAxesHas[gridModel.id],
yAxisDeclared: yAxesHas[gridModel.id]
} as BrushTargetInfoCartesian2D);
});
},
geo: function (foundCpts, targetInfoList) {
each(foundCpts.geoModels, function (geoModel: GeoModel) {
const coordSys = geoModel.coordinateSystem;
targetInfoList.push({
panelId: 'geo--' + geoModel.id,
geoModel: geoModel,
coordSysModel: geoModel,
coordSys: coordSys,
coordSyses: [coordSys],
getPanelRect: panelRectBuilders.geo
} as BrushTargetInfoGeo);
});
}
};
type TargetInfoMatcher = (
foundCpts: ParsedModelFinderKnown, targetInfo: BrushTargetInfo
) => boolean;
const targetInfoMatchers: TargetInfoMatcher[] = [
// grid
function (foundCpts, targetInfo) {
const xAxisModel = foundCpts.xAxisModel;
const yAxisModel = foundCpts.yAxisModel;
let gridModel = foundCpts.gridModel;
!gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
!gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
return gridModel && gridModel === (targetInfo as BrushTargetInfoCartesian2D).gridModel;
},
// geo
function (foundCpts, targetInfo) {
const geoModel = foundCpts.geoModel;
return geoModel && geoModel === (targetInfo as BrushTargetInfoGeo).geoModel;
}
];
type PanelRectBuilder = (this: BrushTargetInfo) => graphic.BoundingRect;
const panelRectBuilders: Record<BrushTargetBuilderKey, PanelRectBuilder> = {
grid: function (this: BrushTargetInfoCartesian2D) {
// grid is not Transformable.
return this.coordSys.master.getRect().clone();
},
geo: function (this: BrushTargetInfoGeo) {
const coordSys = this.coordSys;
const rect = coordSys.getBoundingRect().clone();
// geo roam and zoom transform
rect.applyTransform(graphic.getTransform(coordSys));
return rect;
}
};
type ConvertCoord = (
to: COORD_CONVERTS_INDEX,
coordSys: BrushableCoordinateSystem,
rangeOrCoordRange: BrushAreaRange,
clamp?: boolean
) => {
values: BrushAreaRange,
xyMinMax: BrushDimensionMinMax[]
};
const coordConvert: Record<BrushType, ConvertCoord> = {
lineX: curry(axisConvert, 0),
lineY: curry(axisConvert, 1),
rect: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xminymin = to
? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
const xmaxymax = to
? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
const values = [
formatMinMax([xminymin[0], xmaxymax[0]]),
formatMinMax([xminymin[1], xmaxymax[1]])
];
return {values: values, xyMinMax: values};
},
polygon: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
const values = map(rangeOrCoordRange, function (item) {
const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);
xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
return p;
});
return {values: values, xyMinMax: xyMinMax};
}
};
function axisConvert(
axisNameIndex: 0 | 1,
to: COORD_CONVERTS_INDEX,
coordSys: Cartesian2D,
rangeOrCoordRange: BrushDimensionMinMax
): {
values: BrushDimensionMinMax,
xyMinMax: BrushDimensionMinMax[]
} {
if (__DEV__) {
assert(
coordSys.type === 'cartesian2d',
'lineX/lineY brush is available only in cartesian2d.'
);
}
const axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
const values = formatMinMax(map([0, 1], function (i) {
return to
? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true)
: axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
}));
const xyMinMax = [];
xyMinMax[axisNameIndex] = values;
xyMinMax[1 - axisNameIndex] = [NaN, NaN];
return {values: values, xyMinMax: xyMinMax};
}
type DiffProcess = (
values: BrushDimensionMinMax | BrushDimensionMinMax[],
refer: BrushDimensionMinMax | BrushDimensionMinMax[],
scales: ReturnType<typeof getScales>
) => BrushDimensionMinMax | BrushDimensionMinMax[];
const diffProcessor: Record<BrushType, DiffProcess> = {
lineX: curry(axisDiffProcessor, 0),
lineY: curry(axisDiffProcessor, 1),
rect: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return [
[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
[values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
];
},
polygon: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return map(values, function (item, idx) {
return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
});
}
};
function axisDiffProcessor(
axisNameIndex: 0 | 1,
values: BrushDimensionMinMax,
refer: BrushDimensionMinMax,
scales: ReturnType<typeof getScales>
): BrushDimensionMinMax {
return [
values[0] - scales[axisNameIndex] * refer[0],
values[1] - scales[axisNameIndex] * refer[1]
];
}
// We have to process scale caused by dataZoom manually,
// although it might be not accurate.
// Return [0~1, 0~1]
function getScales(xyMinMaxCurr: BrushDimensionMinMax[], xyMinMaxOrigin: BrushDimensionMinMax[]): number[] {
const sizeCurr = getSize(xyMinMaxCurr);
const sizeOrigin = getSize(xyMinMaxOrigin);
const scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
function getSize(xyMinMax: BrushDimensionMinMax[]): number[] {
return xyMinMax
? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
: [NaN, NaN];
}
export default BrushTargetManager;
| src/component/helper/BrushTargetManager.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.9897652864456177,
0.035861533135175705,
0.0001643420837353915,
0.00017607747577130795,
0.18332475423812866
] |
{
"id": 0,
"code_window": [
"import SeriesModel from '../../model/Series';\n",
"import { Dictionary } from '../../util/types';\n",
"import {\n",
" ModelFinderObject, ParsedModelFinder, ModelFinder,\n",
" parseFinder as modelUtilParseFinder,\n",
" ParsedModelFinderKnown\n",
"} from '../../util/model';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ModelFinderObject, ModelFinder,\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 38
} |
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<script src="lib/jquery.min.js"></script>
<script src="lib/facePrint.js"></script>
<script src="lib/testHelper.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="lib/reset.css">
</head>
<body>
<style>
h1 {
line-height: 60px;
height: 60px;
background: #146402;
text-align: center;
font-weight: bold;
color: #eee;
font-size: 14px;
}
.chart {
height: 400px;
}
</style>
<div class="chart" id="main1"></div>
<h1>Narrow grid</h1>
<div class="chart" id="main2"></div>
<div class="chart" id="main3"></div>
<div class="chart" id="main4"></div>
<div class="chart" id="main5"></div>
<div class="chart" id="main6"></div>
<script>
require([
'echarts'
// 'echarts/chart/bar',
// 'echarts/component/legend',
// 'echarts/component/grid',
// 'echarts/component/tooltip',
// 'echarts/component/markLine'
], function (echarts) {
var chart = echarts.init(document.getElementById('main1'), null, {
});
chart.setOption({
tooltip : {
trigger: 'axis',
axisPointer : { // 坐标轴指示器,坐标轴触发有效
type : 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
legend: {
data:['直接访问','邮件营销','联盟广告','视频广告','搜索引擎','百度','谷歌','必应','其他']
},
toolbox: {
show : true,
orient: 'vertical',
left: 'right',
top: 'center',
feature : {
mark : {show: true},
dataView : {show: true, readOnly: false},
magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
restore : {show: true},
saveAsImage : {show: true}
}
},
calculable : true,
xAxis : [
{
type : 'category',
data : ['周一','周二','周三','周四','周五','周六','周日']
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'直接访问',
type:'bar',
data:[320, 332, 301, 334, 390, 330, 320]
},
{
name:'邮件营销',
type:'bar',
stack: '广告',
data:[120, 132, 101, 134, 90, 230, 210]
},
{
name:'联盟广告',
type:'bar',
stack: '广告',
data:[220, 182, 191, 234, 290, 330, 310]
},
{
name:'视频广告',
type:'bar',
stack: '广告',
data:[150, 232, 201, 154, 190, 330, 410]
},
{
name:'搜索引擎',
type:'bar',
data:[862, 1018, 964, 1026, 1679, 1600, 1570],
markLine : {
itemStyle:{
normal:{
label: {
formatter: function (params) {
console.log(params);
}
},
lineStyle:{
type: 'dashed'
}
}
},
data : [
[{type : 'min'}, {type : 'max'}]
]
}
},
{
name:'百度',
type:'bar',
barWidth : 5,
stack: '搜索引擎',
data:[620, 732, 701, 734, 1090, 1130, 1120]
},
{
name:'谷歌',
type:'bar',
stack: '搜索引擎',
data:[120, 132, 101, 134, 290, 230, 220]
},
{
name:'必应',
type:'bar',
stack: '搜索引擎',
data:[60, 72, 71, 74, 190, 130, 110]
},
{
name:'其他',
type:'bar',
stack: '搜索引擎',
data:[62, 82, 91, 84, 109, 110, 120]
}
]
});
});
</script>
<script>
var echarts;
var chart;
var myChart;
var groupCategories = [];
var groupColors = [];
require([
'echarts'
// 'echarts/chart/line',
// 'echarts/chart/bar',
// 'echarts/chart/pie',
// 'echarts/chart/scatter',
// 'echarts/chart/map',
// 'echarts/chart/parallel',
// 'echarts/chart/radar',
// 'echarts/component/grid',
// 'echarts/component/polar',
// 'echarts/component/geo',
// 'echarts/component/singleAxis',
// 'echarts/component/legend',
// 'echarts/component/tooltip',
// 'echarts/component/toolbox',
// 'echarts/component/visualMap',
// 'echarts/component/dataZoom'
], function (ec) {
echarts = ec;
option = {
color: [{
type: 'linear',
colorStops: [{
offset: 0,
color: 'rgba(42, 20, 20, 0.8)'
}, {
offset: 1,
color: 'rgba(42, 20, 20, 0)'
}],
x: 0.5,
y: 0,
x2: 0.49999999999999994,
y2: 1
}],
xAxis: {
// data: ['a', 'b', 'c', 'd'],
data: ['a', 'b'],
axisTick: {show: false},
axisLabel: {
formatter: 'barGap: \'-100%\''
}
},
yAxis: {
splitLine: {show: false}
},
animationDurationUpdate: 1200,
grid: {
width: 100
},
animation: false,
series: [{
type: 'bar',
itemStyle: {
normal: {
color: '#ddd'
}
},
silent: true,
barWidth: 40,
barGap: '-100%', // Make series be overlap
data: [60, 60],
label: {
show: true,
color: 'blue',
position: 'top'
}
}, {
type: 'bar',
barWidth: 40,
z: 10,
data: [45, 55]
}]
};
testHelper.createChart(echarts, 'main2', option);
});
</script>
<script>
var echarts;
var chart;
var myChart;
var groupCategories = [];
var groupColors = [];
require([
'echarts'
], function (ec) {
echarts = ec;
var dataCount = 10;
var dayTimestamp = 24 * 60 * 60 * 1000;
function makeSeriesData() {
var result = [];
var date = +(new Date(2019, 8, 10));
for (var i = 0; i < dataCount; i++) {
result.push([+date, Math.random() * 1000]);
date += dayTimestamp;
}
return result;
}
option = {
xAxis: {
type: 'time',
boundaryGap: ['20%', '20%'],
splitLine: {show: false}
},
yAxis: {
axisLine: {show: false},
axisTick: {show: false},
splitLine: {show: false}
},
legend: {},
series: [{
name: 'barA1',
type: 'bar',
stack: 'a',
itemStyle: {
shadowBlur: 10,
borderColor: '#ef1',
borderWidth: 5
},
data: makeSeriesData()
}, {
name: 'barA2',
type: 'bar',
stack: 'a',
itemStyle: {
borderColor: '#1dd',
borderWidth: 5
},
data: makeSeriesData()
}, {
name: 'barB',
type: 'bar',
itemStyle: {
shadowBlur: 5,
borderColor: '#ef1',
borderWidth: 3
},
data: makeSeriesData()
}]
};
var chart = testHelper.create(echarts, 'main3', {
title: [
'bar on time axis',
'click the legend, the bar should display normally'
],
option: option
// recordCanvas: true
});
});
</script>
<script>
var echarts;
var chart;
var myChart;
var groupCategories = [];
var groupColors = [];
require([
'echarts'
], function (ec) {
echarts = ec;
var dataCount = 5;
function makeSeriesData() {
var result = [];
var date = 0;
for (var i = 0; i < dataCount; i++) {
result.push([+date, Math.random() * 1000]);
date += Math.ceil(Math.random() * 10);
}
return result;
}
var itemStyle = {
shadowBlur: 5
};
option = {
xAxis: {
scale: true,
// boundaryGap: ['0.5%', .1],
splitLine: {show: false}
},
yAxis: {
axisLabel: {
margin: 40
},
axisLine: {show: false},
axisTick: {show: false},
splitLine: {show: false}
},
dataZoom: [{
type: 'slider'
}, {
type: 'inside'
}],
legend: {},
series: [{
name: 'barA',
type: 'bar',
itemStyle: itemStyle,
data: makeSeriesData()
}, {
name: 'barB',
type: 'bar',
itemStyle: itemStyle,
data: makeSeriesData()
}],
animation: false
};
var chart = testHelper.create(echarts, 'main4', {
title: [
'bar on value axis',
'click the legend, the bar should display normally'
],
option: option
// recordCanvas: true
});
});
</script>
<script>
var echarts;
var chart;
var myChart;
var groupCategories = [];
var groupColors = [];
require([
'echarts'
], function (ec) {
echarts = ec;
var dataCount = 10;
function makeSeriesData() {
var result = [];
var date = 10;
for (var i = 0; i < dataCount; i++) {
result.push([+date, Math.random() * 1000]);
date += 1;
}
return result;
}
var itemStyle = {
shadowBlur: 5
};
option = {
xAxis: {
type: 'category',
scale: true,
boundaryGap: false,
splitLine: {show: false},
axisLine: {show: false}
},
yAxis: {
axisLabel: {
margin: 40
},
axisLine: {show: false},
axisTick: {show: false},
splitLine: {show: false}
},
legend: {},
series: [{
name: 'lineA',
type: 'line',
data: makeSeriesData()
}, {
name: 'barA',
type: 'bar',
itemStyle: itemStyle,
data: makeSeriesData()
}, {
name: 'barB',
type: 'bar',
itemStyle: itemStyle,
data: makeSeriesData()
}]
};
var chart = testHelper.create(echarts, 'main5', {
title: [
'bar on category axis',
'click the legend, the bar should display normally'
],
option: option
// recordCanvas: true
});
});
</script>
<script>
require(['echarts'], function (echarts) {
option = {
animation: false,
dataZoom: [
{
"type": "slider",
"show": true
}
],
color: ['#003366', '#e5323e'],
legend: {
data: ['Forest', 'Desert']
},
xAxis: [
{
type: 'time'
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Forest',
type: 'bar',
barGap: 0,
data: [["2017-05-26", 320], ["2017-05-25", 340], ["2017-05-24", 310]]
},
{
name: 'Desert',
type: 'bar',
data: [["2017-05-26", 240], ["2017-05-24", 315]]
}
]
};
var chart = testHelper.create(echarts, 'main6', {
title: [
'Bar series with time axis',
'Zoom in and bars should not overlap'
],
option: option
});
});
</script>
</body>
</html> | test/bar2.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0001946584670804441,
0.0001738859573379159,
0.00016506733663845807,
0.00017365836538374424,
0.000004840178462472977
] |
{
"id": 0,
"code_window": [
"import SeriesModel from '../../model/Series';\n",
"import { Dictionary } from '../../util/types';\n",
"import {\n",
" ModelFinderObject, ParsedModelFinder, ModelFinder,\n",
" parseFinder as modelUtilParseFinder,\n",
" ParsedModelFinderKnown\n",
"} from '../../util/model';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ModelFinderObject, ModelFinder,\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 38
} |
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
</head>
<body>
<style>
html, body, #main {
width: 100%;
height: 100%;
}
</style>
<div id="main"></div>
<script>
require([
'echarts'
// 'echarts/chart/radar',
// 'echarts/component/legend',
// 'echarts/component/tooltip',
// 'echarts/component/visualMap'
], function (echarts) {
var chart = echarts.init(document.getElementById('main'));
chart.setOption({
title : {
text: '浏览器占比变化',
subtext: '纯属虚构',
x:'right',
y:'bottom'
},
tooltip : {
trigger: 'item',
backgroundColor : 'rgba(0,0,250,0.2)'
},
legend: {
data: (function (){
var list = [];
for (var i = 1; i <=28; i++) {
list.push(i + 2000 + '');
}
return list;
})()
},
visualMap: {
color: ['red', 'yellow']
},
radar: {
indicator : [
{ text: 'IE8-', max: 400},
{ text: 'IE9+', max: 400},
{ text: 'Safari', max: 400},
{ text: 'Firefox', max: 400},
{ text: 'Chrome', max: 400}
]
},
series : (function (){
var series = [];
for (var i = 1; i <= 28; i++) {
series.push({
name:'浏览器(数据纯属虚构)',
type: 'radar',
symbol: 'none',
itemStyle: {
normal: {
lineStyle: {
width:1
}
}
},
emphasis: {
areaStyle: {
color:'rgba(0,250,0,0.3)'
}
},
data:[
{
value:[
(40 - i) * 10,
(38 - i) * 4 + 60,
i * 5 + 10,
i * 9,
i * i /2
],
name:i + 2000 + ''
}
]
});
}
return series;
})()
});
});
</script>
</body>
</html> | test/radar2.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00023920994135551155,
0.00017860507068689913,
0.00016352269449271262,
0.00017403883975930512,
0.00001881147727544885
] |
{
"id": 0,
"code_window": [
"import SeriesModel from '../../model/Series';\n",
"import { Dictionary } from '../../util/types';\n",
"import {\n",
" ModelFinderObject, ParsedModelFinder, ModelFinder,\n",
" parseFinder as modelUtilParseFinder,\n",
" ParsedModelFinderKnown\n",
"} from '../../util/model';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ModelFinderObject, ModelFinder,\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 38
} | <!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<script src="lib/jquery.min.js"></script>
<script src="lib/facePrint.js"></script>
<script src="lib/testHelper.js"></script>
<!-- <script src="ut/lib/canteen.js"></script> -->
<link rel="stylesheet" href="lib/reset.css" />
</head>
<body>
<style>
</style>
<h1>Bar/Line chart stack normal with dataZoom in the toolbox(should not exceed the range of coord)</h1>
<div id="main0"></div>
<div id="main1"></div>
<div id="main2"></div>
<div id="main3"></div>
<div id="main4"></div>
<div id="main5"></div>
<div id="main6"></div>
<script>
require([
'echarts'
], function (echarts) {
var option = {
top: '30%',
title: {
text: 'ECharts test'
},
tooltip: {},
legend: {
data:['test']
},
xAxis: {
data: ["AA","BB","CC","DD","EE","FF"]
},
yAxis: {},
series: [{
name: 'Y',
type: 'bar',
data: [5, 20, 36, 10, 10, 20],
stack: 1,
}, {
name: 'X',
type: 'bar',
data: [1, 2, 30, 10, 8, 2],
stack: 1,
}],
toolbox: {
feature: {
dataZoom: {show: true}
}
}
};
var chart = testHelper.create(echarts, 'main0', {
option: option,
// recordCanvas: true
});
});
</script>
<script>
require([
'echarts'
], function (echarts) {
var option = {
"backgroundColor": "#fff",
"legend": {
"orient": "horizontal",
"x": "center",
"left": "2%",
"top": "2%"
},
"textStyle": {
"fontFamily": "Lato"
},
"tooltip":{
"show": true,
"trigger": "axis",
"backgroundColor": "#fff",
"borderColor": "#e0e5ec",
"borderWidth": 1,
"textStyle": {
"color": "#495057",
"fontSize": 10
},
"enterable": true,
"axisPointer": {
"lineStyle": {
"color": "#e0e5ec"
}
}
},
"toolbox":{
"feature":{
"dataZoom":{
"show":true,
"title":{
"zoom":"Zoom",
"back":"Restore Zoom"
}
}
}
},
"color": [
"rgba(101,116, 205, 0.9 )",
"rgba(246,109, 155, 0.9 )",
"rgba(43,203, 186, 0.9 )",
"rgba(253,150, 68, 0.9 )",
"rgba(205,32, 31, 0.9 )",
"rgba(165,94, 234, 0.9 )",
"rgba(123,210, 53, 0.9 )",
"rgba(241,196, 15, 0.9 )",
"rgba(70,127, 207, 0.9 )",
"rgba(23,162, 184, 0.9 )",
"rgba(69,170, 242, 0.9 )",
"rgba(94,186, 0, 0.9 )",
"rgba(33,150, 243, 0.9 )",
"rgba(0,150, 136, 0.9 )",
"rgba(244,67, 54, 0.9 )",
"rgba(156,39, 176, 0.9 )",
"rgba(0,150, 136, 0.9 )",
"rgba(103,58, 183, 0.9 )",
"rgba(63,81, 181, 0.9 )",
"rgba(76,175, 80, 0.9 )",
"rgba(233,30, 99, 0.9 )",
"rgba(96,125, 139, 0.9 )",
"rgba(255,87, 34, 0.9 )",
"rgba(28,147, 99, 0.9 )",
"rgba(255,113, 91, 0.9 )",
"rgba(43,89, 195, 0.9 )",
"rgba(33,91, 86, 0.9 )",
"rgba(0,188, 212, 0.9 )",
"rgba(255,87, 34, 0.9 )",
"rgba(255,193, 7, 0.9 )",
"rgba(48,25, 102, 0.9 )",
"rgba(211,101, 130, 0.9 )",
"rgba(130,6, 70, 0.9 )",
"rgba(100,155, 193, 0.9 )",
"rgba(75,63, 114, 0.9 )",
"rgba(219,51, 64, 0.9 )",
"rgba(223,81, 76, 0.9 )",
"rgba(92,45, 80, 0.9 )",
"rgba(94,52, 72, 0.9 )",
"rgba(83,187, 244, 0.9 )",
"rgba(89,196, 197, 0.9 )",
"rgba(191,240, 115, 0.9 )",
"rgba(228,95, 86, 0.9 )",
"rgba(201,27, 38, 0.9 )",
"rgba(115,116, 149, 0.9 )",
"rgba(92,45, 80, 0.9 )",
"rgba(32,69, 124, 0.9 )",
"rgba(15,89, 89, 0.9 )",
"rgba(159,146, 170, 0.9 )",
"rgba(255,162, 0, 0.9 )",
"rgba(36,168, 172, 0.9 )",
"rgba(255,76, 101, 0.9 )",
"rgba(233,76, 111, 0.9 )",
"rgba(53,68, 88, 0.9 )",
"rgba(105,210, 231, 0.9 )",
"rgba(220,39, 66, 0.9 )",
"rgba(58,2, 86, 0.9 )",
"rgba(23,166, 151, 0.9 )",
"rgba(6,71, 137, 0.9 )",
"rgba(255,195, 60, 0.9 )"
],
"xAxis": {
"show": true,
"type": "category",
"name": "Inserted_at By Day",
"nameLocation": "center",
"nameTextStyle": {
"padding": 8,
"color": "#495057",
"fontSize": 12
},
"axisLine": {
"onZero": false,
"lineStyle": {
"color": "#e0e5ec"
}
},
"axisLabel": {
"color": "#495057",
"fontSize": 10
},
"splitLine": {
"show": false
}
},
"yAxis": {
"show": true,
"type": "value",
"name": false,
"nameLocation": "center",
"nameTextStyle": {
"padding": 8,
"color": "#495057",
"fontSize": 12
},
"axisLine": {
"onZero": false,
"lineStyle": {
"color": "#e0e5ec"
}
},
"axisLabel": {
"color": "#495057",
"fontSize": 10
},
"splitLine": {
"show": false
}
},
"series": [
{
"type": "bar",
"name": "count",
"itemStyle": null,
"stack": true,
"data": [
[
"2018-03-08 05:30:00.000",
156
],
[
"2018-03-23 05:30:00.000",
24
],
[
"2018-04-18 05:30:00.000",
513
],
[
"2018-05-16 05:30:00.000",
7
],
[
"2018-05-20 05:30:00.000",
21
],
[
"2018-05-31 05:30:00.000",
7
],
[
"2018-06-07 05:30:00.000",
7
],
[
"2018-06-08 05:30:00.000",
2
],
[
"2018-06-10 05:30:00.000",
6
]
]
},
{
"type": "bar",
"name": "?column?",
"itemStyle": null,
"stack": true,
"data": [
[
"2018-03-08 05:30:00.000",
9
],
[
"2018-03-23 05:30:00.000",
"1"
],
[
"2018-04-18 05:30:00.000",
356
],
[
"2018-05-16 05:30:00.000",
5
],
[
"2018-05-20 05:30:00.000",
15
],
[
"2018-05-31 05:30:00.000",
5
],
[
"2018-06-07 05:30:00.000",
5
],
[
"2018-06-08 05:30:00.000",
"1"
],
[
"2018-06-10 05:30:00.000",
4
]
]
}
]
};
var chart = testHelper.create(echarts, 'main1', {
option: option,
// recordCanvas: true
});
});
</script>
<script>
require([
'echarts'
], function (echarts) {
var option = {
"calculable": false,
"renderAsImage": false,
"series": [
{
"largeThreshold" : 2000,
"legendHoverLink" : true,
"smooth" : false,
"barCategoryGap" : "30%",
"clickable" : true,
"z" : 2,
"dataFilter" : "nearest",
"showAllSymbol" : false,
"yAxisIndex" : 0,
"type" : "bar",
"data" : [
23756.529999999999,
26716.48,
9424.25,
9530.8999999999996,
6035.3400000000001,
0,
3381.3499999999999,
6528.8599999999997,
3760.21,
3502.3800000000001,
1194.3599999999999,
4612.3400000000001,
0,
1296.3800000000001,
3743.4499999999998,
26284.240000000002,
1809.24,
0,
1947.3199999999999,
2511,
15559.23,
0,
5936.9399999999996,
0,
0,
0,
4760.2700000000004,
0,
0,
0,
0,
0,
0,
0,
0,
3428.1500000000001,
2521.0999999999999,
1607.8599999999999,
2441.52,
4354.8100000000004,
2960.9899999999998,
10408.42,
0,
0,
0,
0,
0,
0,
0
],
"barGap" : "30%",
"itemStyle" : {
"emphasis" : {
"color" : "#1886E3",
"label" : {
"distance" : 10,
"show" : false,
"position" : "outer",
"rotate" : false
},
"labelLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"length" : 40
}
},
"normal" : {
"color" : "#1886E3",
"label" : {
"distance" : 10,
"show" : false,
"position" : "outer",
"rotate" : false
},
"labelLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"length" : 40
}
}
},
"large" : false,
"name" : "51周平均日用量"
},
{
"largeThreshold" : 2000,
"legendHoverLink" : true,
"smooth" : false,
"barCategoryGap" : "30%",
"clickable" : true,
"z" : 2,
"dataFilter" : "nearest",
"showAllSymbol" : false,
"yAxisIndex" : 0,
"type" : "bar",
"data" : [
30489.049999999999,
36026.639999999999,
8183.5699999999997,
14145.48,
7167.7200000000003,
880.82000000000005,
6253.9200000000001,
8826.25,
4777.7399999999998,
3638.1700000000001,
3584.2800000000002,
5062.5,
1168.51,
1114.8299999999999,
11842.41,
30060.919999999998,
706.26999999999998,
3996.46,
4380.8100000000004,
5187.4099999999999,
3824.5999999999999,
2262.4499999999998,
2967.6999999999998,
4495.6300000000001,
4126.5699999999997,
0,
3858.75,
2924.0999999999999,
1746.75,
1975.5,
2082,
3088.5,
0,
0,
0,
1785.53,
4356.0100000000002,
8033.8199999999997,
4208.71,
13157.700000000001,
12462.93,
13743.9,
0,
0,
0,
0,
0,
0,
0
],
"barGap" : "30%",
"itemStyle" : {
"emphasis" : {
"color" : "#F6A623",
"label" : {
"distance" : 10,
"show" : false,
"position" : "outer",
"rotate" : false
},
"labelLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"length" : 40
}
},
"normal" : {
"color" : "#F6A623",
"label" : {
"distance" : 10,
"show" : false,
"position" : "outer",
"rotate" : false
},
"labelLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"length" : 40
}
}
},
"large" : false,
"name" : "52周平均日用量"
},
{
"largeThreshold" : 2000,
"legendHoverLink" : true,
"smooth" : false,
"barCategoryGap" : "30%",
"clickable" : true,
"z" : 2,
"dataFilter" : "nearest",
"showAllSymbol" : false,
"yAxisIndex" : 0,
"type" : "bar",
"data" : [
29524.110000000001,
14007.120000000001,
8411.6900000000005,
10003.469999999999,
11589.879999999999,
896.50999999999999,
4791.6000000000004,
6617.21,
7026.1099999999997,
5556.4899999999998,
3061.27,
8506.9099999999999,
416.82999999999998,
1337.75,
12256.059999999999,
22903.669999999998,
1427.8,
1533.5699999999999,
27902.540000000001,
5579.8100000000004,
28220.360000000001,
754.44000000000005,
3196.9299999999998,
6200.3400000000001,
6716.3900000000003,
0,
939.21000000000004,
803.39999999999998,
0,
11446.959999999999,
2096.5599999999999,
4544.4799999999996,
3509.3200000000002,
0,
761.25,
4916.1400000000003,
3039.4000000000001,
6166.8000000000002,
3378.46,
8787.6399999999994,
5666.96,
12500.610000000001,
5281.7299999999996,
8854.1399999999994,
328.94999999999999,
0,
0,
0,
0
],
"barGap" : "30%",
"itemStyle" : {
"emphasis" : {
"color" : "#90AFE4",
"label" : {
"distance" : 10,
"show" : false,
"position" : "outer",
"rotate" : false
},
"labelLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"length" : 40
}
},
"normal" : {
"color" : "#90AFE4",
"label" : {
"distance" : 10,
"show" : false,
"position" : "outer",
"rotate" : false
},
"labelLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"length" : 40
}
}
},
"large" : false,
"name" : "1周平均日用量"
},
{
"largeThreshold" : 2000,
"legendHoverLink" : true,
"smooth" : false,
"barCategoryGap" : "30%",
"clickable" : true,
"z" : 2,
"dataFilter" : "nearest",
"showAllSymbol" : false,
"yAxisIndex" : 0,
"type" : "bar",
"data" : [
35376.440000000002,
21978.869999999999,
6576.0299999999997,
8786.5499999999993,
10064.26,
2063.1399999999999,
6502.3400000000001,
13495.48,
5614.5100000000002,
6085.6499999999996,
2312.5799999999999,
8553.2600000000002,
8796.3999999999996,
1880.26,
8418.7900000000009,
49651.620000000003,
1466.8,
6279.8599999999997,
7088.9499999999998,
8273.3099999999995,
12138.690000000001,
7607.8699999999999,
5459.1599999999999,
4296.71,
5477.7399999999998,
1249.6300000000001,
5644.4700000000003,
1487.8099999999999,
2465.04,
6923.5200000000004,
5541.7799999999997,
2260.6999999999998,
2172.1500000000001,
1944,
8513.8600000000006,
10300.84,
2953.7600000000002,
10124.91,
12560.67,
7698.3199999999997,
9854.2099999999991,
11715.85,
3042.8299999999999,
11900.15,
19656.810000000001,
2519.0900000000001,
3384.0500000000002,
1441.74,
690.61000000000001
],
"barGap" : "30%",
"itemStyle" : {
"emphasis" : {
"color" : "#6ED4DA",
"label" : {
"distance" : 10,
"show" : false,
"position" : "outer",
"rotate" : false
},
"labelLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"length" : 40
}
},
"normal" : {
"color" : "#6ED4DA",
"label" : {
"distance" : 10,
"show" : false,
"position" : "outer",
"rotate" : false
},
"labelLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"length" : 40
}
}
},
"large" : false,
"name" : "2周平均日用量"
}
],
"grid" : {
"y" : 75,
"x2" : 45,
"z" : 0,
"x" : 45,
"zlevel" : 0,
"y2" : 40
},
"xAxis" : [
{
"splitLine" : {
"show" : true,
"onGap" : false,
"lineStyle" : {
"type" : "solid"
}
},
"scale" : false,
"position" : "'bottom'|'left'",
"axisLabel" : {
"interval" : "auto",
"show" : true,
"clickable" : false,
"rotate" : 0,
"margin" : 8
},
"show" : true,
"z" : 0,
"type" : "category",
"data" : [
"小华1号普通A+C",
"小华2号A+C两层加硬",
"小华3号170gA+B",
"小华4号170gA+A",
"小华5号(美牛双加硬)",
"10号(Q636B)\/BE瓦",
"11号(H737B)\/BC瓦",
"12号(H737H)\/BC瓦",
"13号(H636B)\/BC瓦",
"14号(M535B)\/BC瓦",
"15号(M536B)\/BC瓦",
"16号(M636B)\/BC瓦",
"17号(M535B)\/BE瓦",
"18号(M536B)\/BE瓦",
"19号(A5B)\/单B瓦",
"1号(A535B)\/BC瓦",
"20号(Q5B)\/单B瓦",
"21号(Q6B)\/单B瓦",
"22号(5B)\/E瓦",
"23号(6B)\/E瓦",
"24号(535B)\/BE瓦",
"25号(A5B)\/E瓦",
"26号(W5C)\/E瓦",
"27号(H7H)\/单B瓦",
"28号(636A)\/BE瓦",
"29号(6A)\/E瓦",
"2号(A536B)\/BC瓦",
"30号(B53)\/单E瓦",
"31号(B63)\/单E瓦",
"32号(M33)\/单B瓦",
"33号(B3C)\/单B瓦",
"34号(M3C)\/单B瓦",
"35号(B333C)\/BC瓦",
"36号(M3333)\/BC瓦",
"37号(M333C)\/BC瓦",
"3号(A636B)\/BC瓦",
"4号(A535B)\/BE瓦",
"5号(A536B)\/BE瓦",
"6号(A636B)\/BE瓦",
"7号(Q535B)\/BC瓦",
"8号(Q536B)\/BC瓦",
"9号(Q636B)\/BC瓦",
"38号(Q6B)\/单E层",
"39号(B33)\/单B瓦",
"40号(Q536B)\/BE瓦",
"小华6号(A+C一层加硬)",
"小华7号(A+C单B瓦)",
"小华6号(120gA+C \/BE)",
"43号(536B)\/BE瓦"
],
"nameLocation" : "end",
"zlevel" : 0,
"axisLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"onZero" : true
},
"name" : ""
}
],
"tooltip" : {
"transitionDuration" : 0.40000000000000002,
"borderColor" : "rgba(3,3,3,1.00)",
"padding" : 5,
"axisPointer" : {
"show" : false,
"type" : "shadow"
},
"position" : "(function (p){return ['50%', p[1] - 10]} )",
"islandFormmater" : "{a} < br\/>{b} : {c}",
"backgroundColor" : "rgba(0,0,0,0.70)",
"trigger" : "axis",
"show" : true,
"z" : 8,
"showContent" : true,
"showDelay" : 20,
"enterable" : false,
"hideDelay" : 100,
"borderWidth" : 0,
"zlevel" : 1,
"borderRadius" : 4
},
"dataZoom" : {
"handleColor" : "rgba(70,130,180,0.80)",
"start" : 0,
"fillerColor" : "rgba(144,197,237,0.20)",
"dataBackgroundColor" : "rgba(14,14,14,1.00)",
"backgroundColor" : "rgba(0,0,0,0.00)",
"realtime" : false,
"show" : false,
"z" : 4,
"type" : "inside",
"minSpan" : 5,
"orient" : "horizontal",
"zlevel" : 0,
"handleSize" : 8,
"end" : 100,
"zoomLock" : false,
"showDetail" : true
},
"title" : {
"padding" : 5,
"borderColor" : "rgba(12,12,12,1.00)",
"textStyle" : {
"fontFamily" : "Arial, Verdana, sans-serif",
"fontStyle" : "normal",
"fontWeight" : "bolder",
"decoration" : "none",
"fontSize" : 17
},
"subtextStyle" : {
"fontFamily" : "Arial, Verdana, sans-serif",
"fontSize" : 12,
"fontStyle" : "normal",
"fontWeight" : "normal",
"decoration" : "none",
"color" : "rgba(10,10,10,1.00)"
},
"sublink" : "",
"x" : "left",
"backgroundColor" : "rgba(0,0,0,0.00)",
"y" : "top",
"link" : "",
"itemGap" : 5,
"show" : true,
"z" : 0,
"borderWidth" : 0,
"text" : "",
"subtext" : "",
"zlevel" : 0
},
"animation" : true,
"toolbox" : {
"padding" : 5,
"borderColor" : "rgba(12,12,12,1.00)",
"disableColor" : "rgba(13,13,13,0.00)",
"x" : "right",
"backgroundColor" : "rgba(0,0,0,0.00)",
"effectiveColor" : "rgba(255,0,0,1.00)",
"y" : "top",
"itemSize" : 16,
"itemGap" : 10,
"show" : false,
"z" : 6,
"color" : [
"rgba(30,144,255,1.00)",
"rgba(34,187,34,1.00)",
"rgba(75,0,130,1.00)",
"rgba(210,105,30,1.00)"
],
"showTitle" : true,
"borderWidth" : 0,
"feature" : {
"dataView" : {
"title" : "数据视图",
"show" : false,
"readOnly" : false,
"lang" : [
"数据视图",
"关闭",
"刷新"
]
},
"magicType" : {
"show" : false,
"title" : {
"bar" : "柱形图切换",
"chord" : "和弦图切换",
"funnel" : "漏斗图切换",
"force" : "力导向布局图切换",
"tiled" : "平铺",
"stack" : "堆积",
"pie" : "饼图切换",
"line" : "折线图切换"
}
},
"mark" : {
"show" : false,
"title" : {
"markClear" : "清空辅助线",
"mark" : "辅助线开关",
"markUndo" : "删除辅助线"
},
"lineStyle" : {
"color" : "rgba(30,144,255,1.00)",
"type" : "dashed",
"width" : 2
}
},
"restore" : {
"show" : false,
"title" : "还原"
},
"dataZoom" : {
"show" : true,
"title" : {
"dataZoom" : "区域缩放",
"dataZoomReset" : "区域缩放后退"
}
}
},
"orient" : "horizontal",
"zlevel" : 0
},
"yAxis" : [
{
"splitLine" : {
"show" : true,
"onGap" : false,
"lineStyle" : {
"type" : "solid"
}
},
"scale" : true,
"position" : "'bottom'|'left'",
"show" : true,
"z" : 0,
"type" : "value",
"data" : [
],
"nameLocation" : "end",
"zlevel" : 0,
"axisLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"onZero" : true
},
"name" : "㎡"
},
{
"splitLine" : {
"show" : true,
"onGap" : false,
"lineStyle" : {
"type" : "solid"
}
},
"scale" : true,
"position" : "'bottom'|'left'",
"axisLabel" : {
"formatter" : "(function (params) {if(params >= 10000000) { return (params\/ 10000000 + '千万' );} if (params >= 10000) { return (params\/ 10000 + '万' );} else {return params;}})",
"interval" : "auto",
"show" : true,
"clickable" : false,
"rotate" : 0,
"margin" : 8
},
"show" : true,
"z" : 0,
"type" : "value",
"data" : [
],
"nameLocation" : "end",
"zlevel" : 0,
"axisLine" : {
"show" : true,
"lineStyle" : {
"type" : "solid"
},
"onZero" : true
},
"name" : ""
}
],
"legend" : {
"borderColor" : "#ccc",
"textStyle" : {
"fontFamily" : "Arial, Verdana, sans-serif",
"fontSize" : 12,
"fontStyle" : "normal",
"fontWeight" : "normal",
"decoration" : "none",
"color" : "rgba(3,3,3,1.00)"
},
"x" : "center",
"y" : 29,
"itemGap" : 5,
"show" : true,
"z" : 4,
"itemWidth" : 20,
"data" : [
"51周",
"52周",
"1周",
"2周"
],
"selectedMode" : true,
"orient" : "horizontal",
"itemHeight" : 14
}
};
var chart = testHelper.create(echarts, 'main2', {
option: option,
// recordCanvas: true
});
});
</script>
<script>
require([
'echarts'
], function (echarts) {
var option = {
"title": {
"text": "option传入的title"
},
"tooltip": {
"trigger": "axis"
},
"legend": {
"data": ["邮件营销", "联盟广告"]
},
"grid": {
"containLabel": true
},
"series": [{
"type": "line",
"stack": "all",
"data": [120, 132, 101, 134, 90, 230, 210],
"name": "邮件营销"
}, {
"type": "line",
"stack": "all",
"data": [220, 182, 191, 234, 290, 330, 310],
"name": "联盟广告"
}],
"yAxis": {
"type": "category",
"data": ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
},
"xAxis": {
"type": "value",
},
"toolbox": {
"feature": {
"saveAsImage": {
"type": "jpeg",
"title": "保存保存"
},
"dataZoom": {
show:true
}
}
}
};
var chart = testHelper.create(echarts, 'main3', {
option: option,
// recordCanvas: true
});
});
</script>
<script>
require([
'echarts'
], function (echarts) {
var option = {
"xAxis": [{
"type": "category",
"name": "COLUMN_NAME",
"gridIndex": 0
}],
"yAxis": [{
"gridIndex": 0
}],
"series": [{
"type": "bar",
"stack": "COLUMN_NAME",
"xAxisIndex": 0,
"yAxisIndex": 0,
"encode": {
"x": "COLUMN_NAME",
"y": "SUB_TYPE"
}
}, {
"type": "bar",
"stack": "COLUMN_NAME",
"xAxisIndex": 0,
"yAxisIndex": 0,
"encode": {
"x": "COLUMN_NAME",
"y": "s1"
}
}],
"brush": {
"toolbox": ["rect", "polygon", "lineX", "lineY", "clear"],
"throttleType": "debounce",
"throttleDelay": 300
},
"toolbox": {
"feature": {
"saveAsImage": {
"show": true
},
"dataZoom": {
"show": true
}
},
"show": true,
"left": "40px"
},
"axisPointer": {
"show": false
},
"tooltip": {
"show": true
},
"color": ["#44bd89", "#4db7c8", "#eaad56", "#9fbd74", "#82cda4", "#ff942b", "#17988d", "#4e6783", "#bababa", "#bed38b", "#3eadb5", "#f75700", "#8f5989"],
"dataset": {
"source": [
["COLUMN_NAME", "SUB_TYPE", "s1"],
["column_name_0", 394, 394],
["column_name_1", 426.5, 426.5],
["column_name_2", 285, 285],
["column_name_3", 404, 404],
["column_name_4", 496.53846153846155, 496],
["column_name_5", 244, 244],
["column_name_6", 543, 543],
["column_name_7", 528, 528],
["column_name_8", 393, 393],
["column_name_9", 539, 539]
],
"dimensions": ["COLUMN_NAME", "SUB_TYPE", "s1"]
},
"grid": [{
"left": "2%",
"top": "8%",
"width": "90%",
"height": "90%",
"containLabel": true
}],
"dataZoom": [{
"type": "inside",
"xAxisIndex": 0,
"disabled": true
}, {
"type": "inside",
"yAxisIndex": 0,
"disabled": true
}]
}
var chart = testHelper.create(echarts, 'main4', {
option: option,
// recordCanvas: true
});
});
</script>
<script>
require([
'echarts'
], function (echarts) {
var option = {
title: {
text: '折线图堆叠'
},
tooltip: {
trigger: 'axis'
},
legend: {
data:['邮件营销','联盟广告','视频广告','直接访问','搜索引擎']
},
dataZoom: [{
type: 'slider',
xAxisIndex: 0,
start: 0,
end: 100,
filterMode: 'filter',
},{
type: 'inside',
start: 0,
end: 100,
filterMode: 'filter',
}],
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一','周二','周三','周四','周五','周六','周日']
},
yAxis: {
type: 'value'
},
series: [
{
name:'邮件营销',
type:'line',
stack: '总量',
data:[120, 132, 101, 134, 90, 230, 210]
},
{
name:'联盟广告',
type:'line',
stack: '总量',
data:[220, 182, 191, 234, 290, 330, 310]
},
{
name:'视频广告',
type:'line',
stack: '总量',
data:[150, 232, 201, 154, 190, 330, 410]
},
{
name:'直接访问',
type:'line',
stack: '总量',
data:[320, 332, 301, 334, 390, 330, 320]
},
{
name:'搜索引擎',
type:'line',
stack: '总量',
data:[820, 932, 901, 934, 1290, 1330, 1320]
}
]
};
var chart = testHelper.create(echarts, 'main5', {
option: option,
// recordCanvas: true
});
});
</script>
<script>
require([
'echarts'
], function (echarts) {
var option = {
tooltip : {
trigger: 'axis',
axisPointer : { // 坐标轴指示器,坐标轴触发有效
type : 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
legend: {
data:['直接访问','邮件营销','联盟广告','视频广告','搜索引擎','百度','谷歌','必应','其他']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis : [
{
type : 'category',
data : ['周一','周二','周三','周四','周五','周六','周日']
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'邮件营销',
type:'bar',
stack: '广告',
data:[120, 132, 101, 134, 90, 230, 210]
},
{
name:'联盟广告',
type:'bar',
stack: '广告',
data:[220, 182, 191, 234, 290, 330, 310]
},
{
name:'视频广告',
type:'bar',
stack: '广告',
data:[150, 232, 201, 154, 190, 330, 410]
}],
dataZoom: [
{
show: true,
filterMode: 'filter',
}
]
};
var chart = testHelper.create(echarts, 'main6', {
option: option,
// recordCanvas: true
});
});
</script>
</body>
</html> | test/stackBar-dataZoom.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00019338863785378635,
0.00017302826745435596,
0.00016436621081084013,
0.00017295440193265676,
0.0000030973742468631826
] |
{
"id": 1,
"code_window": [
" parseFinder as modelUtilParseFinder,\n",
" ParsedModelFinderKnown\n",
"} from '../../util/model';\n",
"\n",
"\n",
"const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;\n",
"type COORD_CONVERTS_INDEX = 0 | 1;\n",
"\n",
"// FIXME\n",
"// how to genarialize to more coordinate systems.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*
* 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 { each, indexOf, curry, assert, map, createHashMap } from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as brushHelper from './brushHelper';
import {
BrushPanelConfig, BrushControllerEvents, BrushType,
BrushAreaRange, BrushDimensionMinMax
} from './BrushController';
import ExtensionAPI from '../../core/ExtensionAPI';
import GridModel from '../../coord/cartesian/GridModel';
import GeoModel from '../../coord/geo/GeoModel';
import { CoordinateSystemMaster } from '../../coord/CoordinateSystem';
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Geo from '../../coord/geo/Geo';
import GlobalModel from '../../model/Global';
import { BrushAreaParam, BrushAreaParamInternal } from '../brush/BrushModel';
import SeriesModel from '../../model/Series';
import { Dictionary } from '../../util/types';
import {
ModelFinderObject, ParsedModelFinder, ModelFinder,
parseFinder as modelUtilParseFinder,
ParsedModelFinderKnown
} from '../../util/model';
const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;
type COORD_CONVERTS_INDEX = 0 | 1;
// FIXME
// how to genarialize to more coordinate systems.
const INCLUDE_FINDER_MAIN_TYPES = [
'grid', 'xAxis', 'yAxis', 'geo', 'graph',
'polar', 'radiusAxis', 'angleAxis', 'bmap'
];
type BrushableCoordinateSystem = Cartesian2D | Geo;
type BrushTargetBuilderKey = 'grid' | 'geo';
/**
* There can be multiple axes in a single targetInfo. Consider the case
* of `grid` component, a targetInfo represents a grid which contains one or more
* cartesian and one or more axes. And consider the case of parallel system,
* which has multiple axes in a coordinate system.
*/
interface BrushTargetInfo {
panelId: string;
coordSysModel: CoordinateSystemMaster['model'];
// Use the first one as the representitive coordSys.
// A representitive cartesian in grid (first cartesian by default).
coordSys: BrushableCoordinateSystem;
// All cartesians.
coordSyses: BrushableCoordinateSystem[];
getPanelRect: GetPanelRect,
}
export interface BrushTargetInfoCartesian2D extends BrushTargetInfo {
gridModel: GridModel;
coordSys: Cartesian2D;
coordSyses: Cartesian2D[];
xAxisDeclared: boolean;
yAxisDeclared: boolean;
}
export interface BrushTargetInfoGeo extends BrushTargetInfo {
geoModel: GeoModel,
coordSysModel: GeoModel,
coordSys: Geo,
coordSyses: Geo[],
}
type GetPanelRect = () => graphic.BoundingRect;
class BrushTargetManager {
private _targetInfoList: BrushTargetInfo[] = [];
/**
* @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
* Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
* @param opt.include include coordinate system types.
*/
constructor(
finder: ModelFinderObject,
ecModel: GlobalModel,
opt?: {include?: BrushTargetBuilderKey[]}
) {
const foundCpts = parseFinder(ecModel, finder);
each(targetInfoBuilders, (builder, type) => {
if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
builder(foundCpts, this._targetInfoList);
}
});
}
setOutputRanges(
areas: BrushControllerEvents['brush']['areas'],
ecModel: GlobalModel
): BrushAreaParam[] {
this.matchOutputRanges(areas, ecModel, function (
area: BrushAreaParam,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem
) {
(area.coordRanges || (area.coordRanges = [])).push(coordRange);
// area.coordRange is the first of area.coordRanges
if (!area.coordRange) {
area.coordRange = coordRange;
// In 'category' axis, coord to pixel is not reversible, so we can not
// rebuild range by coordRange accrately, which may bring trouble when
// brushing only one item. So we use __rangeOffset to rebuilding range
// by coordRange. And this it only used in brush component so it is no
// need to be adapted to coordRanges.
const result = coordConvert[area.brushType](0, coordSys, coordRange);
area.__rangeOffset = {
offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
xyMinMax: result.xyMinMax
};
}
});
return areas;
}
matchOutputRanges<T extends (
Parameters<BrushTargetManager['findTargetInfo']>[0] & {
brushType: BrushType;
range: BrushAreaRange;
}
)>(
areas: T[],
ecModel: GlobalModel,
cb: (
area: T,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem,
ecModel: GlobalModel
) => void
) {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (targetInfo && targetInfo !== true) {
each(
targetInfo.coordSyses,
function (coordSys) {
const result = coordConvert[area.brushType](1, coordSys, area.range, true);
cb(area, result.values, coordSys, ecModel);
}
);
}
}, this);
}
/**
* the `areas` is `BrushModel.areas`.
* Called in layout stage.
* convert `area.coordRange` to global range and set panelId to `area.range`.
*/
setInputRanges(
areas: BrushAreaParamInternal[],
ecModel: GlobalModel
): void {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (__DEV__) {
assert(
!targetInfo || targetInfo === true || area.coordRange,
'coordRange must be specified when coord index specified.'
);
assert(
!targetInfo || targetInfo !== true || area.range,
'range must be specified in global brush.'
);
}
area.range = area.range || [];
// convert coordRange to global range and set panelId.
if (targetInfo && targetInfo !== true) {
area.panelId = targetInfo.panelId;
// (1) area.range shoule always be calculate from coordRange but does
// not keep its original value, for the sake of the dataZoom scenario,
// where area.coordRange remains unchanged but area.range may be changed.
// (2) Only support converting one coordRange to pixel range in brush
// component. So do not consider `coordRanges`.
// (3) About __rangeOffset, see comment above.
const result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
const rangeOffset = area.__rangeOffset;
area.range = rangeOffset
? diffProcessor[area.brushType](
result.values,
rangeOffset.offset,
getScales(result.xyMinMax, rangeOffset.xyMinMax)
)
: result.values;
}
}, this);
}
makePanelOpts(
api: ExtensionAPI,
getDefaultBrushType?: (targetInfo: BrushTargetInfo) => BrushType
): BrushPanelConfig[] {
return map(this._targetInfoList, function (targetInfo) {
const rect = targetInfo.getPanelRect();
return {
panelId: targetInfo.panelId,
defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
clipPath: brushHelper.makeRectPanelClipPath(rect),
isTargetByCursor: brushHelper.makeRectIsTargetByCursor(
rect, api, targetInfo.coordSysModel
),
getLinearBrushOtherExtent: brushHelper.makeLinearBrushOtherExtent(rect)
};
});
}
controlSeries(area: BrushAreaParamInternal, seriesModel: SeriesModel, ecModel: GlobalModel): boolean {
// Check whether area is bound in coord, and series do not belong to that coord.
// If do not do this check, some brush (like lineX) will controll all axes.
const targetInfo = this.findTargetInfo(area, ecModel);
return targetInfo === true || (
targetInfo && indexOf(
targetInfo.coordSyses, seriesModel.coordinateSystem as BrushableCoordinateSystem
) >= 0
);
}
/**
* If return Object, a coord found.
* If reutrn true, global found.
* Otherwise nothing found.
*/
findTargetInfo(
area: ModelFinderObject & {
panelId?: string
},
ecModel: GlobalModel
): BrushTargetInfo | true {
const targetInfoList = this._targetInfoList;
const foundCpts = parseFinder(ecModel, area);
for (let i = 0; i < targetInfoList.length; i++) {
const targetInfo = targetInfoList[i];
const areaPanelId = area.panelId;
if (areaPanelId) {
if (targetInfo.panelId === areaPanelId) {
return targetInfo;
}
}
else {
for (let j = 0; j < targetInfoMatchers.length; j++) {
if (targetInfoMatchers[j](foundCpts, targetInfo)) {
return targetInfo;
}
}
}
}
return true;
}
}
function formatMinMax(minMax: BrushDimensionMinMax): BrushDimensionMinMax {
minMax[0] > minMax[1] && minMax.reverse();
return minMax;
}
function parseFinder(
ecModel: GlobalModel, finder: ModelFinder
): ParsedModelFinderKnown {
return modelUtilParseFinder(
ecModel, finder, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
);
}
type TargetInfoBuilder = (
foundCpts: ParsedModelFinderKnown, targetInfoList: BrushTargetInfo[]
) => void;
const targetInfoBuilders: Record<BrushTargetBuilderKey, TargetInfoBuilder> = {
grid: function (foundCpts, targetInfoList) {
const xAxisModels = foundCpts.xAxisModels;
const yAxisModels = foundCpts.yAxisModels;
const gridModels = foundCpts.gridModels;
// Remove duplicated.
const gridModelMap = createHashMap<GridModel>();
const xAxesHas = {} as Dictionary<boolean>;
const yAxesHas = {} as Dictionary<boolean>;
if (!xAxisModels && !yAxisModels && !gridModels) {
return;
}
each(xAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
});
each(yAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
yAxesHas[gridModel.id] = true;
});
each(gridModels, function (gridModel) {
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
yAxesHas[gridModel.id] = true;
});
gridModelMap.each(function (gridModel) {
const grid = gridModel.coordinateSystem;
const cartesians = [] as Cartesian2D[];
each(grid.getCartesians(), function (cartesian, index) {
if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0
|| indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0
) {
cartesians.push(cartesian);
}
});
targetInfoList.push({
panelId: 'grid--' + gridModel.id,
gridModel: gridModel,
coordSysModel: gridModel,
// Use the first one as the representitive coordSys.
coordSys: cartesians[0],
coordSyses: cartesians,
getPanelRect: panelRectBuilders.grid,
xAxisDeclared: xAxesHas[gridModel.id],
yAxisDeclared: yAxesHas[gridModel.id]
} as BrushTargetInfoCartesian2D);
});
},
geo: function (foundCpts, targetInfoList) {
each(foundCpts.geoModels, function (geoModel: GeoModel) {
const coordSys = geoModel.coordinateSystem;
targetInfoList.push({
panelId: 'geo--' + geoModel.id,
geoModel: geoModel,
coordSysModel: geoModel,
coordSys: coordSys,
coordSyses: [coordSys],
getPanelRect: panelRectBuilders.geo
} as BrushTargetInfoGeo);
});
}
};
type TargetInfoMatcher = (
foundCpts: ParsedModelFinderKnown, targetInfo: BrushTargetInfo
) => boolean;
const targetInfoMatchers: TargetInfoMatcher[] = [
// grid
function (foundCpts, targetInfo) {
const xAxisModel = foundCpts.xAxisModel;
const yAxisModel = foundCpts.yAxisModel;
let gridModel = foundCpts.gridModel;
!gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
!gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
return gridModel && gridModel === (targetInfo as BrushTargetInfoCartesian2D).gridModel;
},
// geo
function (foundCpts, targetInfo) {
const geoModel = foundCpts.geoModel;
return geoModel && geoModel === (targetInfo as BrushTargetInfoGeo).geoModel;
}
];
type PanelRectBuilder = (this: BrushTargetInfo) => graphic.BoundingRect;
const panelRectBuilders: Record<BrushTargetBuilderKey, PanelRectBuilder> = {
grid: function (this: BrushTargetInfoCartesian2D) {
// grid is not Transformable.
return this.coordSys.master.getRect().clone();
},
geo: function (this: BrushTargetInfoGeo) {
const coordSys = this.coordSys;
const rect = coordSys.getBoundingRect().clone();
// geo roam and zoom transform
rect.applyTransform(graphic.getTransform(coordSys));
return rect;
}
};
type ConvertCoord = (
to: COORD_CONVERTS_INDEX,
coordSys: BrushableCoordinateSystem,
rangeOrCoordRange: BrushAreaRange,
clamp?: boolean
) => {
values: BrushAreaRange,
xyMinMax: BrushDimensionMinMax[]
};
const coordConvert: Record<BrushType, ConvertCoord> = {
lineX: curry(axisConvert, 0),
lineY: curry(axisConvert, 1),
rect: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xminymin = to
? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
const xmaxymax = to
? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
const values = [
formatMinMax([xminymin[0], xmaxymax[0]]),
formatMinMax([xminymin[1], xmaxymax[1]])
];
return {values: values, xyMinMax: values};
},
polygon: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
const values = map(rangeOrCoordRange, function (item) {
const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);
xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
return p;
});
return {values: values, xyMinMax: xyMinMax};
}
};
function axisConvert(
axisNameIndex: 0 | 1,
to: COORD_CONVERTS_INDEX,
coordSys: Cartesian2D,
rangeOrCoordRange: BrushDimensionMinMax
): {
values: BrushDimensionMinMax,
xyMinMax: BrushDimensionMinMax[]
} {
if (__DEV__) {
assert(
coordSys.type === 'cartesian2d',
'lineX/lineY brush is available only in cartesian2d.'
);
}
const axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
const values = formatMinMax(map([0, 1], function (i) {
return to
? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true)
: axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
}));
const xyMinMax = [];
xyMinMax[axisNameIndex] = values;
xyMinMax[1 - axisNameIndex] = [NaN, NaN];
return {values: values, xyMinMax: xyMinMax};
}
type DiffProcess = (
values: BrushDimensionMinMax | BrushDimensionMinMax[],
refer: BrushDimensionMinMax | BrushDimensionMinMax[],
scales: ReturnType<typeof getScales>
) => BrushDimensionMinMax | BrushDimensionMinMax[];
const diffProcessor: Record<BrushType, DiffProcess> = {
lineX: curry(axisDiffProcessor, 0),
lineY: curry(axisDiffProcessor, 1),
rect: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return [
[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
[values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
];
},
polygon: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return map(values, function (item, idx) {
return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
});
}
};
function axisDiffProcessor(
axisNameIndex: 0 | 1,
values: BrushDimensionMinMax,
refer: BrushDimensionMinMax,
scales: ReturnType<typeof getScales>
): BrushDimensionMinMax {
return [
values[0] - scales[axisNameIndex] * refer[0],
values[1] - scales[axisNameIndex] * refer[1]
];
}
// We have to process scale caused by dataZoom manually,
// although it might be not accurate.
// Return [0~1, 0~1]
function getScales(xyMinMaxCurr: BrushDimensionMinMax[], xyMinMaxOrigin: BrushDimensionMinMax[]): number[] {
const sizeCurr = getSize(xyMinMaxCurr);
const sizeOrigin = getSize(xyMinMaxOrigin);
const scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
function getSize(xyMinMax: BrushDimensionMinMax[]): number[] {
return xyMinMax
? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
: [NaN, NaN];
}
export default BrushTargetManager;
| src/component/helper/BrushTargetManager.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.999302864074707,
0.07121191173791885,
0.00016748336201999336,
0.00017851086158771068,
0.2526291310787201
] |
{
"id": 1,
"code_window": [
" parseFinder as modelUtilParseFinder,\n",
" ParsedModelFinderKnown\n",
"} from '../../util/model';\n",
"\n",
"\n",
"const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;\n",
"type COORD_CONVERTS_INDEX = 0 | 1;\n",
"\n",
"// FIXME\n",
"// how to genarialize to more coordinate systems.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*
* 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.
*/
const socket = io('/client');
const LOCAL_SAVE_KEY = 'visual-regression-testing-config';
function processTestsData(tests, oldTestsData) {
tests.forEach((test, idx) => {
let passed = 0;
test.index = idx;
test.results.forEach(result => {
// Threshold?
if (result.diffRatio < 0.0001) {
passed++;
}
let timestamp = test.lastRun || 0;
result.diff = result.diff + '?' + timestamp;
result.actual = result.actual + '?' + timestamp;
result.expected = result.expected + '?' + timestamp;
});
test.percentage = passed === 0 ? 0 : Math.round(passed / test.results.length * 100);
if (test.percentage === 100) {
test.summary = 'success';
}
else if (test.percentage < 50) {
test.summary = 'exception';
}
else {
test.summary = 'warning';
}
// Keep select status not change.
if (oldTestsData && oldTestsData[idx]) {
test.selected = oldTestsData[idx].selected;
}
else {
test.selected = false;
}
});
return tests;
}
const app = new Vue({
el: '#app',
data: {
fullTests: [],
currentTestName: '',
sortBy: 'name',
searchString: '',
running: false,
allSelected: false,
lastSelectedIndex: -1,
versions: [],
showIframeDialog: false,
previewIframeSrc: '',
previewTitle: '',
runConfig: {
noHeadless: false,
replaySpeed: 5,
actualVersion: 'local',
expectedVersion: null,
renderer: 'canvas',
threads: 1
}
},
computed: {
tests() {
let sortFunc = this.sortBy === 'name'
? (a, b) => a.name.localeCompare(b.name)
: (a, b) => {
if (a.percentage === b.percentage) {
if (a.actualErrors && b.actualErrors) {
if (a.actualErrors.length === b.actualErrors.length) {
return a.name.localeCompare(b.name);
}
else {
return b.actualErrors.length - a.actualErrors.length;
}
}
else {
return a.name.localeCompare(b.name);
}
}
return a.percentage - b.percentage;
};
if (!this.searchString) {
// Not modify the original tests data.
return this.fullTests.slice().sort(sortFunc);
}
let searchString = this.searchString.toLowerCase();
return this.fullTests.filter(test => {
return test.name.toLowerCase().match(searchString);
}).sort(sortFunc);
},
selectedTests() {
return this.fullTests.filter(test => {
return test.selected;
});
},
unfinishedTests() {
return this.fullTests.filter(test => {
return test.status !== 'finished';
});
},
failedTests() {
return this.fullTests.filter(test => {
return test.status === 'finished' && test.summary !== 'success';
});
},
currentTest() {
let currentTest = this.fullTests.find(item => item.name === this.currentTestName);
if (!currentTest) {
currentTest = this.fullTests[0];
}
return currentTest;
},
currentTestUrl() {
return window.location.origin + '/test/' + this.currentTestName + '.html';
},
currentTestRecordUrl() {
return window.location.origin + '/test/runTest/recorder/index.html#' + this.currentTestName;
},
isSelectAllIndeterminate: {
get() {
if (!this.tests.length) {
return true;
}
return this.tests.some(test => {
return test.selected !== this.tests[0].selected;
});
},
set() {}
}
},
methods: {
goto(url) {
window.location.hash = '#' + url;
},
toggleSort() {
this.sortBy = this.sortBy === 'name' ? 'percentage' : 'name';
},
handleSelectAllChange(val) {
// Only select filtered tests.
this.tests.forEach(test => {
test.selected = val;
});
this.isSelectAllIndeterminate = false;
},
handleSelect(idx) {
Vue.nextTick(() => {
this.lastSelectedIndex = idx;
});
},
handleShiftSelect(idx) {
if (this.lastSelectedIndex < 0) {
return;
}
let start = Math.min(this.lastSelectedIndex, idx);
let end = Math.max(this.lastSelectedIndex, idx);
let selected = !this.tests[idx].selected; // Will change
for (let i = start; i < end; i++) {
this.tests[i].selected = selected;
}
},
runSingleTest(testName) {
runTests([testName]);
},
run(runTarget) {
let tests;
if (runTarget === 'selected') {
tests = this.selectedTests;
}
else if (runTarget === 'unfinished') {
tests = this.unfinishedTests;
}
else if (runTarget === 'failed') {
tests = this.failedTests;
}
else {
tests = this.fullTests;
}
runTests(tests.map(test => test.name));
},
stopTests() {
this.running = false;
socket.emit('stop');
},
preview(test, version) {
let searches = [];
let ecVersion = test[version + 'Version'];
if (ecVersion !== 'local') {
searches.push('__ECDIST__=' + ecVersion);
}
if (test.useSVG) {
searches.push('__RENDERER__=svg');
}
let src = test.fileUrl;
if (searches.length) {
src = src + '?' + searches.join('&');
}
this.previewIframeSrc = `../../${src}`;
this.previewTitle = src;
this.showIframeDialog = true;
}
}
});
// Save and restore
try {
Object.assign(app.runConfig, JSON.parse(localStorage.getItem(LOCAL_SAVE_KEY)));
}
catch (e) {}
app.$watch('runConfig', () => {
localStorage.setItem(LOCAL_SAVE_KEY, JSON.stringify(app.runConfig));
}, {deep: true});
function runTests(tests) {
if (!tests.length) {
app.$notify({
title: 'No test selected.',
position: 'top-right'
});
return;
}
if (!app.runConfig.expectedVersion || !app.runConfig.actualVersion) {
app.$notify({
title: 'No echarts version selected.',
position: 'top-right'
});
return;
}
app.running = true;
socket.emit('run', {
tests,
expectedVersion: app.runConfig.expectedVersion,
actualVersion: app.runConfig.actualVersion,
threads: app.runConfig.threads,
renderer: app.runConfig.renderer,
noHeadless: app.runConfig.noHeadless,
replaySpeed: app.runConfig.noHeadless
? app.runConfig.replaySpeed
: 5 // Force run at 5x speed
});
}
socket.on('connect', () => {
console.log('Connected');
app.$el.style.display = 'block';
});
let firstUpdate = true;
socket.on('update', msg => {
let hasFinishedTest = !!msg.tests.find(test => test.status === 'finished');
if (!hasFinishedTest && firstUpdate) {
app.$confirm('It seems you haven\'t run any test yet!<br />Do you want to start now?', 'Tip', {
confirmButtonText: 'Yes',
cancelButtonText: 'No',
dangerouslyUseHTMLString: true,
center: true
}).then(value => {
runTests(msg.tests.map(test => test.name));
}).catch(() => {});
}
// TODO
app.running = !!msg.running;
app.fullTests = processTestsData(msg.tests, app.fullTests);
firstUpdate = false;
});
socket.on('finish', res => {
app.$notify({
type: 'success',
title: `${res.count} test complete`,
message: `Cost: ${(res.time / 1000).toFixed(1)} s. Threads: ${res.threads}`,
position: 'top-right',
duration: 8000
});
console.log(`${res.count} test complete, Cost: ${(res.time / 1000).toFixed(1)} s. Threads: ${res.threads}`);
app.running = false;
});
socket.on('abort', res => {
app.$notify({
type: 'info',
title: `Aborted`,
duration: 4000
});
app.running = false;
});
socket.on('versions', versions => {
app.versions = versions.filter(version => {
return !version.startsWith('2.');
}).reverse();
if (!app.runConfig.expectedVersion) {
app.runConfig.expectedVersion = app.versions[0];
}
app.versions.unshift('local');
});
function updateTestHash() {
app.currentTestName = window.location.hash.slice(1);
}
updateTestHash();
window.addEventListener('hashchange', updateTestHash); | test/runTest/client/client.js | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00023703154874965549,
0.00017389764252584428,
0.00016868329839780927,
0.00017140738782472908,
0.000011220608939765953
] |
{
"id": 1,
"code_window": [
" parseFinder as modelUtilParseFinder,\n",
" ParsedModelFinderKnown\n",
"} from '../../util/model';\n",
"\n",
"\n",
"const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;\n",
"type COORD_CONVERTS_INDEX = 0 | 1;\n",
"\n",
"// FIXME\n",
"// how to genarialize to more coordinate systems.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 43
} |
/*
* 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.
*/
const path = require('path');
const {build} = require('esbuild');
const outFilePath = path.resolve(__dirname, '../dist/echarts.js');
const umdMark = '// ------------- WRAPPED UMD --------------- //';
const umdWrapperHead = `
${umdMark}
(function (root, factory) {
window.__DEV__ = true;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports'], factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
factory(exports);
} else {
// Browser globals
factory((root.echarts = {}));
}
}(typeof self !== 'undefined' ? self : this, function (exports, b) {
`;
const umdWrapperTail = `
}));`;
build({
entryPoints: [path.resolve(__dirname, '../src/echarts.all.ts')],
outfile: outFilePath,
format: 'cjs',
sourcemap: true,
bundle: true,
banner: umdWrapperHead,
footer: umdWrapperTail,
watch: {
async onRebuild(error) {
if (error) {
console.error('watch build failed:', error)
} else {
console.log('build done')
}
},
},
}).then(async () => {
console.log('build done')
}).catch(e => console.error(e.toString()))
| build/dev-fast.js | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00018032881780527532,
0.00017497691442258656,
0.0001683572627371177,
0.00017578880942892283,
0.000003933410425815964
] |
{
"id": 1,
"code_window": [
" parseFinder as modelUtilParseFinder,\n",
" ParsedModelFinderKnown\n",
"} from '../../util/model';\n",
"\n",
"\n",
"const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;\n",
"type COORD_CONVERTS_INDEX = 0 | 1;\n",
"\n",
"// FIXME\n",
"// how to genarialize to more coordinate systems.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 43
} | /*
* 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 * as axisPointerModelHelper from '../axisPointer/modelHelper';
import ComponentView from '../../view/Component';
import { AxisBaseModel } from '../../coord/AxisBaseModel';
import GlobalModel from '../../model/Global';
import ExtensionAPI from '../../core/ExtensionAPI';
import { Payload, Dictionary } from '../../util/types';
import type BaseAxisPointer from '../axisPointer/BaseAxisPointer';
const axisPointerClazz: Dictionary<AxisPointerConstructor> = {};
interface AxisPointerConstructor {
new(): BaseAxisPointer
}
/**
* Base class of AxisView.
*/
class AxisView extends ComponentView {
static type = 'axis';
type = AxisView.type;
/**
* @private
*/
private _axisPointer: BaseAxisPointer;
/**
* @protected
*/
axisPointerClass: string;
/**
* @override
*/
render(axisModel: AxisBaseModel, ecModel: GlobalModel, api: ExtensionAPI, payload: Payload) {
// FIXME
// This process should proformed after coordinate systems updated
// (axis scale updated), and should be performed each time update.
// So put it here temporarily, although it is not appropriate to
// put a model-writing procedure in `view`.
this.axisPointerClass && axisPointerModelHelper.fixValue(axisModel);
super.render.apply(this, arguments as any);
this._doUpdateAxisPointerClass(axisModel, api, true);
}
/**
* Action handler.
*/
updateAxisPointer(
axisModel: AxisBaseModel,
ecModel: GlobalModel,
api: ExtensionAPI,
payload: Payload
) {
this._doUpdateAxisPointerClass(axisModel, api, false);
}
/**
* @override
*/
remove(ecModel: GlobalModel, api: ExtensionAPI) {
const axisPointer = this._axisPointer;
axisPointer && axisPointer.remove(api);
}
/**
* @override
*/
dispose(ecModel: GlobalModel, api: ExtensionAPI) {
this._disposeAxisPointer(api);
super.dispose.apply(this, arguments as any);
}
private _doUpdateAxisPointerClass(axisModel: AxisBaseModel, api: ExtensionAPI, forceRender?: boolean) {
const Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
if (!Clazz) {
return;
}
const axisPointerModel = axisPointerModelHelper.getAxisPointerModel(axisModel);
axisPointerModel
? (this._axisPointer || (this._axisPointer = new Clazz()))
.render(axisModel, axisPointerModel, api, forceRender)
: this._disposeAxisPointer(api);
}
private _disposeAxisPointer(api: ExtensionAPI) {
this._axisPointer && this._axisPointer.dispose(api);
this._axisPointer = null;
}
static registerAxisPointerClass(type: string, clazz: AxisPointerConstructor) {
if (__DEV__) {
if (axisPointerClazz[type]) {
throw new Error('axisPointer ' + type + ' exists');
}
}
axisPointerClazz[type] = clazz;
};
static getAxisPointerClass(type: string) {
return type && axisPointerClazz[type];
};
}
export default AxisView; | src/component/axis/AxisView.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0004334454715717584,
0.0001922727096825838,
0.0001666321186348796,
0.00017149336053989828,
0.00006967613444430754
] |
{
"id": 2,
"code_window": [
" xyMinMax: BrushDimensionMinMax[]\n",
" } {\n",
" const xminymin = to\n",
" ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);\n",
" const xmaxymax = to\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 430
} | /*
* 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 { each, indexOf, curry, assert, map, createHashMap } from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as brushHelper from './brushHelper';
import {
BrushPanelConfig, BrushControllerEvents, BrushType,
BrushAreaRange, BrushDimensionMinMax
} from './BrushController';
import ExtensionAPI from '../../core/ExtensionAPI';
import GridModel from '../../coord/cartesian/GridModel';
import GeoModel from '../../coord/geo/GeoModel';
import { CoordinateSystemMaster } from '../../coord/CoordinateSystem';
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Geo from '../../coord/geo/Geo';
import GlobalModel from '../../model/Global';
import { BrushAreaParam, BrushAreaParamInternal } from '../brush/BrushModel';
import SeriesModel from '../../model/Series';
import { Dictionary } from '../../util/types';
import {
ModelFinderObject, ParsedModelFinder, ModelFinder,
parseFinder as modelUtilParseFinder,
ParsedModelFinderKnown
} from '../../util/model';
const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;
type COORD_CONVERTS_INDEX = 0 | 1;
// FIXME
// how to genarialize to more coordinate systems.
const INCLUDE_FINDER_MAIN_TYPES = [
'grid', 'xAxis', 'yAxis', 'geo', 'graph',
'polar', 'radiusAxis', 'angleAxis', 'bmap'
];
type BrushableCoordinateSystem = Cartesian2D | Geo;
type BrushTargetBuilderKey = 'grid' | 'geo';
/**
* There can be multiple axes in a single targetInfo. Consider the case
* of `grid` component, a targetInfo represents a grid which contains one or more
* cartesian and one or more axes. And consider the case of parallel system,
* which has multiple axes in a coordinate system.
*/
interface BrushTargetInfo {
panelId: string;
coordSysModel: CoordinateSystemMaster['model'];
// Use the first one as the representitive coordSys.
// A representitive cartesian in grid (first cartesian by default).
coordSys: BrushableCoordinateSystem;
// All cartesians.
coordSyses: BrushableCoordinateSystem[];
getPanelRect: GetPanelRect,
}
export interface BrushTargetInfoCartesian2D extends BrushTargetInfo {
gridModel: GridModel;
coordSys: Cartesian2D;
coordSyses: Cartesian2D[];
xAxisDeclared: boolean;
yAxisDeclared: boolean;
}
export interface BrushTargetInfoGeo extends BrushTargetInfo {
geoModel: GeoModel,
coordSysModel: GeoModel,
coordSys: Geo,
coordSyses: Geo[],
}
type GetPanelRect = () => graphic.BoundingRect;
class BrushTargetManager {
private _targetInfoList: BrushTargetInfo[] = [];
/**
* @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
* Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
* @param opt.include include coordinate system types.
*/
constructor(
finder: ModelFinderObject,
ecModel: GlobalModel,
opt?: {include?: BrushTargetBuilderKey[]}
) {
const foundCpts = parseFinder(ecModel, finder);
each(targetInfoBuilders, (builder, type) => {
if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
builder(foundCpts, this._targetInfoList);
}
});
}
setOutputRanges(
areas: BrushControllerEvents['brush']['areas'],
ecModel: GlobalModel
): BrushAreaParam[] {
this.matchOutputRanges(areas, ecModel, function (
area: BrushAreaParam,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem
) {
(area.coordRanges || (area.coordRanges = [])).push(coordRange);
// area.coordRange is the first of area.coordRanges
if (!area.coordRange) {
area.coordRange = coordRange;
// In 'category' axis, coord to pixel is not reversible, so we can not
// rebuild range by coordRange accrately, which may bring trouble when
// brushing only one item. So we use __rangeOffset to rebuilding range
// by coordRange. And this it only used in brush component so it is no
// need to be adapted to coordRanges.
const result = coordConvert[area.brushType](0, coordSys, coordRange);
area.__rangeOffset = {
offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
xyMinMax: result.xyMinMax
};
}
});
return areas;
}
matchOutputRanges<T extends (
Parameters<BrushTargetManager['findTargetInfo']>[0] & {
brushType: BrushType;
range: BrushAreaRange;
}
)>(
areas: T[],
ecModel: GlobalModel,
cb: (
area: T,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem,
ecModel: GlobalModel
) => void
) {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (targetInfo && targetInfo !== true) {
each(
targetInfo.coordSyses,
function (coordSys) {
const result = coordConvert[area.brushType](1, coordSys, area.range, true);
cb(area, result.values, coordSys, ecModel);
}
);
}
}, this);
}
/**
* the `areas` is `BrushModel.areas`.
* Called in layout stage.
* convert `area.coordRange` to global range and set panelId to `area.range`.
*/
setInputRanges(
areas: BrushAreaParamInternal[],
ecModel: GlobalModel
): void {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (__DEV__) {
assert(
!targetInfo || targetInfo === true || area.coordRange,
'coordRange must be specified when coord index specified.'
);
assert(
!targetInfo || targetInfo !== true || area.range,
'range must be specified in global brush.'
);
}
area.range = area.range || [];
// convert coordRange to global range and set panelId.
if (targetInfo && targetInfo !== true) {
area.panelId = targetInfo.panelId;
// (1) area.range shoule always be calculate from coordRange but does
// not keep its original value, for the sake of the dataZoom scenario,
// where area.coordRange remains unchanged but area.range may be changed.
// (2) Only support converting one coordRange to pixel range in brush
// component. So do not consider `coordRanges`.
// (3) About __rangeOffset, see comment above.
const result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
const rangeOffset = area.__rangeOffset;
area.range = rangeOffset
? diffProcessor[area.brushType](
result.values,
rangeOffset.offset,
getScales(result.xyMinMax, rangeOffset.xyMinMax)
)
: result.values;
}
}, this);
}
makePanelOpts(
api: ExtensionAPI,
getDefaultBrushType?: (targetInfo: BrushTargetInfo) => BrushType
): BrushPanelConfig[] {
return map(this._targetInfoList, function (targetInfo) {
const rect = targetInfo.getPanelRect();
return {
panelId: targetInfo.panelId,
defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
clipPath: brushHelper.makeRectPanelClipPath(rect),
isTargetByCursor: brushHelper.makeRectIsTargetByCursor(
rect, api, targetInfo.coordSysModel
),
getLinearBrushOtherExtent: brushHelper.makeLinearBrushOtherExtent(rect)
};
});
}
controlSeries(area: BrushAreaParamInternal, seriesModel: SeriesModel, ecModel: GlobalModel): boolean {
// Check whether area is bound in coord, and series do not belong to that coord.
// If do not do this check, some brush (like lineX) will controll all axes.
const targetInfo = this.findTargetInfo(area, ecModel);
return targetInfo === true || (
targetInfo && indexOf(
targetInfo.coordSyses, seriesModel.coordinateSystem as BrushableCoordinateSystem
) >= 0
);
}
/**
* If return Object, a coord found.
* If reutrn true, global found.
* Otherwise nothing found.
*/
findTargetInfo(
area: ModelFinderObject & {
panelId?: string
},
ecModel: GlobalModel
): BrushTargetInfo | true {
const targetInfoList = this._targetInfoList;
const foundCpts = parseFinder(ecModel, area);
for (let i = 0; i < targetInfoList.length; i++) {
const targetInfo = targetInfoList[i];
const areaPanelId = area.panelId;
if (areaPanelId) {
if (targetInfo.panelId === areaPanelId) {
return targetInfo;
}
}
else {
for (let j = 0; j < targetInfoMatchers.length; j++) {
if (targetInfoMatchers[j](foundCpts, targetInfo)) {
return targetInfo;
}
}
}
}
return true;
}
}
function formatMinMax(minMax: BrushDimensionMinMax): BrushDimensionMinMax {
minMax[0] > minMax[1] && minMax.reverse();
return minMax;
}
function parseFinder(
ecModel: GlobalModel, finder: ModelFinder
): ParsedModelFinderKnown {
return modelUtilParseFinder(
ecModel, finder, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
);
}
type TargetInfoBuilder = (
foundCpts: ParsedModelFinderKnown, targetInfoList: BrushTargetInfo[]
) => void;
const targetInfoBuilders: Record<BrushTargetBuilderKey, TargetInfoBuilder> = {
grid: function (foundCpts, targetInfoList) {
const xAxisModels = foundCpts.xAxisModels;
const yAxisModels = foundCpts.yAxisModels;
const gridModels = foundCpts.gridModels;
// Remove duplicated.
const gridModelMap = createHashMap<GridModel>();
const xAxesHas = {} as Dictionary<boolean>;
const yAxesHas = {} as Dictionary<boolean>;
if (!xAxisModels && !yAxisModels && !gridModels) {
return;
}
each(xAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
});
each(yAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
yAxesHas[gridModel.id] = true;
});
each(gridModels, function (gridModel) {
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
yAxesHas[gridModel.id] = true;
});
gridModelMap.each(function (gridModel) {
const grid = gridModel.coordinateSystem;
const cartesians = [] as Cartesian2D[];
each(grid.getCartesians(), function (cartesian, index) {
if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0
|| indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0
) {
cartesians.push(cartesian);
}
});
targetInfoList.push({
panelId: 'grid--' + gridModel.id,
gridModel: gridModel,
coordSysModel: gridModel,
// Use the first one as the representitive coordSys.
coordSys: cartesians[0],
coordSyses: cartesians,
getPanelRect: panelRectBuilders.grid,
xAxisDeclared: xAxesHas[gridModel.id],
yAxisDeclared: yAxesHas[gridModel.id]
} as BrushTargetInfoCartesian2D);
});
},
geo: function (foundCpts, targetInfoList) {
each(foundCpts.geoModels, function (geoModel: GeoModel) {
const coordSys = geoModel.coordinateSystem;
targetInfoList.push({
panelId: 'geo--' + geoModel.id,
geoModel: geoModel,
coordSysModel: geoModel,
coordSys: coordSys,
coordSyses: [coordSys],
getPanelRect: panelRectBuilders.geo
} as BrushTargetInfoGeo);
});
}
};
type TargetInfoMatcher = (
foundCpts: ParsedModelFinderKnown, targetInfo: BrushTargetInfo
) => boolean;
const targetInfoMatchers: TargetInfoMatcher[] = [
// grid
function (foundCpts, targetInfo) {
const xAxisModel = foundCpts.xAxisModel;
const yAxisModel = foundCpts.yAxisModel;
let gridModel = foundCpts.gridModel;
!gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
!gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
return gridModel && gridModel === (targetInfo as BrushTargetInfoCartesian2D).gridModel;
},
// geo
function (foundCpts, targetInfo) {
const geoModel = foundCpts.geoModel;
return geoModel && geoModel === (targetInfo as BrushTargetInfoGeo).geoModel;
}
];
type PanelRectBuilder = (this: BrushTargetInfo) => graphic.BoundingRect;
const panelRectBuilders: Record<BrushTargetBuilderKey, PanelRectBuilder> = {
grid: function (this: BrushTargetInfoCartesian2D) {
// grid is not Transformable.
return this.coordSys.master.getRect().clone();
},
geo: function (this: BrushTargetInfoGeo) {
const coordSys = this.coordSys;
const rect = coordSys.getBoundingRect().clone();
// geo roam and zoom transform
rect.applyTransform(graphic.getTransform(coordSys));
return rect;
}
};
type ConvertCoord = (
to: COORD_CONVERTS_INDEX,
coordSys: BrushableCoordinateSystem,
rangeOrCoordRange: BrushAreaRange,
clamp?: boolean
) => {
values: BrushAreaRange,
xyMinMax: BrushDimensionMinMax[]
};
const coordConvert: Record<BrushType, ConvertCoord> = {
lineX: curry(axisConvert, 0),
lineY: curry(axisConvert, 1),
rect: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xminymin = to
? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
const xmaxymax = to
? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
const values = [
formatMinMax([xminymin[0], xmaxymax[0]]),
formatMinMax([xminymin[1], xmaxymax[1]])
];
return {values: values, xyMinMax: values};
},
polygon: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
const values = map(rangeOrCoordRange, function (item) {
const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);
xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
return p;
});
return {values: values, xyMinMax: xyMinMax};
}
};
function axisConvert(
axisNameIndex: 0 | 1,
to: COORD_CONVERTS_INDEX,
coordSys: Cartesian2D,
rangeOrCoordRange: BrushDimensionMinMax
): {
values: BrushDimensionMinMax,
xyMinMax: BrushDimensionMinMax[]
} {
if (__DEV__) {
assert(
coordSys.type === 'cartesian2d',
'lineX/lineY brush is available only in cartesian2d.'
);
}
const axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
const values = formatMinMax(map([0, 1], function (i) {
return to
? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true)
: axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
}));
const xyMinMax = [];
xyMinMax[axisNameIndex] = values;
xyMinMax[1 - axisNameIndex] = [NaN, NaN];
return {values: values, xyMinMax: xyMinMax};
}
type DiffProcess = (
values: BrushDimensionMinMax | BrushDimensionMinMax[],
refer: BrushDimensionMinMax | BrushDimensionMinMax[],
scales: ReturnType<typeof getScales>
) => BrushDimensionMinMax | BrushDimensionMinMax[];
const diffProcessor: Record<BrushType, DiffProcess> = {
lineX: curry(axisDiffProcessor, 0),
lineY: curry(axisDiffProcessor, 1),
rect: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return [
[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
[values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
];
},
polygon: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return map(values, function (item, idx) {
return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
});
}
};
function axisDiffProcessor(
axisNameIndex: 0 | 1,
values: BrushDimensionMinMax,
refer: BrushDimensionMinMax,
scales: ReturnType<typeof getScales>
): BrushDimensionMinMax {
return [
values[0] - scales[axisNameIndex] * refer[0],
values[1] - scales[axisNameIndex] * refer[1]
];
}
// We have to process scale caused by dataZoom manually,
// although it might be not accurate.
// Return [0~1, 0~1]
function getScales(xyMinMaxCurr: BrushDimensionMinMax[], xyMinMaxOrigin: BrushDimensionMinMax[]): number[] {
const sizeCurr = getSize(xyMinMaxCurr);
const sizeOrigin = getSize(xyMinMaxOrigin);
const scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
function getSize(xyMinMax: BrushDimensionMinMax[]): number[] {
return xyMinMax
? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
: [NaN, NaN];
}
export default BrushTargetManager;
| src/component/helper/BrushTargetManager.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.9982571005821228,
0.08272441476583481,
0.00016480311751365662,
0.00041875761235132813,
0.2534027397632599
] |
{
"id": 2,
"code_window": [
" xyMinMax: BrushDimensionMinMax[]\n",
" } {\n",
" const xminymin = to\n",
" ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);\n",
" const xmaxymax = to\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 430
} |
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<link rel="stylesheet" href="lib/reset.css">
<script src="lib/jquery.min.js"></script>
</head>
<body>
<style>
.main {
height: 400px;
margin: 10px 0 80px 0;
}
.label {
background: #ddd;
line-height: 30px;
font-weight: bold;
text-align: center;
}
</style>
<div class="label">Color Alpha in scatter (using outOfRange as 'selected')</div>
<div class="main" id="main1"></div>
<div class="label">Opacity in bar (label color specified)</div>
<div class="main" id="main2"></div>
<div class="label">Opacity in scatter (label color specified)</div>
<div class="main" id="main3"></div>
<div class="label">Opacity in graph (label color specified)</div>
<div class="main" id="main4"></div>
<div class="label">Opacity in heatmap (inactive color default using opacity)</div>
<div class="main" id="main5"></div>
<div class="label">Opacity in pie (label color and label line color specified)</div>
<div class="main" id="main6"></div>
<!-- ALPHA SCATTER -->
<script type="text/javascript">
require([
'echarts'
// 'echarts/chart/scatter',
// 'echarts/component/legend',
// 'echarts/component/grid',
// 'echarts/component/visualMapPiecewise'
], function (echarts) {
var main = document.getElementById('main1');
if (!main) {
return;
}
var chart = echarts.init(main);
var data1 = [];
var data2 = [];
var data3 = [];
var symbolCount = 6;
for (var i = 0; i < 100; i++) {
data1.push([
Math.random() * 5,
Math.random() * 4,
Math.random() * 20,
Math.round(Math.random() * (symbolCount - 1))
]);
data2.push([
Math.random() * 10,
Math.random() * 5,
Math.random() * 20,
Math.round(Math.random() * (symbolCount - 1))
]);
data3.push([
Math.random() * 15,
Math.random() * 10,
Math.random() * 20,
Math.round(Math.random() * (symbolCount - 1))
]);
}
chart.on('click', function (params) {
console.log(params);
});
chart.setOption({
color: ['#bcd3bb', '#928ea8', '#edc1a5'],
legend: {
data: ['scatter', 'scatter2', 'scatter3']
},
grid: {
top: 50,
bottom: 30
},
xAxis: {
type: 'value',
splitLine: {
show: false
}
},
yAxis: {
type: 'value',
splitLine: {
show: false
}
},
visualMap: [
{
type: 'piecewise',
splitNumber: 6,
left: 'right',
bottom: 30,
// selectedMode: 'single',
selectedMode: 'multiple',
selected: {
0: false, 1: false, 2: false, 3: false, 4: false, 5: false
},
dimension: 'value',
min: 0,
max: 24,
precision: 0,
inRange: { // visual for short cut
color: ['rgb(20,1,0)'],
symbolSize: [40, 5]
},
outOfRange: {
colorAlpha: [0.3, 1],
symbolSize: [40, 5]
}
}
],
series: [
{
name: 'scatter',
type: 'scatter',
itemStyle: {
normal: {
opacity: 0.8,
shadowBlur: 10,
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
},
data: data1
},
{
name: 'scatter2',
type: 'scatter',
itemStyle: {
normal: {
opacity: 0.8,
shadowBlur: 10,
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
},
data: data2
},
{
name: 'scatter3',
type: 'scatter',
itemStyle: {
normal: {
opacity: 0.8,
shadowBlur: 10,
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
},
data: data3
}
]
});
window.addEventListener('resize', function () {
chart.resize();
});
});
</script>
<!-- OPACITY BAR -->
<script>
require([
'echarts'
// 'echarts/chart/bar',
// 'echarts/chart/line',
// 'echarts/component/legend',
// 'echarts/component/grid',
// 'echarts/component/tooltip',
// 'echarts/component/toolbox',
// 'echarts/component/visualMap',
// 'zrender/vml/vml'
], function (echarts) {
var main = document.getElementById('main2');
if (!main) {
return;
}
var chart = echarts.init(main);
var xAxisData = [];
var data1 = [];
var data2 = [];
var data3 = [];
var data4 = [];
var DATA_MAX = 5.5;
for (var i = 0; i < 10; i++) {
xAxisData.push('类目' + i);
data1.push((Math.random() * DATA_MAX).toFixed(2));
data2.push(-Math.random().toFixed(2));
data3.push((Math.random() + 0.5).toFixed(2));
data4.push((Math.random() + 0.3).toFixed(2));
}
var labelStyle = {
normal: {
show: true,
position: 'outside',
textStyle: {
color: '#333'
}
}
};
var itemStyle = {
normal: {
},
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowColor: 'rgba(0,0,0,0.5)'
}
};
chart.setOption({
legend: {
data: ['bar', 'bar2', 'bar3'],
align: 'left'
},
toolbox: {
// y: 'bottom',
feature: {
magicType: {
type: ['line', 'bar', 'stack', 'tiled']
},
dataView: {}
}
},
tooltip: {},
xAxis: {
data: xAxisData,
axisLine: {
onZero: true
},
splitLine: {
show: false
},
splitArea: {
show: false
}
},
yAxis: {
splitArea: {
show: false
},
max: 6,
min: -2
},
visualMap: [
{
type: 'continuous',
right: 0,
itemWidth: 15,
bottom: 30,
dimension: 1,
calculable: true,
min: -2,
max: DATA_MAX,
precision: 2,
inRange: {
opacity: [1, 1] // Using opacity when label color specified
},
controller: {
inRange: {
color: '#888'
},
outOfRange: {
color: '#888'
}
},
outOfRange: {
opacity: [0.2, 0.2] // Using opacity when label color specified
}
}
],
series: [
{
name: 'bar',
type: 'bar',
stack: 'one',
itemStyle: itemStyle,
label: labelStyle,
data: data1
},
{
name: 'bar2',
type: 'bar',
stack: 'one',
itemStyle: itemStyle,
label: labelStyle,
data: data2
},
{
name: 'bar3',
type: 'bar',
itemStyle: itemStyle,
label: labelStyle,
data: data3
}
]
});
window.addEventListener('resize', function () {
chart.resize();
});
});
</script>
<!-- OPACITY SCATTER -->
<script type="text/javascript">
require([
'echarts'
// 'echarts/chart/scatter',
// 'echarts/component/legend',
// 'echarts/component/grid',
// 'echarts/component/visualMapPiecewise'
], function (echarts) {
var main = document.getElementById('main3');
if (!main) {
return;
}
var chart = echarts.init(main);
var data1 = [];
var symbolCount = 6;
for (var i = 0; i < 100; i++) {
data1.push([
Math.random() * 5,
Math.random() * 4,
+(Math.random() * 20).toFixed(2),
Math.round(Math.random() * (symbolCount - 1))
]);
}
chart.setOption({
legend: {
data: ['scatter', 'scatter2', 'scatter3']
},
grid: {
top: 50,
bottom: 30
},
xAxis: {
type: 'value',
splitLine: {
show: false
}
},
yAxis: {
type: 'value',
splitLine: {
show: false
}
},
visualMap: [
{
type: 'piecewise',
splitNumber: 6,
left: 'right',
bottom: 30,
selectedMode: 'multiple',
dimension: 'value',
min: 0,
max: 24,
precision: 0,
inRange: { // visual for short cut
opacity: 1,
symbolSize: [15, 50]
},
outOfRange: {
opacity: 0.3,
symbolSize: [15, 50]
}
}
],
series: [
{
name: 'scatter',
type: 'scatter',
itemStyle: {
normal: {
opacity: 0.8,
shadowBlur: 10,
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
},
label: {
normal: {
show: true,
formatter: '{@[2]}',
position: 'inside'
}
},
data: data1
}
]
});
window.addEventListener('resize', function () {
chart.resize();
});
});
</script>
<!-- OPACITY GRAPH -->
<script>
require([
'echarts',
'extension/dataTool',
// 'echarts/chart/graph',
// 'echarts/component/title',
// 'echarts/component/legend',
// 'echarts/component/geo',
// 'echarts/component/tooltip',
// 'echarts/component/visualMap',
'theme/vintage'
], function (echarts, dataTool) {
var gexf = dataTool.gexf;
var main = document.getElementById('main4');
if (!main) {
return;
}
var chart = echarts.init(main);
$.get('./data/les-miserables.gexf', function (xml) {
var graph = gexf.parse(xml);
var categories = [];
for (var i = 0; i < 9; i++) {
categories[i] = {
name: '类目' + i
};
}
graph.nodes.forEach(function (node) {
delete node.itemStyle;
node.value = node.symbolSize;
node.label = {
normal: {
show: node.symbolSize > 30
}
};
node.category = node.attributes['modularity_class'];
});
graph.links.forEach(function (link) {
delete link.lineStyle;
});
var option = {
tooltip: {},
legend: [{
// selectedMode: 'single',
data: categories.map(function (a) {
return a.name;
})
}],
visualMap: {
min: 0,
max: 100,
dimension: 0,
calculable: true,
inRange: {
opacity: 1,
symbolSize: [10, 100]
},
outOfRange: {
opacity: 0.2,
symbolSize: [10, 100]
}
},
animationDurationUpdate: 1500,
animationEasingUpdate: 'quinticInOut',
series : [
{
name: 'Les Miserables',
type: 'graph',
layout: 'none',
data: graph.nodes,
links: graph.links,
categories: categories,
roam: true,
label: {
normal: {
textStyle: {
color: '#333'
},
position: 'right',
formatter: '{b}'
}
},
lineStyle: {
normal: {
curveness: 0.3
}
}
}
]
};
chart.setOption(option);
});
});
</script>
<!-- OPACITY HEATMAP -->
<script type="text/javascript">
require([
'echarts'
// 'echarts/chart/heatmap',
// 'echarts/component/grid',
// 'echarts/component/tooltip',
// 'echarts/component/visualMapPiecewise'
], function (echarts) {
var main = document.getElementById('main5');
if (!main) {
return;
}
var chart = echarts.init(main, null, {
});
var hours = ['12a', '1a', '2a', '3a', '4a', '5a', '6a',
'7a', '8a', '9a','10a','11a',
'12p', '1p', '2p', '3p', '4p', '5p',
'6p', '7p', '8p', '9p', '10p', '11p'];
var days = ['Saturday', 'Friday', 'Thursday',
'Wednesday', 'Tuesday', 'Monday', 'Sunday'];
var data = [[0,0,5],[0,1,1],[0,2,0],[0,3,0],[0,4,0],[0,5,0],[0,6,0],[0,7,0],[0,8,0],[0,9,0],[0,10,0],[0,11,2],[0,12,4],[0,13,1],[0,14,1],[0,15,3],[0,16,4],[0,17,6],[0,18,4],[0,19,4],[0,20,3],[0,21,3],[0,22,2],[0,23,5],[1,0,7],[1,1,0],[1,2,0],[1,3,0],[1,4,0],[1,5,0],[1,6,0],[1,7,0],[1,8,0],[1,9,0],[1,10,5],[1,11,2],[1,12,2],[1,13,6],[1,14,9],[1,15,11],[1,16,6],[1,17,7],[1,18,8],[1,19,12],[1,20,5],[1,21,5],[1,22,7],[1,23,2],[2,0,1],[2,1,1],[2,2,0],[2,3,0],[2,4,0],[2,5,0],[2,6,0],[2,7,0],[2,8,0],[2,9,0],[2,10,3],[2,11,2],[2,12,1],[2,13,9],[2,14,8],[2,15,10],[2,16,6],[2,17,5],[2,18,5],[2,19,5],[2,20,7],[2,21,4],[2,22,2],[2,23,4],[3,0,7],[3,1,3],[3,2,0],[3,3,0],[3,4,0],[3,5,0],[3,6,0],[3,7,0],[3,8,1],[3,9,0],[3,10,5],[3,11,4],[3,12,7],[3,13,14],[3,14,13],[3,15,12],[3,16,9],[3,17,5],[3,18,5],[3,19,10],[3,20,6],[3,21,4],[3,22,4],[3,23,1],[4,0,1],[4,1,3],[4,2,0],[4,3,0],[4,4,0],[4,5,1],[4,6,0],[4,7,0],[4,8,0],[4,9,2],[4,10,4],[4,11,4],[4,12,2],[4,13,4],[4,14,4],[4,15,14],[4,16,12],[4,17,1],[4,18,8],[4,19,5],[4,20,3],[4,21,7],[4,22,3],[4,23,0],[5,0,2],[5,1,1],[5,2,0],[5,3,3],[5,4,0],[5,5,0],[5,6,0],[5,7,0],[5,8,2],[5,9,0],[5,10,4],[5,11,1],[5,12,5],[5,13,10],[5,14,5],[5,15,7],[5,16,11],[5,17,6],[5,18,0],[5,19,5],[5,20,3],[5,21,4],[5,22,2],[5,23,0],[6,0,1],[6,1,0],[6,2,0],[6,3,0],[6,4,0],[6,5,0],[6,6,0],[6,7,0],[6,8,0],[6,9,0],[6,10,1],[6,11,0],[6,12,2],[6,13,1],[6,14,3],[6,15,4],[6,16,0],[6,17,0],[6,18,0],[6,19,0],[6,20,1],[6,21,2],[6,22,2],[6,23,6]];
data = data.map(function (item) {
return [item[1], item[0], item[2] || '-'];
});
option = {
backgroundColor: '#eee4ee',
tooltip: {
position: 'top'
},
animation: false,
grid: {
height: '50%',
y: '10%'
},
xAxis: {
type: 'category',
data: hours
},
yAxis: {
type: 'category',
data: days
},
visualMap: {
min: 1,
max: 10,
calculable: true,
range: [3, 6],
orient: 'horizontal',
left: 'center',
bottom: '15%'
},
series: [{
name: 'Punch Card',
type: 'heatmap',
data: data,
label: {
normal: {
show: true
}
},
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
};
chart.setOption(option);
});
</script>
<!-- OPACITY HEATMAP -->
<script>
require([
'echarts'
// 'echarts/chart/pie',
// 'echarts/component/legend',
// 'echarts/component/grid',
// 'echarts/component/tooltip'
], function (echarts) {
var main = document.getElementById('main6');
if (!main) {
return;
}
var chart = echarts.init(main);
chart.setOption({
legend: {
data:['直接访问','邮件营销','联盟广告','视频广告','搜索引擎']
},
tooltip: {},
visualMap: {
type: 'continuous',
top: 'middle',
min: 0,
max: 700,
dimension: 1,
calculable: true,
inRange: {
color: ['yellow', 'green']
}
},
series: [{
name: 'pie',
type: 'pie',
selectedMode: 'single',
selectedOffset: 30,
clockwise: true,
label: {
normal: {
textStyle: {
color: '#333'
}
}
},
labelLine: {
normal: {
lineStyle: {
color: '#333'
}
}
},
data:[
{value: [335, 632], name:'直接访问'},
{value: [310, 434], name:'邮件营销'},
{value: [234, 233], name:'联盟广告'},
{value: [135, 544], name:'视频广告'},
{value: [1548, 381], name:'搜索引擎'}
]
}]
});
});
</script>
</body>
</html> | test/visualMap-opacity.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0008236736757680774,
0.0001816611475078389,
0.00016423837223555893,
0.0001714739773888141,
0.00007509200077038258
] |
{
"id": 2,
"code_window": [
" xyMinMax: BrushDimensionMinMax[]\n",
" } {\n",
" const xminymin = to\n",
" ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);\n",
" const xmaxymax = to\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 430
} | <!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<script src="lib/jquery.min.js"></script>
<script src="lib/facePrint.js"></script>
<script src="lib/testHelper.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="lib/reset.css">
</head>
<body>
<style>
h1 {
line-height: 60px;
height: 60px;
background: #146402;
text-align: center;
font-weight: bold;
color: #eee;
font-size: 14px;
}
.chart {
height: 500px;
}
</style>
<div class="chart" id="main"></div>
<script>
var echarts;
var chart;
var myChart;
var groupCategories = [];
var groupColors = [];
require([
'echarts'
], function (ec) {
echarts = ec;
chart = myChart = echarts.init(document.getElementById('main'));
var data = [
{name:'广州', value: 50},
{name:'深圳', value: 72},
{name:'珠海', value: 30},
{name:'佛山', value: 38},
{name:'杭州', value: 42},
{name:'舟山', value: 32},
{name:'宁波', value: 52}
];
option = {
tooltip : {
trigger: 'item'
},
legend: {
data:['广州','深圳','珠海','佛山','杭州','舟山','宁波'],
top: 0,
left: 'center'
},
xAxis : [
{
type : 'category',
data : [0],
axisTick: {show: false},
axisLabel: {show: false}
},
],
yAxis : [
{
type : 'value'
}
],
series : echarts.util.map(data, function (item) {
return {
name: item.name,
type: 'bar',
label: {
normal: {
show: true,
position: 'bottom',
formatter: function (param) {
return param.seriesName;
}
}
},
data: [item.value]
}
}).concat([{
type: 'custom',
renderItem: renderProvinceName,
data: [0]
}])
};
function renderProvinceName(param, api) {
var currentSeriesIndices = api.currentSeriesIndices();
currentSeriesIndices.pop(); // remove custom series;
var barLayout = api.barLayout({
count: currentSeriesIndices.length
});
var nameTexts = echarts.util.map(currentSeriesIndices, function (serIdx, index) {
var point = api.coord([0, 0]);
point[0] += barLayout[index].offsetCenter;
point[1] = api.getHeight() - 20;
return {
position: point,
name: serIdx,
type: 'circle',
shape: {
cx: 0, cy: 0, r: 10
},
style: {
text: serIdx,
fill: '#333',
textFill: '#eee',
stroke: null
}
};
});
return {
type: 'group',
$mergeChildren: 'byName',
children: nameTexts
};
}
chart.setOption(option);
});
</script>
</body>
</html> | test/custom-children-remove.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0001778358273440972,
0.00017206264601554722,
0.00016746963956393301,
0.00017168985505122691,
0.0000024310236312885536
] |
{
"id": 2,
"code_window": [
" xyMinMax: BrushDimensionMinMax[]\n",
" } {\n",
" const xminymin = to\n",
" ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);\n",
" const xmaxymax = to\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 430
} | <!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<script src="lib/jquery.min.js"></script>
<script src="lib/facePrint.js"></script>
<script src="lib/facePrint.js"></script>
<script src="lib/testHelper.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="lib/reset.css">
</head>
<body>
<style>
</style>
<div class="chart" id="a"></div>
<script>
require(['echarts'], function (echarts) {
var axisData = [
"2013/1/24", "2013/1/25", "2013/1/28", "2013/1/29", "2013/1/30",
"2013/1/31", "2013/2/1", "2013/2/4", "2013/2/5", "2013/2/6",
"2013/2/7", "2013/2/8", "2013/2/18", "2013/2/19", "2013/2/20",
"2013/2/21", "2013/2/22", "2013/2/25", "2013/2/26", "2013/2/27",
"2013/2/28", "2013/3/1", "2013/3/4", "2013/3/5", "2013/3/6",
"2013/3/7", "2013/3/8", "2013/3/11", "2013/3/12", "2013/3/13",
"2013/3/14", "2013/3/15", "2013/3/18", "2013/3/19", "2013/3/20",
"2013/3/21", "2013/3/22", "2013/3/25", "2013/3/26", "2013/3/27",
"2013/3/28", "2013/3/29", "2013/4/1", "2013/4/2", "2013/4/3",
"2013/4/8", "2013/4/9", "2013/4/10", "2013/4/11", "2013/4/12",
"2013/4/15", "2013/4/16", "2013/4/17", "2013/4/18", "2013/4/19",
"2013/4/22", "2013/4/23", "2013/4/24", "2013/4/25", "2013/4/26",
"2013/5/2", "2013/5/3", "2013/5/6", "2013/5/7", "2013/5/8",
"2013/5/9", "2013/5/10", "2013/5/13", "2013/5/14", "2013/5/15",
"2013/5/16", "2013/5/17", "2013/5/20", "2013/5/21", "2013/5/22",
"2013/5/23", "2013/5/24", "2013/5/27", "2013/5/28", "2013/5/29",
"2013/5/30", "2013/5/31", "2013/6/3", "2013/6/4", "2013/6/5",
"2013/6/6", "2013/6/7", "2013/6/13"
];
var option = {
tooltip : {
trigger: 'axis',
},
legend: {
y : -30,
data:['上证指数','成交金额(万)','虚拟数据']
},
dataZoom : {
show : true,
realtime: true,
start : 50,
end : 70
},
grid: {
x: 80,
y: 20,
x2: 20,
y2: 60
},
xAxis : [
{
type : 'category',
// axisTick: {
// alignWithLabel: true
// },
boundaryGap : true,
data : axisData
}
],
yAxis : [
{
type : 'value',
splitArea : {show : true}
}
],
series : [
{
name:'成交金额(万)',
type:'line',
data:[
13560434, 8026738.5, 11691637, 12491697, 12485603,
11620504, 12555496, 15253370, 12709611, 10458354,
10933507, 9896523, 10365702, 10633095, 9722230,
12662783, 8757982, 7764234, 10591719, 8826293,
11591827, 11153111, 14304651, 11672120, 12536480,
12608589, 8843860, 7391994.5, 10063709, 7768895.5,
6921859, 10157810, 8148617.5, 7551207, 11397426,
10478607, 8595132, 8541862, 9181132, 8570842,
10759351, 7335819, 6699753.5, 7759666.5, 6880135.5,
7366616.5, 7313504, 7109021.5, 6213270, 5619688,
5816217.5, 6695584.5, 5998655.5, 6188812.5, 9538301,
8224500, 8221751.5, 7897721, 8448324, 6525151,
5987761, 7831570, 8162560.5, 7904092, 8139084.5,
9116529, 8128014, 7919148, 7566047, 6665826.5,
10225527, 11124881, 12884353, 11302521, 11529046,
11105205, 9202153, 9992016, 12035250, 11431155,
10354677, 10070399, 9164861, 9237718, 7114268,
7526158.5, 8105835, 7971452.5
]
}
]
};
testHelper.create(echarts, 'a', {
title: [
'default {boundaryGap:true, alignWithLabel: false}, in category axis, axis tick and label should be consistent'
],
height: 200,
option: option
});
});
</script>
</body>
</html> | test/axis-boundaryGap.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0001778358273440972,
0.00017142850265372545,
0.000168076905538328,
0.00017103161371778697,
0.0000025793833628995344
] |
{
"id": 3,
"code_window": [
" const xmaxymax = to\n",
" ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);\n",
" const values = [\n",
" formatMinMax([xminymin[0], xmaxymax[0]]),\n",
" formatMinMax([xminymin[1], xmaxymax[1]])\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 433
} | /*
* 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 { each, indexOf, curry, assert, map, createHashMap } from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as brushHelper from './brushHelper';
import {
BrushPanelConfig, BrushControllerEvents, BrushType,
BrushAreaRange, BrushDimensionMinMax
} from './BrushController';
import ExtensionAPI from '../../core/ExtensionAPI';
import GridModel from '../../coord/cartesian/GridModel';
import GeoModel from '../../coord/geo/GeoModel';
import { CoordinateSystemMaster } from '../../coord/CoordinateSystem';
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Geo from '../../coord/geo/Geo';
import GlobalModel from '../../model/Global';
import { BrushAreaParam, BrushAreaParamInternal } from '../brush/BrushModel';
import SeriesModel from '../../model/Series';
import { Dictionary } from '../../util/types';
import {
ModelFinderObject, ParsedModelFinder, ModelFinder,
parseFinder as modelUtilParseFinder,
ParsedModelFinderKnown
} from '../../util/model';
const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;
type COORD_CONVERTS_INDEX = 0 | 1;
// FIXME
// how to genarialize to more coordinate systems.
const INCLUDE_FINDER_MAIN_TYPES = [
'grid', 'xAxis', 'yAxis', 'geo', 'graph',
'polar', 'radiusAxis', 'angleAxis', 'bmap'
];
type BrushableCoordinateSystem = Cartesian2D | Geo;
type BrushTargetBuilderKey = 'grid' | 'geo';
/**
* There can be multiple axes in a single targetInfo. Consider the case
* of `grid` component, a targetInfo represents a grid which contains one or more
* cartesian and one or more axes. And consider the case of parallel system,
* which has multiple axes in a coordinate system.
*/
interface BrushTargetInfo {
panelId: string;
coordSysModel: CoordinateSystemMaster['model'];
// Use the first one as the representitive coordSys.
// A representitive cartesian in grid (first cartesian by default).
coordSys: BrushableCoordinateSystem;
// All cartesians.
coordSyses: BrushableCoordinateSystem[];
getPanelRect: GetPanelRect,
}
export interface BrushTargetInfoCartesian2D extends BrushTargetInfo {
gridModel: GridModel;
coordSys: Cartesian2D;
coordSyses: Cartesian2D[];
xAxisDeclared: boolean;
yAxisDeclared: boolean;
}
export interface BrushTargetInfoGeo extends BrushTargetInfo {
geoModel: GeoModel,
coordSysModel: GeoModel,
coordSys: Geo,
coordSyses: Geo[],
}
type GetPanelRect = () => graphic.BoundingRect;
class BrushTargetManager {
private _targetInfoList: BrushTargetInfo[] = [];
/**
* @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
* Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
* @param opt.include include coordinate system types.
*/
constructor(
finder: ModelFinderObject,
ecModel: GlobalModel,
opt?: {include?: BrushTargetBuilderKey[]}
) {
const foundCpts = parseFinder(ecModel, finder);
each(targetInfoBuilders, (builder, type) => {
if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
builder(foundCpts, this._targetInfoList);
}
});
}
setOutputRanges(
areas: BrushControllerEvents['brush']['areas'],
ecModel: GlobalModel
): BrushAreaParam[] {
this.matchOutputRanges(areas, ecModel, function (
area: BrushAreaParam,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem
) {
(area.coordRanges || (area.coordRanges = [])).push(coordRange);
// area.coordRange is the first of area.coordRanges
if (!area.coordRange) {
area.coordRange = coordRange;
// In 'category' axis, coord to pixel is not reversible, so we can not
// rebuild range by coordRange accrately, which may bring trouble when
// brushing only one item. So we use __rangeOffset to rebuilding range
// by coordRange. And this it only used in brush component so it is no
// need to be adapted to coordRanges.
const result = coordConvert[area.brushType](0, coordSys, coordRange);
area.__rangeOffset = {
offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
xyMinMax: result.xyMinMax
};
}
});
return areas;
}
matchOutputRanges<T extends (
Parameters<BrushTargetManager['findTargetInfo']>[0] & {
brushType: BrushType;
range: BrushAreaRange;
}
)>(
areas: T[],
ecModel: GlobalModel,
cb: (
area: T,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem,
ecModel: GlobalModel
) => void
) {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (targetInfo && targetInfo !== true) {
each(
targetInfo.coordSyses,
function (coordSys) {
const result = coordConvert[area.brushType](1, coordSys, area.range, true);
cb(area, result.values, coordSys, ecModel);
}
);
}
}, this);
}
/**
* the `areas` is `BrushModel.areas`.
* Called in layout stage.
* convert `area.coordRange` to global range and set panelId to `area.range`.
*/
setInputRanges(
areas: BrushAreaParamInternal[],
ecModel: GlobalModel
): void {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (__DEV__) {
assert(
!targetInfo || targetInfo === true || area.coordRange,
'coordRange must be specified when coord index specified.'
);
assert(
!targetInfo || targetInfo !== true || area.range,
'range must be specified in global brush.'
);
}
area.range = area.range || [];
// convert coordRange to global range and set panelId.
if (targetInfo && targetInfo !== true) {
area.panelId = targetInfo.panelId;
// (1) area.range shoule always be calculate from coordRange but does
// not keep its original value, for the sake of the dataZoom scenario,
// where area.coordRange remains unchanged but area.range may be changed.
// (2) Only support converting one coordRange to pixel range in brush
// component. So do not consider `coordRanges`.
// (3) About __rangeOffset, see comment above.
const result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
const rangeOffset = area.__rangeOffset;
area.range = rangeOffset
? diffProcessor[area.brushType](
result.values,
rangeOffset.offset,
getScales(result.xyMinMax, rangeOffset.xyMinMax)
)
: result.values;
}
}, this);
}
makePanelOpts(
api: ExtensionAPI,
getDefaultBrushType?: (targetInfo: BrushTargetInfo) => BrushType
): BrushPanelConfig[] {
return map(this._targetInfoList, function (targetInfo) {
const rect = targetInfo.getPanelRect();
return {
panelId: targetInfo.panelId,
defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
clipPath: brushHelper.makeRectPanelClipPath(rect),
isTargetByCursor: brushHelper.makeRectIsTargetByCursor(
rect, api, targetInfo.coordSysModel
),
getLinearBrushOtherExtent: brushHelper.makeLinearBrushOtherExtent(rect)
};
});
}
controlSeries(area: BrushAreaParamInternal, seriesModel: SeriesModel, ecModel: GlobalModel): boolean {
// Check whether area is bound in coord, and series do not belong to that coord.
// If do not do this check, some brush (like lineX) will controll all axes.
const targetInfo = this.findTargetInfo(area, ecModel);
return targetInfo === true || (
targetInfo && indexOf(
targetInfo.coordSyses, seriesModel.coordinateSystem as BrushableCoordinateSystem
) >= 0
);
}
/**
* If return Object, a coord found.
* If reutrn true, global found.
* Otherwise nothing found.
*/
findTargetInfo(
area: ModelFinderObject & {
panelId?: string
},
ecModel: GlobalModel
): BrushTargetInfo | true {
const targetInfoList = this._targetInfoList;
const foundCpts = parseFinder(ecModel, area);
for (let i = 0; i < targetInfoList.length; i++) {
const targetInfo = targetInfoList[i];
const areaPanelId = area.panelId;
if (areaPanelId) {
if (targetInfo.panelId === areaPanelId) {
return targetInfo;
}
}
else {
for (let j = 0; j < targetInfoMatchers.length; j++) {
if (targetInfoMatchers[j](foundCpts, targetInfo)) {
return targetInfo;
}
}
}
}
return true;
}
}
function formatMinMax(minMax: BrushDimensionMinMax): BrushDimensionMinMax {
minMax[0] > minMax[1] && minMax.reverse();
return minMax;
}
function parseFinder(
ecModel: GlobalModel, finder: ModelFinder
): ParsedModelFinderKnown {
return modelUtilParseFinder(
ecModel, finder, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
);
}
type TargetInfoBuilder = (
foundCpts: ParsedModelFinderKnown, targetInfoList: BrushTargetInfo[]
) => void;
const targetInfoBuilders: Record<BrushTargetBuilderKey, TargetInfoBuilder> = {
grid: function (foundCpts, targetInfoList) {
const xAxisModels = foundCpts.xAxisModels;
const yAxisModels = foundCpts.yAxisModels;
const gridModels = foundCpts.gridModels;
// Remove duplicated.
const gridModelMap = createHashMap<GridModel>();
const xAxesHas = {} as Dictionary<boolean>;
const yAxesHas = {} as Dictionary<boolean>;
if (!xAxisModels && !yAxisModels && !gridModels) {
return;
}
each(xAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
});
each(yAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
yAxesHas[gridModel.id] = true;
});
each(gridModels, function (gridModel) {
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
yAxesHas[gridModel.id] = true;
});
gridModelMap.each(function (gridModel) {
const grid = gridModel.coordinateSystem;
const cartesians = [] as Cartesian2D[];
each(grid.getCartesians(), function (cartesian, index) {
if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0
|| indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0
) {
cartesians.push(cartesian);
}
});
targetInfoList.push({
panelId: 'grid--' + gridModel.id,
gridModel: gridModel,
coordSysModel: gridModel,
// Use the first one as the representitive coordSys.
coordSys: cartesians[0],
coordSyses: cartesians,
getPanelRect: panelRectBuilders.grid,
xAxisDeclared: xAxesHas[gridModel.id],
yAxisDeclared: yAxesHas[gridModel.id]
} as BrushTargetInfoCartesian2D);
});
},
geo: function (foundCpts, targetInfoList) {
each(foundCpts.geoModels, function (geoModel: GeoModel) {
const coordSys = geoModel.coordinateSystem;
targetInfoList.push({
panelId: 'geo--' + geoModel.id,
geoModel: geoModel,
coordSysModel: geoModel,
coordSys: coordSys,
coordSyses: [coordSys],
getPanelRect: panelRectBuilders.geo
} as BrushTargetInfoGeo);
});
}
};
type TargetInfoMatcher = (
foundCpts: ParsedModelFinderKnown, targetInfo: BrushTargetInfo
) => boolean;
const targetInfoMatchers: TargetInfoMatcher[] = [
// grid
function (foundCpts, targetInfo) {
const xAxisModel = foundCpts.xAxisModel;
const yAxisModel = foundCpts.yAxisModel;
let gridModel = foundCpts.gridModel;
!gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
!gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
return gridModel && gridModel === (targetInfo as BrushTargetInfoCartesian2D).gridModel;
},
// geo
function (foundCpts, targetInfo) {
const geoModel = foundCpts.geoModel;
return geoModel && geoModel === (targetInfo as BrushTargetInfoGeo).geoModel;
}
];
type PanelRectBuilder = (this: BrushTargetInfo) => graphic.BoundingRect;
const panelRectBuilders: Record<BrushTargetBuilderKey, PanelRectBuilder> = {
grid: function (this: BrushTargetInfoCartesian2D) {
// grid is not Transformable.
return this.coordSys.master.getRect().clone();
},
geo: function (this: BrushTargetInfoGeo) {
const coordSys = this.coordSys;
const rect = coordSys.getBoundingRect().clone();
// geo roam and zoom transform
rect.applyTransform(graphic.getTransform(coordSys));
return rect;
}
};
type ConvertCoord = (
to: COORD_CONVERTS_INDEX,
coordSys: BrushableCoordinateSystem,
rangeOrCoordRange: BrushAreaRange,
clamp?: boolean
) => {
values: BrushAreaRange,
xyMinMax: BrushDimensionMinMax[]
};
const coordConvert: Record<BrushType, ConvertCoord> = {
lineX: curry(axisConvert, 0),
lineY: curry(axisConvert, 1),
rect: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xminymin = to
? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
const xmaxymax = to
? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
const values = [
formatMinMax([xminymin[0], xmaxymax[0]]),
formatMinMax([xminymin[1], xmaxymax[1]])
];
return {values: values, xyMinMax: values};
},
polygon: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
const values = map(rangeOrCoordRange, function (item) {
const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);
xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
return p;
});
return {values: values, xyMinMax: xyMinMax};
}
};
function axisConvert(
axisNameIndex: 0 | 1,
to: COORD_CONVERTS_INDEX,
coordSys: Cartesian2D,
rangeOrCoordRange: BrushDimensionMinMax
): {
values: BrushDimensionMinMax,
xyMinMax: BrushDimensionMinMax[]
} {
if (__DEV__) {
assert(
coordSys.type === 'cartesian2d',
'lineX/lineY brush is available only in cartesian2d.'
);
}
const axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
const values = formatMinMax(map([0, 1], function (i) {
return to
? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true)
: axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
}));
const xyMinMax = [];
xyMinMax[axisNameIndex] = values;
xyMinMax[1 - axisNameIndex] = [NaN, NaN];
return {values: values, xyMinMax: xyMinMax};
}
type DiffProcess = (
values: BrushDimensionMinMax | BrushDimensionMinMax[],
refer: BrushDimensionMinMax | BrushDimensionMinMax[],
scales: ReturnType<typeof getScales>
) => BrushDimensionMinMax | BrushDimensionMinMax[];
const diffProcessor: Record<BrushType, DiffProcess> = {
lineX: curry(axisDiffProcessor, 0),
lineY: curry(axisDiffProcessor, 1),
rect: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return [
[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
[values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
];
},
polygon: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return map(values, function (item, idx) {
return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
});
}
};
function axisDiffProcessor(
axisNameIndex: 0 | 1,
values: BrushDimensionMinMax,
refer: BrushDimensionMinMax,
scales: ReturnType<typeof getScales>
): BrushDimensionMinMax {
return [
values[0] - scales[axisNameIndex] * refer[0],
values[1] - scales[axisNameIndex] * refer[1]
];
}
// We have to process scale caused by dataZoom manually,
// although it might be not accurate.
// Return [0~1, 0~1]
function getScales(xyMinMaxCurr: BrushDimensionMinMax[], xyMinMaxOrigin: BrushDimensionMinMax[]): number[] {
const sizeCurr = getSize(xyMinMaxCurr);
const sizeOrigin = getSize(xyMinMaxOrigin);
const scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
function getSize(xyMinMax: BrushDimensionMinMax[]): number[] {
return xyMinMax
? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
: [NaN, NaN];
}
export default BrushTargetManager;
| src/component/helper/BrushTargetManager.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.9983623623847961,
0.05346750468015671,
0.00016412409604527056,
0.00019986683037132025,
0.20535582304000854
] |
{
"id": 3,
"code_window": [
" const xmaxymax = to\n",
" ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);\n",
" const values = [\n",
" formatMinMax([xminymin[0], xmaxymax[0]]),\n",
" formatMinMax([xminymin[1], xmaxymax[1]])\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 433
} | /*
* 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 BoundingRect, { RectLike } from 'zrender/src/core/BoundingRect';
import * as matrix from 'zrender/src/core/matrix';
import * as graphic from '../../util/graphic';
import { createTextStyle } from '../../label/labelStyle';
import * as layout from '../../util/layout';
import TimelineView from './TimelineView';
import TimelineAxis from './TimelineAxis';
import {createSymbol} from '../../util/symbol';
import * as numberUtil from '../../util/number';
import GlobalModel from '../../model/Global';
import ExtensionAPI from '../../core/ExtensionAPI';
import { merge, each, extend, isString, bind, defaults, retrieve2 } from 'zrender/src/core/util';
import SliderTimelineModel from './SliderTimelineModel';
import { LayoutOrient, ZRTextAlign, ZRTextVerticalAlign, ZRElementEvent, ScaleTick } from '../../util/types';
import TimelineModel, { TimelineDataItemOption, TimelineCheckpointStyle } from './TimelineModel';
import { TimelineChangePayload, TimelinePlayChangePayload } from './timelineAction';
import Model from '../../model/Model';
import { PathProps, PathStyleProps } from 'zrender/src/graphic/Path';
import Scale from '../../scale/Scale';
import OrdinalScale from '../../scale/Ordinal';
import TimeScale from '../../scale/Time';
import IntervalScale from '../../scale/Interval';
import { VectorArray } from 'zrender/src/core/vector';
import { parsePercent } from 'zrender/src/contain/text';
import { makeInner } from '../../util/model';
import { getECData } from '../../util/innerStore';
import { enableHoverEmphasis } from '../../util/states';
import { createTooltipMarkup } from '../tooltip/tooltipMarkup';
import Displayable from 'zrender/src/graphic/Displayable';
const PI = Math.PI;
type TimelineSymbol = ReturnType<typeof createSymbol>;
type RenderMethodName = '_renderAxisLine' | '_renderAxisTick' | '_renderControl' | '_renderCurrentPointer';
type ControlName = 'play' | 'stop' | 'next' | 'prev';
type ControlIconName = 'playIcon' | 'stopIcon' | 'nextIcon' | 'prevIcon';
const labelDataIndexStore = makeInner<{
dataIndex: number
}, graphic.Text>();
interface LayoutInfo {
viewRect: BoundingRect
mainLength: number
orient: LayoutOrient
rotation: number
labelRotation: number
labelPosOpt: number | '+' | '-'
labelAlign: ZRTextAlign
labelBaseline: ZRTextVerticalAlign
playPosition: number[]
prevBtnPosition: number[]
nextBtnPosition: number[]
axisExtent: number[]
controlSize: number
controlGap: number
}
class SliderTimelineView extends TimelineView {
static type = 'timeline.slider';
type = SliderTimelineView.type;
api: ExtensionAPI;
model: SliderTimelineModel;
ecModel: GlobalModel;
private _axis: TimelineAxis;
private _viewRect: BoundingRect;
private _timer: number;
private _currentPointer: TimelineSymbol;
private _progressLine: graphic.Line;
private _mainGroup: graphic.Group;
private _labelGroup: graphic.Group;
private _tickSymbols: graphic.Path[];
private _tickLabels: graphic.Text[];
init(ecModel: GlobalModel, api: ExtensionAPI) {
this.api = api;
}
/**
* @override
*/
render(timelineModel: SliderTimelineModel, ecModel: GlobalModel, api: ExtensionAPI) {
this.model = timelineModel;
this.api = api;
this.ecModel = ecModel;
this.group.removeAll();
if (timelineModel.get('show', true)) {
const layoutInfo = this._layout(timelineModel, api);
const mainGroup = this._createGroup('_mainGroup');
const labelGroup = this._createGroup('_labelGroup');
const axis = this._axis = this._createAxis(layoutInfo, timelineModel);
timelineModel.formatTooltip = function (dataIndex: number) {
const name = axis.scale.getLabel({value: dataIndex});
return createTooltipMarkup('nameValue', { noName: true, value: name });
};
each(
['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'] as const,
function (name) {
this['_render' + name as RenderMethodName](layoutInfo, mainGroup, axis, timelineModel);
},
this
);
this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
this._position(layoutInfo, timelineModel);
}
this._doPlayStop();
this._updateTicksStatus();
}
/**
* @override
*/
remove() {
this._clearTimer();
this.group.removeAll();
}
/**
* @override
*/
dispose() {
this._clearTimer();
}
private _layout(timelineModel: SliderTimelineModel, api: ExtensionAPI): LayoutInfo {
const labelPosOpt = timelineModel.get(['label', 'position']);
const orient = timelineModel.get('orient');
const viewRect = getViewRect(timelineModel, api);
let parsedLabelPos: number | '+' | '-';
// Auto label offset.
if (labelPosOpt == null || labelPosOpt === 'auto') {
parsedLabelPos = orient === 'horizontal'
? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
: ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
}
else if (isString(labelPosOpt)) {
parsedLabelPos = ({
horizontal: {top: '-', bottom: '+'},
vertical: {left: '-', right: '+'}
} as const)[orient][labelPosOpt];
}
else {
// is number
parsedLabelPos = labelPosOpt;
}
const labelAlignMap = {
horizontal: 'center',
vertical: (parsedLabelPos >= 0 || parsedLabelPos === '+') ? 'left' : 'right'
};
const labelBaselineMap = {
horizontal: (parsedLabelPos >= 0 || parsedLabelPos === '+') ? 'top' : 'bottom',
vertical: 'middle'
};
const rotationMap = {
horizontal: 0,
vertical: PI / 2
};
// Position
const mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
const controlModel = timelineModel.getModel('controlStyle');
const showControl = controlModel.get('show', true);
const controlSize = showControl ? controlModel.get('itemSize') : 0;
const controlGap = showControl ? controlModel.get('itemGap') : 0;
const sizePlusGap = controlSize + controlGap;
// Special label rotate.
let labelRotation = timelineModel.get(['label', 'rotate']) || 0;
labelRotation = labelRotation * PI / 180; // To radian.
let playPosition: number[];
let prevBtnPosition: number[];
let nextBtnPosition: number[];
const controlPosition = controlModel.get('position', true);
const showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
const showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
const showNextBtn = showControl && controlModel.get('showNextBtn', true);
let xLeft = 0;
let xRight = mainLength;
// position[0] means left, position[1] means middle.
if (controlPosition === 'left' || controlPosition === 'bottom') {
showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
}
else { // 'top' 'right'
showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
}
const axisExtent = [xLeft, xRight];
if (timelineModel.get('inverse')) {
axisExtent.reverse();
}
return {
viewRect: viewRect,
mainLength: mainLength,
orient: orient,
rotation: rotationMap[orient],
labelRotation: labelRotation,
labelPosOpt: parsedLabelPos,
labelAlign: timelineModel.get(['label', 'align']) || labelAlignMap[orient] as ZRTextAlign,
labelBaseline: timelineModel.get(['label', 'verticalAlign'])
|| timelineModel.get(['label', 'baseline'])
|| labelBaselineMap[orient] as ZRTextVerticalAlign,
// Based on mainGroup.
playPosition: playPosition,
prevBtnPosition: prevBtnPosition,
nextBtnPosition: nextBtnPosition,
axisExtent: axisExtent,
controlSize: controlSize,
controlGap: controlGap
};
}
private _position(layoutInfo: LayoutInfo, timelineModel: SliderTimelineModel) {
// Position is be called finally, because bounding rect is needed for
// adapt content to fill viewRect (auto adapt offset).
// Timeline may be not all in the viewRect when 'offset' is specified
// as a number, because it is more appropriate that label aligns at
// 'offset' but not the other edge defined by viewRect.
const mainGroup = this._mainGroup;
const labelGroup = this._labelGroup;
let viewRect = layoutInfo.viewRect;
if (layoutInfo.orient === 'vertical') {
// transform to horizontal, inverse rotate by left-top point.
const m = matrix.create();
const rotateOriginX = viewRect.x;
const rotateOriginY = viewRect.y + viewRect.height;
matrix.translate(m, m, [-rotateOriginX, -rotateOriginY]);
matrix.rotate(m, m, -PI / 2);
matrix.translate(m, m, [rotateOriginX, rotateOriginY]);
viewRect = viewRect.clone();
viewRect.applyTransform(m);
}
const viewBound = getBound(viewRect);
const mainBound = getBound(mainGroup.getBoundingRect());
const labelBound = getBound(labelGroup.getBoundingRect());
const mainPosition = [mainGroup.x, mainGroup.y];
const labelsPosition = [labelGroup.x, labelGroup.y];
labelsPosition[0] = mainPosition[0] = viewBound[0][0];
const labelPosOpt = layoutInfo.labelPosOpt;
if (labelPosOpt == null || isString(labelPosOpt)) { // '+' or '-'
const mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
}
else {
const mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
labelsPosition[1] = mainPosition[1] + labelPosOpt;
}
mainGroup.setPosition(mainPosition);
labelGroup.setPosition(labelsPosition);
mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
setOrigin(mainGroup);
setOrigin(labelGroup);
function setOrigin(targetGroup: graphic.Group) {
targetGroup.originX = viewBound[0][0] - targetGroup.x;
targetGroup.originY = viewBound[1][0] - targetGroup.y;
}
function getBound(rect: RectLike) {
// [[xmin, xmax], [ymin, ymax]]
return [
[rect.x, rect.x + rect.width],
[rect.y, rect.y + rect.height]
];
}
function toBound(fromPos: VectorArray, from: number[][], to: number[][], dimIdx: number, boundIdx: number) {
fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
}
}
private _createAxis(layoutInfo: LayoutInfo, timelineModel: SliderTimelineModel) {
const data = timelineModel.getData();
const axisType = timelineModel.get('axisType');
const scale = createScaleByModel(timelineModel, axisType);
// Customize scale. The `tickValue` is `dataIndex`.
scale.getTicks = function () {
return data.mapArray(['value'], function (value: number) {
return {value};
});
};
const dataExtent = data.getDataExtent('value');
scale.setExtent(dataExtent[0], dataExtent[1]);
scale.niceTicks();
const axis = new TimelineAxis('value', scale, layoutInfo.axisExtent as [number, number], axisType);
axis.model = timelineModel;
return axis;
}
private _createGroup(key: '_mainGroup' | '_labelGroup') {
const newGroup = this[key] = new graphic.Group();
this.group.add(newGroup);
return newGroup;
}
private _renderAxisLine(
layoutInfo: LayoutInfo,
group: graphic.Group,
axis: TimelineAxis,
timelineModel: SliderTimelineModel
) {
const axisExtent = axis.getExtent();
if (!timelineModel.get(['lineStyle', 'show'])) {
return;
}
const line = new graphic.Line({
shape: {
x1: axisExtent[0], y1: 0,
x2: axisExtent[1], y2: 0
},
style: extend(
{lineCap: 'round'},
timelineModel.getModel('lineStyle').getLineStyle()
),
silent: true,
z2: 1
});
group.add(line);
const progressLine = this._progressLine = new graphic.Line({
shape: {
x1: axisExtent[0],
x2: this._currentPointer
? this._currentPointer.x : axisExtent[0],
y1: 0, y2: 0
},
style: defaults(
{ lineCap: 'round', lineWidth: line.style.lineWidth } as PathStyleProps,
timelineModel.getModel(['progress', 'lineStyle']).getLineStyle()
),
silent: true,
z2: 1
});
group.add(progressLine);
}
private _renderAxisTick(
layoutInfo: LayoutInfo,
group: graphic.Group,
axis: TimelineAxis,
timelineModel: SliderTimelineModel
) {
const data = timelineModel.getData();
// Show all ticks, despite ignoring strategy.
const ticks = axis.scale.getTicks();
this._tickSymbols = [];
// The value is dataIndex, see the costomized scale.
each(ticks, (tick: ScaleTick) => {
const tickCoord = axis.dataToCoord(tick.value);
const itemModel = data.getItemModel<TimelineDataItemOption>(tick.value);
const itemStyleModel = itemModel.getModel('itemStyle');
const hoverStyleModel = itemModel.getModel(['emphasis', 'itemStyle']);
const progressStyleModel = itemModel.getModel(['progress', 'itemStyle']);
const symbolOpt = {
x: tickCoord,
y: 0,
onclick: bind(this._changeTimeline, this, tick.value)
};
const el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
el.ensureState('emphasis').style = hoverStyleModel.getItemStyle();
el.ensureState('progress').style = progressStyleModel.getItemStyle();
enableHoverEmphasis(el);
const ecData = getECData(el);
if (itemModel.get('tooltip')) {
ecData.dataIndex = tick.value;
ecData.dataModel = timelineModel;
}
else {
ecData.dataIndex = ecData.dataModel = null;
}
this._tickSymbols.push(el);
});
}
private _renderAxisLabel(
layoutInfo: LayoutInfo,
group: graphic.Group,
axis: TimelineAxis,
timelineModel: SliderTimelineModel
) {
const labelModel = axis.getLabelModel();
if (!labelModel.get('show')) {
return;
}
const data = timelineModel.getData();
const labels = axis.getViewLabels();
this._tickLabels = [];
each(labels, (labelItem) => {
// The tickValue is dataIndex, see the costomized scale.
const dataIndex = labelItem.tickValue;
const itemModel = data.getItemModel<TimelineDataItemOption>(dataIndex);
const normalLabelModel = itemModel.getModel('label');
const hoverLabelModel = itemModel.getModel(['emphasis', 'label']);
const progressLabelModel = itemModel.getModel(['progress', 'label']);
const tickCoord = axis.dataToCoord(labelItem.tickValue);
const textEl = new graphic.Text({
x: tickCoord,
y: 0,
rotation: layoutInfo.labelRotation - layoutInfo.rotation,
onclick: bind(this._changeTimeline, this, dataIndex),
silent: false,
style: createTextStyle(normalLabelModel, {
text: labelItem.formattedLabel,
align: layoutInfo.labelAlign,
verticalAlign: layoutInfo.labelBaseline
})
});
textEl.ensureState('emphasis').style = createTextStyle(hoverLabelModel);
textEl.ensureState('progress').style = createTextStyle(progressLabelModel);
group.add(textEl);
enableHoverEmphasis(textEl);
labelDataIndexStore(textEl).dataIndex = dataIndex;
this._tickLabels.push(textEl);
});
}
private _renderControl(
layoutInfo: LayoutInfo,
group: graphic.Group,
axis: TimelineAxis,
timelineModel: SliderTimelineModel
) {
const controlSize = layoutInfo.controlSize;
const rotation = layoutInfo.rotation;
const itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
const hoverStyle = timelineModel.getModel(['emphasis', 'controlStyle']).getItemStyle();
const playState = timelineModel.getPlayState();
const inverse = timelineModel.get('inverse', true);
makeBtn(
layoutInfo.nextBtnPosition,
'next',
bind(this._changeTimeline, this, inverse ? '-' : '+')
);
makeBtn(
layoutInfo.prevBtnPosition,
'prev',
bind(this._changeTimeline, this, inverse ? '+' : '-')
);
makeBtn(
layoutInfo.playPosition,
(playState ? 'stop' : 'play'),
bind(this._handlePlayClick, this, !playState),
true
);
function makeBtn(
position: number[],
iconName: ControlName,
onclick: () => void,
willRotate?: boolean
) {
if (!position) {
return;
}
const iconSize = parsePercent(
retrieve2(timelineModel.get(['controlStyle', iconName + 'BtnSize' as any]), controlSize),
controlSize
);
const rect = [0, -iconSize / 2, iconSize, iconSize];
const opt = {
position: position,
origin: [controlSize / 2, 0],
rotation: willRotate ? -rotation : 0,
rectHover: true,
style: itemStyle,
onclick: onclick
};
const btn = makeControlIcon(timelineModel, iconName + 'Icon' as ControlIconName, rect, opt);
btn.ensureState('emphasis').style = hoverStyle;
group.add(btn);
enableHoverEmphasis(btn);
}
}
private _renderCurrentPointer(
layoutInfo: LayoutInfo,
group: graphic.Group,
axis: TimelineAxis,
timelineModel: SliderTimelineModel
) {
const data = timelineModel.getData();
const currentIndex = timelineModel.getCurrentIndex();
const pointerModel = data.getItemModel<TimelineDataItemOption>(currentIndex)
.getModel('checkpointStyle');
const me = this;
const callback = {
onCreate(pointer: TimelineSymbol) {
pointer.draggable = true;
pointer.drift = bind(me._handlePointerDrag, me);
pointer.ondragend = bind(me._handlePointerDragend, me);
pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel, true);
},
onUpdate(pointer: TimelineSymbol) {
pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel);
}
};
// Reuse when exists, for animation and drag.
this._currentPointer = giveSymbol(
pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
);
}
private _handlePlayClick(nextState: boolean) {
this._clearTimer();
this.api.dispatchAction({
type: 'timelinePlayChange',
playState: nextState,
from: this.uid
} as TimelinePlayChangePayload);
}
private _handlePointerDrag(dx: number, dy: number, e: ZRElementEvent) {
this._clearTimer();
this._pointerChangeTimeline([e.offsetX, e.offsetY]);
}
private _handlePointerDragend(e: ZRElementEvent) {
this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
}
private _pointerChangeTimeline(mousePos: number[], trigger?: boolean) {
let toCoord = this._toAxisCoord(mousePos)[0];
const axis = this._axis;
const axisExtent = numberUtil.asc(axis.getExtent().slice());
toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
this._currentPointer.x = toCoord;
this._currentPointer.markRedraw();
this._progressLine.shape.x2 = toCoord;
this._progressLine.dirty();
const targetDataIndex = this._findNearestTick(toCoord);
const timelineModel = this.model;
if (trigger || (
targetDataIndex !== timelineModel.getCurrentIndex()
&& timelineModel.get('realtime')
)) {
this._changeTimeline(targetDataIndex);
}
}
private _doPlayStop() {
this._clearTimer();
if (this.model.getPlayState()) {
this._timer = setTimeout(
() => {
// Do not cache
const timelineModel = this.model;
this._changeTimeline(
timelineModel.getCurrentIndex()
+ (timelineModel.get('rewind', true) ? -1 : 1)
);
},
this.model.get('playInterval')
) as any;
}
}
private _toAxisCoord(vertex: number[]) {
const trans = this._mainGroup.getLocalTransform();
return graphic.applyTransform(vertex, trans, true);
}
private _findNearestTick(axisCoord: number) {
const data = this.model.getData();
let dist = Infinity;
let targetDataIndex;
const axis = this._axis;
data.each(['value'], function (value, dataIndex) {
const coord = axis.dataToCoord(value);
const d = Math.abs(coord - axisCoord);
if (d < dist) {
dist = d;
targetDataIndex = dataIndex;
}
});
return targetDataIndex;
}
private _clearTimer() {
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
}
private _changeTimeline(nextIndex: number | '+' | '-') {
const currentIndex = this.model.getCurrentIndex();
if (nextIndex === '+') {
nextIndex = currentIndex + 1;
}
else if (nextIndex === '-') {
nextIndex = currentIndex - 1;
}
this.api.dispatchAction({
type: 'timelineChange',
currentIndex: nextIndex,
from: this.uid
} as TimelineChangePayload);
}
private _updateTicksStatus() {
const currentIndex = this.model.getCurrentIndex();
const tickSymbols = this._tickSymbols;
const tickLabels = this._tickLabels;
if (tickSymbols) {
for (let i = 0; i < tickSymbols.length; i++) {
tickSymbols && tickSymbols[i]
&& tickSymbols[i].toggleState('progress', i < currentIndex);
}
}
if (tickLabels) {
for (let i = 0; i < tickLabels.length; i++) {
tickLabels && tickLabels[i]
&& tickLabels[i].toggleState(
'progress', labelDataIndexStore(tickLabels[i]).dataIndex <= currentIndex
);
}
}
}
}
function createScaleByModel(model: SliderTimelineModel, axisType?: string): Scale {
axisType = axisType || model.get('type');
if (axisType) {
switch (axisType) {
// Buildin scale
case 'category':
return new OrdinalScale({
ordinalMeta: model.getCategories(),
extent: [Infinity, -Infinity]
});
case 'time':
return new TimeScale({
locale: model.ecModel.getLocaleModel(),
useUTC: model.ecModel.get('useUTC')
});
default:
// default to be value
return new IntervalScale();
}
}
}
function getViewRect(model: SliderTimelineModel, api: ExtensionAPI) {
return layout.getLayoutRect(
model.getBoxLayoutParams(),
{
width: api.getWidth(),
height: api.getHeight()
},
model.get('padding')
);
}
function makeControlIcon(
timelineModel: TimelineModel,
objPath: ControlIconName,
rect: number[],
opts: PathProps
) {
const style = opts.style;
const icon = graphic.createIcon(
timelineModel.get(['controlStyle', objPath]),
opts || {},
new BoundingRect(rect[0], rect[1], rect[2], rect[3])
);
// TODO createIcon won't use style in opt.
if (style) {
(icon as Displayable).setStyle(style);
}
return icon;
}
/**
* Create symbol or update symbol
* opt: basic position and event handlers
*/
function giveSymbol(
hostModel: Model<TimelineDataItemOption | TimelineCheckpointStyle>,
itemStyleModel: Model<TimelineDataItemOption['itemStyle'] | TimelineCheckpointStyle>,
group: graphic.Group,
opt: PathProps,
symbol?: TimelineSymbol,
callback?: {
onCreate?: (symbol: TimelineSymbol) => void
onUpdate?: (symbol: TimelineSymbol) => void
}
) {
const color = itemStyleModel.get('color');
if (!symbol) {
const symbolType = hostModel.get('symbol');
symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
symbol.setStyle('strokeNoScale', true);
group.add(symbol);
callback && callback.onCreate(symbol);
}
else {
symbol.setColor(color);
group.add(symbol); // Group may be new, also need to add.
callback && callback.onUpdate(symbol);
}
// Style
const itemStyle = itemStyleModel.getItemStyle(['color']);
symbol.setStyle(itemStyle);
// Transform and events.
opt = merge({
rectHover: true,
z2: 100
}, opt, true);
let symbolSize = hostModel.get('symbolSize');
symbolSize = symbolSize instanceof Array
? symbolSize.slice()
: [+symbolSize, +symbolSize];
opt.scaleX = symbolSize[0] / 2;
opt.scaleY = symbolSize[1] / 2;
const symbolOffset = hostModel.get('symbolOffset');
if (symbolOffset) {
opt.x = opt.x || 0;
opt.y = opt.y || 0;
opt.x += numberUtil.parsePercent(symbolOffset[0], symbolSize[0]);
opt.y += numberUtil.parsePercent(symbolOffset[1], symbolSize[1]);
}
const symbolRotate = hostModel.get('symbolRotate');
opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
symbol.attr(opt);
// FIXME
// (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
// getBoundingRect will return wrong result.
// (This is supposed to be resolved in zrender, but it is a little difficult to
// leverage performance and auto updateTransform)
// (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
symbol.updateTransform();
return symbol;
}
function pointerMoveTo(
pointer: TimelineSymbol,
progressLine: graphic.Line,
dataIndex: number,
axis: TimelineAxis,
timelineModel: SliderTimelineModel,
noAnimation?: boolean
) {
if (pointer.dragging) {
return;
}
const pointerModel = timelineModel.getModel('checkpointStyle');
const toCoord = axis.dataToCoord(timelineModel.getData().get('value', dataIndex));
if (noAnimation || !pointerModel.get('animation', true)) {
pointer.attr({
x: toCoord,
y: 0
});
progressLine && progressLine.attr({
shape: { x2: toCoord }
});
}
else {
const animationCfg = {
duration: pointerModel.get('animationDuration', true),
easing: pointerModel.get('animationEasing', true)
};
pointer.stopAnimation(null, true);
pointer.animateTo({
x: toCoord,
y: 0
}, animationCfg);
progressLine && progressLine.animateTo({
shape: { x2: toCoord }
}, animationCfg);
}
}
export default SliderTimelineView; | src/component/timeline/SliderTimelineView.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0002138335257768631,
0.0001709113275865093,
0.00016279848932754248,
0.00017007756105158478,
0.0000055919258556969
] |
{
"id": 3,
"code_window": [
" const xmaxymax = to\n",
" ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);\n",
" const values = [\n",
" formatMinMax([xminymin[0], xmaxymax[0]]),\n",
" formatMinMax([xminymin[1], xmaxymax[1]])\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 433
} |
<!DOCTYPE html>
<!--
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.
-->
<meta charset="utf-8">
<style>
text {
font: 10px sans-serif;
text-anchor: middle;
}
.node--hover circle {
stroke: #000;
stroke-width: 1.2px;
}
#main {
width: 1000px;
height: 500px;
}
</style>
<div id="main" style="width:1200px; height:960px;"></div>
<svg width="960" height="960"><g transform="translate(1,1)"></g></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="../dist/echarts.js"></script>
<script src="./lib/testHelper.js"></script>
<script src="./lib/config.js"></script>
<script>
var stratify = d3.stratify()
.parentId(function(d) {
return d.id.substring(0, d.id.lastIndexOf("."));
});
d3.csv("data/flare.csv", function(error, rawData) {
if (error) throw error;
var root = stratify(rawData)
.sum(function(d) {
return d.value;
})
.sort(function(a, b) {
return b.value - a.value;
});
var maxDepth = 0;
var seriesData = root.descendants().map(function (node) {
maxDepth = Math.max(maxDepth, node.depth);
return [
node.value,
node.depth,
node.id
];
});
var chart = echarts.init(document.getElementById('main'));
function renderItem(params, api) {
var context = params.context;
if (!context.layout) {
d3.pack()
.size([api.getWidth() - 2, api.getHeight() - 2])
.padding(3)(root);
context.nodes = {};
root.descendants().forEach(function (node, index) {
context.nodes[node.id] = {
index: index,
node: node
}
});
}
var nodePath = api.value(2);
var node = context.nodes[nodePath].node;
var isLeaf = !node.children || !node.children.length;
var textFont = api.font({
fontSize: 12,
fontFamily: 'Arial'
});
var focus = new Uint32Array(node.descendants().map(function (node) {
return context.nodes[node.id].index;
}));
var nodeName = isLeaf ? nodePath.slice(nodePath.lastIndexOf('.') + 1).split(/(?=[A-Z][^A-Z])/g).join('\n') : '';
var z2 = api.value(1) * 2;
return {
type: 'circle',
focus: focus,
shape: {
cx: node.x,
cy: node.y,
r: node.r
},
z2: z2,
textContent: {
type: 'text',
style: {
text: nodeName,
width: node.r * 1.3,
overflow: 'truncate',
fontSize: node.r / 3
// fill: 'blue'
},
emphasis: {
style: {
overflow: null,
fontSize: Math.max(node.r / 3, 12)
// fill: 'red'
}
}
},
textConfig: {
position: 'inside'
},
style: {
fill: api.visual('color'),
text: nodeName,
font: textFont,
},
emphasis: {
style: {
font: textFont,
shadowBlur: 20,
shadowOffsetX: 3,
shadowOffsetY: 5,
shadowColor: 'rgba(0,0,0,0.3)'
}
}
};
}
var option = {
xAxis: {
axisLine: {show: false},
axisTick: {show: false},
axisLabel: {show: false},
splitLine: {show: false}
},
yAxis: {
axisLine: {show: false},
axisTick: {show: false},
axisLabel: {show: false},
splitLine: {show: false}
},
tooltip: {},
visualMap: {
show: false,
min: 0,
max: maxDepth,
dimension: 1,
inRange: {
color: ['#006edd', '#e0ffff']
}
},
series: {
type: 'custom',
renderItem: renderItem,
encode: {
tooltip: 0,
itemName: 2
},
data: seriesData
}
};
chart.setOption(option);
// testHelper.printElements(chart, {
// attr: ['z', 'z2', 'style.text', 'style.fill', 'style.stroke'],
// filter: function (el) {
// return el.style && el.style.text;
// }
// });
});
</script>
| test/circle-packing-with-d3.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00017751935229171067,
0.0001724815956549719,
0.00016741071885917336,
0.00017233377730008215,
0.0000028466713501984486
] |
{
"id": 3,
"code_window": [
" const xmaxymax = to\n",
" ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);\n",
" const values = [\n",
" formatMinMax([xminymin[0], xmaxymax[0]]),\n",
" formatMinMax([xminymin[1], xmaxymax[1]])\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp)\n",
" : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 433
} | /*
* 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 * as zrUtil from 'zrender/src/core/util';
import { Dictionary } from 'zrender/src/core/types';
import { ComponentFullType, ComponentTypeInfo, ComponentMainType, ComponentSubType } from './types';
const TYPE_DELIMITER = '.';
const IS_CONTAINER = '___EC__COMPONENT__CONTAINER___' as const;
const IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___' as const;
/**
* Notice, parseClassType('') should returns {main: '', sub: ''}
* @public
*/
export function parseClassType(componentType: ComponentFullType): ComponentTypeInfo {
const ret = {main: '', sub: ''};
if (componentType) {
const typeArr = componentType.split(TYPE_DELIMITER);
ret.main = typeArr[0] || '';
ret.sub = typeArr[1] || '';
}
return ret;
}
/**
* @public
*/
function checkClassType(componentType: ComponentFullType): void {
zrUtil.assert(
/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
'componentType "' + componentType + '" illegal'
);
}
export function isExtendedClass(clz: any): boolean {
return !!(clz && clz[IS_EXTENDED_CLASS]);
}
export interface ExtendableConstructor {
new (...args: any): any;
$constructor?: new (...args: any) => any;
extend: (proto: {[name: string]: any}) => ExtendableConstructor;
superCall: (context: any, methodName: string, ...args: any) => any;
superApply: (context: any, methodName: string, args: []) => any;
superClass?: ExtendableConstructor;
[IS_EXTENDED_CLASS]?: boolean;
}
/**
* Implements `ExtendableConstructor` for `rootClz`.
*
* @usage
* ```ts
* class Xxx {}
* type XxxConstructor = typeof Xxx & ExtendableConstructor
* enableClassExtend(Xxx as XxxConstructor);
* ```
*/
export function enableClassExtend(rootClz: ExtendableConstructor, mandatoryMethods?: string[]): void {
rootClz.$constructor = rootClz; // FIXME: not necessary?
rootClz.extend = function (proto: Dictionary<any>) {
if (__DEV__) {
zrUtil.each(mandatoryMethods, function (method) {
if (!proto[method]) {
console.warn(
'Method `' + method + '` should be implemented'
+ (proto.type ? ' in ' + proto.type : '') + '.'
);
}
});
}
const superClass = this;
// For backward compat, we both support ts class inheritance and this
// "extend" approach.
// The constructor should keep the same behavior as ts class inheritance:
// If this constructor/$constructor is not declared, auto invoke the super
// constructor.
// If this constructor/$constructor is declared, it is responsible for
// calling the super constructor.
function ExtendedClass(this: any, ...args: any[]) {
if (!proto.$constructor) {
if (!isESClass(superClass)) {
// Will throw error if superClass is an es6 native class.
superClass.apply(this, arguments);
}
else {
const ins = zrUtil.createObject(
// @ts-ignore
ExtendedClass.prototype, new superClass(...args)
);
return ins;
}
}
else {
proto.$constructor.apply(this, arguments);
}
}
ExtendedClass[IS_EXTENDED_CLASS] = true;
zrUtil.extend(ExtendedClass.prototype, proto);
ExtendedClass.extend = this.extend;
ExtendedClass.superCall = superCall;
ExtendedClass.superApply = superApply;
zrUtil.inherits(ExtendedClass, this);
ExtendedClass.superClass = superClass;
return ExtendedClass as unknown as ExtendableConstructor;
};
}
function isESClass(fn: unknown): boolean {
return typeof fn === 'function'
&& /^class\s/.test(Function.prototype.toString.call(fn));
}
/**
* A work around to both support ts extend and this extend mechanism.
* on sub-class.
* @usage
* ```ts
* class Component { ... }
* classUtil.enableClassExtend(Component);
* classUtil.enableClassManagement(Component, {registerWhenExtend: true});
*
* class Series extends Component { ... }
* // Without calling `markExtend`, `registerWhenExtend` will not work.
* Component.markExtend(Series);
* ```
*/
export function mountExtend(SubClz: any, SupperClz: any): void {
SubClz.extend = SupperClz.extend;
}
export interface CheckableConstructor {
new (...args: any): any;
isInstance: (ins: any) => boolean;
}
// A random offset.
let classBase = Math.round(Math.random() * 10);
/**
* Implements `CheckableConstructor` for `target`.
* Can not use instanceof, consider different scope by
* cross domain or es module import in ec extensions.
* Mount a method "isInstance()" to Clz.
*
* @usage
* ```ts
* class Xxx {}
* type XxxConstructor = typeof Xxx & CheckableConstructor;
* enableClassCheck(Xxx as XxxConstructor)
* ```
*/
export function enableClassCheck(target: CheckableConstructor): void {
const classAttr = ['__\0is_clz', classBase++].join('_');
target.prototype[classAttr] = true;
if (__DEV__) {
zrUtil.assert(!target.isInstance, 'The method "is" can not be defined.');
}
target.isInstance = function (obj) {
return !!(obj && obj[classAttr]);
};
}
// superCall should have class info, which can not be fetch from 'this'.
// Consider this case:
// class A has method f,
// class B inherits class A, overrides method f, f call superApply('f'),
// class C inherits class B, do not overrides method f,
// then when method of class C is called, dead loop occured.
function superCall(this: any, context: any, methodName: string, ...args: any): any {
return this.superClass.prototype[methodName].apply(context, args);
}
function superApply(this: any, context: any, methodName: string, args: any): any {
return this.superClass.prototype[methodName].apply(context, args);
}
export type Constructor = new (...args: any) => any;
type SubclassContainer = {[subType: string]: Constructor} & {[IS_CONTAINER]?: true};
export interface ClassManager {
registerClass: (clz: Constructor) => Constructor;
getClass: (
componentMainType: ComponentMainType, subType?: ComponentSubType, throwWhenNotFound?: boolean
) => Constructor;
getClassesByMainType: (componentType: ComponentMainType) => Constructor[];
hasClass: (componentType: ComponentFullType) => boolean;
getAllClassMainTypes: () => ComponentMainType[];
hasSubTypes: (componentType: ComponentFullType) => boolean;
}
/**
* Implements `ClassManager` for `target`
*
* @usage
* ```ts
* class Xxx {}
* type XxxConstructor = typeof Xxx & ClassManager
* enableClassManagement(Xxx as XxxConstructor);
* ```
*/
export function enableClassManagement(
target: ClassManager
): void {
/**
* Component model classes
* key: componentType,
* value:
* componentClass, when componentType is 'xxx'
* or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
*/
const storage: {
[componentMainType: string]: (Constructor | SubclassContainer)
} = {};
target.registerClass = function (
clz: Constructor
): Constructor {
// `type` should not be a "instance memeber".
// If using TS class, should better declared as `static type = 'series.pie'`.
// otherwise users have to mount `type` on prototype manually.
// For backward compat and enable instance visit type via `this.type`,
// we stil support fetch `type` from prototype.
const componentFullType = (clz as any).type || clz.prototype.type;
if (componentFullType) {
checkClassType(componentFullType);
// If only static type declared, we assign it to prototype mandatorily.
clz.prototype.type = componentFullType;
const componentTypeInfo = parseClassType(componentFullType);
if (!componentTypeInfo.sub) {
if (__DEV__) {
if (storage[componentTypeInfo.main]) {
console.warn(componentTypeInfo.main + ' exists.');
}
}
storage[componentTypeInfo.main] = clz;
}
else if (componentTypeInfo.sub !== IS_CONTAINER) {
const container = makeContainer(componentTypeInfo);
container[componentTypeInfo.sub] = clz;
}
}
return clz;
};
target.getClass = function (
mainType: ComponentMainType,
subType?: ComponentSubType,
throwWhenNotFound?: boolean
): Constructor {
let clz = storage[mainType];
if (clz && (clz as SubclassContainer)[IS_CONTAINER]) {
clz = subType ? (clz as SubclassContainer)[subType] : null;
}
if (throwWhenNotFound && !clz) {
throw new Error(
!subType
? mainType + '.' + 'type should be specified.'
: 'Component ' + mainType + '.' + (subType || '') + ' not exists. Load it first.'
);
}
return clz as Constructor;
};
target.getClassesByMainType = function (componentType: ComponentFullType): Constructor[] {
const componentTypeInfo = parseClassType(componentType);
const result: Constructor[] = [];
const obj = storage[componentTypeInfo.main];
if (obj && (obj as SubclassContainer)[IS_CONTAINER]) {
zrUtil.each(obj as SubclassContainer, function (o, type) {
type !== IS_CONTAINER && result.push(o as Constructor);
});
}
else {
result.push(obj as Constructor);
}
return result;
};
target.hasClass = function (componentType: ComponentFullType): boolean {
// Just consider componentType.main.
const componentTypeInfo = parseClassType(componentType);
return !!storage[componentTypeInfo.main];
};
/**
* @return Like ['aa', 'bb'], but can not be ['aa.xx']
*/
target.getAllClassMainTypes = function (): ComponentMainType[] {
const types: string[] = [];
zrUtil.each(storage, function (obj, type) {
types.push(type);
});
return types;
};
/**
* If a main type is container and has sub types
*/
target.hasSubTypes = function (componentType: ComponentFullType): boolean {
const componentTypeInfo = parseClassType(componentType);
const obj = storage[componentTypeInfo.main];
return obj && (obj as SubclassContainer)[IS_CONTAINER];
};
function makeContainer(componentTypeInfo: ComponentTypeInfo): SubclassContainer {
let container = storage[componentTypeInfo.main];
if (!container || !(container as SubclassContainer)[IS_CONTAINER]) {
container = storage[componentTypeInfo.main] = {};
container[IS_CONTAINER] = true;
}
return container as SubclassContainer;
}
}
// /**
// * @param {string|Array.<string>} properties
// */
// export function setReadOnly(obj, properties) {
// FIXME It seems broken in IE8 simulation of IE11
// if (!zrUtil.isArray(properties)) {
// properties = properties != null ? [properties] : [];
// }
// zrUtil.each(properties, function (prop) {
// let value = obj[prop];
// Object.defineProperty
// && Object.defineProperty(obj, prop, {
// value: value, writable: false
// });
// zrUtil.isArray(obj[prop])
// && Object.freeze
// && Object.freeze(obj[prop]);
// });
// }
| src/util/clazz.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0001775200362317264,
0.00017091064364649355,
0.0001629092002985999,
0.00017067209410015494,
0.0000033512551453895867
] |
{
"id": 4,
"code_window": [
" values: BrushDimensionMinMax[],\n",
" xyMinMax: BrushDimensionMinMax[]\n",
" } {\n",
" const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];\n",
" const values = map(rangeOrCoordRange, function (item) {\n",
" const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);\n",
" xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);\n",
" xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);\n",
" xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);\n",
" xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);\n",
" return p;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 448
} | /*
* 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 BoundingRect from 'zrender/src/core/BoundingRect';
import Cartesian from './Cartesian';
import { ScaleDataValue } from '../../util/types';
import Axis2D from './Axis2D';
import { CoordinateSystem } from '../CoordinateSystem';
import GridModel from './GridModel';
import Grid from './Grid';
import Scale from '../../scale/Scale';
import { invert } from 'zrender/src/core/matrix';
import { applyTransform } from 'zrender/src/core/vector';
export const cartesian2DDimensions = ['x', 'y'];
function canCalculateAffineTransform(scale: Scale) {
return scale.type === 'interval' || scale.type === 'time';
}
class Cartesian2D extends Cartesian<Axis2D> implements CoordinateSystem {
readonly type = 'cartesian2d';
readonly dimensions = cartesian2DDimensions;
model: GridModel;
master: Grid;
private _transform: number[];
private _invTransform: number[];
/**
* Calculate an affine transform matrix if two axes are time or value.
* It's mainly for accelartion on the large time series data.
*/
calcAffineTransform() {
this._transform = this._invTransform = null;
const xAxisScale = this.getAxis('x').scale;
const yAxisScale = this.getAxis('y').scale;
if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
return;
}
const xScaleExtent = xAxisScale.getExtent();
const yScaleExtent = yAxisScale.getExtent();
const start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
const end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
const xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
const yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
if (!xScaleSpan || !yScaleSpan) {
return;
}
// Accelerate data to point calculation on the special large time series data.
const scaleX = (end[0] - start[0]) / xScaleSpan;
const scaleY = (end[1] - start[1]) / yScaleSpan;
const translateX = start[0] - xScaleExtent[0] * scaleX;
const translateY = start[1] - yScaleExtent[0] * scaleY;
const m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
this._invTransform = invert([], m);
}
/**
* Base axis will be used on stacking.
*/
getBaseAxis(): Axis2D {
return this.getAxesByScale('ordinal')[0]
|| this.getAxesByScale('time')[0]
|| this.getAxis('x');
}
containPoint(point: number[]): boolean {
const axisX = this.getAxis('x');
const axisY = this.getAxis('y');
return axisX.contain(axisX.toLocalCoord(point[0]))
&& axisY.contain(axisY.toLocalCoord(point[1]));
}
containData(data: ScaleDataValue[]): boolean {
return this.getAxis('x').containData(data[0])
&& this.getAxis('y').containData(data[1]);
}
dataToPoint(data: ScaleDataValue[], reserved?: unknown, out?: number[]): number[] {
out = out || [];
const xVal = data[0];
const yVal = data[1];
// Fast path
if (this._transform
// It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
&& xVal != null
&& isFinite(xVal as number)
&& yVal != null
&& isFinite(yVal as number)
) {
return applyTransform(out, data as number[], this._transform);
}
const xAxis = this.getAxis('x');
const yAxis = this.getAxis('y');
out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));
out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));
return out;
}
clampData(data: ScaleDataValue[], out?: number[]): number[] {
const xScale = this.getAxis('x').scale;
const yScale = this.getAxis('y').scale;
const xAxisExtent = xScale.getExtent();
const yAxisExtent = yScale.getExtent();
const x = xScale.parse(data[0]);
const y = yScale.parse(data[1]);
out = out || [];
out[0] = Math.min(
Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
Math.max(xAxisExtent[0], xAxisExtent[1])
);
out[1] = Math.min(
Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
Math.max(yAxisExtent[0], yAxisExtent[1])
);
return out;
}
pointToData(point: number[], out?: number[], reserved?: number[], clamp?: boolean): number[] {
out = out || [];
if (this._invTransform) {
return applyTransform(out, point, this._invTransform);
}
const xAxis = this.getAxis('x');
const yAxis = this.getAxis('y');
out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
return out;
}
getOtherAxis(axis: Axis2D): Axis2D {
return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
}
/**
* Get rect area of cartesian.
* Area will have a contain function to determine if a point is in the coordinate system.
*/
getArea(): Cartesian2DArea {
const xExtent = this.getAxis('x').getGlobalExtent();
const yExtent = this.getAxis('y').getGlobalExtent();
const x = Math.min(xExtent[0], xExtent[1]);
const y = Math.min(yExtent[0], yExtent[1]);
const width = Math.max(xExtent[0], xExtent[1]) - x;
const height = Math.max(yExtent[0], yExtent[1]) - y;
return new BoundingRect(x, y, width, height);
}
};
interface Cartesian2DArea extends BoundingRect {}
export default Cartesian2D;
| src/coord/cartesian/Cartesian2D.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.007176155224442482,
0.000991290551610291,
0.0001642665738472715,
0.00017558377294335514,
0.0017728243255987763
] |
{
"id": 4,
"code_window": [
" values: BrushDimensionMinMax[],\n",
" xyMinMax: BrushDimensionMinMax[]\n",
" } {\n",
" const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];\n",
" const values = map(rangeOrCoordRange, function (item) {\n",
" const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);\n",
" xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);\n",
" xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);\n",
" xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);\n",
" xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);\n",
" return p;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 448
} | /*
* 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 {each, createHashMap, HashMap} from 'zrender/src/core/util';
import mapDataStorage, { MapRecord } from './mapDataStorage';
import geoJSONLoader from './geoJSONLoader';
import geoSVGLoader from './geoSVGLoader';
import BoundingRect from 'zrender/src/core/BoundingRect';
import { NameMap } from './geoTypes';
import Region from './Region';
import { Dictionary } from 'zrender/src/core/types';
import Group from 'zrender/src/graphic/Group';
interface Loader {
load: (mapName: string, mapRecord: MapRecord, nameProperty?: string) => {
regions?: Region[];
boundingRect?: BoundingRect;
};
makeGraphic?: (mapName: string, mapRecord: MapRecord, hostKey: string) => Group;
removeGraphic?: (mapName: string, mapRecord: MapRecord, hostKey: string) => void;
}
const loaders = {
geoJSON: geoJSONLoader,
svg: geoSVGLoader
} as Dictionary<Loader>;
export default {
load: function (mapName: string, nameMap: NameMap, nameProperty?: string): {
regions: Region[];
// Key: mapName
regionsMap: HashMap<Region>;
// Key: mapName
nameCoordMap: HashMap<number[]>;
boundingRect: BoundingRect
} {
const regions = [] as Region[];
const regionsMap = createHashMap<Region>();
const nameCoordMap = createHashMap<Region['center']>();
let boundingRect: BoundingRect;
const mapRecords = retrieveMap(mapName);
each(mapRecords, function (record) {
const singleSource = loaders[record.type].load(mapName, record, nameProperty);
each(singleSource.regions, function (region) {
let regionName = region.name;
// Try use the alias in geoNameMap
if (nameMap && nameMap.hasOwnProperty(regionName)) {
region = region.cloneShallow(regionName = nameMap[regionName]);
}
regions.push(region);
regionsMap.set(regionName, region);
nameCoordMap.set(regionName, region.center);
});
const rect = singleSource.boundingRect;
if (rect) {
boundingRect
? boundingRect.union(rect)
: (boundingRect = rect.clone());
}
});
return {
regions: regions,
regionsMap: regionsMap,
nameCoordMap: nameCoordMap,
// FIXME Always return new ?
boundingRect: boundingRect || new BoundingRect(0, 0, 0, 0)
};
},
/**
* @param hostKey For cache.
* @return Roots.
*/
makeGraphic: function (mapName: string, hostKey: string): Group[] {
const mapRecords = retrieveMap(mapName);
const results = [] as Group[];
each(mapRecords, function (record) {
const method = loaders[record.type].makeGraphic;
method && results.push(method(mapName, record, hostKey));
});
return results;
},
/**
* @param hostKey For cache.
*/
removeGraphic: function (mapName: string, hostKey: string): void {
const mapRecords = retrieveMap(mapName);
each(mapRecords, function (record) {
const method = loaders[record.type].makeGraphic;
method && method(mapName, record, hostKey);
});
}
};
function mapNotExistsError(mapName: string): void {
if (__DEV__) {
console.error(
'Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.'
);
}
}
function retrieveMap(mapName: string): MapRecord[] {
const mapRecords = mapDataStorage.retrieveMap(mapName) || [];
if (__DEV__) {
if (!mapRecords.length) {
mapNotExistsError(mapName);
}
}
return mapRecords;
}
| src/coord/geo/geoSourceManager.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00017860902880784124,
0.00017004388791974634,
0.00016605541168246418,
0.00016933120787143707,
0.000003397945647520828
] |
{
"id": 4,
"code_window": [
" values: BrushDimensionMinMax[],\n",
" xyMinMax: BrushDimensionMinMax[]\n",
" } {\n",
" const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];\n",
" const values = map(rangeOrCoordRange, function (item) {\n",
" const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);\n",
" xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);\n",
" xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);\n",
" xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);\n",
" xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);\n",
" return p;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 448
} | /*
* 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.
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory);
} else if (
typeof exports === 'object' &&
typeof exports.nodeName !== 'string'
) {
// CommonJS
factory(exports, require('echarts/lib/echarts'));
} else {
// Browser globals
factory({}, root.echarts);
}
})(this, function(exports, echarts) {
var log = function(msg) {
if (typeof console !== 'undefined') {
console && console.error && console.error(msg);
}
};
if (!echarts) {
log('ECharts is not Loaded');
return;
}
var colorPalette = [
'#cc0000',
'#002266',
'#ff9900',
'#006600',
'#8a150f',
'#076278',
'#808080',
'#f07b75'
];
var theme = {
color: colorPalette,
title: {
textStyle: {
fontWeight: 'normal',
color: '#cc0000'
}
},
visualMap: {
color: ['#cc0000', '#002266']
},
toolbox: {
color: ['#cc0000', '#cc0000', '#cc0000', '#cc0000']
},
tooltip: {
backgroundColor: 'rgba(0,0,0,0.5)',
axisPointer: {
// Axis indicator, coordinate trigger effective
type: 'line', // The default is a straight line: 'line' | 'shadow'
lineStyle: {
// Straight line indicator style settings
color: '#cc0000',
type: 'dashed'
},
crossStyle: {
color: '#cc0000'
},
shadowStyle: {
// Shadow indicator style settings
color: 'rgba(200,200,200,0.3)'
}
}
},
// Area scaling controller
dataZoom: {
dataBackgroundColor: '#eee', // Data background color
fillerColor: 'rgba(200,200,200,0.2)', // Fill the color
handleColor: '#cc0000' // Handle color
},
timeline: {
lineStyle: {
color: '#cc0000'
},
controlStyle: {
color: '#cc0000',
borderColor: '#cc0000'
}
},
candlestick: {
itemStyle: {
color: '#002266',
color0: '#ff9900'
},
lineStyle: {
width: 1,
color: '#8a150f',
color0: '#006600'
},
areaStyle: {
color: '#cc0000',
color0: '#ff9900'
}
},
map: {
itemStyle: {
color: '#ff9900'
},
areaStyle: {
color: '#ddd'
},
label: {
color: '#c12e34'
}
},
graph: {
itemStyle: {
color: '#ff9900'
},
linkStyle: {
color: '#cc0000'
}
},
gauge: {
axisLine: {
lineStyle: {
color: [
[0.2, '#002266'],
[0.8, '#cc0000'],
[1, '8a150f']
],
width: 8
}
}
}
};
echarts.registerTheme('inspired', theme);
});
| theme/inspired.js | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00020790727285202593,
0.00017237066640518606,
0.00016695990052539855,
0.0001691895886324346,
0.000009282254723075312
] |
{
"id": 4,
"code_window": [
" values: BrushDimensionMinMax[],\n",
" xyMinMax: BrushDimensionMinMax[]\n",
" } {\n",
" const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];\n",
" const values = map(rangeOrCoordRange, function (item) {\n",
" const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);\n",
" xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);\n",
" xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);\n",
" xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);\n",
" xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);\n",
" return p;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);\n"
],
"file_path": "src/component/helper/BrushTargetManager.ts",
"type": "replace",
"edit_start_line_idx": 448
} |
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<link rel="stylesheet" href="lib/reset.css">
</head>
<body>
<style>
#main {
position: relative;
min-width: 1080px; /* 4 columns */
text-align: center;
}
.title {
display: block;
cursor: pointer;
text-decoration: none;
clear: both;
text-align: center;
margin: 0;
background: #eef;
line-height: 22px;
}
.block {
display: inline-block;
*display: inline;
*zoom: 1;
vertical-align: top;
margin: 30px 0 30px 50px;
}
.block .ec {
width: 200px;
height: 200px;
}
.block label {
width: 200px;
display: block;
text-align: center;
background: #eee;
border-radius: 3px;
font-size: 12px;
line-height: 18px;
padding: 0 5px;
}
</style>
<div id="main"></div>
<script>
var echarts;
var zrUtil;
require([
'echarts'
// 'zrender/core/util',
// 'echarts/chart/line',
// 'echarts/chart/bar',
// 'echarts/chart/parallel',
// 'echarts/component/legend',
// 'echarts/component/grid',
// 'echarts/component/polar',
// 'echarts/component/parallel',
// 'echarts/component/tooltip'
], function (ec) {
echarts = ec;
zrUtil = ec.util;
var makeCartesian = zrUtil.curry(makeChart, defaultCartesianOption);
var makeCategoryOnY = zrUtil.curry(makeChart, categoryOnYOption);
var makePolar = zrUtil.curry(makeChart, defaultPolarOption);
console.profile('render');
renderTitle('cartesian normal');
// inverse
makeCartesian('x: forward, y: forward', {
xAxis: {},
yAxis: {}
});
makeCartesian('x: inverse, y: inverse', {
xAxis: {inverse: true},
yAxis: {inverse: true}
});
makeCartesian('x: forward, y: inverse', {
xAxis: {},
yAxis: {inverse: true}
});
makeCartesian('x: inverse, y: forward', {
xAxis: {inverse: true},
yAxis: {}
});
renderTitle('cartesian min max and onZero');
makeCartesian('xAxis.axisLine.onZero: false, yAxis.min: 0.4, yAxis.max: 0.8', {
xAxis: {axisLine: {onZero: false}},
yAxis: {min: 0.4, max: 0.8}
});
makeCartesian('xAxis.axisLine.onZero: false, yAxis.min: -5, yAxis.max: 1.8', {
xAxis: {axisLine: {onZero: false}},
yAxis: {min: -5, max: 1.8}
});
makeCartesian('xAxis.axisLine.onZero: false, yAxis.min: -5', {
xAxis: {axisLine: {onZero: false}},
yAxis: {min: -5}
});
makeCartesian('xAxis.axisLine.onZero: false, yAxis.max: 0.8', {
xAxis: {axisLine: {onZero: false}},
yAxis: {max: 0.8}
});
makeCartesian('(zero outside) xAxis.axisLine.onZero: true, yAxis.min: 0.4, yAxis.max: 0.8', {
xAxis: {axisLine: {onZero: true}},
yAxis: {min: 0.4, max: 0.8}
});
makeCartesian('(zero near top) xAxis.axisLine.onZero: true, yAxis.min: -5, yAxis.max: 1.8', {
xAxis: {axisLine: {onZero: true}},
yAxis: {min: -5, max: 1.8}
});
makeCartesian('(zero near bottom) xAxis.axisLine.onZero: true, yAxis.min: -1, yAxis.max: 10', {
xAxis: {axisLine: {onZero: true}},
yAxis: {min: -1, max: 10}
});
makeCategoryOnY('(zero near left) yAxis.axisLine.onZero: true, xAxis.min: -1, xAxis.max: 10', {
xAxis: {min: -1, max: 10},
yAxis: {axisLine: {onZero: true}},
});
makeCategoryOnY('(zero near right) yAxis.axisLine.onZero: true, xAxis.min: -5, xAxis.max: 1.8', {
xAxis: {min: -5, max: 1.8},
yAxis: {axisLine: {onZero: true}},
});
makeCategoryOnY('(zero right) yAxis.axisLine.onZero: true, xAxis.min: -5, xAxis.max: 1.8, yAxis.position: right', {
xAxis: {min: -5, max: 1.8},
yAxis: {axisLine: {onZero: true}, position: 'right'},
});
makeCartesian('(zero top) xAxis.axisLine.onZero: true, yAxis.min: -1, yAxis.max: 1, xAxis.position: top', {
xAxis: {axisLine: {onZero: true}, position: 'top'},
yAxis: {min: -1, max: 1}
});
renderTitle('cartesian category on y');
makeCategoryOnY('x: forward, y: forward', {
xAxis: {},
yAxis: {}
});
makeCategoryOnY('x: inverse, y: inverse', {
xAxis: {inverse: true},
yAxis: {inverse: true}
});
makeCategoryOnY('x: forward, y: inverse', {
xAxis: {},
yAxis: {inverse: true}
});
makeCategoryOnY('x: inverse, y: forward', {
xAxis: {inverse: true},
yAxis: {}
});
renderTitle('cartesian position setting');
// position
makeCartesian('x: forward top, y: forward right', {
xAxis: {position: 'top'},
yAxis: {position: 'right'}
});
makeCartesian('x: inverse bottom, y: inverse right', {
xAxis: {inverse: true, position: 'bottom'},
yAxis: {inverse: true, position: 'right'}
});
makeCartesian('x: forward bottom, y: inverse right', {
xAxis: {position: 'bottom'},
yAxis: {inverse: true, position: 'right'}
});
makeCartesian('x: inverse top, y: forward right', {
xAxis: {inverse: true, position: 'top'},
yAxis: {position: 'right'}
});
renderTitle('cartesian tick or label inside');
makeCartesian('yAxis.axisTick: inside', {
xAxis: {},
yAxis: {axisTick: {inside: true}}
});
makeCartesian('yAxis.axisLabel: inside, yAxis.axisTick: inside', {
xAxis: {},
yAxis: {axisLabel: {inside: true}, axisTick: {inside: true}}
});
makeCartesian('xAxis.axisTick: inside', {
xAxis: {axisTick: {inside: true}},
yAxis: {}
});
makeCartesian('xAxis.axisLabel: inside', {
xAxis: {axisLabel: {inside: true}},
yAxis: {}
});
makeCartesian('xAxis.axisLabel: inside, top, xAxisLine.onZero: false', {
xAxis: {axisLabel: {inside: true}, position: 'top', axisLine: {onZero: false}},
yAxis: {}
});
renderTitle('cartesian name location');
// name location
makeCartesian('x: forward start, y: forward start', {
xAxis: {nameLocation: 'start'},
yAxis: {nameLocation: 'start'}
});
makeCartesian('x: inverse start, y: inverse start', {
xAxis: {inverse: true, nameLocation: 'start'},
yAxis: {inverse: true, nameLocation: 'start'}
});
makeCartesian('x: forward start, y: inverse start', {
xAxis: {nameLocation: 'start'},
yAxis: {inverse: true, nameLocation: 'start'}
});
makeCartesian('x: inverse start, y: forward start', {
xAxis: {inverse: true, nameLocation: 'start'},
yAxis: {nameLocation: 'start'}
});
makeCartesian('x: forward middle, y: forward middle', {
xAxis: {nameLocation: 'middle', nameGap: 30},
yAxis: {nameLocation: 'middle', nameGap: 30}
});
makeCartesian('x: forward middle, y: forward middle right', {
xAxis: {nameLocation: 'middle', nameGap: 30},
yAxis: {nameLocation: 'middle', nameGap: 30, position: 'right'}
});
makeCartesian('x: inverse middle, y: inverse middle', {
xAxis: {inverse: true, nameLocation: 'middle', nameGap: 30},
yAxis: {inverse: true, nameLocation: 'middle', nameGap: 30}
});
makeCartesian('x: inverse middle top, y: inverse middle', {
xAxis: {inverse: true, nameLocation: 'middle', nameGap: 30, position: 'top'},
yAxis: {inverse: true, nameLocation: 'middle', nameGap: 30}
});
renderTitle('polar normal');
// inverse
makePolar('angle: forward, radius: forward', {
angleAxis: {},
radiusAxis: {}
});
makePolar('angle: inverse, radius: inverse', {
angleAxis: {inverse: true},
radiusAxis: {inverse: true}
});
makePolar('angle: forward, radius: inverse', {
angleAxis: {},
radiusAxis: {inverse: true}
});
makePolar('angle: inverse, radius: forward', {
angleAxis: {inverse: true},
radiusAxis: {}
});
renderTitle('polar angle settting');
// startAngle
makePolar('angle: forward startAngle23, radius: forward', {
angleAxis: {startAngle: 23},
radiusAxis: {}
});
makePolar('angle: forward startAngle64, radius: forward', {
angleAxis: {startAngle: 64},
radiusAxis: {}
});
makePolar('angle: forward startAngle90, radius: forward', {
angleAxis: {startAngle: 90},
radiusAxis: {}
});
makePolar('angle: forward startAngle108, radius: forward', {
angleAxis: {startAngle: 108},
radiusAxis: {}
});
makePolar('angle: forward startAngle164, radius: forward', {
angleAxis: {startAngle: 164},
radiusAxis: {}
});
makePolar('angle: forward startAngle180, radius: forward', {
angleAxis: {startAngle: 180},
radiusAxis: {}
});
makePolar('angle: forward startAngle204, radius: forward', {
angleAxis: {startAngle: 204},
radiusAxis: {}
});
makePolar('angle: forward startAngle250, radius: forward', {
angleAxis: {startAngle: 250},
radiusAxis: {}
});
makePolar('angle: forward startAngle270, radius: forward', {
angleAxis: {startAngle: 270},
radiusAxis: {}
});
makePolar('angle: forward startAngle270, radius: forward', {
angleAxis: {startAngle: 270},
radiusAxis: {}
});
makePolar('angle: forward startAngle294, radius: forward', {
angleAxis: {startAngle: 294},
radiusAxis: {}
});
makePolar('angle: forward startAngle344, radius: forward', {
angleAxis: {startAngle: 344},
radiusAxis: {}
});
makePolar('angle: forward startAngle360, radius: forward', {
angleAxis: {startAngle: 360},
radiusAxis: {}
});
renderTitle('polar min max');
makePolar('radiusAxis.min: 1, radiusAxis.max: 3', {
angleAxis: {},
radiusAxis: {min: 1, max: 9}
});
makePolar('radiusAxis.min: -1', {
angleAxis: {},
radiusAxis: {min: -1}
});
renderTitle('polar clockwise');
makePolar('clockwise: true', {
angleAxis: {clockwise: true},
radiusAxis: {}
});
makePolar('clockwise: false', {
angleAxis: {clockwise: false},
radiusAxis: {}
});
renderTitle('polar inverse angle settting');
// startAngle
makePolar('angle: inverse startAngle23, radius: forward', {
angleAxis: {inverse: true, startAngle: 23},
radiusAxis: {}
});
makePolar('angle: forward startAngle23, radius: inverse', {
angleAxis: {startAngle: 23},
radiusAxis: {inverse: true}
});
renderTitle('parallel');
var makeParallel = zrUtil.curry(makeChart, defaultParallelOption);
makeParallel('layout: horizontal', {
});
makeParallel('layout: horizontal, axis2 forward start', {
parallelAxis: makeParallelAxisOption({nameLocation: 'start'})
});
makeParallel('layout: horizontal, axis2 inverse start', {
parallelAxis: makeParallelAxisOption({inverse: true, nameLocation: 'start'})
});
makeParallel('layout: vertical', {
});
makeParallel('layout: vertical, axis2 forward start', {
parallel: {layout: 'vertical'},
parallelAxis: makeParallelAxisOption({nameLocation: 'start'})
});
makeParallel('layout: vertical, axis2 inverse start', {
parallel: {layout: 'vertical'},
parallelAxis: makeParallelAxisOption({inverse: true, nameLocation: 'start'})
});
console.profileEnd('render');
});
function makeParallelAxisOption(secondOpt) {
return [
{dim: 0, name: '维度1'},
zrUtil.merge({dim: 1, name: '维度2'}, secondOpt, true),
{dim: 2, name: '维度3'},
{dim: 3, name: '维度4'}
];
}
function renderTitle(label) {
var containerEl = document.getElementById('main');
var el = document.createElement('a');
el.className = 'title';
var html = encodeHTML(label);
el.innerHTML = html;
el.href = '#' + html.replace(/\s/g, '_');
el.name = html.replace(/\s/g, '_');
containerEl.appendChild(el);
}
function makeChart(getOption, label, opt) {
opt = opt || {};
var containerEl = document.getElementById('main');
var el = document.createElement('div');
el.className = 'block';
el.innerHTML = '<div class="ec"></div><label>' + encodeHTML(label) + '</label>';
containerEl.appendChild(el);
var chart = echarts.init(el.firstChild, null, { });
chart.setOption(zrUtil.merge(opt, getOption()));
}
function defaultCartesianOption() {
var xAxisData = [];
var data1 = [];
for (var i = 0; i < 30; i++) {
xAxisData.push('类目' + i);
data1.push(+(Math.random() + 0.5).toFixed(3));
}
return {
legend: {
data: ['line', 'line2', 'line3']
},
tooltip: {
trigger: 'axis',
axisPointer: {type: 'line'}
},
grid: {x: 50, y: 50, x2: 50, y2: 50},
xAxis: {
data: xAxisData,
name: 'XName',
boundaryGap: false,
splitArea: {show: false},
splitLine: {show: false}
},
yAxis: {
name: 'YName',
splitArea: {show: true}
},
series: [{
name: 'line',
type: 'line',
stack: 'all',
symbol: 'circle',
symbolSize: 10,
data: data1,
itemStyle: {
normal: {
borderColor: 'white',
borderWidth: 3,
lineStyle: {width: 1}
}
}
}]
};
}
function categoryOnYOption() {
var axisData = [];
var data1 = [];
for (var i = 0; i < 30; i++) {
axisData.push('类目' + i);
data1.push(+(Math.random() + 0.5).toFixed(3));
}
return {
legend: {
data: ['line', 'line2', 'line3']
},
tooltip: {
trigger: 'axis',
axisPointer: {type: 'line'}
},
grid: {x: 50, y: 50, x2: 50, y2: 50},
yAxis: {
data: axisData,
type: 'category',
name: 'YName',
boundaryGap: false,
splitArea: {show: false},
splitLine: {show: false}
},
xAxis: {
type: 'value',
name: 'XName',
splitArea: {show: true}
},
series: [{
name: 'line',
type: 'line',
stack: 'all',
symbol: 'circle',
symbolSize: 10,
data: data1,
itemStyle: {
normal: {
borderColor: 'white',
borderWidth: 3,
lineStyle: {width: 1}
}
}
}]
};
}
function defaultPolarOption() {
var xAxisData = [];
var data1 = [];
for (var i = 0; i < 8; i++) {
xAxisData.push('类目' + i);
data1.push((Math.random() * 2 + 1).toFixed(3));
}
return {
legend: {
data: ['line', 'line2', 'line3']
},
tooltip: {
trigger: 'axis',
axisPointer: {type: 'shadow'}
},
polar: {radius: '65%'},
angleAxis: {data: xAxisData},
radiusAxis: {splitNumber: 4, name: 'radiusName'},
series: [{
coordinateSystem: 'polar',
name: 'line',
stack: 'all',
type: 'line',
symbolSize: 10,
itemStyle: {normal: {areaStyle: {}}},
data: data1
}]
};
}
function defaultParallelOption() {
var dataBJ = [];
for (var i = 0; i < 10; i++) {
var item = [];
for (var j = 0; j < 4; j++) {
item.push(Math.random() * 10);
}
dataBJ.push(item);
}
return {
color: [
'#dd4444', '#fec42c', '#80F1BE'
],
parallelAxis: makeParallelAxisOption(),
parallel: {
left: 40,
top: 40,
right: 40,
bottom: 40,
parallelAxisDefault: {
type: 'value'
}
},
series: [
{
name: '北京',
type: 'parallel',
data: dataBJ
}
]
};
}
function encodeHTML(source) {
return source == null
? ''
: String(source)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
</script>
</body>
</html> | test/axes.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0013619600795209408,
0.00019901167252101004,
0.00016461435006931424,
0.00016964043607003987,
0.00015344849089160562
] |
{
"id": 5,
"code_window": [
"\n",
" /**\n",
" * Some coord sys (like Parallel) might do not have `pointToData`,\n",
" * or the meaning of this kind of features is not clear yet.\n",
" * @param point point Point in global pixel coordinate system.\n",
" * @param reserved Defined by the coordinate system itself\n",
" * @param out\n",
" * @return data\n",
" */\n",
" pointToData?(\n",
" point: number[],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param clamp Clamp range\n"
],
"file_path": "src/coord/CoordinateSystem.ts",
"type": "replace",
"edit_start_line_idx": 128
} | /*
* 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 { each, indexOf, curry, assert, map, createHashMap } from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as brushHelper from './brushHelper';
import {
BrushPanelConfig, BrushControllerEvents, BrushType,
BrushAreaRange, BrushDimensionMinMax
} from './BrushController';
import ExtensionAPI from '../../core/ExtensionAPI';
import GridModel from '../../coord/cartesian/GridModel';
import GeoModel from '../../coord/geo/GeoModel';
import { CoordinateSystemMaster } from '../../coord/CoordinateSystem';
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Geo from '../../coord/geo/Geo';
import GlobalModel from '../../model/Global';
import { BrushAreaParam, BrushAreaParamInternal } from '../brush/BrushModel';
import SeriesModel from '../../model/Series';
import { Dictionary } from '../../util/types';
import {
ModelFinderObject, ParsedModelFinder, ModelFinder,
parseFinder as modelUtilParseFinder,
ParsedModelFinderKnown
} from '../../util/model';
const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;
type COORD_CONVERTS_INDEX = 0 | 1;
// FIXME
// how to genarialize to more coordinate systems.
const INCLUDE_FINDER_MAIN_TYPES = [
'grid', 'xAxis', 'yAxis', 'geo', 'graph',
'polar', 'radiusAxis', 'angleAxis', 'bmap'
];
type BrushableCoordinateSystem = Cartesian2D | Geo;
type BrushTargetBuilderKey = 'grid' | 'geo';
/**
* There can be multiple axes in a single targetInfo. Consider the case
* of `grid` component, a targetInfo represents a grid which contains one or more
* cartesian and one or more axes. And consider the case of parallel system,
* which has multiple axes in a coordinate system.
*/
interface BrushTargetInfo {
panelId: string;
coordSysModel: CoordinateSystemMaster['model'];
// Use the first one as the representitive coordSys.
// A representitive cartesian in grid (first cartesian by default).
coordSys: BrushableCoordinateSystem;
// All cartesians.
coordSyses: BrushableCoordinateSystem[];
getPanelRect: GetPanelRect,
}
export interface BrushTargetInfoCartesian2D extends BrushTargetInfo {
gridModel: GridModel;
coordSys: Cartesian2D;
coordSyses: Cartesian2D[];
xAxisDeclared: boolean;
yAxisDeclared: boolean;
}
export interface BrushTargetInfoGeo extends BrushTargetInfo {
geoModel: GeoModel,
coordSysModel: GeoModel,
coordSys: Geo,
coordSyses: Geo[],
}
type GetPanelRect = () => graphic.BoundingRect;
class BrushTargetManager {
private _targetInfoList: BrushTargetInfo[] = [];
/**
* @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
* Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
* @param opt.include include coordinate system types.
*/
constructor(
finder: ModelFinderObject,
ecModel: GlobalModel,
opt?: {include?: BrushTargetBuilderKey[]}
) {
const foundCpts = parseFinder(ecModel, finder);
each(targetInfoBuilders, (builder, type) => {
if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
builder(foundCpts, this._targetInfoList);
}
});
}
setOutputRanges(
areas: BrushControllerEvents['brush']['areas'],
ecModel: GlobalModel
): BrushAreaParam[] {
this.matchOutputRanges(areas, ecModel, function (
area: BrushAreaParam,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem
) {
(area.coordRanges || (area.coordRanges = [])).push(coordRange);
// area.coordRange is the first of area.coordRanges
if (!area.coordRange) {
area.coordRange = coordRange;
// In 'category' axis, coord to pixel is not reversible, so we can not
// rebuild range by coordRange accrately, which may bring trouble when
// brushing only one item. So we use __rangeOffset to rebuilding range
// by coordRange. And this it only used in brush component so it is no
// need to be adapted to coordRanges.
const result = coordConvert[area.brushType](0, coordSys, coordRange);
area.__rangeOffset = {
offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
xyMinMax: result.xyMinMax
};
}
});
return areas;
}
matchOutputRanges<T extends (
Parameters<BrushTargetManager['findTargetInfo']>[0] & {
brushType: BrushType;
range: BrushAreaRange;
}
)>(
areas: T[],
ecModel: GlobalModel,
cb: (
area: T,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem,
ecModel: GlobalModel
) => void
) {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (targetInfo && targetInfo !== true) {
each(
targetInfo.coordSyses,
function (coordSys) {
const result = coordConvert[area.brushType](1, coordSys, area.range, true);
cb(area, result.values, coordSys, ecModel);
}
);
}
}, this);
}
/**
* the `areas` is `BrushModel.areas`.
* Called in layout stage.
* convert `area.coordRange` to global range and set panelId to `area.range`.
*/
setInputRanges(
areas: BrushAreaParamInternal[],
ecModel: GlobalModel
): void {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (__DEV__) {
assert(
!targetInfo || targetInfo === true || area.coordRange,
'coordRange must be specified when coord index specified.'
);
assert(
!targetInfo || targetInfo !== true || area.range,
'range must be specified in global brush.'
);
}
area.range = area.range || [];
// convert coordRange to global range and set panelId.
if (targetInfo && targetInfo !== true) {
area.panelId = targetInfo.panelId;
// (1) area.range shoule always be calculate from coordRange but does
// not keep its original value, for the sake of the dataZoom scenario,
// where area.coordRange remains unchanged but area.range may be changed.
// (2) Only support converting one coordRange to pixel range in brush
// component. So do not consider `coordRanges`.
// (3) About __rangeOffset, see comment above.
const result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
const rangeOffset = area.__rangeOffset;
area.range = rangeOffset
? diffProcessor[area.brushType](
result.values,
rangeOffset.offset,
getScales(result.xyMinMax, rangeOffset.xyMinMax)
)
: result.values;
}
}, this);
}
makePanelOpts(
api: ExtensionAPI,
getDefaultBrushType?: (targetInfo: BrushTargetInfo) => BrushType
): BrushPanelConfig[] {
return map(this._targetInfoList, function (targetInfo) {
const rect = targetInfo.getPanelRect();
return {
panelId: targetInfo.panelId,
defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
clipPath: brushHelper.makeRectPanelClipPath(rect),
isTargetByCursor: brushHelper.makeRectIsTargetByCursor(
rect, api, targetInfo.coordSysModel
),
getLinearBrushOtherExtent: brushHelper.makeLinearBrushOtherExtent(rect)
};
});
}
controlSeries(area: BrushAreaParamInternal, seriesModel: SeriesModel, ecModel: GlobalModel): boolean {
// Check whether area is bound in coord, and series do not belong to that coord.
// If do not do this check, some brush (like lineX) will controll all axes.
const targetInfo = this.findTargetInfo(area, ecModel);
return targetInfo === true || (
targetInfo && indexOf(
targetInfo.coordSyses, seriesModel.coordinateSystem as BrushableCoordinateSystem
) >= 0
);
}
/**
* If return Object, a coord found.
* If reutrn true, global found.
* Otherwise nothing found.
*/
findTargetInfo(
area: ModelFinderObject & {
panelId?: string
},
ecModel: GlobalModel
): BrushTargetInfo | true {
const targetInfoList = this._targetInfoList;
const foundCpts = parseFinder(ecModel, area);
for (let i = 0; i < targetInfoList.length; i++) {
const targetInfo = targetInfoList[i];
const areaPanelId = area.panelId;
if (areaPanelId) {
if (targetInfo.panelId === areaPanelId) {
return targetInfo;
}
}
else {
for (let j = 0; j < targetInfoMatchers.length; j++) {
if (targetInfoMatchers[j](foundCpts, targetInfo)) {
return targetInfo;
}
}
}
}
return true;
}
}
function formatMinMax(minMax: BrushDimensionMinMax): BrushDimensionMinMax {
minMax[0] > minMax[1] && minMax.reverse();
return minMax;
}
function parseFinder(
ecModel: GlobalModel, finder: ModelFinder
): ParsedModelFinderKnown {
return modelUtilParseFinder(
ecModel, finder, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
);
}
type TargetInfoBuilder = (
foundCpts: ParsedModelFinderKnown, targetInfoList: BrushTargetInfo[]
) => void;
const targetInfoBuilders: Record<BrushTargetBuilderKey, TargetInfoBuilder> = {
grid: function (foundCpts, targetInfoList) {
const xAxisModels = foundCpts.xAxisModels;
const yAxisModels = foundCpts.yAxisModels;
const gridModels = foundCpts.gridModels;
// Remove duplicated.
const gridModelMap = createHashMap<GridModel>();
const xAxesHas = {} as Dictionary<boolean>;
const yAxesHas = {} as Dictionary<boolean>;
if (!xAxisModels && !yAxisModels && !gridModels) {
return;
}
each(xAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
});
each(yAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
yAxesHas[gridModel.id] = true;
});
each(gridModels, function (gridModel) {
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
yAxesHas[gridModel.id] = true;
});
gridModelMap.each(function (gridModel) {
const grid = gridModel.coordinateSystem;
const cartesians = [] as Cartesian2D[];
each(grid.getCartesians(), function (cartesian, index) {
if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0
|| indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0
) {
cartesians.push(cartesian);
}
});
targetInfoList.push({
panelId: 'grid--' + gridModel.id,
gridModel: gridModel,
coordSysModel: gridModel,
// Use the first one as the representitive coordSys.
coordSys: cartesians[0],
coordSyses: cartesians,
getPanelRect: panelRectBuilders.grid,
xAxisDeclared: xAxesHas[gridModel.id],
yAxisDeclared: yAxesHas[gridModel.id]
} as BrushTargetInfoCartesian2D);
});
},
geo: function (foundCpts, targetInfoList) {
each(foundCpts.geoModels, function (geoModel: GeoModel) {
const coordSys = geoModel.coordinateSystem;
targetInfoList.push({
panelId: 'geo--' + geoModel.id,
geoModel: geoModel,
coordSysModel: geoModel,
coordSys: coordSys,
coordSyses: [coordSys],
getPanelRect: panelRectBuilders.geo
} as BrushTargetInfoGeo);
});
}
};
type TargetInfoMatcher = (
foundCpts: ParsedModelFinderKnown, targetInfo: BrushTargetInfo
) => boolean;
const targetInfoMatchers: TargetInfoMatcher[] = [
// grid
function (foundCpts, targetInfo) {
const xAxisModel = foundCpts.xAxisModel;
const yAxisModel = foundCpts.yAxisModel;
let gridModel = foundCpts.gridModel;
!gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
!gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
return gridModel && gridModel === (targetInfo as BrushTargetInfoCartesian2D).gridModel;
},
// geo
function (foundCpts, targetInfo) {
const geoModel = foundCpts.geoModel;
return geoModel && geoModel === (targetInfo as BrushTargetInfoGeo).geoModel;
}
];
type PanelRectBuilder = (this: BrushTargetInfo) => graphic.BoundingRect;
const panelRectBuilders: Record<BrushTargetBuilderKey, PanelRectBuilder> = {
grid: function (this: BrushTargetInfoCartesian2D) {
// grid is not Transformable.
return this.coordSys.master.getRect().clone();
},
geo: function (this: BrushTargetInfoGeo) {
const coordSys = this.coordSys;
const rect = coordSys.getBoundingRect().clone();
// geo roam and zoom transform
rect.applyTransform(graphic.getTransform(coordSys));
return rect;
}
};
type ConvertCoord = (
to: COORD_CONVERTS_INDEX,
coordSys: BrushableCoordinateSystem,
rangeOrCoordRange: BrushAreaRange,
clamp?: boolean
) => {
values: BrushAreaRange,
xyMinMax: BrushDimensionMinMax[]
};
const coordConvert: Record<BrushType, ConvertCoord> = {
lineX: curry(axisConvert, 0),
lineY: curry(axisConvert, 1),
rect: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xminymin = to
? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
const xmaxymax = to
? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
const values = [
formatMinMax([xminymin[0], xmaxymax[0]]),
formatMinMax([xminymin[1], xmaxymax[1]])
];
return {values: values, xyMinMax: values};
},
polygon: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
const values = map(rangeOrCoordRange, function (item) {
const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);
xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
return p;
});
return {values: values, xyMinMax: xyMinMax};
}
};
function axisConvert(
axisNameIndex: 0 | 1,
to: COORD_CONVERTS_INDEX,
coordSys: Cartesian2D,
rangeOrCoordRange: BrushDimensionMinMax
): {
values: BrushDimensionMinMax,
xyMinMax: BrushDimensionMinMax[]
} {
if (__DEV__) {
assert(
coordSys.type === 'cartesian2d',
'lineX/lineY brush is available only in cartesian2d.'
);
}
const axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
const values = formatMinMax(map([0, 1], function (i) {
return to
? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true)
: axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
}));
const xyMinMax = [];
xyMinMax[axisNameIndex] = values;
xyMinMax[1 - axisNameIndex] = [NaN, NaN];
return {values: values, xyMinMax: xyMinMax};
}
type DiffProcess = (
values: BrushDimensionMinMax | BrushDimensionMinMax[],
refer: BrushDimensionMinMax | BrushDimensionMinMax[],
scales: ReturnType<typeof getScales>
) => BrushDimensionMinMax | BrushDimensionMinMax[];
const diffProcessor: Record<BrushType, DiffProcess> = {
lineX: curry(axisDiffProcessor, 0),
lineY: curry(axisDiffProcessor, 1),
rect: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return [
[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
[values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
];
},
polygon: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return map(values, function (item, idx) {
return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
});
}
};
function axisDiffProcessor(
axisNameIndex: 0 | 1,
values: BrushDimensionMinMax,
refer: BrushDimensionMinMax,
scales: ReturnType<typeof getScales>
): BrushDimensionMinMax {
return [
values[0] - scales[axisNameIndex] * refer[0],
values[1] - scales[axisNameIndex] * refer[1]
];
}
// We have to process scale caused by dataZoom manually,
// although it might be not accurate.
// Return [0~1, 0~1]
function getScales(xyMinMaxCurr: BrushDimensionMinMax[], xyMinMaxOrigin: BrushDimensionMinMax[]): number[] {
const sizeCurr = getSize(xyMinMaxCurr);
const sizeOrigin = getSize(xyMinMaxOrigin);
const scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
function getSize(xyMinMax: BrushDimensionMinMax[]): number[] {
return xyMinMax
? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
: [NaN, NaN];
}
export default BrushTargetManager;
| src/component/helper/BrushTargetManager.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.9976761937141418,
0.03696132451295853,
0.00016450544353574514,
0.00017374100571032614,
0.18493637442588806
] |
{
"id": 5,
"code_window": [
"\n",
" /**\n",
" * Some coord sys (like Parallel) might do not have `pointToData`,\n",
" * or the meaning of this kind of features is not clear yet.\n",
" * @param point point Point in global pixel coordinate system.\n",
" * @param reserved Defined by the coordinate system itself\n",
" * @param out\n",
" * @return data\n",
" */\n",
" pointToData?(\n",
" point: number[],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param clamp Clamp range\n"
],
"file_path": "src/coord/CoordinateSystem.ts",
"type": "replace",
"edit_start_line_idx": 128
} |
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<script src="lib/jquery.min.js"></script>
</head>
<body>
<style>
html, body, #main {
width: 100%;
height: 100%;
margin: 0;
}
</style>
新疆 should be yellow. The pattern in the right geo should not be blurred.
<div id="main"></div>
<script>
require([
'echarts'
// 'echarts/chart/scatter',
// 'echarts/component/legend',
// 'echarts/component/geo'
], function (echarts) {
$.get('./data/map/json/china.json', function (chinaJson) {
if (typeof chinaJson === 'string') {
chinaJson = eval('(' + chinaJson + ')');
}
echarts.registerMap('china', chinaJson);
var placeList = [
{name:'海门', geoCoord:[121.15, 31.89]},
{name:'鄂尔多斯', geoCoord:[109.781327, 39.608266]},
{name:'招远', geoCoord:[120.38, 37.35]},
{name:'舟山', geoCoord:[122.207216, 29.985295]},
{name:'齐齐哈尔', geoCoord:[123.97, 47.33]},
{name:'盐城', geoCoord:[120.13, 33.38]},
{name:'赤峰', geoCoord:[118.87, 42.28]},
{name:'青岛', geoCoord:[120.33, 36.07]},
{name:'乳山', geoCoord:[121.52, 36.89]},
{name:'金昌', geoCoord:[102.188043, 38.520089]},
{name:'泉州', geoCoord:[118.58, 24.93]},
{name:'莱西', geoCoord:[120.53, 36.86]},
{name:'日照', geoCoord:[119.46, 35.42]},
{name:'胶南', geoCoord:[119.97, 35.88]},
{name:'南通', geoCoord:[121.05, 32.08]},
{name:'拉萨', geoCoord:[91.11, 29.97]},
{name:'云浮', geoCoord:[112.02, 22.93]},
{name:'梅州', geoCoord:[116.1, 24.55]},
{name:'文登', geoCoord:[122.05, 37.2]},
{name:'上海', geoCoord:[121.48, 31.22]},
{name:'攀枝花', geoCoord:[101.718637, 26.582347]},
{name:'威海', geoCoord:[122.1, 37.5]},
{name:'承德', geoCoord:[117.93, 40.97]},
{name:'厦门', geoCoord:[118.1, 24.46]},
{name:'汕尾', geoCoord:[115.375279, 22.786211]},
{name:'潮州', geoCoord:[116.63, 23.68]},
{name:'丹东', geoCoord:[124.37, 40.13]},
{name:'太仓', geoCoord:[121.1, 31.45]},
{name:'曲靖', geoCoord:[103.79, 25.51]},
{name:'烟台', geoCoord:[121.39, 37.52]},
{name:'福州', geoCoord:[119.3, 26.08]},
{name:'瓦房店', geoCoord:[121.979603, 39.627114]},
{name:'即墨', geoCoord:[120.45, 36.38]},
{name:'抚顺', geoCoord:[123.97, 41.97]},
{name:'玉溪', geoCoord:[102.52, 24.35]},
{name:'张家口', geoCoord:[114.87, 40.82]},
{name:'阳泉', geoCoord:[113.57, 37.85]},
{name:'莱州', geoCoord:[119.942327, 37.177017]},
{name:'湖州', geoCoord:[120.1, 30.86]},
{name:'汕头', geoCoord:[116.69, 23.39]},
{name:'昆山', geoCoord:[120.95, 31.39]},
{name:'宁波', geoCoord:[121.56, 29.86]},
{name:'湛江', geoCoord:[110.359377, 21.270708]},
{name:'揭阳', geoCoord:[116.35, 23.55]},
{name:'荣成', geoCoord:[122.41, 37.16]},
{name:'连云港', geoCoord:[119.16, 34.59]},
{name:'葫芦岛', geoCoord:[120.836932, 40.711052]},
{name:'常熟', geoCoord:[120.74, 31.64]},
{name:'东莞', geoCoord:[113.75, 23.04]},
{name:'河源', geoCoord:[114.68, 23.73]},
{name:'淮安', geoCoord:[119.15, 33.5]},
{name:'泰州', geoCoord:[119.9, 32.49]},
{name:'南宁', geoCoord:[108.33, 22.84]},
{name:'营口', geoCoord:[122.18, 40.65]},
{name:'惠州', geoCoord:[114.4, 23.09]},
{name:'江阴', geoCoord:[120.26, 31.91]},
{name:'蓬莱', geoCoord:[120.75, 37.8]},
{name:'韶关', geoCoord:[113.62, 24.84]},
{name:'嘉峪关', geoCoord:[98.289152, 39.77313]},
{name:'广州', geoCoord:[113.23, 23.16]},
{name:'延安', geoCoord:[109.47, 36.6]},
{name:'太原', geoCoord:[112.53, 37.87]},
{name:'清远', geoCoord:[113.01, 23.7]},
{name:'中山', geoCoord:[113.38, 22.52]},
{name:'昆明', geoCoord:[102.73, 25.04]},
{name:'寿光', geoCoord:[118.73, 36.86]},
{name:'盘锦', geoCoord:[122.070714, 41.119997]},
{name:'长治', geoCoord:[113.08, 36.18]},
{name:'深圳', geoCoord:[114.07, 22.62]},
{name:'珠海', geoCoord:[113.52, 22.3]},
{name:'宿迁', geoCoord:[118.3, 33.96]},
{name:'咸阳', geoCoord:[108.72, 34.36]},
{name:'铜川', geoCoord:[109.11, 35.09]},
{name:'平度', geoCoord:[119.97, 36.77]},
{name:'佛山', geoCoord:[113.11, 23.05]},
{name:'海口', geoCoord:[110.35, 20.02]},
{name:'江门', geoCoord:[113.06, 22.61]},
{name:'章丘', geoCoord:[117.53, 36.72]},
{name:'肇庆', geoCoord:[112.44, 23.05]},
{name:'大连', geoCoord:[121.62, 38.92]},
{name:'临汾', geoCoord:[111.5, 36.08]},
{name:'吴江', geoCoord:[120.63, 31.16]},
{name:'石嘴山', geoCoord:[106.39, 39.04]},
{name:'沈阳', geoCoord:[123.38, 41.8]},
{name:'苏州', geoCoord:[120.62, 31.32]},
{name:'茂名', geoCoord:[110.88, 21.68]},
{name:'嘉兴', geoCoord:[120.76, 30.77]},
{name:'长春', geoCoord:[125.35, 43.88]},
{name:'胶州', geoCoord:[120.03336, 36.264622]},
{name:'银川', geoCoord:[106.27, 38.47]},
{name:'张家港', geoCoord:[120.555821, 31.875428]},
{name:'三门峡', geoCoord:[111.19, 34.76]},
{name:'锦州', geoCoord:[121.15, 41.13]},
{name:'南昌', geoCoord:[115.89, 28.68]},
{name:'柳州', geoCoord:[109.4, 24.33]},
{name:'三亚', geoCoord:[109.511909, 18.252847]},
{name:'自贡', geoCoord:[104.778442, 29.33903]},
{name:'吉林', geoCoord:[126.57, 43.87]},
{name:'阳江', geoCoord:[111.95, 21.85]},
{name:'泸州', geoCoord:[105.39, 28.91]},
{name:'西宁', geoCoord:[101.74, 36.56]},
{name:'宜宾', geoCoord:[104.56, 29.77]},
{name:'呼和浩特', geoCoord:[111.65, 40.82]},
{name:'成都', geoCoord:[104.06, 30.67]},
{name:'大同', geoCoord:[113.3, 40.12]},
{name:'镇江', geoCoord:[119.44, 32.2]},
{name:'桂林', geoCoord:[110.28, 25.29]},
{name:'张家界', geoCoord:[110.479191, 29.117096]},
{name:'宜兴', geoCoord:[119.82, 31.36]},
{name:'北海', geoCoord:[109.12, 21.49]},
{name:'西安', geoCoord:[108.95, 34.27]},
{name:'金坛', geoCoord:[119.56, 31.74]},
{name:'东营', geoCoord:[118.49, 37.46]},
{name:'牡丹江', geoCoord:[129.58, 44.6]},
{name:'遵义', geoCoord:[106.9, 27.7]},
{name:'绍兴', geoCoord:[120.58, 30.01]},
{name:'扬州', geoCoord:[119.42, 32.39]},
{name:'常州', geoCoord:[119.95, 31.79]},
{name:'潍坊', geoCoord:[119.1, 36.62]},
{name:'重庆', geoCoord:[106.54, 29.59]},
{name:'台州', geoCoord:[121.420757, 28.656386]},
{name:'南京', geoCoord:[118.78, 32.04]},
{name:'滨州', geoCoord:[118.03, 37.36]},
{name:'贵阳', geoCoord:[106.71, 26.57]},
{name:'无锡', geoCoord:[120.29, 31.59]},
{name:'本溪', geoCoord:[123.73, 41.3]},
{name:'克拉玛依', geoCoord:[84.77, 45.59]},
{name:'渭南', geoCoord:[109.5, 34.52]},
{name:'马鞍山', geoCoord:[118.48, 31.56]},
{name:'宝鸡', geoCoord:[107.15, 34.38]},
{name:'焦作', geoCoord:[113.21, 35.24]},
{name:'句容', geoCoord:[119.16, 31.95]},
{name:'北京', geoCoord:[116.46, 39.92]},
{name:'徐州', geoCoord:[117.2, 34.26]},
{name:'衡水', geoCoord:[115.72, 37.72]},
{name:'包头', geoCoord:[110, 40.58]},
{name:'绵阳', geoCoord:[104.73, 31.48]},
{name:'乌鲁木齐', geoCoord:[87.68, 43.77]},
{name:'枣庄', geoCoord:[117.57, 34.86]},
{name:'杭州', geoCoord:[120.19, 30.26]},
{name:'淄博', geoCoord:[118.05, 36.78]},
{name:'鞍山', geoCoord:[122.85, 41.12]},
{name:'溧阳', geoCoord:[119.48, 31.43]},
{name:'库尔勒', geoCoord:[86.06, 41.68]},
{name:'安阳', geoCoord:[114.35, 36.1]},
{name:'开封', geoCoord:[114.35, 34.79]},
{name:'济南', geoCoord:[117, 36.65]},
{name:'德阳', geoCoord:[104.37, 31.13]},
{name:'温州', geoCoord:[120.65, 28.01]},
{name:'九江', geoCoord:[115.97, 29.71]},
{name:'邯郸', geoCoord:[114.47, 36.6]},
{name:'临安', geoCoord:[119.72, 30.23]},
{name:'兰州', geoCoord:[103.73, 36.03]},
{name:'沧州', geoCoord:[116.83, 38.33]},
{name:'临沂', geoCoord:[118.35, 35.05]},
{name:'南充', geoCoord:[106.110698, 30.837793]},
{name:'天津', geoCoord:[117.2, 39.13]},
{name:'富阳', geoCoord:[119.95, 30.07]},
{name:'泰安', geoCoord:[117.13, 36.18]},
{name:'诸暨', geoCoord:[120.23, 29.71]},
{name:'郑州', geoCoord:[113.65, 34.76]},
{name:'哈尔滨', geoCoord:[126.63, 45.75]},
{name:'聊城', geoCoord:[115.97, 36.45]},
{name:'芜湖', geoCoord:[118.38, 31.33]},
{name:'唐山', geoCoord:[118.02, 39.63]},
{name:'平顶山', geoCoord:[113.29, 33.75]},
{name:'邢台', geoCoord:[114.48, 37.05]},
{name:'德州', geoCoord:[116.29, 37.45]},
{name:'济宁', geoCoord:[116.59, 35.38]},
{name:'荆州', geoCoord:[112.239741, 30.335165]},
{name:'宜昌', geoCoord:[111.3, 30.7]},
{name:'义乌', geoCoord:[120.06, 29.32]},
{name:'丽水', geoCoord:[119.92, 28.45]},
{name:'洛阳', geoCoord:[112.44, 34.7]},
{name:'秦皇岛', geoCoord:[119.57, 39.95]},
{name:'株洲', geoCoord:[113.16, 27.83]},
{name:'石家庄', geoCoord:[114.48, 38.03]},
{name:'莱芜', geoCoord:[117.67, 36.19]},
{name:'常德', geoCoord:[111.69, 29.05]},
{name:'保定', geoCoord:[115.48, 38.85]},
{name:'湘潭', geoCoord:[112.91, 27.87]},
{name:'金华', geoCoord:[119.64, 29.12]},
{name:'岳阳', geoCoord:[113.09, 29.37]},
{name:'长沙', geoCoord:[113, 28.21]},
{name:'衢州', geoCoord:[118.88, 28.97]},
{name:'廊坊', geoCoord:[116.7, 39.53]},
{name:'菏泽', geoCoord:[115.480656, 35.23375]},
{name:'合肥', geoCoord:[117.27, 31.86]},
{name:'武汉', geoCoord:[114.31, 30.52]},
{name:'大庆', geoCoord:[125.03, 46.58]}
];
var chart = echarts.init(document.getElementById('main'), null, {
});
var data = [];
var data2 = [];
var len = 200;
var randomValue = function (geoCoord) {
return [
geoCoord[0] + Math.random() * 1 - 0.5,
geoCoord[1] + Math.random() * 1 - 0.5,
Math.random()
];
};
while(len--) {
var geoCoord = placeList[len % placeList.length].geoCoord;
data.push({
name: placeList[len % placeList.length].name + len,
value: randomValue(geoCoord)
});
data2.push({
name: placeList[len % placeList.length].name + len,
value: randomValue(geoCoord)
});
}
var pattern = new Image();
pattern.onload = function () {
chart.setOption({
legend: {
data: ['scatter', 'scatter2']
},
geo: [{
map: 'china',
roam: true,
left: 100,
width: 300,
selectedMode: 'single',
// zoom: 1.5,
scaleLimit: {
min: 1.5,
max: 2
},
regions: [{
name: '新疆',
label: {
normal: {
formatter: 'asdf',
show: true,
offset: [100, 200]
}
},
itemStyle: {
normal: {
areaColor: 'yellow'
}
}
}]
}, {
map: 'china',
roam: true,
selectedMode: 'multiple',
left: null,
right: 100,
width: 300,
itemStyle: {
repeat: 'repeat',
areaColor: {
image: pattern,
repeat: 'repeat'
}
}
}],
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
}
},
series: []
});
chart.on('geoselectchanged', function (param) {
console.log(param);
});
};
pattern.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQCAMAAAC3Ycb+AAAAQlBMVEX////y8vL19fXS0dLy8fHi4uLc3Nz5+fnx8fHw8PDp6enr6+v39/fa2trl5OXb29v7+vrv7+/19PT08/P09PTX19dlapQUAAAClElEQVR4Xu3cuWrEMBiF0dizT/bt/V81vxuZFGkUBOJydCqDuGBCCAyT78EBgCTHOh/taTnVWdrj66FO313D/7i8/rV83pb77hrOeT0/kK/2dN2Wr+3xeVvuu2u48/Ja52l/utdZ2+PLuU7H3c5hwwAAADiXOm/701Ln0h7fH+v03TXceflY57M93U51bu3x+1Cn767h/ss+lN2HffxueMLfU8PT/Yk0DAAAAPN8O8zwtF/MNOxD2d/DPn43POW/vxgGAAAAZqF1onVi2OtpnQQNa50YBgAAAEkSrRPDWidaJ4a1TgYMa50YBgAAAEkSrRPDWidaJzHDWieGAQAAABCfEZ8xHPt64jMaMeIzhgEAAEAjRnzGsPiM+Ixh8ZkBw+IzhgEAAEAjRnzGsPiM+EzAsPiMYQAAAGASWidaJ4a9ntZJ0LDWiWEAAACQJNE6Max1onViWOtkwLDWiWEAAACQJNE6Max1onUSM6x1YhgAAAAA8RnxGcOxryc+oxEjPmMYAAAANGLEZwyLz4jPGBafGTAsPmMYAAAANGLEZwyLz4jPBAyLzxgGAAAAJqF1onVi2OtpnQQNa50YBgAAAEkSrRPDWidaJ4a1TgYMa50YBgAAAEkSrRPDWidaJzHDWieGAQAAABCfEZ8xHPt64jMaMeIzhgEAAEAjRnzGsPiM+Ixh8ZkBw+IzhgEAAEAjRnzGsPiM+EzAsPiMYQAAAGASWidaJ4a9ntZJ0LDWiWEAAACQJNE6Max1onViWOtkwLDWiWEAAACQJNE6Max1onUSM6x1YhgAAAAA8RnxGcOxryc+oxEjPmMYAAAANGLEZwyLz4jPGBafGTAsPmMYAAAANGLEZwyLz4jPBAyLzxgGAGLOD2dJsYoNf2AgAAAAAElFTkSuQmCC';
});
});
</script>
</body>
</html> | test/geoScatter.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00032095759524963796,
0.0001761894964147359,
0.00016484508523717523,
0.0001682794390944764,
0.00002700773075048346
] |
{
"id": 5,
"code_window": [
"\n",
" /**\n",
" * Some coord sys (like Parallel) might do not have `pointToData`,\n",
" * or the meaning of this kind of features is not clear yet.\n",
" * @param point point Point in global pixel coordinate system.\n",
" * @param reserved Defined by the coordinate system itself\n",
" * @param out\n",
" * @return data\n",
" */\n",
" pointToData?(\n",
" point: number[],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param clamp Clamp range\n"
],
"file_path": "src/coord/CoordinateSystem.ts",
"type": "replace",
"edit_start_line_idx": 128
} | /*
* 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.
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory);
} else if (
typeof exports === 'object' &&
typeof exports.nodeName !== 'string'
) {
// CommonJS
factory(exports, require('echarts/lib/echarts'));
} else {
// Browser globals
factory({}, root.echarts);
}
})(this, function(exports, echarts) {
var log = function(msg) {
if (typeof console !== 'undefined') {
console && console.error && console.error(msg);
}
};
if (!echarts) {
log('ECharts is not Loaded');
return;
}
var colorPalette = [
'#cc0000',
'#002266',
'#ff9900',
'#006600',
'#8a150f',
'#076278',
'#808080',
'#f07b75'
];
var theme = {
color: colorPalette,
title: {
textStyle: {
fontWeight: 'normal',
color: '#cc0000'
}
},
visualMap: {
color: ['#cc0000', '#002266']
},
toolbox: {
color: ['#cc0000', '#cc0000', '#cc0000', '#cc0000']
},
tooltip: {
backgroundColor: 'rgba(0,0,0,0.5)',
axisPointer: {
// Axis indicator, coordinate trigger effective
type: 'line', // The default is a straight line: 'line' | 'shadow'
lineStyle: {
// Straight line indicator style settings
color: '#cc0000',
type: 'dashed'
},
crossStyle: {
color: '#cc0000'
},
shadowStyle: {
// Shadow indicator style settings
color: 'rgba(200,200,200,0.3)'
}
}
},
// Area scaling controller
dataZoom: {
dataBackgroundColor: '#eee', // Data background color
fillerColor: 'rgba(200,200,200,0.2)', // Fill the color
handleColor: '#cc0000' // Handle color
},
timeline: {
lineStyle: {
color: '#cc0000'
},
controlStyle: {
color: '#cc0000',
borderColor: '#cc0000'
}
},
candlestick: {
itemStyle: {
color: '#002266',
color0: '#ff9900'
},
lineStyle: {
width: 1,
color: '#8a150f',
color0: '#006600'
},
areaStyle: {
color: '#cc0000',
color0: '#ff9900'
}
},
map: {
itemStyle: {
color: '#ff9900'
},
areaStyle: {
color: '#ddd'
},
label: {
color: '#c12e34'
}
},
graph: {
itemStyle: {
color: '#ff9900'
},
linkStyle: {
color: '#cc0000'
}
},
gauge: {
axisLine: {
lineStyle: {
color: [
[0.2, '#002266'],
[0.8, '#cc0000'],
[1, '8a150f']
],
width: 8
}
}
}
};
echarts.registerTheme('inspired', theme);
});
| theme/inspired.js | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00017625103646423668,
0.00017209052748512477,
0.00016792103997431695,
0.0001718661078484729,
0.000002783020818242221
] |
{
"id": 5,
"code_window": [
"\n",
" /**\n",
" * Some coord sys (like Parallel) might do not have `pointToData`,\n",
" * or the meaning of this kind of features is not clear yet.\n",
" * @param point point Point in global pixel coordinate system.\n",
" * @param reserved Defined by the coordinate system itself\n",
" * @param out\n",
" * @return data\n",
" */\n",
" pointToData?(\n",
" point: number[],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param clamp Clamp range\n"
],
"file_path": "src/coord/CoordinateSystem.ts",
"type": "replace",
"edit_start_line_idx": 128
} | [{"name":"Action 1","ops":[{"type":"mousedown","time":368,"x":67,"y":492},{"type":"mouseup","time":461,"x":67,"y":492},{"time":462,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":687,"x":67,"y":493},{"type":"mousemove","time":891,"x":63,"y":512},{"type":"mousedown","time":1427,"x":63,"y":512},{"type":"mouseup","time":1537,"x":63,"y":512},{"time":1538,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":1805,"x":63,"y":513},{"type":"mousemove","time":2005,"x":56,"y":534},{"type":"mousemove","time":2207,"x":54,"y":539},{"type":"mousedown","time":2295,"x":54,"y":539},{"type":"mousemove","time":2310,"x":54,"y":539},{"type":"mouseup","time":2388,"x":54,"y":539},{"time":2389,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":2705,"x":54,"y":540},{"type":"mousemove","time":2905,"x":53,"y":562},{"type":"mousemove","time":3105,"x":53,"y":563},{"type":"mousedown","time":3113,"x":53,"y":563},{"type":"mouseup","time":3222,"x":53,"y":563},{"time":3223,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":3305,"x":53,"y":563},{"type":"mousemove","time":3923,"x":53,"y":563},{"type":"mousemove","time":4125,"x":35,"y":588},{"type":"mousedown","time":4257,"x":35,"y":588},{"type":"mouseup","time":4358,"x":35,"y":588},{"time":4359,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":4380,"x":34,"y":588},{"type":"mousemove","time":4580,"x":34,"y":589},{"type":"mousemove","time":4814,"x":38,"y":589},{"type":"mousedown","time":5093,"x":38,"y":589},{"type":"mouseup","time":5176,"x":38,"y":589},{"time":5177,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":5266,"x":40,"y":588},{"type":"mousemove","time":5475,"x":55,"y":574},{"type":"mousemove","time":5677,"x":71,"y":522},{"type":"mousemove","time":5879,"x":71,"y":506},{"type":"mousemove","time":6093,"x":68,"y":494},{"type":"mousedown","time":6152,"x":68,"y":494},{"type":"mouseup","time":6244,"x":68,"y":494},{"time":6245,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":7045,"x":68,"y":495},{"type":"mousemove","time":7246,"x":63,"y":514},{"type":"mousedown","time":7328,"x":63,"y":514},{"type":"mouseup","time":7427,"x":63,"y":514},{"time":7428,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":7611,"x":63,"y":514}],"scrollY":0,"scrollX":0,"timestamp":1568041143365}] | test/runTest/actions/heatmap-map.json | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00016557476192247123,
0.00016557476192247123,
0.00016557476192247123,
0.00016557476192247123,
0
] |
{
"id": 6,
"code_window": [
" */\n",
" pointToData?(\n",
" point: number[],\n",
" reserved?: any,\n",
" out?: number[],\n",
" clamp?: boolean\n",
" ): number | number[];\n",
"\n",
" // @param point Point in global pixel coordinate system.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/coord/CoordinateSystem.ts",
"type": "replace",
"edit_start_line_idx": 134
} | /*
* 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 { each, indexOf, curry, assert, map, createHashMap } from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as brushHelper from './brushHelper';
import {
BrushPanelConfig, BrushControllerEvents, BrushType,
BrushAreaRange, BrushDimensionMinMax
} from './BrushController';
import ExtensionAPI from '../../core/ExtensionAPI';
import GridModel from '../../coord/cartesian/GridModel';
import GeoModel from '../../coord/geo/GeoModel';
import { CoordinateSystemMaster } from '../../coord/CoordinateSystem';
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Geo from '../../coord/geo/Geo';
import GlobalModel from '../../model/Global';
import { BrushAreaParam, BrushAreaParamInternal } from '../brush/BrushModel';
import SeriesModel from '../../model/Series';
import { Dictionary } from '../../util/types';
import {
ModelFinderObject, ParsedModelFinder, ModelFinder,
parseFinder as modelUtilParseFinder,
ParsedModelFinderKnown
} from '../../util/model';
const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;
type COORD_CONVERTS_INDEX = 0 | 1;
// FIXME
// how to genarialize to more coordinate systems.
const INCLUDE_FINDER_MAIN_TYPES = [
'grid', 'xAxis', 'yAxis', 'geo', 'graph',
'polar', 'radiusAxis', 'angleAxis', 'bmap'
];
type BrushableCoordinateSystem = Cartesian2D | Geo;
type BrushTargetBuilderKey = 'grid' | 'geo';
/**
* There can be multiple axes in a single targetInfo. Consider the case
* of `grid` component, a targetInfo represents a grid which contains one or more
* cartesian and one or more axes. And consider the case of parallel system,
* which has multiple axes in a coordinate system.
*/
interface BrushTargetInfo {
panelId: string;
coordSysModel: CoordinateSystemMaster['model'];
// Use the first one as the representitive coordSys.
// A representitive cartesian in grid (first cartesian by default).
coordSys: BrushableCoordinateSystem;
// All cartesians.
coordSyses: BrushableCoordinateSystem[];
getPanelRect: GetPanelRect,
}
export interface BrushTargetInfoCartesian2D extends BrushTargetInfo {
gridModel: GridModel;
coordSys: Cartesian2D;
coordSyses: Cartesian2D[];
xAxisDeclared: boolean;
yAxisDeclared: boolean;
}
export interface BrushTargetInfoGeo extends BrushTargetInfo {
geoModel: GeoModel,
coordSysModel: GeoModel,
coordSys: Geo,
coordSyses: Geo[],
}
type GetPanelRect = () => graphic.BoundingRect;
class BrushTargetManager {
private _targetInfoList: BrushTargetInfo[] = [];
/**
* @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
* Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
* @param opt.include include coordinate system types.
*/
constructor(
finder: ModelFinderObject,
ecModel: GlobalModel,
opt?: {include?: BrushTargetBuilderKey[]}
) {
const foundCpts = parseFinder(ecModel, finder);
each(targetInfoBuilders, (builder, type) => {
if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
builder(foundCpts, this._targetInfoList);
}
});
}
setOutputRanges(
areas: BrushControllerEvents['brush']['areas'],
ecModel: GlobalModel
): BrushAreaParam[] {
this.matchOutputRanges(areas, ecModel, function (
area: BrushAreaParam,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem
) {
(area.coordRanges || (area.coordRanges = [])).push(coordRange);
// area.coordRange is the first of area.coordRanges
if (!area.coordRange) {
area.coordRange = coordRange;
// In 'category' axis, coord to pixel is not reversible, so we can not
// rebuild range by coordRange accrately, which may bring trouble when
// brushing only one item. So we use __rangeOffset to rebuilding range
// by coordRange. And this it only used in brush component so it is no
// need to be adapted to coordRanges.
const result = coordConvert[area.brushType](0, coordSys, coordRange);
area.__rangeOffset = {
offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
xyMinMax: result.xyMinMax
};
}
});
return areas;
}
matchOutputRanges<T extends (
Parameters<BrushTargetManager['findTargetInfo']>[0] & {
brushType: BrushType;
range: BrushAreaRange;
}
)>(
areas: T[],
ecModel: GlobalModel,
cb: (
area: T,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem,
ecModel: GlobalModel
) => void
) {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (targetInfo && targetInfo !== true) {
each(
targetInfo.coordSyses,
function (coordSys) {
const result = coordConvert[area.brushType](1, coordSys, area.range, true);
cb(area, result.values, coordSys, ecModel);
}
);
}
}, this);
}
/**
* the `areas` is `BrushModel.areas`.
* Called in layout stage.
* convert `area.coordRange` to global range and set panelId to `area.range`.
*/
setInputRanges(
areas: BrushAreaParamInternal[],
ecModel: GlobalModel
): void {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (__DEV__) {
assert(
!targetInfo || targetInfo === true || area.coordRange,
'coordRange must be specified when coord index specified.'
);
assert(
!targetInfo || targetInfo !== true || area.range,
'range must be specified in global brush.'
);
}
area.range = area.range || [];
// convert coordRange to global range and set panelId.
if (targetInfo && targetInfo !== true) {
area.panelId = targetInfo.panelId;
// (1) area.range shoule always be calculate from coordRange but does
// not keep its original value, for the sake of the dataZoom scenario,
// where area.coordRange remains unchanged but area.range may be changed.
// (2) Only support converting one coordRange to pixel range in brush
// component. So do not consider `coordRanges`.
// (3) About __rangeOffset, see comment above.
const result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
const rangeOffset = area.__rangeOffset;
area.range = rangeOffset
? diffProcessor[area.brushType](
result.values,
rangeOffset.offset,
getScales(result.xyMinMax, rangeOffset.xyMinMax)
)
: result.values;
}
}, this);
}
makePanelOpts(
api: ExtensionAPI,
getDefaultBrushType?: (targetInfo: BrushTargetInfo) => BrushType
): BrushPanelConfig[] {
return map(this._targetInfoList, function (targetInfo) {
const rect = targetInfo.getPanelRect();
return {
panelId: targetInfo.panelId,
defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
clipPath: brushHelper.makeRectPanelClipPath(rect),
isTargetByCursor: brushHelper.makeRectIsTargetByCursor(
rect, api, targetInfo.coordSysModel
),
getLinearBrushOtherExtent: brushHelper.makeLinearBrushOtherExtent(rect)
};
});
}
controlSeries(area: BrushAreaParamInternal, seriesModel: SeriesModel, ecModel: GlobalModel): boolean {
// Check whether area is bound in coord, and series do not belong to that coord.
// If do not do this check, some brush (like lineX) will controll all axes.
const targetInfo = this.findTargetInfo(area, ecModel);
return targetInfo === true || (
targetInfo && indexOf(
targetInfo.coordSyses, seriesModel.coordinateSystem as BrushableCoordinateSystem
) >= 0
);
}
/**
* If return Object, a coord found.
* If reutrn true, global found.
* Otherwise nothing found.
*/
findTargetInfo(
area: ModelFinderObject & {
panelId?: string
},
ecModel: GlobalModel
): BrushTargetInfo | true {
const targetInfoList = this._targetInfoList;
const foundCpts = parseFinder(ecModel, area);
for (let i = 0; i < targetInfoList.length; i++) {
const targetInfo = targetInfoList[i];
const areaPanelId = area.panelId;
if (areaPanelId) {
if (targetInfo.panelId === areaPanelId) {
return targetInfo;
}
}
else {
for (let j = 0; j < targetInfoMatchers.length; j++) {
if (targetInfoMatchers[j](foundCpts, targetInfo)) {
return targetInfo;
}
}
}
}
return true;
}
}
function formatMinMax(minMax: BrushDimensionMinMax): BrushDimensionMinMax {
minMax[0] > minMax[1] && minMax.reverse();
return minMax;
}
function parseFinder(
ecModel: GlobalModel, finder: ModelFinder
): ParsedModelFinderKnown {
return modelUtilParseFinder(
ecModel, finder, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
);
}
type TargetInfoBuilder = (
foundCpts: ParsedModelFinderKnown, targetInfoList: BrushTargetInfo[]
) => void;
const targetInfoBuilders: Record<BrushTargetBuilderKey, TargetInfoBuilder> = {
grid: function (foundCpts, targetInfoList) {
const xAxisModels = foundCpts.xAxisModels;
const yAxisModels = foundCpts.yAxisModels;
const gridModels = foundCpts.gridModels;
// Remove duplicated.
const gridModelMap = createHashMap<GridModel>();
const xAxesHas = {} as Dictionary<boolean>;
const yAxesHas = {} as Dictionary<boolean>;
if (!xAxisModels && !yAxisModels && !gridModels) {
return;
}
each(xAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
});
each(yAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
yAxesHas[gridModel.id] = true;
});
each(gridModels, function (gridModel) {
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
yAxesHas[gridModel.id] = true;
});
gridModelMap.each(function (gridModel) {
const grid = gridModel.coordinateSystem;
const cartesians = [] as Cartesian2D[];
each(grid.getCartesians(), function (cartesian, index) {
if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0
|| indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0
) {
cartesians.push(cartesian);
}
});
targetInfoList.push({
panelId: 'grid--' + gridModel.id,
gridModel: gridModel,
coordSysModel: gridModel,
// Use the first one as the representitive coordSys.
coordSys: cartesians[0],
coordSyses: cartesians,
getPanelRect: panelRectBuilders.grid,
xAxisDeclared: xAxesHas[gridModel.id],
yAxisDeclared: yAxesHas[gridModel.id]
} as BrushTargetInfoCartesian2D);
});
},
geo: function (foundCpts, targetInfoList) {
each(foundCpts.geoModels, function (geoModel: GeoModel) {
const coordSys = geoModel.coordinateSystem;
targetInfoList.push({
panelId: 'geo--' + geoModel.id,
geoModel: geoModel,
coordSysModel: geoModel,
coordSys: coordSys,
coordSyses: [coordSys],
getPanelRect: panelRectBuilders.geo
} as BrushTargetInfoGeo);
});
}
};
type TargetInfoMatcher = (
foundCpts: ParsedModelFinderKnown, targetInfo: BrushTargetInfo
) => boolean;
const targetInfoMatchers: TargetInfoMatcher[] = [
// grid
function (foundCpts, targetInfo) {
const xAxisModel = foundCpts.xAxisModel;
const yAxisModel = foundCpts.yAxisModel;
let gridModel = foundCpts.gridModel;
!gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
!gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
return gridModel && gridModel === (targetInfo as BrushTargetInfoCartesian2D).gridModel;
},
// geo
function (foundCpts, targetInfo) {
const geoModel = foundCpts.geoModel;
return geoModel && geoModel === (targetInfo as BrushTargetInfoGeo).geoModel;
}
];
type PanelRectBuilder = (this: BrushTargetInfo) => graphic.BoundingRect;
const panelRectBuilders: Record<BrushTargetBuilderKey, PanelRectBuilder> = {
grid: function (this: BrushTargetInfoCartesian2D) {
// grid is not Transformable.
return this.coordSys.master.getRect().clone();
},
geo: function (this: BrushTargetInfoGeo) {
const coordSys = this.coordSys;
const rect = coordSys.getBoundingRect().clone();
// geo roam and zoom transform
rect.applyTransform(graphic.getTransform(coordSys));
return rect;
}
};
type ConvertCoord = (
to: COORD_CONVERTS_INDEX,
coordSys: BrushableCoordinateSystem,
rangeOrCoordRange: BrushAreaRange,
clamp?: boolean
) => {
values: BrushAreaRange,
xyMinMax: BrushDimensionMinMax[]
};
const coordConvert: Record<BrushType, ConvertCoord> = {
lineX: curry(axisConvert, 0),
lineY: curry(axisConvert, 1),
rect: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xminymin = to
? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
const xmaxymax = to
? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
const values = [
formatMinMax([xminymin[0], xmaxymax[0]]),
formatMinMax([xminymin[1], xmaxymax[1]])
];
return {values: values, xyMinMax: values};
},
polygon: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
const values = map(rangeOrCoordRange, function (item) {
const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);
xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
return p;
});
return {values: values, xyMinMax: xyMinMax};
}
};
function axisConvert(
axisNameIndex: 0 | 1,
to: COORD_CONVERTS_INDEX,
coordSys: Cartesian2D,
rangeOrCoordRange: BrushDimensionMinMax
): {
values: BrushDimensionMinMax,
xyMinMax: BrushDimensionMinMax[]
} {
if (__DEV__) {
assert(
coordSys.type === 'cartesian2d',
'lineX/lineY brush is available only in cartesian2d.'
);
}
const axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
const values = formatMinMax(map([0, 1], function (i) {
return to
? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true)
: axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
}));
const xyMinMax = [];
xyMinMax[axisNameIndex] = values;
xyMinMax[1 - axisNameIndex] = [NaN, NaN];
return {values: values, xyMinMax: xyMinMax};
}
type DiffProcess = (
values: BrushDimensionMinMax | BrushDimensionMinMax[],
refer: BrushDimensionMinMax | BrushDimensionMinMax[],
scales: ReturnType<typeof getScales>
) => BrushDimensionMinMax | BrushDimensionMinMax[];
const diffProcessor: Record<BrushType, DiffProcess> = {
lineX: curry(axisDiffProcessor, 0),
lineY: curry(axisDiffProcessor, 1),
rect: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return [
[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
[values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
];
},
polygon: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return map(values, function (item, idx) {
return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
});
}
};
function axisDiffProcessor(
axisNameIndex: 0 | 1,
values: BrushDimensionMinMax,
refer: BrushDimensionMinMax,
scales: ReturnType<typeof getScales>
): BrushDimensionMinMax {
return [
values[0] - scales[axisNameIndex] * refer[0],
values[1] - scales[axisNameIndex] * refer[1]
];
}
// We have to process scale caused by dataZoom manually,
// although it might be not accurate.
// Return [0~1, 0~1]
function getScales(xyMinMaxCurr: BrushDimensionMinMax[], xyMinMaxOrigin: BrushDimensionMinMax[]): number[] {
const sizeCurr = getSize(xyMinMaxCurr);
const sizeOrigin = getSize(xyMinMaxOrigin);
const scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
function getSize(xyMinMax: BrushDimensionMinMax[]): number[] {
return xyMinMax
? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
: [NaN, NaN];
}
export default BrushTargetManager;
| src/component/helper/BrushTargetManager.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.01065223477780819,
0.0005206866771914065,
0.00016312308434862643,
0.00017281778855249286,
0.0015913277165964246
] |
{
"id": 6,
"code_window": [
" */\n",
" pointToData?(\n",
" point: number[],\n",
" reserved?: any,\n",
" out?: number[],\n",
" clamp?: boolean\n",
" ): number | number[];\n",
"\n",
" // @param point Point in global pixel coordinate system.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/coord/CoordinateSystem.ts",
"type": "replace",
"edit_start_line_idx": 134
} | /*
* 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.
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory);
} else if (
typeof exports === 'object' &&
typeof exports.nodeName !== 'string'
) {
// CommonJS
factory(exports, require('echarts/lib/echarts'));
} else {
// Browser globals
factory({}, root.echarts);
}
})(this, function(exports, echarts) {
var log = function(msg) {
if (typeof console !== 'undefined') {
console && console.error && console.error(msg);
}
};
if (!echarts) {
log('ECharts is not Loaded');
return;
}
var contrastColor = '#eee';
var axisCommon = function() {
return {
axisLine: {
lineStyle: {
color: contrastColor
}
},
axisTick: {
lineStyle: {
color: contrastColor
}
},
axisLabel: {
color: contrastColor
},
splitLine: {
lineStyle: {
type: 'dashed',
color: '#aaa'
}
},
splitArea: {
areaStyle: {
color: contrastColor
}
}
};
};
var colorPalette = [
'#00a8c6',
'#40c0cb',
'#ebd3ad',
'#aee239',
'#8fbe00',
'#33e0ff',
'#b3f4ff',
'#e6ff99'
];
var theme = {
color: colorPalette,
backgroundColor: '#333',
tooltip: {
axisPointer: {
lineStyle: {
color: contrastColor
},
crossStyle: {
color: contrastColor
}
}
},
legend: {
textStyle: {
color: contrastColor
}
},
title: {
textStyle: {
color: contrastColor
}
},
toolbox: {
iconStyle: {
borderColor: contrastColor
}
},
// Area scaling controller
dataZoom: {
dataBackgroundColor: '#eee', // Data background color
fillerColor: 'rgba(200,200,200,0.2)', // Fill the color
handleColor: '#00a8c6' // Handle color
},
timeline: {
itemStyle: {
color: colorPalette[1]
},
lineStyle: {
color: contrastColor
},
controlStyle: {
color: contrastColor,
borderColor: contrastColor
},
label: {
color: contrastColor
}
},
timeAxis: axisCommon(),
logAxis: axisCommon(),
valueAxis: axisCommon(),
categoryAxis: axisCommon(),
line: {
symbol: 'circle'
},
graph: {
color: colorPalette
},
gauge: {
axisLine: {
lineStyle: {
color: [
[0.2, '#40c0cb'],
[0.8, '#00a8c6'],
[1, '#8fbe00']
],
width: 8
}
}
}
};
theme.categoryAxis.splitLine.show = false;
echarts.registerTheme('dark-fresh-cut', theme);
});
| theme/dark-fresh-cut.js | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0001801550533855334,
0.00017521536210551858,
0.0001689026685198769,
0.00017539903637953103,
0.0000024998118988150964
] |
{
"id": 6,
"code_window": [
" */\n",
" pointToData?(\n",
" point: number[],\n",
" reserved?: any,\n",
" out?: number[],\n",
" clamp?: boolean\n",
" ): number | number[];\n",
"\n",
" // @param point Point in global pixel coordinate system.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/coord/CoordinateSystem.ts",
"type": "replace",
"edit_start_line_idx": 134
} | /*
* 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.
*/
/**
* Parallel Coordinates
* <https://en.wikipedia.org/wiki/Parallel_coordinates>
*/
import * as zrUtil from 'zrender/src/core/util';
import * as matrix from 'zrender/src/core/matrix';
import * as layoutUtil from '../../util/layout';
import * as axisHelper from '../../coord/axisHelper';
import ParallelAxis from './ParallelAxis';
import * as graphic from '../../util/graphic';
import * as numberUtil from '../../util/number';
import sliderMove from '../../component/helper/sliderMove';
import ParallelModel, { ParallelLayoutDirection } from './ParallelModel';
import GlobalModel from '../../model/Global';
import ExtensionAPI from '../../core/ExtensionAPI';
import { Dictionary, DimensionName, ScaleDataValue } from '../../util/types';
import { CoordinateSystem, CoordinateSystemMaster } from '../CoordinateSystem';
import ParallelAxisModel, { ParallelActiveState } from './AxisModel';
import List from '../../data/List';
const each = zrUtil.each;
const mathMin = Math.min;
const mathMax = Math.max;
const mathFloor = Math.floor;
const mathCeil = Math.ceil;
const round = numberUtil.round;
const PI = Math.PI;
interface ParallelCoordinateSystemLayoutInfo {
layout: ParallelLayoutDirection;
pixelDimIndex: number;
layoutBase: number;
layoutLength: number;
axisBase: number;
axisLength: number;
axisExpandable: boolean;
axisExpandWidth: number;
axisCollapseWidth: number;
axisExpandWindow: number[];
axisCount: number;
winInnerIndices: number[];
axisExpandWindow0Pos: number;
}
export interface ParallelAxisLayoutInfo {
position: number[];
rotation: number;
transform: matrix.MatrixArray;
axisNameAvailableWidth: number;
axisLabelShow: boolean;
nameTruncateMaxWidth: number;
tickDirection: -1 | 1;
labelDirection: -1 | 1;
}
type SlidedAxisExpandBehavior = 'none' | 'slide' | 'jump';
class Parallel implements CoordinateSystemMaster, CoordinateSystem {
readonly type = 'parallel';
/**
* key: dimension
*/
private _axesMap = zrUtil.createHashMap<ParallelAxis>();
/**
* key: dimension
* value: {position: [], rotation, }
*/
private _axesLayout: Dictionary<ParallelAxisLayoutInfo> = {};
/**
* Always follow axis order.
*/
readonly dimensions: ParallelModel['dimensions'];
private _rect: graphic.BoundingRect;
private _model: ParallelModel;
// Inject
name: string;
model: ParallelModel;
constructor(parallelModel: ParallelModel, ecModel: GlobalModel, api: ExtensionAPI) {
this.dimensions = parallelModel.dimensions;
this._model = parallelModel;
this._init(parallelModel, ecModel, api);
}
private _init(parallelModel: ParallelModel, ecModel: GlobalModel, api: ExtensionAPI): void {
const dimensions = parallelModel.dimensions;
const parallelAxisIndex = parallelModel.parallelAxisIndex;
each(dimensions, function (dim, idx) {
const axisIndex = parallelAxisIndex[idx];
const axisModel = ecModel.getComponent('parallelAxis', axisIndex) as ParallelAxisModel;
const axis = this._axesMap.set(dim, new ParallelAxis(
dim,
axisHelper.createScaleByModel(axisModel),
[0, 0],
axisModel.get('type'),
axisIndex
));
const isCategory = axis.type === 'category';
axis.onBand = isCategory && axisModel.get('boundaryGap');
axis.inverse = axisModel.get('inverse');
// Injection
axisModel.axis = axis;
axis.model = axisModel;
axis.coordinateSystem = axisModel.coordinateSystem = this;
}, this);
}
/**
* Update axis scale after data processed
*/
update(ecModel: GlobalModel, api: ExtensionAPI): void {
this._updateAxesFromSeries(this._model, ecModel);
}
containPoint(point: number[]): boolean {
const layoutInfo = this._makeLayoutInfo();
const axisBase = layoutInfo.axisBase;
const layoutBase = layoutInfo.layoutBase;
const pixelDimIndex = layoutInfo.pixelDimIndex;
const pAxis = point[1 - pixelDimIndex];
const pLayout = point[pixelDimIndex];
return pAxis >= axisBase
&& pAxis <= axisBase + layoutInfo.axisLength
&& pLayout >= layoutBase
&& pLayout <= layoutBase + layoutInfo.layoutLength;
}
getModel(): ParallelModel {
return this._model;
}
/**
* Update properties from series
*/
private _updateAxesFromSeries(parallelModel: ParallelModel, ecModel: GlobalModel): void {
ecModel.eachSeries(function (seriesModel) {
if (!parallelModel.contains(seriesModel, ecModel)) {
return;
}
const data = seriesModel.getData();
each(this.dimensions, function (dim) {
const axis = this._axesMap.get(dim);
axis.scale.unionExtentFromData(data, data.mapDimension(dim));
axisHelper.niceScaleExtent(axis.scale, axis.model);
}, this);
}, this);
}
/**
* Resize the parallel coordinate system.
*/
resize(parallelModel: ParallelModel, api: ExtensionAPI): void {
this._rect = layoutUtil.getLayoutRect(
parallelModel.getBoxLayoutParams(),
{
width: api.getWidth(),
height: api.getHeight()
}
);
this._layoutAxes();
}
getRect(): graphic.BoundingRect {
return this._rect;
}
private _makeLayoutInfo(): ParallelCoordinateSystemLayoutInfo {
const parallelModel = this._model;
const rect = this._rect;
const xy = ['x', 'y'] as const;
const wh = ['width', 'height'] as const;
const layout = parallelModel.get('layout');
const pixelDimIndex = layout === 'horizontal' ? 0 : 1;
const layoutLength = rect[wh[pixelDimIndex]];
const layoutExtent = [0, layoutLength];
const axisCount = this.dimensions.length;
const axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
const axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
const axisExpandable = parallelModel.get('axisExpandable')
&& axisCount > 3
&& axisCount > axisExpandCount
&& axisExpandCount > 1
&& axisExpandWidth > 0
&& layoutLength > 0;
// `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
// for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
// where collapsed axes should be overlapped.
let axisExpandWindow = parallelModel.get('axisExpandWindow');
let winSize;
if (!axisExpandWindow) {
winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
const axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor(axisCount / 2);
axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
axisExpandWindow[1] = axisExpandWindow[0] + winSize;
}
else {
winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
axisExpandWindow[1] = axisExpandWindow[0] + winSize;
}
let axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
// Avoid axisCollapseWidth is too small.
axisCollapseWidth < 3 && (axisCollapseWidth = 0);
// Find the first and last indices > ewin[0] and < ewin[1].
const winInnerIndices = [
mathFloor(round(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
mathCeil(round(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
];
// Pos in ec coordinates.
const axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
return {
layout: layout,
pixelDimIndex: pixelDimIndex,
layoutBase: rect[xy[pixelDimIndex]],
layoutLength: layoutLength,
axisBase: rect[xy[1 - pixelDimIndex]],
axisLength: rect[wh[1 - pixelDimIndex]],
axisExpandable: axisExpandable,
axisExpandWidth: axisExpandWidth,
axisCollapseWidth: axisCollapseWidth,
axisExpandWindow: axisExpandWindow,
axisCount: axisCount,
winInnerIndices: winInnerIndices,
axisExpandWindow0Pos: axisExpandWindow0Pos
};
}
private _layoutAxes(): void {
const rect = this._rect;
const axes = this._axesMap;
const dimensions = this.dimensions;
const layoutInfo = this._makeLayoutInfo();
const layout = layoutInfo.layout;
axes.each(function (axis) {
const axisExtent = [0, layoutInfo.axisLength];
const idx = axis.inverse ? 1 : 0;
axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
});
each(dimensions, function (dim, idx) {
const posInfo = (layoutInfo.axisExpandable
? layoutAxisWithExpand : layoutAxisWithoutExpand
)(idx, layoutInfo);
const positionTable = {
horizontal: {
x: posInfo.position,
y: layoutInfo.axisLength
},
vertical: {
x: 0,
y: posInfo.position
}
};
const rotationTable = {
horizontal: PI / 2,
vertical: 0
};
const position = [
positionTable[layout].x + rect.x,
positionTable[layout].y + rect.y
];
const rotation = rotationTable[layout];
const transform = matrix.create();
matrix.rotate(transform, transform, rotation);
matrix.translate(transform, transform, position);
// TODO
// tick layout info
// TODO
// update dimensions info based on axis order.
this._axesLayout[dim] = {
position: position,
rotation: rotation,
transform: transform,
axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
axisLabelShow: posInfo.axisLabelShow,
nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
tickDirection: 1,
labelDirection: 1
};
}, this);
}
/**
* Get axis by dim.
*/
getAxis(dim: DimensionName): ParallelAxis {
return this._axesMap.get(dim);
}
/**
* Convert a dim value of a single item of series data to Point.
*/
dataToPoint(value: ScaleDataValue, dim: DimensionName): number[] {
return this.axisCoordToPoint(
this._axesMap.get(dim).dataToCoord(value),
dim
);
}
/**
* Travel data for one time, get activeState of each data item.
* @param start the start dataIndex that travel from.
* @param end the next dataIndex of the last dataIndex will be travel.
*/
eachActiveState(
data: List,
callback: (activeState: ParallelActiveState, dataIndex: number) => void,
start?: number,
end?: number
): void {
start == null && (start = 0);
end == null && (end = data.count());
const axesMap = this._axesMap;
const dimensions = this.dimensions;
const dataDimensions = [] as DimensionName[];
const axisModels = [] as ParallelAxisModel[];
zrUtil.each(dimensions, function (axisDim) {
dataDimensions.push(data.mapDimension(axisDim));
axisModels.push(axesMap.get(axisDim).model);
});
const hasActiveSet = this.hasAxisBrushed();
for (let dataIndex = start; dataIndex < end; dataIndex++) {
let activeState: ParallelActiveState;
if (!hasActiveSet) {
activeState = 'normal';
}
else {
activeState = 'active';
const values = data.getValues(dataDimensions, dataIndex);
for (let j = 0, lenj = dimensions.length; j < lenj; j++) {
const state = axisModels[j].getActiveState(values[j]);
if (state === 'inactive') {
activeState = 'inactive';
break;
}
}
}
callback(activeState, dataIndex);
}
}
/**
* Whether has any activeSet.
*/
hasAxisBrushed(): boolean {
const dimensions = this.dimensions;
const axesMap = this._axesMap;
let hasActiveSet = false;
for (let j = 0, lenj = dimensions.length; j < lenj; j++) {
if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
hasActiveSet = true;
}
}
return hasActiveSet;
}
/**
* Convert coords of each axis to Point.
* Return point. For example: [10, 20]
*/
axisCoordToPoint(coord: number, dim: DimensionName): number[] {
const axisLayout = this._axesLayout[dim];
return graphic.applyTransform([coord, 0], axisLayout.transform);
}
/**
* Get axis layout.
*/
getAxisLayout(dim: DimensionName): ParallelAxisLayoutInfo {
return zrUtil.clone(this._axesLayout[dim]);
}
/**
* @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
*/
getSlidedAxisExpandWindow(point: number[]): {
axisExpandWindow: number[],
behavior: SlidedAxisExpandBehavior
} {
const layoutInfo = this._makeLayoutInfo();
const pixelDimIndex = layoutInfo.pixelDimIndex;
let axisExpandWindow = layoutInfo.axisExpandWindow.slice();
const winSize = axisExpandWindow[1] - axisExpandWindow[0];
const extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
// Out of the area of coordinate system.
if (!this.containPoint(point)) {
return {behavior: 'none', axisExpandWindow: axisExpandWindow};
}
// Conver the point from global to expand coordinates.
const pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
// For dragging operation convenience, the window should not be
// slided when mouse is the center area of the window.
let delta;
let behavior: SlidedAxisExpandBehavior = 'slide';
const axisCollapseWidth = layoutInfo.axisCollapseWidth;
const triggerArea = this._model.get('axisExpandSlideTriggerArea');
// But consider touch device, jump is necessary.
const useJump = triggerArea[0] != null;
if (axisCollapseWidth) {
if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
behavior = 'jump';
delta = pointCoord - winSize * triggerArea[2];
}
else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
behavior = 'jump';
delta = pointCoord - winSize * (1 - triggerArea[2]);
}
else {
(delta = pointCoord - winSize * triggerArea[1]) >= 0
&& (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
&& (delta = 0);
}
delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
delta
? sliderMove(delta, axisExpandWindow, extent, 'all')
// Avoid nonsense triger on mousemove.
: (behavior = 'none');
}
// When screen is too narrow, make it visible and slidable, although it is hard to interact.
else {
const winSize2 = axisExpandWindow[1] - axisExpandWindow[0];
const pos = extent[1] * pointCoord / winSize2;
axisExpandWindow = [mathMax(0, pos - winSize2 / 2)];
axisExpandWindow[1] = mathMin(extent[1], axisExpandWindow[0] + winSize2);
axisExpandWindow[0] = axisExpandWindow[1] - winSize2;
}
return {
axisExpandWindow: axisExpandWindow,
behavior: behavior
};
}
// TODO
// convertToPixel
// convertFromPixel
// Note:
// (1) Consider Parallel, the return type of `convertToPixel` could be number[][] (Point[]).
// (2) In parallel coord sys, how to make `convertFromPixel` make sense?
// Perhaps convert a point based on "a rensent most axis" is more meaningful rather than based on all axes?
}
function restrict(len: number, extent: number[]): number {
return mathMin(mathMax(len, extent[0]), extent[1]);
}
interface ParallelAxisLayoutPositionInfo {
position: number;
axisNameAvailableWidth: number;
axisLabelShow: boolean;
nameTruncateMaxWidth?: number;
}
function layoutAxisWithoutExpand(
axisIndex: number,
layoutInfo: ParallelCoordinateSystemLayoutInfo
): ParallelAxisLayoutPositionInfo {
const step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
return {
position: step * axisIndex,
axisNameAvailableWidth: step,
axisLabelShow: true
};
}
function layoutAxisWithExpand(
axisIndex: number,
layoutInfo: ParallelCoordinateSystemLayoutInfo
): ParallelAxisLayoutPositionInfo {
const layoutLength = layoutInfo.layoutLength;
const axisExpandWidth = layoutInfo.axisExpandWidth;
const axisCount = layoutInfo.axisCount;
const axisCollapseWidth = layoutInfo.axisCollapseWidth;
const winInnerIndices = layoutInfo.winInnerIndices;
let position;
let axisNameAvailableWidth = axisCollapseWidth;
let axisLabelShow = false;
let nameTruncateMaxWidth;
if (axisIndex < winInnerIndices[0]) {
position = axisIndex * axisCollapseWidth;
nameTruncateMaxWidth = axisCollapseWidth;
}
else if (axisIndex <= winInnerIndices[1]) {
position = layoutInfo.axisExpandWindow0Pos
+ axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
axisNameAvailableWidth = axisExpandWidth;
axisLabelShow = true;
}
else {
position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
nameTruncateMaxWidth = axisCollapseWidth;
}
return {
position: position,
axisNameAvailableWidth: axisNameAvailableWidth,
axisLabelShow: axisLabelShow,
nameTruncateMaxWidth: nameTruncateMaxWidth
};
}
export default Parallel;
| src/coord/parallel/Parallel.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0021934164687991142,
0.00031974262674339116,
0.00016502247308380902,
0.00017368639237247407,
0.00038084539119154215
] |
{
"id": 6,
"code_window": [
" */\n",
" pointToData?(\n",
" point: number[],\n",
" reserved?: any,\n",
" out?: number[],\n",
" clamp?: boolean\n",
" ): number | number[];\n",
"\n",
" // @param point Point in global pixel coordinate system.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/coord/CoordinateSystem.ts",
"type": "replace",
"edit_start_line_idx": 134
} | /*
* 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 Path, {PathProps} from 'zrender/src/graphic/Path';
import Group from 'zrender/src/graphic/Group';
import {extend, defaults, each, map} from 'zrender/src/core/util';
import {
Rect,
Sector,
updateProps,
initProps,
removeElementWithFadeOut
} from '../../util/graphic';
import { getECData } from '../../util/innerStore';
import { enableHoverEmphasis, setStatesStylesFromModel } from '../../util/states';
import { setLabelStyle, getLabelStatesModels, setLabelValueAnimation } from '../../label/labelStyle';
import {throttle} from '../../util/throttle';
import {createClipPath} from '../helper/createClipPathFromCoordSys';
import Sausage from '../../util/shape/sausage';
import ChartView from '../../view/Chart';
import List, {DefaultDataVisual} from '../../data/List';
import GlobalModel from '../../model/Global';
import ExtensionAPI from '../../core/ExtensionAPI';
import {
StageHandlerProgressParams,
ZRElementEvent,
ColorString,
OrdinalSortInfo,
Payload,
OrdinalNumber,
ParsedValue
} from '../../util/types';
import BarSeriesModel, {BarSeriesOption, BarDataItemOption} from './BarSeries';
import type Axis2D from '../../coord/cartesian/Axis2D';
import type Cartesian2D from '../../coord/cartesian/Cartesian2D';
import type Polar from '../../coord/polar/Polar';
import type Model from '../../model/Model';
import { isCoordinateSystemType } from '../../coord/CoordinateSystem';
import { getDefaultLabel, getDefaultInterpolatedLabel } from '../helper/labelHelper';
import OrdinalScale from '../../scale/Ordinal';
import SeriesModel from '../../model/Series';
import {AngleAxisModel, RadiusAxisModel} from '../../coord/polar/AxisModel';
import CartesianAxisModel from '../../coord/cartesian/AxisModel';
import {LayoutRect} from '../../util/layout';
import {EventCallback} from 'zrender/src/core/Eventful';
import { warn } from '../../util/log';
const BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'borderWidth'] as const;
const BAR_BORDER_RADIUS_QUERY = ['itemStyle', 'borderRadius'] as const;
const _eventPos = [0, 0];
const mathMax = Math.max;
const mathMin = Math.min;
type CoordSysOfBar = BarSeriesModel['coordinateSystem'];
type RectShape = Rect['shape'];
type SectorShape = Sector['shape'];
type SectorLayout = SectorShape;
type RectLayout = RectShape;
type BarPossiblePath = Sector | Rect | Sausage;
type CartesianCoordArea = ReturnType<Cartesian2D['getArea']>;
type PolarCoordArea = ReturnType<Polar['getArea']>;
type RealtimeSortConfig = {
baseAxis: Axis2D;
otherAxis: Axis2D;
};
// Return a number, based on which the ordinal sorted.
type OrderMapping = (dataIndex: number) => number;
function getClipArea(coord: CoordSysOfBar, data: List) {
const coordSysClipArea = coord.getArea && coord.getArea();
if (isCoordinateSystemType<Cartesian2D>(coord, 'cartesian2d')) {
const baseAxis = coord.getBaseAxis();
// When boundaryGap is false or using time axis. bar may exceed the grid.
// We should not clip this part.
// See test/bar2.html
if (baseAxis.type !== 'category' || !baseAxis.onBand) {
const expandWidth = data.getLayout('bandWidth');
if (baseAxis.isHorizontal()) {
(coordSysClipArea as CartesianCoordArea).x -= expandWidth;
(coordSysClipArea as CartesianCoordArea).width += expandWidth * 2;
}
else {
(coordSysClipArea as CartesianCoordArea).y -= expandWidth;
(coordSysClipArea as CartesianCoordArea).height += expandWidth * 2;
}
}
}
return coordSysClipArea as PolarCoordArea | CartesianCoordArea;
}
class BarView extends ChartView {
static type = 'bar' as const;
type = BarView.type;
private _data: List;
private _isLargeDraw: boolean;
private _isFirstFrame: boolean; // First frame after series added
private _onRendered: EventCallback<unknown, unknown>;
private _backgroundGroup: Group;
private _backgroundEls: (Rect | Sector)[];
private _model: BarSeriesModel;
constructor() {
super();
this._isFirstFrame = true;
}
render(seriesModel: BarSeriesModel, ecModel: GlobalModel, api: ExtensionAPI, payload: Payload) {
this._model = seriesModel;
this._removeOnRenderedListener(api);
this._updateDrawMode(seriesModel);
const coordinateSystemType = seriesModel.get('coordinateSystem');
if (coordinateSystemType === 'cartesian2d'
|| coordinateSystemType === 'polar'
) {
this._isLargeDraw
? this._renderLarge(seriesModel, ecModel, api)
: this._renderNormal(seriesModel, ecModel, api, payload);
}
else if (__DEV__) {
warn('Only cartesian2d and polar supported for bar.');
}
}
incrementalPrepareRender(seriesModel: BarSeriesModel): void {
this._clear();
this._updateDrawMode(seriesModel);
// incremental also need to clip, otherwise might be overlow.
// But must not set clip in each frame, otherwise all of the children will be marked redraw.
this._updateLargeClip(seriesModel);
}
incrementalRender(params: StageHandlerProgressParams, seriesModel: BarSeriesModel): void {
// Do not support progressive in normal mode.
this._incrementalRenderLarge(params, seriesModel);
}
private _updateDrawMode(seriesModel: BarSeriesModel): void {
const isLargeDraw = seriesModel.pipelineContext.large;
if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
this._isLargeDraw = isLargeDraw;
this._clear();
}
}
private _renderNormal(
seriesModel: BarSeriesModel,
ecModel: GlobalModel,
api: ExtensionAPI,
payload: Payload
): void {
const group = this.group;
const data = seriesModel.getData();
const oldData = this._data;
const coord = seriesModel.coordinateSystem;
const baseAxis = coord.getBaseAxis();
let isHorizontalOrRadial: boolean;
if (coord.type === 'cartesian2d') {
isHorizontalOrRadial = (baseAxis as Axis2D).isHorizontal();
}
else if (coord.type === 'polar') {
isHorizontalOrRadial = baseAxis.dim === 'angle';
}
const animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
const realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
if (realtimeSortCfg) {
this._enableRealtimeSort(realtimeSortCfg, data, api);
}
const needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
const coordSysClipArea = getClipArea(coord, data);
// If there is clipPath created in large mode. Remove it.
group.removeClipPath();
// We don't use clipPath in normal mode because we needs a perfect animation
// And don't want the label are clipped.
const roundCap = seriesModel.get('roundCap', true);
const drawBackground = seriesModel.get('showBackground', true);
const backgroundModel = seriesModel.getModel('backgroundStyle');
const barBorderRadius = backgroundModel.get('borderRadius') || 0;
const bgEls: BarView['_backgroundEls'] = [];
const oldBgEls = this._backgroundEls;
const isInitSort = payload && payload.isInitSort;
const isChangeOrder = payload && payload.type === 'changeAxisOrder';
function createBackground(dataIndex: number) {
const bgLayout = getLayout[coord.type](data, dataIndex);
const bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
bgEl.useStyle(backgroundModel.getItemStyle());
// Only cartesian2d support borderRadius.
if (coord.type === 'cartesian2d') {
(bgEl as Rect).setShape('r', barBorderRadius);
}
bgEls[dataIndex] = bgEl;
return bgEl;
};
data.diff(oldData)
.add(function (dataIndex) {
const itemModel = data.getItemModel<BarDataItemOption>(dataIndex);
const layout = getLayout[coord.type](data, dataIndex, itemModel);
if (drawBackground) {
createBackground(dataIndex);
}
// If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
if (!data.hasValue(dataIndex)) {
return;
}
let isClipped = false;
if (needsClip) {
// Clip will modify the layout params.
// And return a boolean to determine if the shape are fully clipped.
isClipped = clip[coord.type](coordSysClipArea, layout);
}
const el = elementCreator[coord.type](
seriesModel,
data,
dataIndex,
layout,
isHorizontalOrRadial,
animationModel,
baseAxis.model,
false,
roundCap
);
updateStyle(
el, data, dataIndex, itemModel, layout,
seriesModel, isHorizontalOrRadial, coord.type === 'polar'
);
if (isInitSort) {
(el as Rect).attr({ shape: layout });
}
else if (realtimeSortCfg) {
updateRealtimeAnimation(
realtimeSortCfg,
animationModel,
el as Rect,
layout as LayoutRect,
dataIndex,
isHorizontalOrRadial,
false,
false
);
}
else {
initProps(el, {shape: layout} as any, seriesModel, dataIndex);
}
data.setItemGraphicEl(dataIndex, el);
group.add(el);
el.ignore = isClipped;
})
.update(function (newIndex, oldIndex) {
const itemModel = data.getItemModel<BarDataItemOption>(newIndex);
const layout = getLayout[coord.type](data, newIndex, itemModel);
if (drawBackground) {
let bgEl: Rect | Sector;
if (oldBgEls.length === 0) {
bgEl = createBackground(oldIndex);
}
else {
bgEl = oldBgEls[oldIndex];
bgEl.useStyle(backgroundModel.getItemStyle());
// Only cartesian2d support borderRadius.
if (coord.type === 'cartesian2d') {
(bgEl as Rect).setShape('r', barBorderRadius);
}
bgEls[newIndex] = bgEl;
}
const bgLayout = getLayout[coord.type](data, newIndex);
const shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
updateProps(bgEl, { shape: shape }, animationModel, newIndex);
}
let el = oldData.getItemGraphicEl(oldIndex) as BarPossiblePath;
if (!data.hasValue(newIndex)) {
group.remove(el);
el = null;
return;
}
let isClipped = false;
if (needsClip) {
isClipped = clip[coord.type](coordSysClipArea, layout);
if (isClipped) {
group.remove(el);
}
}
if (!el) {
el = elementCreator[coord.type](
seriesModel,
data,
newIndex,
layout,
isHorizontalOrRadial,
animationModel,
baseAxis.model,
!!el,
roundCap
);
}
// Not change anything if only order changed.
// Especially not change label.
if (!isChangeOrder) {
updateStyle(
el, data, newIndex, itemModel, layout,
seriesModel, isHorizontalOrRadial, coord.type === 'polar'
);
}
if (isInitSort) {
(el as Rect).attr({ shape: layout });
}
else if (realtimeSortCfg) {
updateRealtimeAnimation(
realtimeSortCfg,
animationModel,
el as Rect,
layout as LayoutRect,
newIndex,
isHorizontalOrRadial,
true,
isChangeOrder
);
}
else {
updateProps(el, {
shape: layout
} as any, seriesModel, newIndex, null);
}
data.setItemGraphicEl(newIndex, el);
el.ignore = isClipped;
group.add(el);
})
.remove(function (dataIndex) {
const el = oldData.getItemGraphicEl(dataIndex) as Path;
el && removeElementWithFadeOut(el, seriesModel, dataIndex);
})
.execute();
const bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
bgGroup.removeAll();
for (let i = 0; i < bgEls.length; ++i) {
bgGroup.add(bgEls[i]);
}
group.add(bgGroup);
this._backgroundEls = bgEls;
this._data = data;
}
private _renderLarge(seriesModel: BarSeriesModel, ecModel: GlobalModel, api: ExtensionAPI): void {
this._clear();
createLarge(seriesModel, this.group);
this._updateLargeClip(seriesModel);
}
private _incrementalRenderLarge(params: StageHandlerProgressParams, seriesModel: BarSeriesModel): void {
this._removeBackground();
createLarge(seriesModel, this.group, true);
}
private _updateLargeClip(seriesModel: BarSeriesModel): void {
// Use clipPath in large mode.
const clipPath = seriesModel.get('clip', true)
? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
: null;
if (clipPath) {
this.group.setClipPath(clipPath);
}
else {
this.group.removeClipPath();
}
}
private _enableRealtimeSort(
realtimeSortCfg: RealtimeSortConfig,
data: ReturnType<BarSeriesModel['getData']>,
api: ExtensionAPI
): void {
// If no data in the first frame, wait for data to initSort
if (!data.count()) {
return;
}
const baseAxis = realtimeSortCfg.baseAxis;
if (this._isFirstFrame) {
this._dispatchInitSort(data, realtimeSortCfg, api);
this._isFirstFrame = false;
}
else {
const orderMapping = (idx: number) => {
const el = (data.getItemGraphicEl(idx) as Rect);
if (el) {
const shape = el.shape;
// If data is NaN, shape.xxx may be NaN, so use || 0 here in case
return (
baseAxis.isHorizontal()
// The result should be consistent with the initial sort by data value.
// Do not support the case that both positive and negative exist.
? Math.abs(shape.height)
: Math.abs(shape.width)
) || 0;
}
else {
return 0;
}
};
this._onRendered = () => {
this._updateSortWithinSameData(data, orderMapping, baseAxis, api);
};
api.getZr().on('rendered', this._onRendered);
}
}
private _dataSort(
data: List<BarSeriesModel, DefaultDataVisual>,
baseAxis: Axis2D,
orderMapping: OrderMapping
): OrdinalSortInfo {
type SortValueInfo = {
dataIndex: number,
mappedValue: number,
ordinalNumber: OrdinalNumber
};
const info: SortValueInfo[] = [];
data.each(data.mapDimension(baseAxis.dim), (ordinalNumber: OrdinalNumber, dataIdx: number) => {
let mappedValue = orderMapping(dataIdx);
mappedValue = mappedValue == null ? NaN : mappedValue;
info.push({
dataIndex: dataIdx,
mappedValue: mappedValue,
ordinalNumber: ordinalNumber
});
});
info.sort((a, b) => {
// If NaN, it will be treated as min val.
return b.mappedValue - a.mappedValue;
});
return {
ordinalNumbers: map(info, item => item.ordinalNumber)
};
}
private _isOrderChangedWithinSameData(
data: List<BarSeriesModel, DefaultDataVisual>,
orderMapping: OrderMapping,
baseAxis: Axis2D
): boolean {
const scale = baseAxis.scale as OrdinalScale;
const ordinalDataDim = data.mapDimension(baseAxis.dim);
let lastValue = Number.MAX_VALUE;
for (let tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
const rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
const value = rawIdx < 0
// If some tick have no bar, the tick will be treated as min.
? Number.MIN_VALUE
// PENDING: if dataZoom on baseAxis exits, is it a performance issue?
: orderMapping(data.indexOfRawIndex(rawIdx));
if (value > lastValue) {
return true;
}
lastValue = value;
}
return false;
}
/*
* Consider the case when A and B changed order, whose representing
* bars are both out of sight, we don't wish to trigger reorder action
* as long as the order in the view doesn't change.
*/
private _isOrderDifferentInView(
orderInfo: OrdinalSortInfo,
baseAxis: Axis2D
): boolean {
const scale = baseAxis.scale as OrdinalScale;
const extent = scale.getExtent();
let tickNum = Math.max(0, extent[0]);
const tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
for (;tickNum <= tickMax; ++tickNum) {
if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
return true;
}
}
}
private _updateSortWithinSameData(
data: List<BarSeriesModel, DefaultDataVisual>,
orderMapping: OrderMapping,
baseAxis: Axis2D,
api: ExtensionAPI
) {
if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
return;
}
const sortInfo = this._dataSort(data, baseAxis, orderMapping);
if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
this._removeOnRenderedListener(api);
api.dispatchAction({
type: 'changeAxisOrder',
componentType: baseAxis.dim + 'Axis',
axisId: baseAxis.index,
sortInfo: sortInfo
});
}
}
private _dispatchInitSort(
data: List<BarSeriesModel, DefaultDataVisual>,
realtimeSortCfg: RealtimeSortConfig,
api: ExtensionAPI
) {
const baseAxis = realtimeSortCfg.baseAxis;
const sortResult = this._dataSort(
data,
baseAxis,
dataIdx => data.get(
data.mapDimension(realtimeSortCfg.otherAxis.dim),
dataIdx
) as number
);
api.dispatchAction({
type: 'changeAxisOrder',
componentType: baseAxis.dim + 'Axis',
isInitSort: true,
axisId: baseAxis.index,
sortInfo: sortResult,
animation: {
// Update the axis label from the natural initial layout to
// sorted layout should has no animation.
duration: 0
}
});
}
remove(ecModel: GlobalModel, api: ExtensionAPI) {
this._clear(this._model);
this._removeOnRenderedListener(api);
}
dispose(ecModel: GlobalModel, api: ExtensionAPI) {
this._removeOnRenderedListener(api);
}
private _removeOnRenderedListener(api: ExtensionAPI) {
if (this._onRendered) {
api.getZr().off('rendered', this._onRendered);
this._onRendered = null;
}
}
private _clear(model?: SeriesModel): void {
const group = this.group;
const data = this._data;
if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
this._removeBackground();
this._backgroundEls = [];
data.eachItemGraphicEl(function (el: Path) {
removeElementWithFadeOut(el, model, getECData(el).dataIndex);
});
}
else {
group.removeAll();
}
this._data = null;
this._isFirstFrame = true;
}
private _removeBackground(): void {
this.group.remove(this._backgroundGroup);
this._backgroundGroup = null;
}
}
interface Clipper {
(coordSysBoundingRect: PolarCoordArea | CartesianCoordArea, layout: RectLayout | SectorLayout): boolean
}
const clip: {
[key in 'cartesian2d' | 'polar']: Clipper
} = {
cartesian2d(coordSysBoundingRect: CartesianCoordArea, layout: Rect['shape']) {
const signWidth = layout.width < 0 ? -1 : 1;
const signHeight = layout.height < 0 ? -1 : 1;
// Needs positive width and height
if (signWidth < 0) {
layout.x += layout.width;
layout.width = -layout.width;
}
if (signHeight < 0) {
layout.y += layout.height;
layout.height = -layout.height;
}
const coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
const coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
const x = mathMax(layout.x, coordSysBoundingRect.x);
const x2 = mathMin(layout.x + layout.width, coordSysX2);
const y = mathMax(layout.y, coordSysBoundingRect.y);
const y2 = mathMin(layout.y + layout.height, coordSysY2);
const xClipped = x2 < x;
const yClipped = y2 < y;
// When xClipped or yClipped, the element will be marked as `ignore`.
// But we should also place the element at the edge of the coord sys bounding rect.
// Beause if data changed and the bar show again, its transition animaiton
// will begin at this place.
layout.x = (xClipped && x > coordSysX2) ? x2 : x;
layout.y = (yClipped && y > coordSysY2) ? y2 : y;
layout.width = xClipped ? 0 : x2 - x;
layout.height = yClipped ? 0 : y2 - y;
// Reverse back
if (signWidth < 0) {
layout.x += layout.width;
layout.width = -layout.width;
}
if (signHeight < 0) {
layout.y += layout.height;
layout.height = -layout.height;
}
return xClipped || yClipped;
},
polar(coordSysClipArea: PolarCoordArea, layout: Sector['shape']) {
const signR = layout.r0 <= layout.r ? 1 : -1;
// Make sure r is larger than r0
if (signR < 0) {
const tmp = layout.r;
layout.r = layout.r0;
layout.r0 = tmp;
}
const r = mathMin(layout.r, coordSysClipArea.r);
const r0 = mathMax(layout.r0, coordSysClipArea.r0);
layout.r = r;
layout.r0 = r0;
const clipped = r - r0 < 0;
// Reverse back
if (signR < 0) {
const tmp = layout.r;
layout.r = layout.r0;
layout.r0 = tmp;
}
return clipped;
}
};
interface ElementCreator {
(
seriesModel: BarSeriesModel, data: List, newIndex: number,
layout: RectLayout | SectorLayout, isHorizontalOrRadial: boolean,
animationModel: BarSeriesModel,
axisModel: CartesianAxisModel | AngleAxisModel | RadiusAxisModel,
isUpdate: boolean,
roundCap?: boolean
): BarPossiblePath
}
const elementCreator: {
[key in 'polar' | 'cartesian2d']: ElementCreator
} = {
cartesian2d(
seriesModel, data, newIndex, layout: RectLayout, isHorizontal,
animationModel, axisModel, isUpdate, roundCap
) {
const rect = new Rect({
shape: extend({}, layout),
z2: 1
});
(rect as any).__dataIndex = newIndex;
rect.name = 'item';
if (animationModel) {
const rectShape = rect.shape;
const animateProperty = isHorizontal ? 'height' : 'width' as 'width' | 'height';
rectShape[animateProperty] = 0;
}
return rect;
},
polar(
seriesModel, data, newIndex, layout: SectorLayout, isRadial: boolean,
animationModel, axisModel, isUpdate, roundCap
) {
// Keep the same logic with bar in catesion: use end value to control
// direction. Notice that if clockwise is true (by default), the sector
// will always draw clockwisely, no matter whether endAngle is greater
// or less than startAngle.
const clockwise = layout.startAngle < layout.endAngle;
const ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
const sector = new ShapeClass({
shape: defaults({clockwise: clockwise}, layout),
z2: 1
});
sector.name = 'item';
// Animation
if (animationModel) {
const sectorShape = sector.shape;
const animateProperty = isRadial ? 'r' : 'endAngle' as 'r' | 'endAngle';
const animateTarget = {} as SectorShape;
sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
animateTarget[animateProperty] = layout[animateProperty];
(isUpdate ? updateProps : initProps)(sector, {
shape: animateTarget
// __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
}, animationModel);
}
return sector;
}
};
function shouldRealtimeSort(
seriesModel: BarSeriesModel,
coordSys: Cartesian2D | Polar
): RealtimeSortConfig {
const realtimeSortOption = seriesModel.get('realtimeSort', true);
const baseAxis = coordSys.getBaseAxis() as Axis2D;
if (__DEV__) {
if (realtimeSortOption) {
if (baseAxis.type !== 'category') {
warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
}
if (coordSys.type !== 'cartesian2d') {
warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
}
}
}
if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
return {
baseAxis: baseAxis as Axis2D,
otherAxis: coordSys.getOtherAxis(baseAxis)
};
}
}
function updateRealtimeAnimation(
realtimeSortCfg: RealtimeSortConfig,
seriesAnimationModel: BarSeriesModel,
el: Rect,
layout: LayoutRect,
newIndex: number,
isHorizontal: boolean,
isUpdate: boolean,
isChangeOrder: boolean
) {
let seriesTarget;
let axisTarget;
if (isHorizontal) {
axisTarget = {
x: layout.x,
width: layout.width
};
seriesTarget = {
y: layout.y,
height: layout.height
};
}
else {
axisTarget = {
y: layout.y,
height: layout.height
};
seriesTarget = {
x: layout.x,
width: layout.width
};
}
if (!isChangeOrder) {
// Keep the original growth animation if only axis order changed.
// Not start a new animation.
(isUpdate ? updateProps : initProps)(el, {
shape: seriesTarget
}, seriesAnimationModel, newIndex, null);
}
const axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
(isUpdate ? updateProps : initProps)(el, {
shape: axisTarget
}, axisAnimationModel, newIndex);
}
interface GetLayout {
(data: List, dataIndex: number, itemModel?: Model<BarDataItemOption>): RectLayout | SectorLayout
}
const getLayout: {
[key in 'cartesian2d' | 'polar']: GetLayout
} = {
// itemModel is only used to get borderWidth, which is not needed
// when calculating bar background layout.
cartesian2d(data, dataIndex, itemModel?): RectLayout {
const layout = data.getItemLayout(dataIndex) as RectLayout;
const fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0;
// fix layout with lineWidth
const signX = layout.width > 0 ? 1 : -1;
const signY = layout.height > 0 ? 1 : -1;
return {
x: layout.x + signX * fixedLineWidth / 2,
y: layout.y + signY * fixedLineWidth / 2,
width: layout.width - signX * fixedLineWidth,
height: layout.height - signY * fixedLineWidth
};
},
polar(data, dataIndex, itemModel?): SectorLayout {
const layout = data.getItemLayout(dataIndex);
return {
cx: layout.cx,
cy: layout.cy,
r0: layout.r0,
r: layout.r,
startAngle: layout.startAngle,
endAngle: layout.endAngle
} as SectorLayout;
}
};
function isZeroOnPolar(layout: SectorLayout) {
return layout.startAngle != null
&& layout.endAngle != null
&& layout.startAngle === layout.endAngle;
}
function updateStyle(
el: BarPossiblePath,
data: List, dataIndex: number,
itemModel: Model<BarDataItemOption>,
layout: RectLayout | SectorLayout,
seriesModel: BarSeriesModel,
isHorizontal: boolean,
isPolar: boolean
) {
const style = data.getItemVisual(dataIndex, 'style');
if (!isPolar) {
(el as Rect).setShape('r', itemModel.get(BAR_BORDER_RADIUS_QUERY) || 0);
}
el.useStyle(style);
const cursorStyle = itemModel.getShallow('cursor');
cursorStyle && (el as Path).attr('cursor', cursorStyle);
if (!isPolar) {
const labelPositionOutside = isHorizontal
? ((layout as RectLayout).height > 0 ? 'bottom' as const : 'top' as const)
: ((layout as RectLayout).width > 0 ? 'left' as const : 'right' as const);
const labelStatesModels = getLabelStatesModels(itemModel);
setLabelStyle(
el, labelStatesModels,
{
labelFetcher: seriesModel,
labelDataIndex: dataIndex,
defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
inheritColor: style.fill as ColorString,
defaultOpacity: style.opacity,
defaultOutsidePosition: labelPositionOutside
}
);
const label = el.getTextContent();
setLabelValueAnimation(
label,
labelStatesModels,
seriesModel.getRawValue(dataIndex) as ParsedValue,
(value: number) => getDefaultInterpolatedLabel(data, value)
);
}
const emphasisModel = itemModel.getModel(['emphasis']);
enableHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
setStatesStylesFromModel(el, itemModel);
if (isZeroOnPolar(layout as SectorLayout)) {
el.style.fill = 'none';
el.style.stroke = 'none';
each(el.states, (state) => {
if (state.style) {
state.style.fill = state.style.stroke = 'none';
}
});
}
}
// In case width or height are too small.
function getLineWidth(
itemModel: Model<BarDataItemOption>,
rawLayout: RectLayout
) {
const lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
// width or height may be NaN for empty data
const width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
const height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
return Math.min(lineWidth, width, height);
}
class LagePathShape {
points: ArrayLike<number>;
}
interface LargePathProps extends PathProps {
shape?: LagePathShape
}
class LargePath extends Path<LargePathProps> {
type = 'largeBar';
shape: LagePathShape;
;
__startPoint: number[];
__baseDimIdx: number;
__largeDataIndices: ArrayLike<number>;
__barWidth: number;
constructor(opts?: LargePathProps) {
super(opts);
}
getDefaultShape() {
return new LagePathShape();
}
buildPath(ctx: CanvasRenderingContext2D, shape: LagePathShape) {
// Drawing lines is more efficient than drawing
// a whole line or drawing rects.
const points = shape.points;
const startPoint = this.__startPoint;
const baseDimIdx = this.__baseDimIdx;
for (let i = 0; i < points.length; i += 2) {
startPoint[baseDimIdx] = points[i + baseDimIdx];
ctx.moveTo(startPoint[0], startPoint[1]);
ctx.lineTo(points[i], points[i + 1]);
}
}
}
function createLarge(
seriesModel: BarSeriesModel,
group: Group,
incremental?: boolean
) {
// TODO support polar
const data = seriesModel.getData();
const startPoint = [];
const baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
const largeDataIndices = data.getLayout('largeDataIndices');
const barWidth = data.getLayout('barWidth');
const backgroundModel = seriesModel.getModel('backgroundStyle');
const drawBackground = seriesModel.get('showBackground', true);
if (drawBackground) {
const points = data.getLayout('largeBackgroundPoints');
const backgroundStartPoint: number[] = [];
backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
const bgEl = new LargePath({
shape: {points: points},
incremental: !!incremental,
silent: true,
z2: 0
});
bgEl.__startPoint = backgroundStartPoint;
bgEl.__baseDimIdx = baseDimIdx;
bgEl.__largeDataIndices = largeDataIndices;
bgEl.__barWidth = barWidth;
setLargeBackgroundStyle(bgEl, backgroundModel, data);
group.add(bgEl);
}
const el = new LargePath({
shape: {points: data.getLayout('largePoints')},
incremental: !!incremental
});
el.__startPoint = startPoint;
el.__baseDimIdx = baseDimIdx;
el.__largeDataIndices = largeDataIndices;
el.__barWidth = barWidth;
group.add(el);
setLargeStyle(el, seriesModel, data);
// Enable tooltip and user mouse/touch event handlers.
getECData(el).seriesIndex = seriesModel.seriesIndex;
if (!seriesModel.get('silent')) {
el.on('mousedown', largePathUpdateDataIndex);
el.on('mousemove', largePathUpdateDataIndex);
}
}
// Use throttle to avoid frequently traverse to find dataIndex.
const largePathUpdateDataIndex = throttle(function (this: LargePath, event: ZRElementEvent) {
const largePath = this;
const dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
}, 30, false);
function largePathFindDataIndex(largePath: LargePath, x: number, y: number) {
const baseDimIdx = largePath.__baseDimIdx;
const valueDimIdx = 1 - baseDimIdx;
const points = largePath.shape.points;
const largeDataIndices = largePath.__largeDataIndices;
const barWidthHalf = Math.abs(largePath.__barWidth / 2);
const startValueVal = largePath.__startPoint[valueDimIdx];
_eventPos[0] = x;
_eventPos[1] = y;
const pointerBaseVal = _eventPos[baseDimIdx];
const pointerValueVal = _eventPos[1 - baseDimIdx];
const baseLowerBound = pointerBaseVal - barWidthHalf;
const baseUpperBound = pointerBaseVal + barWidthHalf;
for (let i = 0, len = points.length / 2; i < len; i++) {
const ii = i * 2;
const barBaseVal = points[ii + baseDimIdx];
const barValueVal = points[ii + valueDimIdx];
if (
barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
&& (
startValueVal <= barValueVal
? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
: (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
)
) {
return largeDataIndices[i];
}
}
return -1;
}
function setLargeStyle(
el: LargePath,
seriesModel: BarSeriesModel,
data: List
) {
const globalStyle = data.getVisual('style');
el.useStyle(extend({}, globalStyle));
// Use stroke instead of fill.
el.style.fill = null;
el.style.stroke = globalStyle.fill;
el.style.lineWidth = data.getLayout('barWidth');
}
function setLargeBackgroundStyle(
el: LargePath,
backgroundModel: Model<BarSeriesOption['backgroundStyle']>,
data: List
) {
const borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
const itemStyle = backgroundModel.getItemStyle();
el.useStyle(itemStyle);
el.style.fill = null;
el.style.stroke = borderColor;
el.style.lineWidth = data.getLayout('barWidth') as number;
}
function createBackgroundShape(
isHorizontalOrRadial: boolean,
layout: SectorLayout | RectLayout,
coord: CoordSysOfBar
): SectorShape | RectShape {
if (isCoordinateSystemType<Cartesian2D>(coord, 'cartesian2d')) {
const rectShape = layout as RectShape;
const coordLayout = coord.getArea();
return {
x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
} as RectShape;
}
else {
const coordLayout = coord.getArea();
const sectorShape = layout as SectorShape;
return {
cx: coordLayout.cx,
cy: coordLayout.cy,
r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
} as SectorShape;
}
}
function createBackgroundEl(
coord: CoordSysOfBar,
isHorizontalOrRadial: boolean,
layout: SectorLayout | RectLayout
): Rect | Sector {
const ElementClz = coord.type === 'polar' ? Sector : Rect;
return new ElementClz({
shape: createBackgroundShape(isHorizontalOrRadial, layout, coord) as any,
silent: true,
z2: 0
});
}
export default BarView;
| src/chart/bar/BarView.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.001616115216165781,
0.00021579601161647588,
0.00016324974421877414,
0.00017302359628956765,
0.00018587220984045416
] |
{
"id": 7,
"code_window": [
" containData(data: ScaleDataValue[]): boolean {\n",
" return this.getAxis('x').containData(data[0])\n",
" && this.getAxis('y').containData(data[1]);\n",
" }\n",
"\n",
" dataToPoint(data: ScaleDataValue[], reserved?: unknown, out?: number[]): number[] {\n",
" out = out || [];\n",
" const xVal = data[0];\n",
" const yVal = data[1];\n",
" // Fast path\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dataToPoint(data: ScaleDataValue[], clamp?: boolean, out?: number[]): number[] {\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 107
} | /*
* 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 BoundingRect from 'zrender/src/core/BoundingRect';
import Cartesian from './Cartesian';
import { ScaleDataValue } from '../../util/types';
import Axis2D from './Axis2D';
import { CoordinateSystem } from '../CoordinateSystem';
import GridModel from './GridModel';
import Grid from './Grid';
import Scale from '../../scale/Scale';
import { invert } from 'zrender/src/core/matrix';
import { applyTransform } from 'zrender/src/core/vector';
export const cartesian2DDimensions = ['x', 'y'];
function canCalculateAffineTransform(scale: Scale) {
return scale.type === 'interval' || scale.type === 'time';
}
class Cartesian2D extends Cartesian<Axis2D> implements CoordinateSystem {
readonly type = 'cartesian2d';
readonly dimensions = cartesian2DDimensions;
model: GridModel;
master: Grid;
private _transform: number[];
private _invTransform: number[];
/**
* Calculate an affine transform matrix if two axes are time or value.
* It's mainly for accelartion on the large time series data.
*/
calcAffineTransform() {
this._transform = this._invTransform = null;
const xAxisScale = this.getAxis('x').scale;
const yAxisScale = this.getAxis('y').scale;
if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
return;
}
const xScaleExtent = xAxisScale.getExtent();
const yScaleExtent = yAxisScale.getExtent();
const start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
const end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
const xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
const yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
if (!xScaleSpan || !yScaleSpan) {
return;
}
// Accelerate data to point calculation on the special large time series data.
const scaleX = (end[0] - start[0]) / xScaleSpan;
const scaleY = (end[1] - start[1]) / yScaleSpan;
const translateX = start[0] - xScaleExtent[0] * scaleX;
const translateY = start[1] - yScaleExtent[0] * scaleY;
const m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
this._invTransform = invert([], m);
}
/**
* Base axis will be used on stacking.
*/
getBaseAxis(): Axis2D {
return this.getAxesByScale('ordinal')[0]
|| this.getAxesByScale('time')[0]
|| this.getAxis('x');
}
containPoint(point: number[]): boolean {
const axisX = this.getAxis('x');
const axisY = this.getAxis('y');
return axisX.contain(axisX.toLocalCoord(point[0]))
&& axisY.contain(axisY.toLocalCoord(point[1]));
}
containData(data: ScaleDataValue[]): boolean {
return this.getAxis('x').containData(data[0])
&& this.getAxis('y').containData(data[1]);
}
dataToPoint(data: ScaleDataValue[], reserved?: unknown, out?: number[]): number[] {
out = out || [];
const xVal = data[0];
const yVal = data[1];
// Fast path
if (this._transform
// It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
&& xVal != null
&& isFinite(xVal as number)
&& yVal != null
&& isFinite(yVal as number)
) {
return applyTransform(out, data as number[], this._transform);
}
const xAxis = this.getAxis('x');
const yAxis = this.getAxis('y');
out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));
out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));
return out;
}
clampData(data: ScaleDataValue[], out?: number[]): number[] {
const xScale = this.getAxis('x').scale;
const yScale = this.getAxis('y').scale;
const xAxisExtent = xScale.getExtent();
const yAxisExtent = yScale.getExtent();
const x = xScale.parse(data[0]);
const y = yScale.parse(data[1]);
out = out || [];
out[0] = Math.min(
Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
Math.max(xAxisExtent[0], xAxisExtent[1])
);
out[1] = Math.min(
Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
Math.max(yAxisExtent[0], yAxisExtent[1])
);
return out;
}
pointToData(point: number[], out?: number[], reserved?: number[], clamp?: boolean): number[] {
out = out || [];
if (this._invTransform) {
return applyTransform(out, point, this._invTransform);
}
const xAxis = this.getAxis('x');
const yAxis = this.getAxis('y');
out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
return out;
}
getOtherAxis(axis: Axis2D): Axis2D {
return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
}
/**
* Get rect area of cartesian.
* Area will have a contain function to determine if a point is in the coordinate system.
*/
getArea(): Cartesian2DArea {
const xExtent = this.getAxis('x').getGlobalExtent();
const yExtent = this.getAxis('y').getGlobalExtent();
const x = Math.min(xExtent[0], xExtent[1]);
const y = Math.min(yExtent[0], yExtent[1]);
const width = Math.max(xExtent[0], xExtent[1]) - x;
const height = Math.max(yExtent[0], yExtent[1]) - y;
return new BoundingRect(x, y, width, height);
}
};
interface Cartesian2DArea extends BoundingRect {}
export default Cartesian2D;
| src/coord/cartesian/Cartesian2D.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.9981895089149475,
0.33608439564704895,
0.00016348465578630567,
0.000488479039631784,
0.4463135004043579
] |
{
"id": 7,
"code_window": [
" containData(data: ScaleDataValue[]): boolean {\n",
" return this.getAxis('x').containData(data[0])\n",
" && this.getAxis('y').containData(data[1]);\n",
" }\n",
"\n",
" dataToPoint(data: ScaleDataValue[], reserved?: unknown, out?: number[]): number[] {\n",
" out = out || [];\n",
" const xVal = data[0];\n",
" const yVal = data[1];\n",
" // Fast path\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dataToPoint(data: ScaleDataValue[], clamp?: boolean, out?: number[]): number[] {\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 107
} | /*
* 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.
*/
/**
* Parallel Coordinates
* <https://en.wikipedia.org/wiki/Parallel_coordinates>
*/
import * as zrUtil from 'zrender/src/core/util';
import * as matrix from 'zrender/src/core/matrix';
import * as layoutUtil from '../../util/layout';
import * as axisHelper from '../../coord/axisHelper';
import ParallelAxis from './ParallelAxis';
import * as graphic from '../../util/graphic';
import * as numberUtil from '../../util/number';
import sliderMove from '../../component/helper/sliderMove';
import ParallelModel, { ParallelLayoutDirection } from './ParallelModel';
import GlobalModel from '../../model/Global';
import ExtensionAPI from '../../core/ExtensionAPI';
import { Dictionary, DimensionName, ScaleDataValue } from '../../util/types';
import { CoordinateSystem, CoordinateSystemMaster } from '../CoordinateSystem';
import ParallelAxisModel, { ParallelActiveState } from './AxisModel';
import List from '../../data/List';
const each = zrUtil.each;
const mathMin = Math.min;
const mathMax = Math.max;
const mathFloor = Math.floor;
const mathCeil = Math.ceil;
const round = numberUtil.round;
const PI = Math.PI;
interface ParallelCoordinateSystemLayoutInfo {
layout: ParallelLayoutDirection;
pixelDimIndex: number;
layoutBase: number;
layoutLength: number;
axisBase: number;
axisLength: number;
axisExpandable: boolean;
axisExpandWidth: number;
axisCollapseWidth: number;
axisExpandWindow: number[];
axisCount: number;
winInnerIndices: number[];
axisExpandWindow0Pos: number;
}
export interface ParallelAxisLayoutInfo {
position: number[];
rotation: number;
transform: matrix.MatrixArray;
axisNameAvailableWidth: number;
axisLabelShow: boolean;
nameTruncateMaxWidth: number;
tickDirection: -1 | 1;
labelDirection: -1 | 1;
}
type SlidedAxisExpandBehavior = 'none' | 'slide' | 'jump';
class Parallel implements CoordinateSystemMaster, CoordinateSystem {
readonly type = 'parallel';
/**
* key: dimension
*/
private _axesMap = zrUtil.createHashMap<ParallelAxis>();
/**
* key: dimension
* value: {position: [], rotation, }
*/
private _axesLayout: Dictionary<ParallelAxisLayoutInfo> = {};
/**
* Always follow axis order.
*/
readonly dimensions: ParallelModel['dimensions'];
private _rect: graphic.BoundingRect;
private _model: ParallelModel;
// Inject
name: string;
model: ParallelModel;
constructor(parallelModel: ParallelModel, ecModel: GlobalModel, api: ExtensionAPI) {
this.dimensions = parallelModel.dimensions;
this._model = parallelModel;
this._init(parallelModel, ecModel, api);
}
private _init(parallelModel: ParallelModel, ecModel: GlobalModel, api: ExtensionAPI): void {
const dimensions = parallelModel.dimensions;
const parallelAxisIndex = parallelModel.parallelAxisIndex;
each(dimensions, function (dim, idx) {
const axisIndex = parallelAxisIndex[idx];
const axisModel = ecModel.getComponent('parallelAxis', axisIndex) as ParallelAxisModel;
const axis = this._axesMap.set(dim, new ParallelAxis(
dim,
axisHelper.createScaleByModel(axisModel),
[0, 0],
axisModel.get('type'),
axisIndex
));
const isCategory = axis.type === 'category';
axis.onBand = isCategory && axisModel.get('boundaryGap');
axis.inverse = axisModel.get('inverse');
// Injection
axisModel.axis = axis;
axis.model = axisModel;
axis.coordinateSystem = axisModel.coordinateSystem = this;
}, this);
}
/**
* Update axis scale after data processed
*/
update(ecModel: GlobalModel, api: ExtensionAPI): void {
this._updateAxesFromSeries(this._model, ecModel);
}
containPoint(point: number[]): boolean {
const layoutInfo = this._makeLayoutInfo();
const axisBase = layoutInfo.axisBase;
const layoutBase = layoutInfo.layoutBase;
const pixelDimIndex = layoutInfo.pixelDimIndex;
const pAxis = point[1 - pixelDimIndex];
const pLayout = point[pixelDimIndex];
return pAxis >= axisBase
&& pAxis <= axisBase + layoutInfo.axisLength
&& pLayout >= layoutBase
&& pLayout <= layoutBase + layoutInfo.layoutLength;
}
getModel(): ParallelModel {
return this._model;
}
/**
* Update properties from series
*/
private _updateAxesFromSeries(parallelModel: ParallelModel, ecModel: GlobalModel): void {
ecModel.eachSeries(function (seriesModel) {
if (!parallelModel.contains(seriesModel, ecModel)) {
return;
}
const data = seriesModel.getData();
each(this.dimensions, function (dim) {
const axis = this._axesMap.get(dim);
axis.scale.unionExtentFromData(data, data.mapDimension(dim));
axisHelper.niceScaleExtent(axis.scale, axis.model);
}, this);
}, this);
}
/**
* Resize the parallel coordinate system.
*/
resize(parallelModel: ParallelModel, api: ExtensionAPI): void {
this._rect = layoutUtil.getLayoutRect(
parallelModel.getBoxLayoutParams(),
{
width: api.getWidth(),
height: api.getHeight()
}
);
this._layoutAxes();
}
getRect(): graphic.BoundingRect {
return this._rect;
}
private _makeLayoutInfo(): ParallelCoordinateSystemLayoutInfo {
const parallelModel = this._model;
const rect = this._rect;
const xy = ['x', 'y'] as const;
const wh = ['width', 'height'] as const;
const layout = parallelModel.get('layout');
const pixelDimIndex = layout === 'horizontal' ? 0 : 1;
const layoutLength = rect[wh[pixelDimIndex]];
const layoutExtent = [0, layoutLength];
const axisCount = this.dimensions.length;
const axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
const axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
const axisExpandable = parallelModel.get('axisExpandable')
&& axisCount > 3
&& axisCount > axisExpandCount
&& axisExpandCount > 1
&& axisExpandWidth > 0
&& layoutLength > 0;
// `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
// for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
// where collapsed axes should be overlapped.
let axisExpandWindow = parallelModel.get('axisExpandWindow');
let winSize;
if (!axisExpandWindow) {
winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
const axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor(axisCount / 2);
axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
axisExpandWindow[1] = axisExpandWindow[0] + winSize;
}
else {
winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
axisExpandWindow[1] = axisExpandWindow[0] + winSize;
}
let axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
// Avoid axisCollapseWidth is too small.
axisCollapseWidth < 3 && (axisCollapseWidth = 0);
// Find the first and last indices > ewin[0] and < ewin[1].
const winInnerIndices = [
mathFloor(round(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
mathCeil(round(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
];
// Pos in ec coordinates.
const axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
return {
layout: layout,
pixelDimIndex: pixelDimIndex,
layoutBase: rect[xy[pixelDimIndex]],
layoutLength: layoutLength,
axisBase: rect[xy[1 - pixelDimIndex]],
axisLength: rect[wh[1 - pixelDimIndex]],
axisExpandable: axisExpandable,
axisExpandWidth: axisExpandWidth,
axisCollapseWidth: axisCollapseWidth,
axisExpandWindow: axisExpandWindow,
axisCount: axisCount,
winInnerIndices: winInnerIndices,
axisExpandWindow0Pos: axisExpandWindow0Pos
};
}
private _layoutAxes(): void {
const rect = this._rect;
const axes = this._axesMap;
const dimensions = this.dimensions;
const layoutInfo = this._makeLayoutInfo();
const layout = layoutInfo.layout;
axes.each(function (axis) {
const axisExtent = [0, layoutInfo.axisLength];
const idx = axis.inverse ? 1 : 0;
axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
});
each(dimensions, function (dim, idx) {
const posInfo = (layoutInfo.axisExpandable
? layoutAxisWithExpand : layoutAxisWithoutExpand
)(idx, layoutInfo);
const positionTable = {
horizontal: {
x: posInfo.position,
y: layoutInfo.axisLength
},
vertical: {
x: 0,
y: posInfo.position
}
};
const rotationTable = {
horizontal: PI / 2,
vertical: 0
};
const position = [
positionTable[layout].x + rect.x,
positionTable[layout].y + rect.y
];
const rotation = rotationTable[layout];
const transform = matrix.create();
matrix.rotate(transform, transform, rotation);
matrix.translate(transform, transform, position);
// TODO
// tick layout info
// TODO
// update dimensions info based on axis order.
this._axesLayout[dim] = {
position: position,
rotation: rotation,
transform: transform,
axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
axisLabelShow: posInfo.axisLabelShow,
nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
tickDirection: 1,
labelDirection: 1
};
}, this);
}
/**
* Get axis by dim.
*/
getAxis(dim: DimensionName): ParallelAxis {
return this._axesMap.get(dim);
}
/**
* Convert a dim value of a single item of series data to Point.
*/
dataToPoint(value: ScaleDataValue, dim: DimensionName): number[] {
return this.axisCoordToPoint(
this._axesMap.get(dim).dataToCoord(value),
dim
);
}
/**
* Travel data for one time, get activeState of each data item.
* @param start the start dataIndex that travel from.
* @param end the next dataIndex of the last dataIndex will be travel.
*/
eachActiveState(
data: List,
callback: (activeState: ParallelActiveState, dataIndex: number) => void,
start?: number,
end?: number
): void {
start == null && (start = 0);
end == null && (end = data.count());
const axesMap = this._axesMap;
const dimensions = this.dimensions;
const dataDimensions = [] as DimensionName[];
const axisModels = [] as ParallelAxisModel[];
zrUtil.each(dimensions, function (axisDim) {
dataDimensions.push(data.mapDimension(axisDim));
axisModels.push(axesMap.get(axisDim).model);
});
const hasActiveSet = this.hasAxisBrushed();
for (let dataIndex = start; dataIndex < end; dataIndex++) {
let activeState: ParallelActiveState;
if (!hasActiveSet) {
activeState = 'normal';
}
else {
activeState = 'active';
const values = data.getValues(dataDimensions, dataIndex);
for (let j = 0, lenj = dimensions.length; j < lenj; j++) {
const state = axisModels[j].getActiveState(values[j]);
if (state === 'inactive') {
activeState = 'inactive';
break;
}
}
}
callback(activeState, dataIndex);
}
}
/**
* Whether has any activeSet.
*/
hasAxisBrushed(): boolean {
const dimensions = this.dimensions;
const axesMap = this._axesMap;
let hasActiveSet = false;
for (let j = 0, lenj = dimensions.length; j < lenj; j++) {
if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
hasActiveSet = true;
}
}
return hasActiveSet;
}
/**
* Convert coords of each axis to Point.
* Return point. For example: [10, 20]
*/
axisCoordToPoint(coord: number, dim: DimensionName): number[] {
const axisLayout = this._axesLayout[dim];
return graphic.applyTransform([coord, 0], axisLayout.transform);
}
/**
* Get axis layout.
*/
getAxisLayout(dim: DimensionName): ParallelAxisLayoutInfo {
return zrUtil.clone(this._axesLayout[dim]);
}
/**
* @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
*/
getSlidedAxisExpandWindow(point: number[]): {
axisExpandWindow: number[],
behavior: SlidedAxisExpandBehavior
} {
const layoutInfo = this._makeLayoutInfo();
const pixelDimIndex = layoutInfo.pixelDimIndex;
let axisExpandWindow = layoutInfo.axisExpandWindow.slice();
const winSize = axisExpandWindow[1] - axisExpandWindow[0];
const extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
// Out of the area of coordinate system.
if (!this.containPoint(point)) {
return {behavior: 'none', axisExpandWindow: axisExpandWindow};
}
// Conver the point from global to expand coordinates.
const pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
// For dragging operation convenience, the window should not be
// slided when mouse is the center area of the window.
let delta;
let behavior: SlidedAxisExpandBehavior = 'slide';
const axisCollapseWidth = layoutInfo.axisCollapseWidth;
const triggerArea = this._model.get('axisExpandSlideTriggerArea');
// But consider touch device, jump is necessary.
const useJump = triggerArea[0] != null;
if (axisCollapseWidth) {
if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
behavior = 'jump';
delta = pointCoord - winSize * triggerArea[2];
}
else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
behavior = 'jump';
delta = pointCoord - winSize * (1 - triggerArea[2]);
}
else {
(delta = pointCoord - winSize * triggerArea[1]) >= 0
&& (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
&& (delta = 0);
}
delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
delta
? sliderMove(delta, axisExpandWindow, extent, 'all')
// Avoid nonsense triger on mousemove.
: (behavior = 'none');
}
// When screen is too narrow, make it visible and slidable, although it is hard to interact.
else {
const winSize2 = axisExpandWindow[1] - axisExpandWindow[0];
const pos = extent[1] * pointCoord / winSize2;
axisExpandWindow = [mathMax(0, pos - winSize2 / 2)];
axisExpandWindow[1] = mathMin(extent[1], axisExpandWindow[0] + winSize2);
axisExpandWindow[0] = axisExpandWindow[1] - winSize2;
}
return {
axisExpandWindow: axisExpandWindow,
behavior: behavior
};
}
// TODO
// convertToPixel
// convertFromPixel
// Note:
// (1) Consider Parallel, the return type of `convertToPixel` could be number[][] (Point[]).
// (2) In parallel coord sys, how to make `convertFromPixel` make sense?
// Perhaps convert a point based on "a rensent most axis" is more meaningful rather than based on all axes?
}
function restrict(len: number, extent: number[]): number {
return mathMin(mathMax(len, extent[0]), extent[1]);
}
interface ParallelAxisLayoutPositionInfo {
position: number;
axisNameAvailableWidth: number;
axisLabelShow: boolean;
nameTruncateMaxWidth?: number;
}
function layoutAxisWithoutExpand(
axisIndex: number,
layoutInfo: ParallelCoordinateSystemLayoutInfo
): ParallelAxisLayoutPositionInfo {
const step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
return {
position: step * axisIndex,
axisNameAvailableWidth: step,
axisLabelShow: true
};
}
function layoutAxisWithExpand(
axisIndex: number,
layoutInfo: ParallelCoordinateSystemLayoutInfo
): ParallelAxisLayoutPositionInfo {
const layoutLength = layoutInfo.layoutLength;
const axisExpandWidth = layoutInfo.axisExpandWidth;
const axisCount = layoutInfo.axisCount;
const axisCollapseWidth = layoutInfo.axisCollapseWidth;
const winInnerIndices = layoutInfo.winInnerIndices;
let position;
let axisNameAvailableWidth = axisCollapseWidth;
let axisLabelShow = false;
let nameTruncateMaxWidth;
if (axisIndex < winInnerIndices[0]) {
position = axisIndex * axisCollapseWidth;
nameTruncateMaxWidth = axisCollapseWidth;
}
else if (axisIndex <= winInnerIndices[1]) {
position = layoutInfo.axisExpandWindow0Pos
+ axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
axisNameAvailableWidth = axisExpandWidth;
axisLabelShow = true;
}
else {
position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
nameTruncateMaxWidth = axisCollapseWidth;
}
return {
position: position,
axisNameAvailableWidth: axisNameAvailableWidth,
axisLabelShow: axisLabelShow,
nameTruncateMaxWidth: nameTruncateMaxWidth
};
}
export default Parallel;
| src/coord/parallel/Parallel.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0035950196906924248,
0.00031461461912840605,
0.00016488847904838622,
0.00017216717242263258,
0.00058776541845873
] |
{
"id": 7,
"code_window": [
" containData(data: ScaleDataValue[]): boolean {\n",
" return this.getAxis('x').containData(data[0])\n",
" && this.getAxis('y').containData(data[1]);\n",
" }\n",
"\n",
" dataToPoint(data: ScaleDataValue[], reserved?: unknown, out?: number[]): number[] {\n",
" out = out || [];\n",
" const xVal = data[0];\n",
" const yVal = data[1];\n",
" // Fast path\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dataToPoint(data: ScaleDataValue[], clamp?: boolean, out?: number[]): number[] {\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 107
} | /**
* Canteen v1.0.4
* August 19th, 2015
*
* Copyright 2015 Platfora, Inc.
*
* 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.
*/
;(function() {
// ================================ Constants ================================
var CONTEXT_2D_ATTRIBUTES = [
'fillStyle',
'font',
'globalAlpha',
'globalCompositeOperation',
'lineCap',
'lineDashOffset',
'lineJoin',
'lineWidth',
'miterLimit',
'shadowBlur',
'shadowColor',
'shadowOffsetX',
'shadowOffsetY',
'strokeStyle',
'textAlign',
'textBaseline'
];
// ================================ Utils ================================
function each(arr, func) {
var len = arr.length,
n;
for (n=0; n<len; n++) {
func(arr[n], n);
}
}
function round(val, decimalPoints) {
var power = Math.pow(10, decimalPoints);
return Math.round(val * power) / power;
}
function roundArr(arr, decimalPoints) {
var len = arr.length,
ret = [],
n;
for (n=0; n<len; n++) {
if (isNumber(arr[n])) {
ret.push(round(arr[n], decimalPoints));
}
else {
ret.push(arr[n]);
}
}
return ret;
}
function isFunction(func) {
return func && {}.toString.call(func) === '[object Function]';
}
function isNumber(val) {
return typeof val === 'number';
}
// ================================ Canteen Class ================================
/**
* Canteen Constructor
* @constructor
*/
var Canteen = function(context) {
var that = this;
this._stack = [];
this.context = context;
// add observable attributes
each(CONTEXT_2D_ATTRIBUTES, function(key, n) {
Object.defineProperty(that, key, {
get: function() {
return that.context[key];
},
set: function(val) {
that._pushAttr(key, val);
that.context[key] = val;
}
});
});
};
// Canteen methods
Canteen.prototype = {
/**
* get a stack of operations
* @method stack
* @param {Object} config
* @param {String} [config.loose=false] - strict mode returns method calls with arguments and property names
* with values. loose mode only returns method calls and property names
* @param {Number} [config.decimalPoints=3] - number of decimal points to round numeric values to. The default is
* 3, i.e. 1.23456 will round to 1.234
* @returns {Array}
* @public
*/
stack: function(config) {
var config = config || {},
loose = config.loose,
decimalPoints = config.decimalPoints === undefined ? 3 : config.decimalPoints,
ret = [];
if (loose) {
each(this._stack, function(el, n) {
ret.push(el.method || el.attr);
});
}
else {
each(this._stack, function(el, n) {
// if method instruction
if (el.method) {
ret.push({
method: el.method,
arguments: roundArr(el.arguments, decimalPoints)
});
}
// if attr
else if (el.attr) {
ret.push({
attr: el.attr,
val: isNumber(el.val) ? round(el.val, decimalPoints) : el.val
});
}
});
}
return ret;
},
/**
* serialize a stack into a string
* @method json
* @param {Object} config
* @param {String} [config.loose=false] - strict mode returns method calls with arguments and property names
* with values. loose mode only returns method calls and property names
* @param {Number} [config.decimalPoints=3] - number of decimal points to round numeric values to. The default is
* 3, i.e. 1.23456 will round to 1.234
* @returns {String}
* @public
*/
json: function(config) {
return JSON.stringify(this.stack(config));
},
/**
* convert a stack into a small hash string for easy comparisons
* @method hash
* @param {Object} config
* @param {String} [config.loose=false] - strict mode returns method calls with arguments and property names
* with values. loose mode only returns method calls and property names
* @param {Number} [config.decimalPoints=3] - number of decimal points to round numeric values to. The default is
* 3, i.e. 1.23456 will round to 1.234
* @public
* @returns {String}
*/
hash: function(config) {
return Canteen.md5(this.json(config));
},
/**
* clear the stack
* @method clear
* @public
*/
clear: function() {
this._stack = [];
},
/**
* push instruction method onto the stack
* @method _pushMethod
* @param {String} method
* @param {arguments} args
* @private
*/
_pushMethod: function(method, args) {
this._stack.push({
method: method,
arguments: Array.prototype.slice.call(args, 0)
});
this._slice();
},
/**
* push instruction attribute onto the stack
* @method _pushAttr
* @param {String} attr
* @param {*} val
* @private
*/
_pushAttr: function(attr, val) {
this._stack.push({
attr: attr,
val: val
});
this._slice();
},
/**
* slice the stack if needed. This means making sure that it doesn't exceed
* the STACK_SIZE. if it does, then shorten the stack starting from the beginning
* @method _slice
* @private
*/
_slice: function() {
var stack = this._stack,
len = stack.length,
exceded = len - Canteen.globals.STACK_SIZE;
if (exceded > 0) {
this._stack = stack.slice(exceded);
}
}
};
// generate observable methods and add them to the Canteen prototype
(function(){
var proto = CanvasRenderingContext2D.prototype,
key, val, desc;
function addMethod(key, val) {
Canteen.prototype[key] = function() {
this._pushMethod(key, arguments);
return this.context[key].apply(this.context, arguments);
};
}
for (key in proto) {
desc = Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, key);
val = (desc && desc.value ? proto[key] : null);
if (isFunction(val)) {
addMethod(key, val);
}
}
})();
// ================================ Global Config ================================
/**
* global config. You can directly change these values in order to configure Canteen
* @static
* @example
* // change stack size to 3000
* Canteen.globals.STACK_SIZE = 3000;
*/
Canteen.globals = {
STACK_SIZE: 10000
};
// ================================ Initialization ================================
// override the canvas context getContext method in order to automatically instantiate
// a Canteen instance and wrap the native context object
(function(){
var origGetContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.getContext = function() {
var context = origGetContext.apply(this, arguments);
// if the context already has a canteen instance, then return it
if (context.canteen) {
return context.canteen
}
// if the context does not have a canteen instance, then instantiate one
// and return it
else {
context.canteen = new Canteen(context);
return context.canteen;
}
}
})();
// make the Canteen namespace global so that developers can configure
// it via Canteen.globals, or override methods if desired
window.Canteen = Canteen;
})();
;/*
* JavaScript MD5 1.0.1
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*jslint bitwise: true */
/*global unescape, define */
(function ($) {
'use strict';
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function binl_md5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (len % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var i, olda, oldb, oldc, oldd,
a = 1732584193,
b = -271733879,
c = -1732584194,
d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5_ff(a, b, c, d, x[i], 7, -680876936);
d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i], 20, -373897302);
a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5_hh(d, a, b, c, x[i], 11, -358537222);
c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i], 6, -198630844);
d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return [a, b, c, d];
}
/*
* Convert an array of little-endian words to a string
*/
function binl2rstr(input) {
var i,
output = '';
for (i = 0; i < input.length * 32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
}
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binl(input) {
var i,
output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
for (i = 0; i < input.length * 8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
}
return output;
}
/*
* Calculate the MD5 of a raw string
*/
function rstr_md5(s) {
return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function rstr_hmac_md5(key, data) {
var i,
bkey = rstr2binl(key),
ipad = [],
opad = [],
hash;
ipad[15] = opad[15] = undefined;
if (bkey.length > 16) {
bkey = binl_md5(bkey, key.length * 8);
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex(input) {
var hex_tab = '0123456789abcdef',
output = '',
x,
i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F) +
hex_tab.charAt(x & 0x0F);
}
return output;
}
/*
* Encode a string as utf-8
*/
function str2rstr_utf8(input) {
return unescape(encodeURIComponent(input));
}
/*
* Take string arguments and return either raw or hex encoded strings
*/
function raw_md5(s) {
return rstr_md5(str2rstr_utf8(s));
}
function hex_md5(s) {
return rstr2hex(raw_md5(s));
}
function raw_hmac_md5(k, d) {
return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d));
}
function hex_hmac_md5(k, d) {
return rstr2hex(raw_hmac_md5(k, d));
}
function md5(string, key, raw) {
if (!key) {
if (!raw) {
return hex_md5(string);
}
return raw_md5(string);
}
if (!raw) {
return hex_hmac_md5(key, string);
}
return raw_hmac_md5(key, string);
}
if (typeof define === 'function' && define.amd) {
define(function () {
return md5;
});
} else {
$.md5 = md5;
}
}(Canteen));
| test/lib/canteen.js | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00019261315173935145,
0.00017275841673836112,
0.00016525411047041416,
0.00017307976668234915,
0.00000397669964513625
] |
{
"id": 7,
"code_window": [
" containData(data: ScaleDataValue[]): boolean {\n",
" return this.getAxis('x').containData(data[0])\n",
" && this.getAxis('y').containData(data[1]);\n",
" }\n",
"\n",
" dataToPoint(data: ScaleDataValue[], reserved?: unknown, out?: number[]): number[] {\n",
" out = out || [];\n",
" const xVal = data[0];\n",
" const yVal = data[1];\n",
" // Fast path\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" dataToPoint(data: ScaleDataValue[], clamp?: boolean, out?: number[]): number[] {\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 107
} |
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<meta name="viewport" content="user-scalable=no,width=device-width,height=device-height">
</head>
<body>
<style>
html, body, #main {
width: 100%;
height: 100%;
margin: 0;
}
</style>
markArea should be displayed.
<div id="main"></div>
<script>
require([
'echarts'
// 'echarts/chart/line',
// 'echarts/component/legend',
// 'echarts/component/grid',
// 'echarts/component/tooltip',
// 'echarts/component/title',
// 'echarts/component/dataZoom'
], function (echarts) {
var chart = echarts.init(document.getElementById('main'), null, {
});
var sampling = 'none';
chart.setOption({
title : {
text: '雨量流量关系图',
subtext: '数据来自西安兰特水电测控技术有限公司',
x: 'center'
},
tooltip : {
trigger: 'axis',
formatter: function(params) {
return params[0].name + '<br/>'
+ (
params[0]
? params[0].seriesName + ' : ' + params[0].value + ' (m^3/s)<br/>'
: ''
)
+ (
params[1]
? params[1].seriesName + ' : ' + -params[1].value + ' (mm)'
: ''
);
},
axisPointer: {
animation: false
}
},
legend: {
data:['流量','降雨量'],
x: 'left'
},
toolbox: {
show : true,
feature : {
mark : {show: true},
dataView : {show: true, readOnly: false},
magicType : {show: true, type: ['line', 'bar']},
restore : {show: true},
saveAsImage : {show: true}
}
},
dataZoom: [
{
show: true,
realtime: true,
start: 80,
end: 100
},
{
type: 'inside',
show: true,
realtime: true,
start: 80,
end: 100
}
],
xAxis : [
{
type : 'category',
boundaryGap : false,
axisLine: {onZero: false},
data : [
'2009/6/12 2:00', '2009/6/12 3:00', '2009/6/12 4:00', '2009/6/12 5:00', '2009/6/12 6:00', '2009/6/12 7:00', '2009/6/12 8:00', '2009/6/12 9:00', '2009/6/12 10:00', '2009/6/12 11:00', '2009/6/12 12:00', '2009/6/12 13:00', '2009/6/12 14:00', '2009/6/12 15:00', '2009/6/12 16:00', '2009/6/12 17:00', '2009/6/12 18:00', '2009/6/12 19:00', '2009/6/12 20:00', '2009/6/12 21:00', '2009/6/12 22:00', '2009/6/12 23:00',
'2009/6/13 0:00', '2009/6/13 1:00', '2009/6/13 2:00', '2009/6/13 3:00', '2009/6/13 4:00', '2009/6/13 5:00', '2009/6/13 6:00', '2009/6/13 7:00', '2009/6/13 8:00', '2009/6/13 9:00', '2009/6/13 10:00', '2009/6/13 11:00', '2009/6/13 12:00', '2009/6/13 13:00', '2009/6/13 14:00', '2009/6/13 15:00', '2009/6/13 16:00', '2009/6/13 17:00', '2009/6/13 18:00', '2009/6/13 19:00', '2009/6/13 20:00', '2009/6/13 21:00', '2009/6/13 22:00', '2009/6/13 23:00',
'2009/6/14 0:00', '2009/6/14 1:00', '2009/6/14 2:00', '2009/6/14 3:00', '2009/6/14 4:00', '2009/6/14 5:00', '2009/6/14 6:00', '2009/6/14 7:00', '2009/6/14 8:00', '2009/6/14 9:00', '2009/6/14 10:00', '2009/6/14 11:00', '2009/6/14 12:00', '2009/6/14 13:00', '2009/6/14 14:00', '2009/6/14 15:00', '2009/6/14 16:00', '2009/6/14 17:00', '2009/6/14 18:00', '2009/6/14 19:00', '2009/6/14 20:00', '2009/6/14 21:00', '2009/6/14 22:00', '2009/6/14 23:00',
'2009/6/15 0:00', '2009/6/15 1:00', '2009/6/15 2:00', '2009/6/15 3:00', '2009/6/15 4:00', '2009/6/15 5:00', '2009/6/15 6:00', '2009/6/15 7:00', '2009/6/15 8:00', '2009/6/15 9:00', '2009/6/15 10:00', '2009/6/15 11:00', '2009/6/15 12:00', '2009/6/15 13:00', '2009/6/15 14:00', '2009/6/15 15:00', '2009/6/15 16:00', '2009/6/15 17:00', '2009/6/15 18:00', '2009/6/15 19:00', '2009/6/15 20:00', '2009/6/15 21:00', '2009/6/15 22:00', '2009/6/15 23:00',
'2009/6/15 0:00', '2009/6/16 1:00', '2009/6/16 2:00', '2009/6/16 3:00', '2009/6/16 4:00', '2009/6/16 5:00', '2009/6/16 6:00', '2009/6/16 7:00', '2009/6/16 8:00', '2009/6/16 9:00', '2009/6/16 10:00', '2009/6/16 11:00', '2009/6/16 12:00', '2009/6/16 13:00', '2009/6/16 14:00', '2009/6/16 15:00', '2009/6/16 16:00', '2009/6/16 17:00', '2009/6/16 18:00', '2009/6/16 19:00', '2009/6/16 20:00', '2009/6/16 21:00', '2009/6/16 22:00', '2009/6/16 23:00',
'2009/6/15 0:00', '2009/6/17 1:00', '2009/6/17 2:00', '2009/6/17 3:00', '2009/6/17 4:00', '2009/6/17 5:00', '2009/6/17 6:00', '2009/6/17 7:00', '2009/6/17 8:00', '2009/6/17 9:00', '2009/6/17 10:00', '2009/6/17 11:00', '2009/6/17 12:00', '2009/6/17 13:00', '2009/6/17 14:00', '2009/6/17 15:00', '2009/6/17 16:00', '2009/6/17 17:00', '2009/6/17 18:00', '2009/6/17 19:00', '2009/6/17 20:00', '2009/6/17 21:00', '2009/6/17 22:00', '2009/6/17 23:00',
'2009/6/18 0:00', '2009/6/18 1:00', '2009/6/18 2:00', '2009/6/18 3:00', '2009/6/18 4:00', '2009/6/18 5:00', '2009/6/18 6:00', '2009/6/18 7:00', '2009/6/18 8:00', '2009/6/18 9:00', '2009/6/18 10:00', '2009/6/18 11:00', '2009/6/18 12:00', '2009/6/18 13:00', '2009/6/18 14:00', '2009/6/18 15:00', '2009/6/18 16:00', '2009/6/18 17:00', '2009/6/18 18:00', '2009/6/18 19:00', '2009/6/18 20:00', '2009/6/18 21:00', '2009/6/18 22:00', '2009/6/18 23:00',
'2009/6/15 0:00', '2009/6/19 1:00', '2009/6/19 2:00', '2009/6/19 3:00', '2009/6/19 4:00', '2009/6/19 5:00', '2009/6/19 6:00', '2009/6/19 7:00', '2009/6/19 8:00', '2009/6/19 9:00', '2009/6/19 10:00', '2009/6/19 11:00', '2009/6/19 12:00', '2009/6/19 13:00', '2009/6/19 14:00', '2009/6/19 15:00', '2009/6/19 16:00', '2009/6/19 17:00', '2009/6/19 18:00', '2009/6/19 19:00', '2009/6/19 20:00', '2009/6/19 21:00', '2009/6/19 22:00', '2009/6/19 23:00',
'2009/6/20 0:00', '2009/6/20 1:00', '2009/6/20 2:00', '2009/6/20 3:00', '2009/6/20 4:00', '2009/6/20 5:00', '2009/6/20 6:00', '2009/6/20 7:00', '2009/6/20 8:00', '2009/6/20 9:00', '2009/6/20 10:00', '2009/6/20 11:00', '2009/6/20 12:00', '2009/6/20 13:00', '2009/6/20 14:00', '2009/6/20 15:00', '2009/6/20 16:00', '2009/6/20 17:00', '2009/6/20 18:00', '2009/6/20 19:00', '2009/6/20 20:00', '2009/6/20 21:00', '2009/6/20 22:00', '2009/6/20 23:00',
'2009/6/21 0:00', '2009/6/21 1:00', '2009/6/21 2:00', '2009/6/21 3:00', '2009/6/21 4:00', '2009/6/21 5:00', '2009/6/21 6:00', '2009/6/21 7:00', '2009/6/21 8:00', '2009/6/21 9:00', '2009/6/21 10:00', '2009/6/21 11:00', '2009/6/21 12:00', '2009/6/21 13:00', '2009/6/21 14:00', '2009/6/21 15:00', '2009/6/21 16:00', '2009/6/21 17:00', '2009/6/21 18:00', '2009/6/21 19:00', '2009/6/21 20:00', '2009/6/21 21:00', '2009/6/21 22:00', '2009/6/21 23:00',
'2009/6/22 0:00', '2009/6/22 1:00', '2009/6/22 2:00', '2009/6/22 3:00', '2009/6/22 4:00', '2009/6/22 5:00', '2009/6/22 6:00', '2009/6/22 7:00', '2009/6/22 8:00', '2009/6/22 9:00', '2009/6/22 10:00', '2009/6/22 11:00', '2009/6/22 12:00', '2009/6/22 13:00', '2009/6/22 14:00', '2009/6/22 15:00', '2009/6/22 16:00', '2009/6/22 17:00', '2009/6/22 18:00', '2009/6/22 19:00', '2009/6/22 20:00', '2009/6/22 21:00', '2009/6/22 22:00', '2009/6/22 23:00',
'2009/6/23 0:00', '2009/6/23 1:00', '2009/6/23 2:00', '2009/6/23 3:00', '2009/6/23 4:00', '2009/6/23 5:00', '2009/6/23 6:00', '2009/6/23 7:00', '2009/6/23 8:00', '2009/6/23 9:00', '2009/6/23 10:00', '2009/6/23 11:00', '2009/6/23 12:00', '2009/6/23 13:00', '2009/6/23 14:00', '2009/6/23 15:00', '2009/6/23 16:00', '2009/6/23 17:00', '2009/6/23 18:00', '2009/6/23 19:00', '2009/6/23 20:00', '2009/6/23 21:00', '2009/6/23 22:00', '2009/6/23 23:00',
'2009/6/24 0:00', '2009/6/24 1:00', '2009/6/24 2:00', '2009/6/24 3:00', '2009/6/24 4:00', '2009/6/24 5:00', '2009/6/24 6:00', '2009/6/24 7:00', '2009/6/24 8:00', '2009/6/24 9:00', '2009/6/24 10:00', '2009/6/24 11:00', '2009/6/24 12:00', '2009/6/24 13:00', '2009/6/24 14:00', '2009/6/24 15:00', '2009/6/24 16:00', '2009/6/24 17:00', '2009/6/24 18:00', '2009/6/24 19:00', '2009/6/24 20:00', '2009/6/24 21:00', '2009/6/24 22:00', '2009/6/24 23:00',
'2009/6/25 0:00', '2009/6/25 1:00', '2009/6/25 2:00', '2009/6/25 3:00', '2009/6/25 4:00', '2009/6/25 5:00', '2009/6/25 6:00', '2009/6/25 7:00', '2009/6/25 8:00', '2009/6/25 9:00', '2009/6/25 10:00', '2009/6/25 11:00', '2009/6/25 12:00', '2009/6/25 13:00', '2009/6/25 14:00', '2009/6/25 15:00', '2009/6/25 16:00', '2009/6/25 17:00', '2009/6/25 18:00', '2009/6/25 19:00', '2009/6/25 20:00', '2009/6/25 21:00', '2009/6/25 22:00', '2009/6/25 23:00',
'2009/6/26 0:00', '2009/6/26 1:00', '2009/6/26 2:00', '2009/6/26 3:00', '2009/6/26 4:00', '2009/6/26 5:00', '2009/6/26 6:00', '2009/6/26 7:00', '2009/6/26 8:00', '2009/6/26 9:00', '2009/6/26 10:00', '2009/6/26 11:00', '2009/6/26 12:00', '2009/6/26 13:00', '2009/6/26 14:00', '2009/6/26 15:00', '2009/6/26 16:00', '2009/6/26 17:00', '2009/6/26 18:00', '2009/6/26 19:00', '2009/6/26 20:00', '2009/6/26 21:00', '2009/6/26 22:00', '2009/6/26 23:00',
'2009/6/27 0:00', '2009/6/27 1:00', '2009/6/27 2:00', '2009/6/27 3:00', '2009/6/27 4:00', '2009/6/27 5:00', '2009/6/27 6:00', '2009/6/27 7:00', '2009/6/27 8:00', '2009/6/27 9:00', '2009/6/27 10:00', '2009/6/27 11:00', '2009/6/27 12:00', '2009/6/27 13:00', '2009/6/27 14:00', '2009/6/27 15:00', '2009/6/27 16:00', '2009/6/27 17:00', '2009/6/27 18:00', '2009/6/27 19:00', '2009/6/27 20:00', '2009/6/27 21:00', '2009/6/27 22:00', '2009/6/27 23:00',
'2009/6/28 0:00', '2009/6/28 1:00', '2009/6/28 2:00', '2009/6/28 3:00', '2009/6/28 4:00', '2009/6/28 5:00', '2009/6/28 6:00', '2009/6/28 7:00', '2009/6/28 8:00', '2009/6/28 9:00', '2009/6/28 10:00', '2009/6/28 11:00', '2009/6/28 12:00', '2009/6/28 13:00', '2009/6/28 14:00', '2009/6/28 15:00', '2009/6/28 16:00', '2009/6/28 17:00', '2009/6/28 18:00', '2009/6/28 19:00', '2009/6/28 20:00', '2009/6/28 21:00', '2009/6/28 22:00', '2009/6/28 23:00',
'2009/6/29 0:00', '2009/6/29 1:00', '2009/6/29 2:00', '2009/6/29 3:00', '2009/6/29 4:00', '2009/6/29 5:00', '2009/6/29 6:00', '2009/6/29 7:00', '2009/6/29 8:00', '2009/6/29 9:00', '2009/6/29 10:00', '2009/6/29 11:00', '2009/6/29 12:00', '2009/6/29 13:00', '2009/6/29 14:00', '2009/6/29 15:00', '2009/6/29 16:00', '2009/6/29 17:00', '2009/6/29 18:00', '2009/6/29 19:00', '2009/6/29 20:00', '2009/6/29 21:00', '2009/6/29 22:00', '2009/6/29 23:00',
'2009/6/30 0:00', '2009/6/30 1:00', '2009/6/30 2:00', '2009/6/30 3:00', '2009/6/30 4:00', '2009/6/30 5:00', '2009/6/30 6:00', '2009/6/30 7:00', '2009/6/30 8:00', '2009/6/30 9:00', '2009/6/30 10:00', '2009/6/30 11:00', '2009/6/30 12:00', '2009/6/30 13:00', '2009/6/30 14:00', '2009/6/30 15:00', '2009/6/30 16:00', '2009/6/30 17:00', '2009/6/30 18:00', '2009/6/30 19:00', '2009/6/30 20:00', '2009/6/30 21:00', '2009/6/30 22:00', '2009/6/30 23:00',
'2009/7/1 0:00', '2009/7/1 1:00', '2009/7/1 2:00', '2009/7/1 3:00', '2009/7/1 4:00', '2009/7/1 5:00', '2009/7/1 6:00', '2009/7/1 7:00', '2009/7/1 8:00', '2009/7/1 9:00', '2009/7/1 10:00', '2009/7/1 11:00', '2009/7/1 12:00', '2009/7/1 13:00', '2009/7/1 14:00', '2009/7/1 15:00', '2009/7/1 16:00', '2009/7/1 17:00', '2009/7/1 18:00', '2009/7/1 19:00', '2009/7/1 20:00', '2009/7/1 21:00', '2009/7/1 22:00', '2009/7/1 23:00',
'2009/7/2 0:00', '2009/7/2 1:00', '2009/7/2 2:00', '2009/7/2 3:00', '2009/7/2 4:00', '2009/7/2 5:00', '2009/7/2 6:00', '2009/7/2 7:00', '2009/7/2 8:00', '2009/7/2 9:00', '2009/7/2 10:00', '2009/7/2 11:00', '2009/7/2 12:00', '2009/7/2 13:00', '2009/7/2 14:00', '2009/7/2 15:00', '2009/7/2 16:00', '2009/7/2 17:00', '2009/7/2 18:00', '2009/7/2 19:00', '2009/7/2 20:00', '2009/7/2 21:00', '2009/7/2 22:00', '2009/7/2 23:00',
'2009/7/3 0:00', '2009/7/3 1:00', '2009/7/3 2:00', '2009/7/3 3:00', '2009/7/3 4:00', '2009/7/3 5:00', '2009/7/3 6:00', '2009/7/3 7:00', '2009/7/3 8:00', '2009/7/3 9:00', '2009/7/3 10:00', '2009/7/3 11:00', '2009/7/3 12:00', '2009/7/3 13:00', '2009/7/3 14:00', '2009/7/3 15:00', '2009/7/3 16:00', '2009/7/3 17:00', '2009/7/3 18:00', '2009/7/3 19:00', '2009/7/3 20:00', '2009/7/3 21:00', '2009/7/3 22:00', '2009/7/3 23:00',
'2009/7/4 0:00', '2009/7/4 1:00', '2009/7/4 2:00', '2009/7/4 3:00', '2009/7/4 4:00', '2009/7/4 5:00', '2009/7/4 6:00', '2009/7/4 7:00', '2009/7/4 8:00', '2009/7/4 9:00', '2009/7/4 10:00', '2009/7/4 11:00', '2009/7/4 12:00', '2009/7/4 13:00', '2009/7/4 14:00', '2009/7/4 15:00', '2009/7/4 16:00', '2009/7/4 17:00', '2009/7/4 18:00', '2009/7/4 19:00', '2009/7/4 20:00', '2009/7/4 21:00', '2009/7/4 22:00', '2009/7/4 23:00',
'2009/7/5 0:00', '2009/7/5 1:00', '2009/7/5 2:00', '2009/7/5 3:00', '2009/7/5 4:00', '2009/7/5 5:00', '2009/7/5 6:00', '2009/7/5 7:00', '2009/7/5 8:00', '2009/7/5 9:00', '2009/7/5 10:00', '2009/7/5 11:00', '2009/7/5 12:00', '2009/7/5 13:00', '2009/7/5 14:00', '2009/7/5 15:00', '2009/7/5 16:00', '2009/7/5 17:00', '2009/7/5 18:00', '2009/7/5 19:00', '2009/7/5 20:00', '2009/7/5 21:00', '2009/7/5 22:00', '2009/7/5 23:00',
'2009/7/6 0:00', '2009/7/6 1:00', '2009/7/6 2:00', '2009/7/6 3:00', '2009/7/6 4:00', '2009/7/6 5:00', '2009/7/6 6:00', '2009/7/6 7:00', '2009/7/6 8:00', '2009/7/6 9:00', '2009/7/6 10:00', '2009/7/6 11:00', '2009/7/6 12:00', '2009/7/6 13:00', '2009/7/6 14:00', '2009/7/6 15:00', '2009/7/6 16:00', '2009/7/6 17:00', '2009/7/6 18:00', '2009/7/6 19:00', '2009/7/6 20:00', '2009/7/6 21:00', '2009/7/6 22:00', '2009/7/6 23:00',
'2009/7/7 0:00', '2009/7/7 1:00', '2009/7/7 2:00', '2009/7/7 3:00', '2009/7/7 4:00', '2009/7/7 5:00', '2009/7/7 6:00', '2009/7/7 7:00', '2009/7/7 8:00', '2009/7/7 9:00', '2009/7/7 10:00', '2009/7/7 11:00', '2009/7/7 12:00', '2009/7/7 13:00', '2009/7/7 14:00', '2009/7/7 15:00', '2009/7/7 16:00', '2009/7/7 17:00', '2009/7/7 18:00', '2009/7/7 19:00', '2009/7/7 20:00', '2009/7/7 21:00', '2009/7/7 22:00', '2009/7/7 23:00',
'2009/7/8 0:00', '2009/7/8 1:00', '2009/7/8 2:00', '2009/7/8 3:00', '2009/7/8 4:00', '2009/7/8 5:00', '2009/7/8 6:00', '2009/7/8 7:00', '2009/7/8 8:00', '2009/7/8 9:00', '2009/7/8 10:00', '2009/7/8 11:00', '2009/7/8 12:00', '2009/7/8 13:00', '2009/7/8 14:00', '2009/7/8 15:00', '2009/7/8 16:00', '2009/7/8 17:00', '2009/7/8 18:00', '2009/7/8 19:00', '2009/7/8 20:00', '2009/7/8 21:00', '2009/7/8 22:00', '2009/7/8 23:00',
'2009/7/9 0:00', '2009/7/9 1:00', '2009/7/9 2:00', '2009/7/9 3:00', '2009/7/9 4:00', '2009/7/9 5:00', '2009/7/9 6:00', '2009/7/9 7:00', '2009/7/9 8:00', '2009/7/9 9:00', '2009/7/9 10:00', '2009/7/9 11:00', '2009/7/9 12:00', '2009/7/9 13:00', '2009/7/9 14:00', '2009/7/9 15:00', '2009/7/9 16:00', '2009/7/9 17:00', '2009/7/9 18:00', '2009/7/9 19:00', '2009/7/9 20:00', '2009/7/9 21:00', '2009/7/9 22:00', '2009/7/9 23:00',
'2009/7/10 0:00', '2009/7/10 1:00', '2009/7/10 2:00', '2009/7/10 3:00', '2009/7/10 4:00', '2009/7/10 5:00', '2009/7/10 6:00', '2009/7/10 7:00', '2009/7/10 8:00', '2009/7/10 9:00', '2009/7/10 10:00', '2009/7/10 11:00', '2009/7/10 12:00', '2009/7/10 13:00', '2009/7/10 14:00', '2009/7/10 15:00', '2009/7/10 16:00', '2009/7/10 17:00', '2009/7/10 18:00', '2009/7/10 19:00', '2009/7/10 20:00', '2009/7/10 21:00', '2009/7/10 22:00', '2009/7/10 23:00',
'2009/7/11 0:00', '2009/7/11 1:00', '2009/7/11 2:00', '2009/7/11 3:00', '2009/7/11 4:00', '2009/7/11 5:00', '2009/7/11 6:00', '2009/7/11 7:00', '2009/7/11 8:00', '2009/7/11 9:00', '2009/7/11 10:00', '2009/7/11 11:00', '2009/7/11 12:00', '2009/7/11 13:00', '2009/7/11 14:00', '2009/7/11 15:00', '2009/7/11 16:00', '2009/7/11 17:00', '2009/7/11 18:00', '2009/7/11 19:00', '2009/7/11 20:00', '2009/7/11 21:00', '2009/7/11 22:00', '2009/7/11 23:00',
'2009/7/12 0:00', '2009/7/12 1:00', '2009/7/12 2:00', '2009/7/12 3:00', '2009/7/12 4:00', '2009/7/12 5:00', '2009/7/12 6:00', '2009/7/12 7:00', '2009/7/12 8:00', '2009/7/12 9:00', '2009/7/12 10:00', '2009/7/12 11:00', '2009/7/12 12:00', '2009/7/12 13:00', '2009/7/12 14:00', '2009/7/12 15:00', '2009/7/12 16:00', '2009/7/12 17:00', '2009/7/12 18:00', '2009/7/12 19:00', '2009/7/12 20:00', '2009/7/12 21:00', '2009/7/12 22:00', '2009/7/12 23:00',
'2009/7/13 0:00', '2009/7/13 1:00', '2009/7/13 2:00', '2009/7/13 3:00', '2009/7/13 4:00', '2009/7/13 5:00', '2009/7/13 6:00', '2009/7/13 7:00', '2009/7/13 8:00', '2009/7/13 9:00', '2009/7/13 10:00', '2009/7/13 11:00', '2009/7/13 12:00', '2009/7/13 13:00', '2009/7/13 14:00', '2009/7/13 15:00', '2009/7/13 16:00', '2009/7/13 17:00', '2009/7/13 18:00', '2009/7/13 19:00', '2009/7/13 20:00', '2009/7/13 21:00', '2009/7/13 22:00', '2009/7/13 23:00',
'2009/7/14 0:00', '2009/7/14 1:00', '2009/7/14 2:00', '2009/7/14 3:00', '2009/7/14 4:00', '2009/7/14 5:00', '2009/7/14 6:00', '2009/7/14 7:00', '2009/7/14 8:00', '2009/7/14 9:00', '2009/7/14 10:00', '2009/7/14 11:00', '2009/7/14 12:00', '2009/7/14 13:00', '2009/7/14 14:00', '2009/7/14 15:00', '2009/7/14 16:00', '2009/7/14 17:00', '2009/7/14 18:00', '2009/7/14 19:00', '2009/7/14 20:00', '2009/7/14 21:00', '2009/7/14 22:00', '2009/7/14 23:00',
'2009/7/15 0:00', '2009/7/15 1:00', '2009/7/15 2:00', '2009/7/15 3:00', '2009/7/15 4:00', '2009/7/15 5:00', '2009/7/15 6:00', '2009/7/15 7:00', '2009/7/15 8:00', '2009/7/15 9:00', '2009/7/15 10:00', '2009/7/15 11:00', '2009/7/15 12:00', '2009/7/15 13:00', '2009/7/15 14:00', '2009/7/15 15:00', '2009/7/15 16:00', '2009/7/15 17:00', '2009/7/15 18:00', '2009/7/15 19:00', '2009/7/15 20:00', '2009/7/15 21:00', '2009/7/15 22:00', '2009/7/15 23:00',
'2009/7/16 0:00', '2009/7/16 1:00', '2009/7/16 2:00', '2009/7/16 3:00', '2009/7/16 4:00', '2009/7/16 5:00', '2009/7/16 6:00', '2009/7/16 7:00', '2009/7/16 8:00', '2009/7/16 9:00', '2009/7/16 10:00', '2009/7/16 11:00', '2009/7/16 12:00', '2009/7/16 13:00', '2009/7/16 14:00', '2009/7/16 15:00', '2009/7/16 16:00', '2009/7/16 17:00', '2009/7/16 18:00', '2009/7/16 19:00', '2009/7/16 20:00', '2009/7/16 21:00', '2009/7/16 22:00', '2009/7/16 23:00',
'2009/7/17 0:00', '2009/7/17 1:00', '2009/7/17 2:00', '2009/7/17 3:00', '2009/7/17 4:00', '2009/7/17 5:00', '2009/7/17 6:00', '2009/7/17 7:00', '2009/7/17 8:00', '2009/7/17 9:00', '2009/7/17 10:00', '2009/7/17 11:00', '2009/7/17 12:00', '2009/7/17 13:00', '2009/7/17 14:00', '2009/7/17 15:00', '2009/7/17 16:00', '2009/7/17 17:00', '2009/7/17 18:00', '2009/7/17 19:00', '2009/7/17 20:00', '2009/7/17 21:00', '2009/7/17 22:00', '2009/7/17 23:00',
'2009/7/18 0:00', '2009/7/18 1:00', '2009/7/18 2:00', '2009/7/18 3:00', '2009/7/18 4:00', '2009/7/18 5:00', '2009/7/18 6:00', '2009/7/18 7:00', '2009/7/18 8:00', '2009/7/18 9:00', '2009/7/18 10:00', '2009/7/18 11:00', '2009/7/18 12:00', '2009/7/18 13:00', '2009/7/18 14:00', '2009/7/18 15:00', '2009/7/18 16:00', '2009/7/18 17:00', '2009/7/18 18:00', '2009/7/18 19:00', '2009/7/18 20:00', '2009/7/18 21:00', '2009/7/18 22:00', '2009/7/18 23:00',
'2009/7/19 0:00', '2009/7/19 1:00', '2009/7/19 2:00', '2009/7/19 3:00', '2009/7/19 4:00', '2009/7/19 5:00', '2009/7/19 6:00', '2009/7/19 7:00', '2009/7/19 8:00', '2009/7/19 9:00', '2009/7/19 10:00', '2009/7/19 11:00', '2009/7/19 12:00', '2009/7/19 13:00', '2009/7/19 14:00', '2009/7/19 15:00', '2009/7/19 16:00', '2009/7/19 17:00', '2009/7/19 18:00', '2009/7/19 19:00', '2009/7/19 20:00', '2009/7/19 21:00', '2009/7/19 22:00', '2009/7/19 23:00',
'2009/7/20 0:00', '2009/7/20 1:00', '2009/7/20 2:00', '2009/7/20 3:00', '2009/7/20 4:00', '2009/7/20 5:00', '2009/7/20 6:00', '2009/7/20 7:00', '2009/7/20 8:00', '2009/7/20 9:00', '2009/7/20 10:00', '2009/7/20 11:00', '2009/7/20 12:00', '2009/7/20 13:00', '2009/7/20 14:00', '2009/7/20 15:00', '2009/7/20 16:00', '2009/7/20 17:00', '2009/7/20 18:00', '2009/7/20 19:00', '2009/7/20 20:00', '2009/7/20 21:00', '2009/7/20 22:00', '2009/7/20 23:00',
'2009/7/21 0:00', '2009/7/21 1:00', '2009/7/21 2:00', '2009/7/21 3:00', '2009/7/21 4:00', '2009/7/21 5:00', '2009/7/21 6:00', '2009/7/21 7:00', '2009/7/21 8:00', '2009/7/21 9:00', '2009/7/21 10:00', '2009/7/21 11:00', '2009/7/21 12:00', '2009/7/21 13:00', '2009/7/21 14:00', '2009/7/21 15:00', '2009/7/21 16:00', '2009/7/21 17:00', '2009/7/21 18:00', '2009/7/21 19:00', '2009/7/21 20:00', '2009/7/21 21:00', '2009/7/21 22:00', '2009/7/21 23:00',
'2009/7/22 0:00', '2009/7/22 1:00', '2009/7/22 2:00', '2009/7/22 3:00', '2009/7/22 4:00', '2009/7/22 5:00', '2009/7/22 6:00', '2009/7/22 7:00', '2009/7/22 8:00', '2009/7/22 9:00', '2009/7/22 10:00', '2009/7/22 11:00', '2009/7/22 12:00', '2009/7/22 13:00', '2009/7/22 14:00', '2009/7/22 15:00', '2009/7/22 16:00', '2009/7/22 17:00', '2009/7/22 18:00', '2009/7/22 19:00', '2009/7/22 20:00', '2009/7/22 21:00', '2009/7/22 22:00', '2009/7/22 23:00',
'2009/7/23 0:00', '2009/7/23 1:00', '2009/7/23 2:00', '2009/7/23 3:00', '2009/7/23 4:00', '2009/7/23 5:00', '2009/7/23 6:00', '2009/7/23 7:00', '2009/7/23 8:00', '2009/7/23 9:00', '2009/7/23 10:00', '2009/7/23 11:00', '2009/7/23 12:00', '2009/7/23 13:00', '2009/7/23 14:00', '2009/7/23 15:00', '2009/7/23 16:00', '2009/7/23 17:00', '2009/7/23 18:00', '2009/7/23 19:00', '2009/7/23 20:00', '2009/7/23 21:00', '2009/7/23 22:00', '2009/7/23 23:00',
'2009/7/24 0:00', '2009/7/24 1:00', '2009/7/24 2:00', '2009/7/24 3:00', '2009/7/24 4:00', '2009/7/24 5:00', '2009/7/24 6:00', '2009/7/24 7:00', '2009/7/24 8:00', '2009/7/24 9:00', '2009/7/24 10:00', '2009/7/24 11:00', '2009/7/24 12:00', '2009/7/24 13:00', '2009/7/24 14:00', '2009/7/24 15:00', '2009/7/24 16:00', '2009/7/24 17:00', '2009/7/24 18:00', '2009/7/24 19:00', '2009/7/24 20:00', '2009/7/24 21:00', '2009/7/24 22:00', '2009/7/24 23:00',
'2009/7/25 0:00', '2009/7/25 1:00', '2009/7/25 2:00', '2009/7/25 3:00', '2009/7/25 4:00', '2009/7/25 5:00', '2009/7/25 6:00', '2009/7/25 7:00', '2009/7/25 8:00', '2009/7/25 9:00', '2009/7/25 10:00', '2009/7/25 11:00', '2009/7/25 12:00', '2009/7/25 13:00', '2009/7/25 14:00', '2009/7/25 15:00', '2009/7/25 16:00', '2009/7/25 17:00', '2009/7/25 18:00', '2009/7/25 19:00', '2009/7/25 20:00', '2009/7/25 21:00', '2009/7/25 22:00', '2009/7/25 23:00',
'2009/7/26 0:00', '2009/7/26 1:00', '2009/7/26 2:00', '2009/7/26 3:00', '2009/7/26 4:00', '2009/7/26 5:00', '2009/7/26 6:00', '2009/7/26 7:00', '2009/7/26 8:00', '2009/7/26 9:00', '2009/7/26 10:00', '2009/7/26 11:00', '2009/7/26 12:00', '2009/7/26 13:00', '2009/7/26 14:00', '2009/7/26 15:00', '2009/7/26 16:00', '2009/7/26 17:00', '2009/7/26 18:00', '2009/7/26 19:00', '2009/7/26 20:00', '2009/7/26 21:00', '2009/7/26 22:00', '2009/7/26 23:00',
'2009/7/27 0:00', '2009/7/27 1:00', '2009/7/27 2:00', '2009/7/27 3:00', '2009/7/27 4:00', '2009/7/27 5:00', '2009/7/27 6:00', '2009/7/27 7:00', '2009/7/27 8:00', '2009/7/27 9:00', '2009/7/27 10:00', '2009/7/27 11:00', '2009/7/27 12:00', '2009/7/27 13:00', '2009/7/27 14:00', '2009/7/27 15:00', '2009/7/27 16:00', '2009/7/27 17:00', '2009/7/27 18:00', '2009/7/27 19:00', '2009/7/27 20:00', '2009/7/27 21:00', '2009/7/27 22:00', '2009/7/27 23:00',
'2009/7/28 0:00', '2009/7/28 1:00', '2009/7/28 2:00', '2009/7/28 3:00', '2009/7/28 4:00', '2009/7/28 5:00', '2009/7/28 6:00', '2009/7/28 7:00', '2009/7/28 8:00', '2009/7/28 9:00', '2009/7/28 10:00', '2009/7/28 11:00', '2009/7/28 12:00', '2009/7/28 13:00', '2009/7/28 14:00', '2009/7/28 15:00', '2009/7/28 16:00', '2009/7/28 17:00', '2009/7/28 18:00', '2009/7/28 19:00', '2009/7/28 20:00', '2009/7/28 21:00', '2009/7/28 22:00', '2009/7/28 23:00',
'2009/7/29 0:00', '2009/7/29 1:00', '2009/7/29 2:00', '2009/7/29 3:00', '2009/7/29 4:00', '2009/7/29 5:00', '2009/7/29 6:00', '2009/7/29 7:00', '2009/7/29 8:00', '2009/7/29 9:00', '2009/7/29 10:00', '2009/7/29 11:00', '2009/7/29 12:00', '2009/7/29 13:00', '2009/7/29 14:00', '2009/7/29 15:00', '2009/7/29 16:00', '2009/7/29 17:00', '2009/7/29 18:00', '2009/7/29 19:00', '2009/7/29 20:00', '2009/7/29 21:00', '2009/7/29 22:00', '2009/7/29 23:00',
'2009/7/30 0:00', '2009/7/30 1:00', '2009/7/30 2:00', '2009/7/30 3:00', '2009/7/30 4:00', '2009/7/30 5:00', '2009/7/30 6:00', '2009/7/30 7:00', '2009/7/30 8:00', '2009/7/30 9:00', '2009/7/30 10:00', '2009/7/30 11:00', '2009/7/30 12:00', '2009/7/30 13:00', '2009/7/30 14:00', '2009/7/30 15:00', '2009/7/30 16:00', '2009/7/30 17:00', '2009/7/30 18:00', '2009/7/30 19:00', '2009/7/30 20:00', '2009/7/30 21:00', '2009/7/30 22:00', '2009/7/30 23:00',
'2009/7/31 0:00', '2009/7/31 1:00', '2009/7/31 2:00', '2009/7/31 3:00', '2009/7/31 4:00', '2009/7/31 5:00', '2009/7/31 6:00', '2009/7/31 7:00', '2009/7/31 8:00', '2009/7/31 9:00', '2009/7/31 10:00', '2009/7/31 11:00', '2009/7/31 12:00', '2009/7/31 13:00', '2009/7/31 14:00', '2009/7/31 15:00', '2009/7/31 16:00', '2009/7/31 17:00', '2009/7/31 18:00', '2009/7/31 19:00', '2009/7/31 20:00', '2009/7/31 21:00', '2009/7/31 22:00', '2009/7/31 23:00',
'2009/8/1 0:00', '2009/8/1 1:00', '2009/8/1 2:00', '2009/8/1 3:00', '2009/8/1 4:00', '2009/8/1 5:00', '2009/8/1 6:00', '2009/8/1 7:00', '2009/8/1 8:00', '2009/8/1 9:00', '2009/8/1 10:00', '2009/8/1 11:00', '2009/8/1 12:00', '2009/8/1 13:00', '2009/8/1 14:00', '2009/8/1 15:00', '2009/8/1 16:00', '2009/8/1 17:00', '2009/8/1 18:00', '2009/8/1 19:00', '2009/8/1 20:00', '2009/8/1 21:00', '2009/8/1 22:00', '2009/8/1 23:00', '2009/8/2 0:00', '2009/8/2 1:00', '2009/8/2 2:00', '2009/8/2 3:00', '2009/8/2 4:00', '2009/8/2 5:00', '2009/8/2 6:00', '2009/8/2 7:00', '2009/8/2 8:00', '2009/8/2 9:00', '2009/8/2 10:00', '2009/8/2 11:00', '2009/8/2 12:00', '2009/8/2 13:00', '2009/8/2 14:00', '2009/8/2 15:00', '2009/8/2 16:00', '2009/8/2 17:00', '2009/8/2 18:00', '2009/8/2 19:00', '2009/8/2 20:00', '2009/8/2 21:00', '2009/8/2 22:00', '2009/8/2 23:00', '2009/8/3 0:00', '2009/8/3 1:00', '2009/8/3 2:00', '2009/8/3 3:00', '2009/8/3 4:00', '2009/8/3 5:00', '2009/8/3 6:00', '2009/8/3 7:00', '2009/8/3 8:00', '2009/8/3 9:00', '2009/8/3 10:00', '2009/8/3 11:00', '2009/8/3 12:00', '2009/8/3 13:00', '2009/8/3 14:00', '2009/8/3 15:00', '2009/8/3 16:00', '2009/8/3 17:00', '2009/8/3 18:00', '2009/8/3 19:00', '2009/8/3 20:00', '2009/8/3 21:00', '2009/8/3 22:00', '2009/8/3 23:00', '2009/8/4 0:00', '2009/8/4 1:00', '2009/8/4 2:00', '2009/8/4 3:00', '2009/8/4 4:00', '2009/8/4 5:00', '2009/8/4 6:00', '2009/8/4 7:00', '2009/8/4 8:00', '2009/8/4 9:00', '2009/8/4 10:00', '2009/8/4 11:00', '2009/8/4 12:00', '2009/8/4 13:00', '2009/8/4 14:00', '2009/8/4 15:00', '2009/8/4 16:00', '2009/8/4 17:00', '2009/8/4 18:00', '2009/8/4 19:00', '2009/8/4 20:00', '2009/8/4 21:00', '2009/8/4 22:00', '2009/8/4 23:00', '2009/8/5 0:00', '2009/8/5 1:00', '2009/8/5 2:00', '2009/8/5 3:00', '2009/8/5 4:00', '2009/8/5 5:00', '2009/8/5 6:00', '2009/8/5 7:00', '2009/8/5 8:00', '2009/8/5 9:00', '2009/8/5 10:00', '2009/8/5 11:00', '2009/8/5 12:00', '2009/8/5 13:00', '2009/8/5 14:00', '2009/8/5 15:00', '2009/8/5 16:00', '2009/8/5 17:00', '2009/8/5 18:00', '2009/8/5 19:00', '2009/8/5 20:00', '2009/8/5 21:00', '2009/8/5 22:00', '2009/8/5 23:00', '2009/8/6 0:00', '2009/8/6 1:00', '2009/8/6 2:00', '2009/8/6 3:00', '2009/8/6 4:00', '2009/8/6 5:00', '2009/8/6 6:00', '2009/8/6 7:00', '2009/8/6 8:00', '2009/8/6 9:00', '2009/8/6 10:00', '2009/8/6 11:00', '2009/8/6 12:00', '2009/8/6 13:00', '2009/8/6 14:00', '2009/8/6 15:00', '2009/8/6 16:00', '2009/8/6 17:00', '2009/8/6 18:00', '2009/8/6 19:00', '2009/8/6 20:00', '2009/8/6 21:00', '2009/8/6 22:00', '2009/8/6 23:00', '2009/8/7 0:00', '2009/8/7 1:00', '2009/8/7 2:00', '2009/8/7 3:00', '2009/8/7 4:00', '2009/8/7 5:00', '2009/8/7 6:00', '2009/8/7 7:00', '2009/8/7 8:00', '2009/8/7 9:00', '2009/8/7 10:00', '2009/8/7 11:00', '2009/8/7 12:00', '2009/8/7 13:00', '2009/8/7 14:00', '2009/8/7 15:00', '2009/8/7 16:00', '2009/8/7 17:00', '2009/8/7 18:00', '2009/8/7 19:00', '2009/8/7 20:00', '2009/8/7 21:00', '2009/8/7 22:00', '2009/8/7 23:00', '2009/8/8 0:00', '2009/8/8 1:00', '2009/8/8 2:00', '2009/8/8 3:00', '2009/8/8 4:00', '2009/8/8 5:00', '2009/8/8 6:00', '2009/8/8 7:00', '2009/8/8 8:00', '2009/8/8 9:00', '2009/8/8 10:00', '2009/8/8 11:00', '2009/8/8 12:00', '2009/8/8 13:00', '2009/8/8 14:00', '2009/8/8 15:00', '2009/8/8 16:00', '2009/8/8 17:00', '2009/8/8 18:00', '2009/8/8 19:00', '2009/8/8 20:00', '2009/8/8 21:00', '2009/8/8 22:00', '2009/8/8 23:00', '2009/8/9 0:00', '2009/8/9 1:00', '2009/8/9 2:00', '2009/8/9 3:00', '2009/8/9 4:00', '2009/8/9 5:00', '2009/8/9 6:00', '2009/8/9 7:00', '2009/8/9 8:00', '2009/8/9 9:00', '2009/8/9 10:00', '2009/8/9 11:00', '2009/8/9 12:00', '2009/8/9 13:00', '2009/8/9 14:00', '2009/8/9 15:00', '2009/8/9 16:00', '2009/8/9 17:00', '2009/8/9 18:00', '2009/8/9 19:00', '2009/8/9 20:00', '2009/8/9 21:00', '2009/8/9 22:00', '2009/8/9 23:00', '2009/8/10 0:00', '2009/8/10 1:00', '2009/8/10 2:00', '2009/8/10 3:00', '2009/8/10 4:00', '2009/8/10 5:00', '2009/8/10 6:00', '2009/8/10 7:00', '2009/8/10 8:00', '2009/8/10 9:00', '2009/8/10 10:00', '2009/8/10 11:00', '2009/8/10 12:00', '2009/8/10 13:00', '2009/8/10 14:00', '2009/8/10 15:00', '2009/8/10 16:00', '2009/8/10 17:00', '2009/8/10 18:00', '2009/8/10 19:00', '2009/8/10 20:00', '2009/8/10 21:00', '2009/8/10 22:00', '2009/8/10 23:00', '2009/8/11 0:00', '2009/8/11 1:00', '2009/8/11 2:00', '2009/8/11 3:00', '2009/8/11 4:00', '2009/8/11 5:00', '2009/8/11 6:00', '2009/8/11 7:00', '2009/8/11 8:00', '2009/8/11 9:00', '2009/8/11 10:00', '2009/8/11 11:00', '2009/8/11 12:00', '2009/8/11 13:00', '2009/8/11 14:00', '2009/8/11 15:00', '2009/8/11 16:00', '2009/8/11 17:00', '2009/8/11 18:00', '2009/8/11 19:00', '2009/8/11 20:00', '2009/8/11 21:00', '2009/8/11 22:00', '2009/8/11 23:00', '2009/8/12 0:00', '2009/8/12 1:00', '2009/8/12 2:00', '2009/8/12 3:00', '2009/8/12 4:00', '2009/8/12 5:00', '2009/8/12 6:00', '2009/8/12 7:00', '2009/8/12 8:00', '2009/8/12 9:00', '2009/8/12 10:00', '2009/8/12 11:00', '2009/8/12 12:00', '2009/8/12 13:00', '2009/8/12 14:00', '2009/8/12 15:00', '2009/8/12 16:00', '2009/8/12 17:00', '2009/8/12 18:00', '2009/8/12 19:00', '2009/8/12 20:00', '2009/8/12 21:00', '2009/8/12 22:00', '2009/8/12 23:00', '2009/8/13 0:00', '2009/8/13 1:00', '2009/8/13 2:00', '2009/8/13 3:00', '2009/8/13 4:00', '2009/8/13 5:00', '2009/8/13 6:00', '2009/8/13 7:00', '2009/8/13 8:00', '2009/8/13 9:00', '2009/8/13 10:00', '2009/8/13 11:00', '2009/8/13 12:00', '2009/8/13 13:00', '2009/8/13 14:00', '2009/8/13 15:00', '2009/8/13 16:00', '2009/8/13 17:00', '2009/8/13 18:00', '2009/8/13 19:00', '2009/8/13 20:00', '2009/8/13 21:00', '2009/8/13 22:00', '2009/8/13 23:00', '2009/8/14 0:00', '2009/8/14 1:00', '2009/8/14 2:00', '2009/8/14 3:00', '2009/8/14 4:00', '2009/8/14 5:00', '2009/8/14 6:00', '2009/8/14 7:00', '2009/8/14 8:00', '2009/8/14 9:00', '2009/8/14 10:00', '2009/8/14 11:00', '2009/8/14 12:00', '2009/8/14 13:00', '2009/8/14 14:00', '2009/8/14 15:00', '2009/8/14 16:00', '2009/8/14 17:00', '2009/8/14 18:00', '2009/8/14 19:00', '2009/8/14 20:00', '2009/8/14 21:00', '2009/8/14 22:00', '2009/8/14 23:00', '2009/8/15 0:00', '2009/8/15 1:00', '2009/8/15 2:00', '2009/8/15 3:00', '2009/8/15 4:00', '2009/8/15 5:00', '2009/8/15 6:00', '2009/8/15 7:00', '2009/8/15 8:00', '2009/8/15 9:00', '2009/8/15 10:00', '2009/8/15 11:00', '2009/8/15 12:00', '2009/8/15 13:00', '2009/8/15 14:00', '2009/8/15 15:00', '2009/8/15 16:00', '2009/8/15 17:00', '2009/8/15 18:00', '2009/8/15 19:00', '2009/8/15 20:00', '2009/8/15 21:00', '2009/8/15 22:00', '2009/8/15 23:00', '2009/8/16 0:00', '2009/8/16 1:00', '2009/8/16 2:00', '2009/8/16 3:00', '2009/8/16 4:00', '2009/8/16 5:00', '2009/8/16 6:00', '2009/8/16 7:00', '2009/8/16 8:00', '2009/8/16 9:00', '2009/8/16 10:00', '2009/8/16 11:00', '2009/8/16 12:00', '2009/8/16 13:00', '2009/8/16 14:00', '2009/8/16 15:00', '2009/8/16 16:00', '2009/8/16 17:00', '2009/8/16 18:00', '2009/8/16 19:00', '2009/8/16 20:00', '2009/8/16 21:00', '2009/8/16 22:00', '2009/8/16 23:00', '2009/8/17 0:00', '2009/8/17 1:00', '2009/8/17 2:00', '2009/8/17 3:00', '2009/8/17 4:00', '2009/8/17 5:00', '2009/8/17 6:00', '2009/8/17 7:00', '2009/8/17 8:00', '2009/8/17 9:00', '2009/8/17 10:00', '2009/8/17 11:00', '2009/8/17 12:00', '2009/8/17 13:00', '2009/8/17 14:00', '2009/8/17 15:00', '2009/8/17 16:00', '2009/8/17 17:00', '2009/8/17 18:00', '2009/8/17 19:00', '2009/8/17 20:00', '2009/8/17 21:00', '2009/8/17 22:00', '2009/8/17 23:00', '2009/8/18 0:00', '2009/8/18 1:00', '2009/8/18 2:00', '2009/8/18 3:00', '2009/8/18 4:00', '2009/8/18 5:00', '2009/8/18 6:00', '2009/8/18 7:00', '2009/8/18 8:00', '2009/8/18 9:00', '2009/8/18 10:00', '2009/8/18 11:00', '2009/8/18 12:00', '2009/8/18 13:00', '2009/8/18 14:00', '2009/8/18 15:00', '2009/8/18 16:00', '2009/8/18 17:00', '2009/8/18 18:00', '2009/8/18 19:00', '2009/8/18 20:00', '2009/8/18 21:00', '2009/8/18 22:00', '2009/8/18 23:00', '2009/8/19 0:00', '2009/8/19 1:00', '2009/8/19 2:00', '2009/8/19 3:00', '2009/8/19 4:00', '2009/8/19 5:00', '2009/8/19 6:00', '2009/8/19 7:00', '2009/8/19 8:00', '2009/8/19 9:00', '2009/8/19 10:00', '2009/8/19 11:00', '2009/8/19 12:00', '2009/8/19 13:00', '2009/8/19 14:00', '2009/8/19 15:00', '2009/8/19 16:00', '2009/8/19 17:00', '2009/8/19 18:00', '2009/8/19 19:00', '2009/8/19 20:00', '2009/8/19 21:00', '2009/8/19 22:00', '2009/8/19 23:00', '2009/8/20 0:00', '2009/8/20 1:00', '2009/8/20 2:00', '2009/8/20 3:00', '2009/8/20 4:00', '2009/8/20 5:00', '2009/8/20 6:00', '2009/8/20 7:00', '2009/8/20 8:00', '2009/8/20 9:00', '2009/8/20 10:00', '2009/8/20 11:00', '2009/8/20 12:00', '2009/8/20 13:00', '2009/8/20 14:00', '2009/8/20 15:00', '2009/8/20 16:00', '2009/8/20 17:00', '2009/8/20 18:00', '2009/8/20 19:00', '2009/8/20 20:00', '2009/8/20 21:00', '2009/8/20 22:00', '2009/8/20 23:00', '2009/8/21 0:00', '2009/8/21 1:00', '2009/8/21 2:00', '2009/8/21 3:00', '2009/8/21 4:00', '2009/8/21 5:00', '2009/8/21 6:00', '2009/8/21 7:00', '2009/8/21 8:00', '2009/8/21 9:00', '2009/8/21 10:00', '2009/8/21 11:00', '2009/8/21 12:00', '2009/8/21 13:00', '2009/8/21 14:00', '2009/8/21 15:00', '2009/8/21 16:00', '2009/8/21 17:00', '2009/8/21 18:00', '2009/8/21 19:00', '2009/8/21 20:00', '2009/8/21 21:00', '2009/8/21 22:00', '2009/8/21 23:00', '2009/8/22 0:00', '2009/8/22 1:00', '2009/8/22 2:00', '2009/8/22 3:00', '2009/8/22 4:00', '2009/8/22 5:00', '2009/8/22 6:00', '2009/8/22 7:00', '2009/8/22 8:00', '2009/8/22 9:00', '2009/8/22 10:00', '2009/8/22 11:00', '2009/8/22 12:00', '2009/8/22 13:00', '2009/8/22 14:00', '2009/8/22 15:00', '2009/8/22 16:00', '2009/8/22 17:00', '2009/8/22 18:00', '2009/8/22 19:00', '2009/8/22 20:00', '2009/8/22 21:00', '2009/8/22 22:00', '2009/8/22 23:00', '2009/8/23 0:00', '2009/8/23 1:00', '2009/8/23 2:00', '2009/8/23 3:00', '2009/8/23 4:00', '2009/8/23 5:00', '2009/8/23 6:00', '2009/8/23 7:00', '2009/8/23 8:00', '2009/8/23 9:00', '2009/8/23 10:00', '2009/8/23 11:00', '2009/8/23 12:00', '2009/8/23 13:00', '2009/8/23 14:00', '2009/8/23 15:00', '2009/8/23 16:00', '2009/8/23 17:00', '2009/8/23 18:00', '2009/8/23 19:00', '2009/8/23 20:00', '2009/8/23 21:00', '2009/8/23 22:00', '2009/8/23 23:00', '2009/8/24 0:00', '2009/8/24 1:00', '2009/8/24 2:00', '2009/8/24 3:00', '2009/8/24 4:00', '2009/8/24 5:00', '2009/8/24 6:00', '2009/8/24 7:00', '2009/8/24 8:00', '2009/8/24 9:00', '2009/8/24 10:00', '2009/8/24 11:00', '2009/8/24 12:00', '2009/8/24 13:00', '2009/8/24 14:00', '2009/8/24 15:00', '2009/8/24 16:00', '2009/8/24 17:00', '2009/8/24 18:00', '2009/8/24 19:00', '2009/8/24 20:00', '2009/8/24 21:00', '2009/8/24 22:00', '2009/8/24 23:00', '2009/8/25 0:00', '2009/8/25 1:00', '2009/8/25 2:00', '2009/8/25 3:00', '2009/8/25 4:00', '2009/8/25 5:00', '2009/8/25 6:00', '2009/8/25 7:00', '2009/8/25 8:00', '2009/8/25 9:00', '2009/8/25 10:00', '2009/8/25 11:00', '2009/8/25 12:00', '2009/8/25 13:00', '2009/8/25 14:00', '2009/8/25 15:00', '2009/8/25 16:00', '2009/8/25 17:00', '2009/8/25 18:00', '2009/8/25 19:00', '2009/8/25 20:00', '2009/8/25 21:00', '2009/8/25 22:00', '2009/8/25 23:00', '2009/8/26 0:00', '2009/8/26 1:00', '2009/8/26 2:00', '2009/8/26 3:00', '2009/8/26 4:00', '2009/8/26 5:00', '2009/8/26 6:00', '2009/8/26 7:00', '2009/8/26 8:00', '2009/8/26 9:00', '2009/8/26 10:00', '2009/8/26 11:00', '2009/8/26 12:00', '2009/8/26 13:00', '2009/8/26 14:00', '2009/8/26 15:00', '2009/8/26 16:00', '2009/8/26 17:00', '2009/8/26 18:00', '2009/8/26 19:00', '2009/8/26 20:00', '2009/8/26 21:00', '2009/8/26 22:00', '2009/8/26 23:00', '2009/8/27 0:00', '2009/8/27 1:00', '2009/8/27 2:00', '2009/8/27 3:00', '2009/8/27 4:00', '2009/8/27 5:00', '2009/8/27 6:00', '2009/8/27 7:00', '2009/8/27 8:00', '2009/8/27 9:00', '2009/8/27 10:00', '2009/8/27 11:00', '2009/8/27 12:00', '2009/8/27 13:00', '2009/8/27 14:00', '2009/8/27 15:00', '2009/8/27 16:00', '2009/8/27 17:00', '2009/8/27 18:00', '2009/8/27 19:00', '2009/8/27 20:00', '2009/8/27 21:00', '2009/8/27 22:00', '2009/8/27 23:00', '2009/8/28 0:00', '2009/8/28 1:00', '2009/8/28 2:00', '2009/8/28 3:00', '2009/8/28 4:00', '2009/8/28 5:00', '2009/8/28 6:00', '2009/8/28 7:00', '2009/8/28 8:00', '2009/8/28 9:00', '2009/8/28 10:00', '2009/8/28 11:00', '2009/8/28 12:00', '2009/8/28 13:00', '2009/8/28 14:00', '2009/8/28 15:00', '2009/8/28 16:00', '2009/8/28 17:00', '2009/8/28 18:00', '2009/8/28 19:00', '2009/8/28 20:00', '2009/8/28 21:00', '2009/8/28 22:00', '2009/8/28 23:00', '2009/8/29 0:00', '2009/8/29 1:00', '2009/8/29 2:00', '2009/8/29 3:00', '2009/8/29 4:00', '2009/8/29 5:00', '2009/8/29 6:00', '2009/8/29 7:00', '2009/8/29 8:00', '2009/8/29 9:00', '2009/8/29 10:00', '2009/8/29 11:00', '2009/8/29 12:00', '2009/8/29 13:00', '2009/8/29 14:00', '2009/8/29 15:00', '2009/8/29 16:00', '2009/8/29 17:00', '2009/8/29 18:00', '2009/8/29 19:00', '2009/8/29 20:00', '2009/8/29 21:00', '2009/8/29 22:00', '2009/8/29 23:00', '2009/8/30 0:00', '2009/8/30 1:00', '2009/8/30 2:00', '2009/8/30 3:00', '2009/8/30 4:00', '2009/8/30 5:00', '2009/8/30 6:00', '2009/8/30 7:00', '2009/8/30 8:00', '2009/8/30 9:00', '2009/8/30 10:00', '2009/8/30 11:00', '2009/8/30 12:00', '2009/8/30 13:00', '2009/8/30 14:00', '2009/8/30 15:00', '2009/8/30 16:00', '2009/8/30 17:00', '2009/8/30 18:00', '2009/8/30 19:00', '2009/8/30 20:00', '2009/8/30 21:00', '2009/8/30 22:00', '2009/8/30 23:00', '2009/8/31 0:00', '2009/8/31 1:00', '2009/8/31 2:00', '2009/8/31 3:00', '2009/8/31 4:00', '2009/8/31 5:00', '2009/8/31 6:00', '2009/8/31 7:00', '2009/8/31 8:00', '2009/8/31 9:00', '2009/8/31 10:00', '2009/8/31 11:00', '2009/8/31 12:00', '2009/8/31 13:00', '2009/8/31 14:00', '2009/8/31 15:00', '2009/8/31 16:00', '2009/8/31 17:00', '2009/8/31 18:00', '2009/8/31 19:00', '2009/8/31 20:00', '2009/8/31 21:00', '2009/8/31 22:00', '2009/8/31 23:00',
'2009/9/1 0:00', '2009/9/1 1:00', '2009/9/1 2:00', '2009/9/1 3:00', '2009/9/1 4:00', '2009/9/1 5:00', '2009/9/1 6:00', '2009/9/1 7:00', '2009/9/1 8:00', '2009/9/1 9:00', '2009/9/1 10:00', '2009/9/1 11:00', '2009/9/1 12:00', '2009/9/1 13:00', '2009/9/1 14:00', '2009/9/1 15:00', '2009/9/1 16:00', '2009/9/1 17:00', '2009/9/1 18:00', '2009/9/1 19:00', '2009/9/1 20:00', '2009/9/1 21:00', '2009/9/1 22:00', '2009/9/1 23:00', '2009/9/2 0:00', '2009/9/2 1:00', '2009/9/2 2:00', '2009/9/2 3:00', '2009/9/2 4:00', '2009/9/2 5:00', '2009/9/2 6:00', '2009/9/2 7:00', '2009/9/2 8:00', '2009/9/2 9:00', '2009/9/2 10:00', '2009/9/2 11:00', '2009/9/2 12:00', '2009/9/2 13:00', '2009/9/2 14:00', '2009/9/2 15:00', '2009/9/2 16:00', '2009/9/2 17:00', '2009/9/2 18:00', '2009/9/2 19:00', '2009/9/2 20:00', '2009/9/2 21:00', '2009/9/2 22:00', '2009/9/2 23:00', '2009/9/3 0:00', '2009/9/3 1:00', '2009/9/3 2:00', '2009/9/3 3:00', '2009/9/3 4:00', '2009/9/3 5:00', '2009/9/3 6:00', '2009/9/3 7:00', '2009/9/3 8:00', '2009/9/3 9:00', '2009/9/3 10:00', '2009/9/3 11:00', '2009/9/3 12:00', '2009/9/3 13:00', '2009/9/3 14:00', '2009/9/3 15:00', '2009/9/3 16:00', '2009/9/3 17:00', '2009/9/3 18:00', '2009/9/3 19:00', '2009/9/3 20:00', '2009/9/3 21:00', '2009/9/3 22:00', '2009/9/3 23:00', '2009/9/4 0:00', '2009/9/4 1:00', '2009/9/4 2:00', '2009/9/4 3:00', '2009/9/4 4:00', '2009/9/4 5:00', '2009/9/4 6:00', '2009/9/4 7:00', '2009/9/4 8:00', '2009/9/4 9:00', '2009/9/4 10:00', '2009/9/4 11:00', '2009/9/4 12:00', '2009/9/4 13:00', '2009/9/4 14:00', '2009/9/4 15:00', '2009/9/4 16:00', '2009/9/4 17:00', '2009/9/4 18:00', '2009/9/4 19:00', '2009/9/4 20:00', '2009/9/4 21:00', '2009/9/4 22:00', '2009/9/4 23:00', '2009/9/5 0:00', '2009/9/5 1:00', '2009/9/5 2:00', '2009/9/5 3:00', '2009/9/5 4:00', '2009/9/5 5:00', '2009/9/5 6:00', '2009/9/5 7:00', '2009/9/5 8:00', '2009/9/5 9:00', '2009/9/5 10:00', '2009/9/5 11:00', '2009/9/5 12:00', '2009/9/5 13:00', '2009/9/5 14:00', '2009/9/5 15:00', '2009/9/5 16:00', '2009/9/5 17:00', '2009/9/5 18:00', '2009/9/5 19:00', '2009/9/5 20:00', '2009/9/5 21:00', '2009/9/5 22:00', '2009/9/5 23:00', '2009/9/6 0:00', '2009/9/6 1:00', '2009/9/6 2:00', '2009/9/6 3:00', '2009/9/6 4:00', '2009/9/6 5:00', '2009/9/6 6:00', '2009/9/6 7:00', '2009/9/6 8:00', '2009/9/6 9:00', '2009/9/6 10:00', '2009/9/6 11:00', '2009/9/6 12:00', '2009/9/6 13:00', '2009/9/6 14:00', '2009/9/6 15:00', '2009/9/6 16:00', '2009/9/6 17:00', '2009/9/6 18:00', '2009/9/6 19:00', '2009/9/6 20:00', '2009/9/6 21:00', '2009/9/6 22:00', '2009/9/6 23:00', '2009/9/7 0:00', '2009/9/7 1:00', '2009/9/7 2:00', '2009/9/7 3:00', '2009/9/7 4:00', '2009/9/7 5:00', '2009/9/7 6:00', '2009/9/7 7:00', '2009/9/7 8:00', '2009/9/7 9:00', '2009/9/7 10:00', '2009/9/7 11:00', '2009/9/7 12:00', '2009/9/7 13:00', '2009/9/7 14:00', '2009/9/7 15:00', '2009/9/7 16:00', '2009/9/7 17:00', '2009/9/7 18:00', '2009/9/7 19:00', '2009/9/7 20:00', '2009/9/7 21:00', '2009/9/7 22:00', '2009/9/7 23:00', '2009/9/8 0:00', '2009/9/8 1:00', '2009/9/8 2:00', '2009/9/8 3:00', '2009/9/8 4:00', '2009/9/8 5:00', '2009/9/8 6:00', '2009/9/8 7:00', '2009/9/8 8:00', '2009/9/8 9:00', '2009/9/8 10:00', '2009/9/8 11:00', '2009/9/8 12:00', '2009/9/8 13:00', '2009/9/8 14:00', '2009/9/8 15:00', '2009/9/8 16:00', '2009/9/8 17:00', '2009/9/8 18:00', '2009/9/8 19:00', '2009/9/8 20:00', '2009/9/8 21:00', '2009/9/8 22:00', '2009/9/8 23:00', '2009/9/9 0:00', '2009/9/9 1:00', '2009/9/9 2:00', '2009/9/9 3:00', '2009/9/9 4:00', '2009/9/9 5:00', '2009/9/9 6:00', '2009/9/9 7:00', '2009/9/9 8:00', '2009/9/9 9:00', '2009/9/9 10:00', '2009/9/9 11:00', '2009/9/9 12:00', '2009/9/9 13:00', '2009/9/9 14:00', '2009/9/9 15:00', '2009/9/9 16:00', '2009/9/9 17:00', '2009/9/9 18:00', '2009/9/9 19:00', '2009/9/9 20:00', '2009/9/9 21:00', '2009/9/9 22:00', '2009/9/9 23:00', '2009/9/10 0:00', '2009/9/10 1:00', '2009/9/10 2:00', '2009/9/10 3:00', '2009/9/10 4:00', '2009/9/10 5:00', '2009/9/10 6:00', '2009/9/10 7:00', '2009/9/10 8:00', '2009/9/10 9:00', '2009/9/10 10:00', '2009/9/10 11:00', '2009/9/10 12:00', '2009/9/10 13:00', '2009/9/10 14:00', '2009/9/10 15:00', '2009/9/10 16:00', '2009/9/10 17:00', '2009/9/10 18:00', '2009/9/10 19:00', '2009/9/10 20:00', '2009/9/10 21:00', '2009/9/10 22:00', '2009/9/10 23:00', '2009/9/11 0:00', '2009/9/11 1:00', '2009/9/11 2:00', '2009/9/11 3:00', '2009/9/11 4:00', '2009/9/11 5:00', '2009/9/11 6:00', '2009/9/11 7:00', '2009/9/11 8:00', '2009/9/11 9:00', '2009/9/11 10:00', '2009/9/11 11:00', '2009/9/11 12:00', '2009/9/11 13:00', '2009/9/11 14:00', '2009/9/11 15:00', '2009/9/11 16:00', '2009/9/11 17:00', '2009/9/11 18:00', '2009/9/11 19:00', '2009/9/11 20:00', '2009/9/11 21:00', '2009/9/11 22:00', '2009/9/11 23:00', '2009/9/12 0:00', '2009/9/12 1:00', '2009/9/12 2:00', '2009/9/12 3:00', '2009/9/12 4:00', '2009/9/12 5:00', '2009/9/12 6:00', '2009/9/12 7:00', '2009/9/12 8:00', '2009/9/12 9:00', '2009/9/12 10:00', '2009/9/12 11:00', '2009/9/12 12:00', '2009/9/12 13:00', '2009/9/12 14:00', '2009/9/12 15:00', '2009/9/12 16:00', '2009/9/12 17:00', '2009/9/12 18:00', '2009/9/12 19:00', '2009/9/12 20:00', '2009/9/12 21:00', '2009/9/12 22:00', '2009/9/12 23:00', '2009/9/13 0:00', '2009/9/13 1:00', '2009/9/13 2:00', '2009/9/13 3:00', '2009/9/13 4:00', '2009/9/13 5:00', '2009/9/13 6:00', '2009/9/13 7:00', '2009/9/13 8:00', '2009/9/13 9:00', '2009/9/13 10:00', '2009/9/13 11:00', '2009/9/13 12:00', '2009/9/13 13:00', '2009/9/13 14:00', '2009/9/13 15:00', '2009/9/13 16:00', '2009/9/13 17:00', '2009/9/13 18:00', '2009/9/13 19:00', '2009/9/13 20:00', '2009/9/13 21:00', '2009/9/13 22:00', '2009/9/13 23:00', '2009/9/14 0:00', '2009/9/14 1:00', '2009/9/14 2:00', '2009/9/14 3:00', '2009/9/14 4:00', '2009/9/14 5:00', '2009/9/14 6:00', '2009/9/14 7:00', '2009/9/14 8:00', '2009/9/14 9:00', '2009/9/14 10:00', '2009/9/14 11:00', '2009/9/14 12:00', '2009/9/14 13:00', '2009/9/14 14:00', '2009/9/14 15:00', '2009/9/14 16:00', '2009/9/14 17:00', '2009/9/14 18:00', '2009/9/14 19:00', '2009/9/14 20:00', '2009/9/14 21:00', '2009/9/14 22:00', '2009/9/14 23:00', '2009/9/15 0:00', '2009/9/15 1:00', '2009/9/15 2:00', '2009/9/15 3:00', '2009/9/15 4:00', '2009/9/15 5:00', '2009/9/15 6:00', '2009/9/15 7:00', '2009/9/15 8:00', '2009/9/15 9:00', '2009/9/15 10:00', '2009/9/15 11:00', '2009/9/15 12:00', '2009/9/15 13:00', '2009/9/15 14:00', '2009/9/15 15:00', '2009/9/15 16:00', '2009/9/15 17:00', '2009/9/15 18:00', '2009/9/15 19:00', '2009/9/15 20:00', '2009/9/15 21:00', '2009/9/15 22:00', '2009/9/15 23:00', '2009/9/16 0:00', '2009/9/16 1:00', '2009/9/16 2:00', '2009/9/16 3:00', '2009/9/16 4:00', '2009/9/16 5:00', '2009/9/16 6:00', '2009/9/16 7:00', '2009/9/16 8:00', '2009/9/16 9:00', '2009/9/16 10:00', '2009/9/16 11:00', '2009/9/16 12:00', '2009/9/16 13:00', '2009/9/16 14:00', '2009/9/16 15:00', '2009/9/16 16:00', '2009/9/16 17:00', '2009/9/16 18:00', '2009/9/16 19:00', '2009/9/16 20:00', '2009/9/16 21:00', '2009/9/16 22:00', '2009/9/16 23:00', '2009/9/17 0:00', '2009/9/17 1:00', '2009/9/17 2:00', '2009/9/17 3:00', '2009/9/17 4:00', '2009/9/17 5:00', '2009/9/17 6:00', '2009/9/17 7:00', '2009/9/17 8:00', '2009/9/17 9:00', '2009/9/17 10:00', '2009/9/17 11:00', '2009/9/17 12:00', '2009/9/17 13:00', '2009/9/17 14:00', '2009/9/17 15:00', '2009/9/17 16:00', '2009/9/17 17:00', '2009/9/17 18:00', '2009/9/17 19:00', '2009/9/17 20:00', '2009/9/17 21:00', '2009/9/17 22:00', '2009/9/17 23:00', '2009/9/18 0:00', '2009/9/18 1:00', '2009/9/18 2:00', '2009/9/18 3:00', '2009/9/18 4:00', '2009/9/18 5:00', '2009/9/18 6:00', '2009/9/18 7:00', '2009/9/18 8:00', '2009/9/18 9:00', '2009/9/18 10:00', '2009/9/18 11:00', '2009/9/18 12:00', '2009/9/18 13:00', '2009/9/18 14:00', '2009/9/18 15:00', '2009/9/18 16:00', '2009/9/18 17:00', '2009/9/18 18:00', '2009/9/18 19:00', '2009/9/18 20:00', '2009/9/18 21:00', '2009/9/18 22:00', '2009/9/18 23:00', '2009/9/19 0:00', '2009/9/19 1:00', '2009/9/19 2:00', '2009/9/19 3:00', '2009/9/19 4:00', '2009/9/19 5:00', '2009/9/19 6:00', '2009/9/19 7:00', '2009/9/19 8:00', '2009/9/19 9:00', '2009/9/19 10:00', '2009/9/19 11:00', '2009/9/19 12:00', '2009/9/19 13:00', '2009/9/19 14:00', '2009/9/19 15:00', '2009/9/19 16:00', '2009/9/19 17:00', '2009/9/19 18:00', '2009/9/19 19:00', '2009/9/19 20:00', '2009/9/19 21:00', '2009/9/19 22:00', '2009/9/19 23:00', '2009/9/20 0:00', '2009/9/20 1:00', '2009/9/20 2:00', '2009/9/20 3:00', '2009/9/20 4:00', '2009/9/20 5:00', '2009/9/20 6:00', '2009/9/20 7:00', '2009/9/20 8:00', '2009/9/20 9:00', '2009/9/20 10:00', '2009/9/20 11:00', '2009/9/20 12:00', '2009/9/20 13:00', '2009/9/20 14:00', '2009/9/20 15:00', '2009/9/20 16:00', '2009/9/20 17:00', '2009/9/20 18:00', '2009/9/20 19:00', '2009/9/20 20:00', '2009/9/20 21:00', '2009/9/20 22:00', '2009/9/20 23:00', '2009/9/21 0:00', '2009/9/21 1:00', '2009/9/21 2:00', '2009/9/21 3:00', '2009/9/21 4:00', '2009/9/21 5:00', '2009/9/21 6:00', '2009/9/21 7:00', '2009/9/21 8:00', '2009/9/21 9:00', '2009/9/21 10:00', '2009/9/21 11:00', '2009/9/21 12:00', '2009/9/21 13:00', '2009/9/21 14:00', '2009/9/21 15:00', '2009/9/21 16:00', '2009/9/21 17:00', '2009/9/21 18:00', '2009/9/21 19:00', '2009/9/21 20:00', '2009/9/21 21:00', '2009/9/21 22:00', '2009/9/21 23:00', '2009/9/22 0:00', '2009/9/22 1:00', '2009/9/22 2:00', '2009/9/22 3:00', '2009/9/22 4:00', '2009/9/22 5:00', '2009/9/22 6:00', '2009/9/22 7:00', '2009/9/22 8:00', '2009/9/22 9:00', '2009/9/22 10:00', '2009/9/22 11:00', '2009/9/22 12:00', '2009/9/22 13:00', '2009/9/22 14:00', '2009/9/22 15:00', '2009/9/22 16:00', '2009/9/22 17:00', '2009/9/22 18:00', '2009/9/22 19:00', '2009/9/22 20:00', '2009/9/22 21:00', '2009/9/22 22:00', '2009/9/22 23:00', '2009/9/23 0:00', '2009/9/23 1:00', '2009/9/23 2:00', '2009/9/23 3:00', '2009/9/23 4:00', '2009/9/23 5:00', '2009/9/23 6:00', '2009/9/23 7:00', '2009/9/23 8:00', '2009/9/23 9:00', '2009/9/23 10:00', '2009/9/23 11:00', '2009/9/23 12:00', '2009/9/23 13:00', '2009/9/23 14:00', '2009/9/23 15:00', '2009/9/23 16:00', '2009/9/23 17:00', '2009/9/23 18:00', '2009/9/23 19:00', '2009/9/23 20:00', '2009/9/23 21:00', '2009/9/23 22:00', '2009/9/23 23:00', '2009/9/24 0:00', '2009/9/24 1:00', '2009/9/24 2:00', '2009/9/24 3:00', '2009/9/24 4:00', '2009/9/24 5:00', '2009/9/24 6:00', '2009/9/24 7:00', '2009/9/24 8:00', '2009/9/24 9:00', '2009/9/24 10:00', '2009/9/24 11:00', '2009/9/24 12:00', '2009/9/24 13:00', '2009/9/24 14:00', '2009/9/24 15:00', '2009/9/24 16:00', '2009/9/24 17:00', '2009/9/24 18:00', '2009/9/24 19:00', '2009/9/24 20:00', '2009/9/24 21:00', '2009/9/24 22:00', '2009/9/24 23:00', '2009/9/25 0:00', '2009/9/25 1:00', '2009/9/25 2:00', '2009/9/25 3:00', '2009/9/25 4:00', '2009/9/25 5:00', '2009/9/25 6:00', '2009/9/25 7:00', '2009/9/25 8:00', '2009/9/25 9:00', '2009/9/25 10:00', '2009/9/25 11:00', '2009/9/25 12:00', '2009/9/25 13:00', '2009/9/25 14:00', '2009/9/25 15:00', '2009/9/25 16:00', '2009/9/25 17:00', '2009/9/25 18:00', '2009/9/25 19:00', '2009/9/25 20:00', '2009/9/25 21:00', '2009/9/25 22:00', '2009/9/25 23:00', '2009/9/26 0:00', '2009/9/26 1:00', '2009/9/26 2:00', '2009/9/26 3:00', '2009/9/26 4:00', '2009/9/26 5:00', '2009/9/26 6:00', '2009/9/26 7:00', '2009/9/26 8:00', '2009/9/26 9:00', '2009/9/26 10:00', '2009/9/26 11:00', '2009/9/26 12:00', '2009/9/26 13:00', '2009/9/26 14:00', '2009/9/26 15:00', '2009/9/26 16:00', '2009/9/26 17:00', '2009/9/26 18:00', '2009/9/26 19:00', '2009/9/26 20:00', '2009/9/26 21:00', '2009/9/26 22:00', '2009/9/26 23:00', '2009/9/27 0:00', '2009/9/27 1:00', '2009/9/27 2:00', '2009/9/27 3:00', '2009/9/27 4:00', '2009/9/27 5:00', '2009/9/27 6:00', '2009/9/27 7:00', '2009/9/27 8:00', '2009/9/27 9:00', '2009/9/27 10:00', '2009/9/27 11:00', '2009/9/27 12:00', '2009/9/27 13:00', '2009/9/27 14:00', '2009/9/27 15:00', '2009/9/27 16:00', '2009/9/27 17:00', '2009/9/27 18:00', '2009/9/27 19:00', '2009/9/27 20:00', '2009/9/27 21:00', '2009/9/27 22:00', '2009/9/27 23:00', '2009/9/28 0:00', '2009/9/28 1:00', '2009/9/28 2:00', '2009/9/28 3:00', '2009/9/28 4:00', '2009/9/28 5:00', '2009/9/28 6:00', '2009/9/28 7:00', '2009/9/28 8:00', '2009/9/28 9:00', '2009/9/28 10:00', '2009/9/28 11:00', '2009/9/28 12:00', '2009/9/28 13:00', '2009/9/28 14:00', '2009/9/28 15:00', '2009/9/28 16:00', '2009/9/28 17:00', '2009/9/28 18:00', '2009/9/28 19:00', '2009/9/28 20:00', '2009/9/28 21:00', '2009/9/28 22:00', '2009/9/28 23:00', '2009/9/29 0:00', '2009/9/29 1:00', '2009/9/29 2:00', '2009/9/29 3:00', '2009/9/29 4:00', '2009/9/29 5:00', '2009/9/29 6:00', '2009/9/29 7:00', '2009/9/29 8:00', '2009/9/29 9:00', '2009/9/29 10:00', '2009/9/29 11:00', '2009/9/29 12:00', '2009/9/29 13:00', '2009/9/29 14:00', '2009/9/29 15:00', '2009/9/29 16:00', '2009/9/29 17:00', '2009/9/29 18:00', '2009/9/29 19:00', '2009/9/29 20:00', '2009/9/29 21:00', '2009/9/29 22:00', '2009/9/29 23:00', '2009/9/30 0:00', '2009/9/30 1:00', '2009/9/30 2:00', '2009/9/30 3:00', '2009/9/30 4:00', '2009/9/30 5:00', '2009/9/30 6:00', '2009/9/30 7:00', '2009/9/30 8:00', '2009/9/30 9:00', '2009/9/30 10:00', '2009/9/30 11:00', '2009/9/30 12:00', '2009/9/30 13:00', '2009/9/30 14:00', '2009/9/30 15:00', '2009/9/30 16:00', '2009/9/30 17:00', '2009/9/30 18:00', '2009/9/30 19:00', '2009/9/30 20:00', '2009/9/30 21:00', '2009/9/30 22:00', '2009/9/30 23:00',
'2009/10/1 0:00', '2009/10/1 1:00', '2009/10/1 2:00', '2009/10/1 3:00', '2009/10/1 4:00', '2009/10/1 5:00', '2009/10/1 6:00', '2009/10/1 7:00', '2009/10/1 8:00', '2009/10/1 9:00', '2009/10/1 10:00', '2009/10/1 11:00', '2009/10/1 12:00', '2009/10/1 13:00', '2009/10/1 14:00', '2009/10/1 15:00', '2009/10/1 16:00', '2009/10/1 17:00', '2009/10/1 18:00', '2009/10/1 19:00', '2009/10/1 20:00', '2009/10/1 21:00', '2009/10/1 22:00', '2009/10/1 23:00', '2009/10/2 0:00', '2009/10/2 1:00', '2009/10/2 2:00', '2009/10/2 3:00', '2009/10/2 4:00', '2009/10/2 5:00', '2009/10/2 6:00', '2009/10/2 7:00', '2009/10/2 8:00', '2009/10/2 9:00', '2009/10/2 10:00', '2009/10/2 11:00', '2009/10/2 12:00', '2009/10/2 13:00', '2009/10/2 14:00', '2009/10/2 15:00', '2009/10/2 16:00', '2009/10/2 17:00', '2009/10/2 18:00', '2009/10/2 19:00', '2009/10/2 20:00', '2009/10/2 21:00', '2009/10/2 22:00', '2009/10/2 23:00', '2009/10/3 0:00', '2009/10/3 1:00', '2009/10/3 2:00', '2009/10/3 3:00', '2009/10/3 4:00', '2009/10/3 5:00', '2009/10/3 6:00', '2009/10/3 7:00', '2009/10/3 8:00', '2009/10/3 9:00', '2009/10/3 10:00', '2009/10/3 11:00', '2009/10/3 12:00', '2009/10/3 13:00', '2009/10/3 14:00', '2009/10/3 15:00', '2009/10/3 16:00', '2009/10/3 17:00', '2009/10/3 18:00', '2009/10/3 19:00', '2009/10/3 20:00', '2009/10/3 21:00', '2009/10/3 22:00', '2009/10/3 23:00', '2009/10/4 0:00', '2009/10/4 1:00', '2009/10/4 2:00', '2009/10/4 3:00', '2009/10/4 4:00', '2009/10/4 5:00', '2009/10/4 6:00', '2009/10/4 7:00', '2009/10/4 8:00', '2009/10/4 9:00', '2009/10/4 10:00', '2009/10/4 11:00', '2009/10/4 12:00', '2009/10/4 13:00', '2009/10/4 14:00', '2009/10/4 15:00', '2009/10/4 16:00', '2009/10/4 17:00', '2009/10/4 18:00', '2009/10/4 19:00', '2009/10/4 20:00', '2009/10/4 21:00', '2009/10/4 22:00', '2009/10/4 23:00', '2009/10/5 0:00', '2009/10/5 1:00', '2009/10/5 2:00', '2009/10/5 3:00', '2009/10/5 4:00', '2009/10/5 5:00', '2009/10/5 6:00', '2009/10/5 7:00', '2009/10/5 8:00', '2009/10/5 9:00', '2009/10/5 10:00', '2009/10/5 11:00', '2009/10/5 12:00', '2009/10/5 13:00', '2009/10/5 14:00', '2009/10/5 15:00', '2009/10/5 16:00', '2009/10/5 17:00', '2009/10/5 18:00', '2009/10/5 19:00', '2009/10/5 20:00', '2009/10/5 21:00', '2009/10/5 22:00', '2009/10/5 23:00', '2009/10/6 0:00', '2009/10/6 1:00', '2009/10/6 2:00', '2009/10/6 3:00', '2009/10/6 4:00', '2009/10/6 5:00', '2009/10/6 6:00', '2009/10/6 7:00', '2009/10/6 8:00', '2009/10/6 9:00', '2009/10/6 10:00', '2009/10/6 11:00', '2009/10/6 12:00', '2009/10/6 13:00', '2009/10/6 14:00', '2009/10/6 15:00', '2009/10/6 16:00', '2009/10/6 17:00', '2009/10/6 18:00', '2009/10/6 19:00', '2009/10/6 20:00', '2009/10/6 21:00', '2009/10/6 22:00', '2009/10/6 23:00', '2009/10/7 0:00', '2009/10/7 1:00', '2009/10/7 2:00', '2009/10/7 3:00', '2009/10/7 4:00', '2009/10/7 5:00', '2009/10/7 6:00', '2009/10/7 7:00', '2009/10/7 8:00', '2009/10/7 9:00', '2009/10/7 10:00', '2009/10/7 11:00', '2009/10/7 12:00', '2009/10/7 13:00', '2009/10/7 14:00', '2009/10/7 15:00', '2009/10/7 16:00', '2009/10/7 17:00', '2009/10/7 18:00', '2009/10/7 19:00', '2009/10/7 20:00', '2009/10/7 21:00', '2009/10/7 22:00', '2009/10/7 23:00', '2009/10/8 0:00', '2009/10/8 1:00', '2009/10/8 2:00', '2009/10/8 3:00', '2009/10/8 4:00', '2009/10/8 5:00', '2009/10/8 6:00', '2009/10/8 7:00', '2009/10/8 8:00', '2009/10/8 9:00', '2009/10/8 10:00', '2009/10/8 11:00', '2009/10/8 12:00', '2009/10/8 13:00', '2009/10/8 14:00', '2009/10/8 15:00', '2009/10/8 16:00', '2009/10/8 17:00', '2009/10/8 18:00', '2009/10/8 19:00', '2009/10/8 20:00', '2009/10/8 21:00', '2009/10/8 22:00', '2009/10/8 23:00', '2009/10/9 0:00', '2009/10/9 1:00', '2009/10/9 2:00', '2009/10/9 3:00', '2009/10/9 4:00', '2009/10/9 5:00', '2009/10/9 6:00', '2009/10/9 7:00', '2009/10/9 8:00', '2009/10/9 9:00', '2009/10/9 10:00', '2009/10/9 11:00', '2009/10/9 12:00', '2009/10/9 13:00', '2009/10/9 14:00', '2009/10/9 15:00', '2009/10/9 16:00', '2009/10/9 17:00', '2009/10/9 18:00', '2009/10/9 19:00', '2009/10/9 20:00', '2009/10/9 21:00', '2009/10/9 22:00', '2009/10/9 23:00', '2009/10/10 0:00', '2009/10/10 1:00', '2009/10/10 2:00', '2009/10/10 3:00', '2009/10/10 4:00', '2009/10/10 5:00', '2009/10/10 6:00', '2009/10/10 7:00', '2009/10/10 8:00', '2009/10/10 9:00', '2009/10/10 10:00', '2009/10/10 11:00', '2009/10/10 12:00', '2009/10/10 13:00', '2009/10/10 14:00', '2009/10/10 15:00', '2009/10/10 16:00', '2009/10/10 17:00', '2009/10/10 18:00', '2009/10/10 19:00', '2009/10/10 20:00', '2009/10/10 21:00', '2009/10/10 22:00', '2009/10/10 23:00', '2009/10/11 0:00', '2009/10/11 1:00', '2009/10/11 2:00', '2009/10/11 3:00', '2009/10/11 4:00', '2009/10/11 5:00', '2009/10/11 6:00', '2009/10/11 7:00', '2009/10/11 8:00', '2009/10/11 9:00', '2009/10/11 10:00', '2009/10/11 11:00', '2009/10/11 12:00', '2009/10/11 13:00', '2009/10/11 14:00', '2009/10/11 15:00', '2009/10/11 16:00', '2009/10/11 17:00', '2009/10/11 18:00', '2009/10/11 19:00', '2009/10/11 20:00', '2009/10/11 21:00', '2009/10/11 22:00', '2009/10/11 23:00', '2009/10/12 0:00', '2009/10/12 1:00', '2009/10/12 2:00', '2009/10/12 3:00', '2009/10/12 4:00', '2009/10/12 5:00', '2009/10/12 6:00', '2009/10/12 7:00', '2009/10/12 8:00', '2009/10/12 9:00', '2009/10/12 10:00', '2009/10/12 11:00', '2009/10/12 12:00', '2009/10/12 13:00', '2009/10/12 14:00', '2009/10/12 15:00', '2009/10/12 16:00', '2009/10/12 17:00', '2009/10/12 18:00', '2009/10/12 19:00', '2009/10/12 20:00', '2009/10/12 21:00', '2009/10/12 22:00', '2009/10/12 23:00', '2009/10/13 0:00', '2009/10/13 1:00', '2009/10/13 2:00', '2009/10/13 3:00', '2009/10/13 4:00', '2009/10/13 5:00', '2009/10/13 6:00', '2009/10/13 7:00', '2009/10/13 8:00', '2009/10/13 9:00', '2009/10/13 10:00', '2009/10/13 11:00', '2009/10/13 12:00', '2009/10/13 13:00', '2009/10/13 14:00', '2009/10/13 15:00', '2009/10/13 16:00', '2009/10/13 17:00', '2009/10/13 18:00', '2009/10/13 19:00', '2009/10/13 20:00', '2009/10/13 21:00', '2009/10/13 22:00', '2009/10/13 23:00', '2009/10/14 0:00', '2009/10/14 1:00', '2009/10/14 2:00', '2009/10/14 3:00', '2009/10/14 4:00', '2009/10/14 5:00', '2009/10/14 6:00', '2009/10/14 7:00', '2009/10/14 8:00', '2009/10/14 9:00', '2009/10/14 10:00', '2009/10/14 11:00', '2009/10/14 12:00', '2009/10/14 13:00', '2009/10/14 14:00', '2009/10/14 15:00', '2009/10/14 16:00', '2009/10/14 17:00', '2009/10/14 18:00', '2009/10/14 19:00', '2009/10/14 20:00', '2009/10/14 21:00', '2009/10/14 22:00', '2009/10/14 23:00', '2009/10/15 0:00', '2009/10/15 1:00', '2009/10/15 2:00', '2009/10/15 3:00', '2009/10/15 4:00', '2009/10/15 5:00', '2009/10/15 6:00', '2009/10/15 7:00', '2009/10/15 8:00', '2009/10/15 9:00', '2009/10/15 10:00', '2009/10/15 11:00', '2009/10/15 12:00', '2009/10/15 13:00', '2009/10/15 14:00', '2009/10/15 15:00', '2009/10/15 16:00', '2009/10/15 17:00', '2009/10/15 18:00', '2009/10/15 19:00', '2009/10/15 20:00', '2009/10/15 21:00', '2009/10/15 22:00', '2009/10/15 23:00', '2009/10/16 0:00', '2009/10/16 1:00', '2009/10/16 2:00', '2009/10/16 3:00', '2009/10/16 4:00', '2009/10/16 5:00', '2009/10/16 6:00', '2009/10/16 7:00', '2009/10/16 8:00', '2009/10/16 9:00', '2009/10/16 10:00', '2009/10/16 11:00', '2009/10/16 12:00', '2009/10/16 13:00', '2009/10/16 14:00', '2009/10/16 15:00', '2009/10/16 16:00', '2009/10/16 17:00', '2009/10/16 18:00', '2009/10/16 19:00', '2009/10/16 20:00', '2009/10/16 21:00', '2009/10/16 22:00', '2009/10/16 23:00', '2009/10/17 0:00', '2009/10/17 1:00', '2009/10/17 2:00', '2009/10/17 3:00', '2009/10/17 4:00', '2009/10/17 5:00', '2009/10/17 6:00', '2009/10/17 7:00', '2009/10/17 8:00', '2009/10/17 9:00', '2009/10/17 10:00', '2009/10/17 11:00', '2009/10/17 12:00', '2009/10/17 13:00', '2009/10/17 14:00', '2009/10/17 15:00', '2009/10/17 16:00', '2009/10/17 17:00', '2009/10/17 18:00', '2009/10/17 19:00', '2009/10/17 20:00', '2009/10/17 21:00', '2009/10/17 22:00', '2009/10/17 23:00', '2009/10/18 0:00', '2009/10/18 1:00', '2009/10/18 2:00', '2009/10/18 3:00', '2009/10/18 4:00', '2009/10/18 5:00', '2009/10/18 6:00', '2009/10/18 7:00', '2009/10/18 8:00'
]
}
],
yAxis : [
{
name : '流量(m^3/s)',
type : 'value',
max : 500
},
{
name : '降雨量(mm)',
type : 'value',
inverse: true
}
],
series : [
{
name:'流量',
type:'line',
notShowSymbol: true,
sampling: sampling,
hoverAnimation: false,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
markArea: {
silent: true,
data: [[{
// name: 'a',
xAxis: '2009/10/2 7:00'
// xAxis: 1
}, {
// name: 'b',
xAxis: '2009/10/12 7:00'
// xAxis: 5
}]]
},
data:[
0.97,0.96,0.96,0.95,0.95,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.93,0.92,0.91,0.9,0.89,0.88,0.87,0.87,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.87,0.88,0.9,0.93,0.96,0.99,1.03,1.06,1.1,1.14,1.17,1.2,1.23,1.26,1.29,1.33,1.36,1.4,1.43,1.45,1.48,1.49,1.51,1.51,1.5,1.49,1.47,1.44,1.41,1.37,1.34,1.3,1.27,1.24,1.22,1.2,1.19,1.18,1.16,1.15,1.14,1.13,1.12,1.11,1.11,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.09,1.09,1.08,1.07,1.06,1.05,1.04,1.03,1.03,1.02,1.01,1.01,1,0.99,0.98,0.97,0.96,0.96,0.95,0.95,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.93,0.92,0.91,0.9,0.89,0.88,0.87,0.87,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.85,0.84,0.83,0.82,0.81,0.8,0.8,0.79,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.77,0.75,0.73,0.71,0.68,0.65,0.63,0.61,0.59,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.57,0.57,0.57,0.56,0.55,0.55,0.54,0.54,0.53,0.52,0.52,0.51,0.51,0.5,0.5,0.49,0.48,0.48,0.47,0.47,0.47,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.46,0.52,0.67,0.9,1.19,1.52,1.87,2.22,2.55,2.84,3.07,3.22,3.28,3.28,3.28,3.28,3.28,3.28,3.28,3.28,3.28,3.28,3.28,3.28,3.28,3.24,3.13,2.97,2.77,2.54,2.3,2.05,1.82,1.62,1.46,1.35,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.31,1.3,1.26,1.21,1.14,1.06,0.97,0.89,0.81,0.74,0.69,0.65,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.63,0.63,0.62,0.62,0.61,0.6,0.59,0.59,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.59,0.61,0.63,0.65,0.68,0.71,0.73,0.75,0.77,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.77,0.75,0.73,0.71,0.68,0.65,0.63,0.61,0.59,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.58,0.59,0.59,0.6,0.61,0.62,0.62,0.63,0.63,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.65,0.66,0.68,0.69,0.71,0.73,0.74,0.76,0.77,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.79,0.81,0.82,0.84,0.86,0.88,0.9,0.92,0.93,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.94,0.93,0.92,0.91,0.9,0.89,0.88,0.87,0.87,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.86,0.85,0.84,0.82,0.8,0.78,0.76,0.75,0.73,0.72,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.72,0.73,0.74,0.76,0.78,0.79,0.82,0.84,0.86,0.89,0.91,0.94,0.97,1,1.02,1.05,1.08,1.11,1.14,1.17,1.19,1.22,1.25,1.27,1.29,1.31,1.33,1.35,1.36,1.38,1.39,1.39,1.4,1.4,1.4,1.39,1.37,1.35,1.32,1.29,1.26,1.22,1.18,1.14,1.1,1.05,1.01,0.97,0.93,0.89,0.85,0.82,0.78,0.76,0.74,0.72,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.72,0.73,0.74,0.75,0.77,0.78,0.8,0.82,0.84,0.87,0.89,0.92,0.94,0.97,0.99,1.02,1.05,1.08,1.1,1.13,1.16,1.18,1.21,1.23,1.26,1.28,1.3,1.32,1.34,1.35,1.37,1.38,1.39,1.4,1.41,1.41,1.42,1.42,1.43,1.43,1.43,1.44,1.44,1.44,1.44,1.45,1.45,1.45,1.46,1.46,1.46,1.47,1.47,1.48,1.48,1.49,1.5,1.51,1.54,1.62,1.73,1.88,2.05,2.24,2.45,2.67,2.89,3.11,3.31,3.51,3.69,3.86,4.03,4.18,4.33,4.48,4.62,4.76,4.89,5.02,5.16,5.29,5.43,5.57,5.71,5.86,6.02,6.18,6.36,6.54,6.73,6.93,7.15,7.38,7.62,7.88,8.16,8.46,8.77,9.11,9.46,9.84,10.24,10.67,11.12,11.6,12.3,13.66,16,38.43,82.21,146.6,218.7,226,225.23,223.08,219.78,212,199.82,184.6,168,151.65,137.21,126.31,119.94,115.52,112.06,108.92,105.44,101,94.56,86.36,77.67,69.76,63.9,60.38,57.41,54.84,52.57,50.56,48.71,46.97,45.25,43.48,41.6,39.5,37.19,34.81,32.46,30.27,28.36,26.85,25.86,25.5,25.5,25.5,25.5,25.5,25.5,25.5,25.5,25.5,25.5,25.5,25.5,25.5,25.27,24.65,23.7,22.52,21.17,19.75,18.33,16.98,15.8,14.85,14.23,14,14.02,14.08,14.17,14.29,14.44,14.61,14.8,15.01,15.23,15.47,15.71,15.95,16.19,16.43,16.67,16.89,17.1,17.29,17.46,17.61,17.73,17.82,17.88,17.9,17.63,16.88,15.75,14.33,12.71,10.98,9.23,7.56,6.05,4.81,3.92,3.47,3.28,3.1,2.93,2.76,2.61,2.46,2.32,2.19,2.07,1.96,1.85,1.75,1.66,1.58,1.51,1.44,1.39,1.34,1.29,1.26,1.23,1.22,1.2,1.2,1.2,1.2,1.2,1.2,1.21,1.21,1.21,1.21,1.22,1.22,1.22,1.23,1.23,1.23,1.24,1.24,1.25,1.25,1.25,1.26,1.26,1.27,1.27,1.27,1.28,1.28,1.28,1.29,1.29,1.29,1.29,1.3,1.3,1.3,1.3,1.3,1.3,1.3,1.3,1.3,1.3,1.3,1.29,1.29,1.29,1.29,1.28,1.28,1.28,1.27,1.27,1.26,1.25,1.25,1.24,1.23,1.23,1.22,1.21,1.2,1.16,1.06,0.95,0.83,0.74,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.71,0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.69,0.69,0.69,0.69,0.69,0.69,0.69,0.69,0.68,0.68,0.68,0.68,0.68,0.68,0.67,0.67,0.67,0.67,0.67,0.67,0.67,0.66,0.66,0.66,0.66,0.66,0.66,0.66,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.65,0.66,0.68,0.69,0.71,0.73,0.74,0.76,0.77,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.78,0.8,0.86,0.95,1.08,1.25,1.46,1.7,1.97,2.28,2.63,3.01,3.42,3.87,4.35,4.86,5.4,5.98,6.59,7.92,10.49,14.04,18.31,23.04,27.98,32.87,37.45,41.46,44.64,46.74,47.5,46.86,45.16,42.77,40.04,37.33,35,32.74,30.21,27.7,25.5,23.9,23.2,23.06,22.94,22.84,22.77,22.72,22.7,22.8,23.23,23.95,24.91,26.04,27.3,28.76,30.7,33.39,37.12,42.15,48.77,65.22,252.1,257,237.32,221.19,212,208.67,206.89,205.2,202.15,189.82,172,165.3,160.49,156.8,153.44,149.62,144.6,138.27,131,123.11,114.9,106.69,98.79,91.5,85.13,80,75.53,71.03,66.65,62.54,58.85,55.73,53.31,51.75,51.2,56.53,68.25,80,91.01,102.03,109,112.37,115.29,117.68,119.48,120.61,121,119.45,115.57,110.52,105.47,101.58,100,99.97,99.94,99.92,99.9,99.88,99.86,99.85,99.84,99.83,99.82,99.81,99.81,99.8,99.8,99.8,122.15,163.65,186,182.96,175.15,164.56,153.18,143,136,131.37,126.98,122.81,118.85,115.09,111.52,108.13,104.9,101.83,98.9,96.11,93.44,90.87,88.41,86.04,83.74,81.51,79.33,77.2,75.1,73.02,70.95,68.88,66.8,64.87,63.14,61.4,59.53,57.67,56,54.6,53.36,52.2,51.05,49.85,48.5,46.87,44.92,42.74,40.42,38.04,35.69,33.46,31.44,29.72,28.38,27.51,27.2,27.2,27.2,27.2,27.2,27.2,27.2,27.2,27.2,27.2,27.2,27.2,27.2,27.14,26.97,26.7,26.35,25.95,25.49,25.02,24.53,24.04,23.58,23.16,22.8,22.46,22.11,21.75,21.39,21.03,20.69,20.36,20.05,19.78,19.54,19.35,19.2,19.09,19,18.92,18.85,18.79,18.74,18.68,18.62,18.56,18.49,18.4,18.3,18.17,18.02,17.83,17.63,17.41,17.18,16.93,16.68,16.43,16.18,15.93,15.7,15.47,15.22,14.97,14.71,14.45,14.18,13.93,13.68,13.44,13.21,13,12.8,12.62,12.46,12.31,12.16,12.03,11.89,11.76,11.62,11.48,11.33,11.17,11,10.81,10.59,10.36,10.12,9.86,9.61,9.36,9.12,8.89,8.68,8.5,8.35,8.21,8.08,7.94,7.81,7.68,7.56,7.46,7.36,7.29,7.23,7.19,7.18,7.51,8.42,9.81,11.58,13.63,15.86,18.16,20.44,22.58,24.49,26.06,27.2,28.08,28.95,29.81,30.65,31.48,32.28,33.07,33.82,34.55,35.25,35.92,36.56,37.15,37.71,38.23,38.7,39.13,39.5,39.83,40.1,40.31,40.47,40.57,40.6,40.49,40.16,39.64,38.94,38.09,37.1,36,34.79,33.51,32.17,30.79,29.39,27.99,26.6,25.25,23.96,22.75,21.63,20.63,19.76,19.04,18.49,18.14,18,17.97,17.95,17.94,17.92,17.91,17.9,17.89,17.88,17.87,17.85,17.83,17.8,17.7,17.46,17.13,16.7,16.21,15.68,15.13,14.57,14.04,13.56,13.14,12.8,12.52,12.27,12.02,11.79,11.57,11.37,11.16,10.97,10.78,10.59,10.39,10.2,10.01,9.81,9.63,9.44,9.26,9.08,8.9,8.73,8.56,8.39,8.22,8.06,7.9,7.73,7.57,7.41,7.25,7.09,6.94,6.79,6.65,6.52,6.4,6.28,6.17,6.08,5.98,5.9,5.81,5.73,5.65,5.57,5.49,5.41,5.32,5.23,5.14,5.04,4.94,4.84,4.74,4.63,4.53,4.43,4.33,4.23,4.13,4.03,3.93,3.81,3.69,3.57,3.45,3.33,3.22,3.12,3.04,2.98,2.93,2.92,2.92,2.92,2.92,2.92,2.92,2.92,2.92,2.92,2.92,2.92,2.92,2.92,2.9,2.86,2.8,2.71,2.62,2.52,2.42,2.33,2.24,2.18,2.14,2.12,2.12,2.12,2.12,2.12,2.12,2.12,2.12,2.12,2.12,2.12,2.12,2.12,2.1,2.06,2,1.91,1.82,1.71,1.61,1.5,1.4,1.32,1.25,1.2,1.16,1.13,1.1,1.06,1.03,1,0.97,0.93,0.9,0.87,0.85,0.82,0.79,0.77,0.74,0.72,0.69,0.67,0.65,0.63,0.61,0.59,0.58,0.56,0.54,0.53,0.52,0.51,0.5,0.49,0.48,0.48,0.47,0.47,0.46,0.46,0.47,0.48,0.5,0.53,0.56,0.59,0.62,0.64,0.67,0.69,0.7,0.71,0.71,0.71,0.71,0.7,0.7,0.7,0.69,0.69,0.69,0.68,0.68,0.67,0.67,0.67,0.66,0.66,0.65,0.65,0.65,0.65,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.64,0.65,0.65,0.65,0.66,0.66,0.67,0.68,0.69,0.69,0.7,0.71,0.73,0.74,0.75,0.76,0.78,0.8,0.81,0.83,0.85,0.87,0.89,0.92,0.94,0.97,0.99,1.02,1.05,1.08,1.11,1.15,1.18,1.32,1.66,2.21,2.97,3.94,5.11,6.5,8.1,9.9,11.92,14.15,16.6,22.3,22.8,24.48,30.38,35.74,42.4,57.14,94.04,112.9,123.4,130.4,130,119.4,120.7,116.8,118.1,119.4,124.8,143.5,204,294,319.2,328.4,365,350.8,347.6,347.6,325,331.6,319.2,308,308,308,308,296.8,300,281,278.4,270.6,271,253.6,233.5,219.2,207.8,205.9,204,189.6,178.8,173.4,160,154.4,146,145,140.5,130.4,126.2,116.8,112.9,106.5,101.6,98.51,82.67,67.3,80.05,76.12,72.3,71.02,69.78,67.3,67.3,68.54,57.6,71.02,66.06,59.12,57.14,55.16,55.16,52.19,52.19,51.2,48.56,44.16,43,45.92,49.44,44.16,36.48,35.74,35,32.36,37.22,32.36,32.36,32.36,33.68,32.36,31.7,35.74,29.72,32.36,30.38,29.72,28.4,28.4,28.4,27.28,25.6,25.04,23.92,22.3,21.8,21.8,21.8,22.8,21.8,25.6,22.8,22.8,17.8,16.04,16.04,16.04,16.04,16.04,16.04,16.04,16.04,16.04,16.04,15.02,14,14.03,14.11,14.25,14.45,14.72,15.06,15.46,15.95,16.51,17.15,17.87,18.69,19.59,20.59,21.69,22.88,24.18,25.59,27.1,28.73,30.48,32.34,34.33,36.44,38.69,41.06,43.57,46.22,49.01,51.95,55.04,58.27,61.66,65.21,68.92,72.8,88.09,104.9,105.7,110.3,111.6,110.3,106.5,105.7,103.3,100,97.02,98.8,91.07,83.98,88.09,81.36,78.74,77.43,77.43,73.5,74.81,72.63,68.58,66.4,68.54,69.78,67.3,64.82,61.1,59.12,56.15,53.18,50.32,49.44,44.16,36.5,42.4,37.96,37.22,33.68,36.48,35.74,35,35,37.22,37.22,39.44,32.6,34.54,36.48,35.74,34.34,33.68,33.02,31.04,29.72,29.72,29.72,26.16,25.6,29.72,18.3,22.3,21.3,21.8,21.8,20.3,20.8,25.04,25.04,25.6,25.6,25.04,25.6,25.04,25.6,23.92,25.04,21.3,21.8,22.3,21.8,20.8,16.1,20.3,18.3,13.22,19.3,19.3,18.3,14.4,13.86,13.36,12.9,12.48,12.1,11.75,11.43,11.15,10.9,10.67,10.48,10.31,10.16,10.04,9.93,9.85,9.78,9.73,9.69,9.67,9.65,9.65,12.08,8.67,11.7,11.38,10.65,9.84,9.32,9.07,8.85,8.66,8.49,8.35,8.22,8.1,7.98,7.86,7.74,7.61,7.47,7.31,7.14,6.96,6.78,6.58,6.39,6.19,5.99,5.78,5.58,5.39,5.2,5.01,4.83,4.67,4.51,4.37,4.24,4.12,4.02,3.95,3.89,3.85,3.84,4.41,5.77,7.39,8.75,9.32,9.18,9,8.94,8.88,8.83,8.78,8.73,8.68,8.64,8.6,8.56,8.53,8.5,8.47,8.45,8.42,8.4,8.39,8.37,8.36,8.35,8.35,8.34,8.34,8.67,9.65,9.62,9.53,9.4,9.21,8.98,8.7,8.4,8.06,7.69,7.3,6.89,6.47,6.03,5.59,5.14,4.7,4.26,3.83,3.42,3.02,2.65,2.3,1.98,1.7,1.45,1.25,1.09,0.99,0.94,0.92,0.91,0.89,0.87,0.85,0.84,0.82,0.81,0.79,0.78,0.77,0.75,0.74,0.73,0.72,0.71,0.7,0.69,0.68,0.67,0.66,0.65,0.64,0.64,0.63,0.63,0.62,0.62,0.61,0.61,0.61,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.6,0.61,0.61,0.61,0.61,0.61,0.61,0.62,0.62,0.62,0.62,0.63,0.63,0.63,0.63,0.63,0.64,0.64,0.64,0.64,0.64,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.65,0.64,0.63,0.62,0.6,0.59,0.57,0.55,0.54,0.53,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.51,0.51,0.51,0.5,0.5,0.49,0.48,0.47,0.47,0.46,0.45,0.45,0.44,0.43,0.42,0.42,0.41,0.41,0.41,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.41,0.42,0.43,0.44,0.46,0.48,0.5,0.53,0.55,0.58,0.61,0.64,0.67,0.7,0.73,0.77,0.8,0.83,0.87,0.9,0.93,0.96,0.99,1.02,1.05,1.08,1.1,1.12,1.14,1.16,1.17,1.18,1.19,1.2,1.2,1.2,1.19,1.17,1.15,1.12,1.09,1.06,1.02,0.98,0.94,0.9,0.86,0.82,0.78,0.74,0.7,0.66,0.63,0.6,0.57,0.55,0.53,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.52,0.51,0.51,0.5,0.5,0.49,0.49,0.48,0.47,0.47,0.47,0.46,0.46,0.45,0.45,0.45,0.44,0.44,0.44,0.43,0.43,0.43,0.42,0.42,0.42,0.41,0.41,0.41,0.41,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.41,0.41,0.41,0.41,0.41,0.41,0.41,0.41,0.41,0.41,0.41,0.41,0.41,0.41,0.41,0.42,0.42,0.42,0.42,0.42,0.42,0.42,0.42,0.42,0.43,0.43,0.43,0.43,0.43,0.43,0.44,0.44,0.44,0.44,0.44,0.44,0.45,0.45,0.45
]
},
{
name:'降雨量',
type:'line',
yAxisIndex:1,
sampling: sampling,
notShowSymbol: true,
hoverAnimation: false,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
markArea: {
silent: true,
data: [[{
// name: 'a',
xAxis: '2009/9/26 7:00'
// xAxis: 1
}, {
// name: 'b',
xAxis: '2009/10/8 7:00'
// xAxis: 5
}]]
},
data: [
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.005,0.017,0.017,0.017,0.017,0.011,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.021,0.026,0.03,0.036,0.036,0.195,0.221,0.019,0.013,0.017,0.03,0.03,0.03,0.046,0.045,0.038,0.084,0.045,0.045,0.037,0.034,0.035,0.036,0.044,0.052,0.048,0.109,0.033,0.029,0.04,0.042,0.042,0.042,0.073,0.076,0.062,0.066,0.066,0.075,0.096,0.128,0.121,0.128,0.14,0.226,0.143,0.097,0.018,0,0,0,0,0,0.018,0.047,0.054,0.054,0.054,0.036,0.185,0.009,0.038,0.061,0.077,0.091,0.126,0.69,0.182,0.349,0.231,0.146,0.128,0.167,0.1,0.075,0.071,0.071,0.117,0.01,0.002,0.002,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.005,0.026,0.038,0.038,0.038,0.076,0.086,0.109,0.213,0.276,0.288,0.297,0.642,1.799,1.236,2.138,0.921,0.497,0.685,0.828,0.41,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.018,0.024,0.024,0.024,0.024,0.006,0.003,0.046,0.046,0.046,0.046,0.043,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.204,0.303,1.028,1.328,1.524,1.41,1.362,1.292,1.191,0.529,0.501,0.944,1.81,2.899,0.859,0.126,0.087,0.047,0,0,0,0,0.011,0.028,0.028,0.028,0.028,0.017,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.099,0.159,0.297,0.309,0.309,0.614,0.818,1.436,1.195,0.553,0.542,0.955,0.898,0.466,0.386,0.556,0.388,0.221,0.192,0.192,0.187,0.166,0.18,0.302,0.158,0.009,0.009,0.009,0.009,0.009,0.007,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.004,0.032,0.032,0.032,0.032,0.082,0.149,0.204,0.247,0.262,0.49,0.51,0.533,0.746,0.847,2.393,1.188,1.114,0.475,0.043,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.017,0.017,0.021,0.042,0.079,0.111,0.126,0.122,0.133,0.846,0.102,0.077,0.067,0.056,0.005,0,0,0,0,0,0,0,0,0,0,0,0,0,0.011,0.017,0.017,0.017,0.017,0.006,0,0,0,0,0,0.01,0.03,0.054,0.067,0.07,0.25,0.251,0.494,0.065,0.054,0.054,0.064,0.084,0.077,0.101,0.132,0.248,0.069,0.117,0.115,0.087,0.326,0.036,0.009,0.009,0.009,0.009,0.009,0.004,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.02,0.039,0.04,0.04,0.04,0.229,0.079,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.023,0.069,0.082,0.082,0.082,0.503,0.774,0.038,0.012,0.012,0.012,0.016,0.02,0.028,0.051,0.06,0.064,0.19,0.15,0.164,0.139,0.13,0.085,0.031,0.023,0.022,0.007,0.005,0.005,0.001,0,0.02,0.048,0.048,0.053,0.056,0.036,0.008,0.008,0.004,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.013,0.017,0.036,0.068,0.095,0.233,0.272,0.377,0.722,1.494,3.756,0.954,0.439,0.442,0.462,0.373,0.249,0.214,0.1,0.044,0.037,0.023,0.002,0,0,0,0,0,0,0.02,0.024,0.024,0.024,0.024,0.004,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.008,0.017,0.017,0.045,0.186,0.308,0.241,0.241,0.893,4.067,4.494,5.015,3.494,2.057,1.411,0.718,0.407,0.313,0.339,1.537,1.105,0.218,0.136,0.03,0.005,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.037,0.448,1.2,1.309,1.309,1.425,1.223,0.471,0.767,0.423,0.273,0.412,0.646,0.481,0.239,0.131,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.044,0.15,0.223,0.388,0.513,0.883,2.828,4.786,5.959,4.95,6.434,6.319,3.35,2.806,4.204,1.395,1.015,1.015,0.836,0.74,0.72,0.615,0.477,0.192,0.046,0.007,0.007,0.007,0.007,0.007,0.007,0.007,0.008,0.005,0.005,0.005,0.005,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.001,0.012,0.012,0.012,0.012,0.011,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.002,0.012,0.028,0.028,0.028,0.138,0.092,0.082,0.082,0.096,0.719,0.155,0.042,0.047,0.129,0.021,0.021,0.014,0.009,0.029,0.067,0.088,0.095,0.095,0.138,0.091,0.032,0.025,0.025,0.003,0,0,0,0,0,0,0,0,0,0,0,0,0.002,0.045,0.228,0.297,0.325,0.339,0.581,1.244,0.796,0.517,0.227,0.053,0.006,0,0,0,0,0,0,0,0,0,0.003,0.005,0.005,0.005,0.005,0.081,0.129,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.014,0.041,0.041,0.041,0.041,0.027,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.009,0.017,0.017,0.017,0.017,0.355,0.174,0.009,0.009,0.012,0.136,0.208,0.208,0.208,0.215,7.359,1.858,0.458,0.053,0.053,0.047,0.045,0.045,0.059,0.136,0.188,0.206,0.21,0.588,1.517,6.02,4.688,4.42,0.624,0.326,0.359,0.553,0.899,0.94,2.95,9.415,5.752,1.092,0.096,0.035,0.026,0.018,0.015,0.011,0.011,0.011,0,0,0,0,0,0,0,0,0,0,0,0.056,0.27,0.314,0.351,0.354,0.609,0.796,1.857,0.848,0.538,0.214,0.178,0.178,0.201,0.231,0.227,0.272,0.397,0.45,1.014,2.917,1.675,0.081,0.059,0.059,0.148,0.075,0.075,0.078,0.236,0.784,0.784,0.784,0.784,0.741,0.115,0.058,0.058,0.058,0.029,0.015,0.015,0.015,0.015,0.012,0.008,0.604,0.985,1.305,2.273,2.528,2.336,2.496,2.281,1.397,1.713,3.259,1.167,0.745,0.548,1.058,0.684,0.728,0.392,0.179,0.283,0.283,0.46,0.08,0.099,0.099,0.099,0.1,0.143,0.137,0.238,0.317,0.262,0.225,0.792,0.426,0.332,0.261,0.11,0.093,0.102,0.171,0.292,0.504,0.605,1.745,2.485,1.964,0.33,0.171,0.259,0.242,0.215,0.366,0.354,0.205,0.203,0.262,0.153,0.13,0.137,0.362,0.691,0.295,0.433,0.154,0.056,0.053,0.053,0.053,0.051,0.047,0.065,0.078,0.091,0.206,0.813,0.102,0.151,0.05,0.024,0.004,0.001,0,0,0,0.021,0.021,0.021,0.021,0.021,0.013,0.013,0.013,0.013,0.013,0.013,0.013,0.013,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.008,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.018,0.021,0.021,0.021,0.021,0.003,0,0,0,0,0,0,0,0,0,0.024,0.173,0.261,0.267,0.267,0.534,1.354,1.772,0.72,0.218,0.018,0.018,0.028,0.036,0.032,0.194,0.082,0.035,0.286,0.027,0.038,0.038,0.027,0.021,0.014,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.016,0.017,0.017,0.031,0.047,0.043,0.056,0.104,0.149,0.179,0.205,0.328,0.998,0.522,1.851,3.727,3.273,2.204,1.169,1.006,1.179,0.74,0.741,1.065,0.925,0.671,0.497,0.431,0.327,0.277,0.126,0.581,0.207,0.359,2.485,0.038,0.036,0.003,0.003,0.003,0.003,0.004,0.098,0.023,0.021,0.021,0.022,0.041,0.041,0.043,0.045,0.043,0.014,0.014,0.014,0.014,0.014,0.014,0.014,0.031,0.046,0.063,0.119,0.107,0.092,0.085,0.065,0.06,0.054,0.042,0.039,0.046,0.044,0.028,0.028,0.02,0.013,0.013,0.013,0.013,0.016,0.032,0.031,0.031,0.031,0.028,0.011,0.011,0.011,0.011,0.011,0.023,0.024,0.024,0.024,0.019,0.015,0.015,0.015,0.015,0.015,0.015,0.013,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.001,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.011,0.017,0.024,0.026,0.061,0.172,0.206,0.213,0.267,0.511,0.668,0.157,0.017,0.017,0.017,0.046,0.054,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.001,0.017,0.017,0.017,0.017,0.016,0,0,0,0,0,0,0,0,0,0.01,0.017,0.017,0.017,0.017,0.012,0.017,0.017,0.017,0.017,0.012,0,0,0,0,0,0.003,0.031,0.066,0.093,0.112,0.122,0.202,0.068,0.041,0.022,0.011,0,0,0,0,0,0,0,0,0,0,0,0.002,0.005,0.012,0.021,0.021,0.019,0.033,0.03,0.026,0.026,0.034,0.095,0.024,0.024,0.024,0.023,0.019,0.018,0.018,0.018,0.011,0.03,0.045,0.044,0.044,0.044,0.022,0.009,0.024,0.033,0.033,0.033,0.024,0.009,0,0,0,0,0,0,0.003,0.017,0.017,0.017,0.017,0.014,0,0,0,0,0,0.032,0.032,0.032,0.032,0.032,0.005,0.008,0.009,0.014,0.014,0.009,0.005,0.004,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.007,0.009,0.009,0.009,0.009,0.043,0.063,0.084,0.098,0.101,0.213,0.334,0.383,0.43,0.448,0.511,0.801,0.835,1.642,1.614,1.496,1.496,1.476,1.068,0.481,0.22,0.119,0.099,0.07,0.072,0.063,0.076,0.14,0.205,0.28,0.297,0.3,0.479,0.877,1.098,1.611,1.629,1.686,1.686,1.631,1.528,1.862,1.703,1.531,2.196,0.395,0.416,0.453,0.728,0.917,0.986,1.17,2.171,3.011,2.909,3.301,1.377,0.778,0.799,0.947,1.039,0.879,0.76,1.372,1.674,1.674,1.68,1.823,1.793,1.162,0.783,0.216,0.152,0.152,0.152,0.049,0,0,0,0.117,0.127,0.127,0.127,0.127,0.127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.003,0.005,0.005,0.005,0.005,0.003,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.309,0.364,0.364,0.364,0.364,0.063,0.01,0.01,0.01,0.012,0.015,0.015,0.11,0.55,0.824,0.825,0.829,1.39,1.429,1.342,1.43,1.636,1.717,2.135,2.203,3.191,3.022,1.589,0.86,0.807,0.645,0.595,0.588,0.557,0.552,1.271,0.708,0.677,0.629,0.714,0.203,0.133,0.061,0.062,0.018,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.001,0.072,0.29,0.438,0.53,0.557,0.873,1.039,1.04,0.208,0.049,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.03,0.039,0.039,0.039,0.039,0.098,0.008,0.007,0.007,0.007,0.007,0.007,0.007,0.007,0.007,0.007,0.056,0.062,0.065,0.065,0.065,0.047,0.216,0.256,0.315,0.4,0.502,0.449,0.47,0.571,0.814,1.153,0.774,0.202,0.086,0.075,0.071,0.032,0.019,0.003,0.004,0.004,0.004,0.004,0.004,0.004,0.007,0.072,0.153,0.256,0.306,0.404,0.698,0.733,0.823,0.715,0.563,0.404,0.293,0.217,0.213,0.202,0.202,0.294,0.704,0.797,1.359,1.101,0.72,0.514,0.539,0.434,0.389,0.387,0.386,0.375,0.369,0.319,0.239,0.183,0.136,0.062,0.052,0.096,0.119,0.119,0.114,0.127,0.132,0.139,0.169,0.191,0.278,0.254,0.214,0.237,0.221,0.143,0.129,0.125,0.109,0.1,0.087,0.06,0.038,0.029,0.029,0.028,0.048,0.053,0.053,0.111,0.125,0.102,0.097,0.097,0.039,0.02,0.02,0.02,0.014,0.004,0.031,0.043,0.047,0.052,0.08,0.144,0.182,0.176,0.171,0.149,0.112,0.025,0,0,0,0,0,0,0,0.016,0.031,0.031,0.031,0.031,0.015,0,0,0,0,0,0.005,0.005,0.005,0.005,0.005,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.005,0.005,0.005,0.005,0.005,0.001,0,0,0
]
}
]
});
})
</script>
</body>
</html> | test/area2.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00026479671942070127,
0.00017472503532189876,
0.00016295083332806826,
0.00017135418602265418,
0.0000191445360542275
] |
{
"id": 8,
"code_window": [
" return applyTransform(out, data as number[], this._transform);\n",
" }\n",
" const xAxis = this.getAxis('x');\n",
" const yAxis = this.getAxis('y');\n",
" out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));\n",
" out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));\n",
" return out;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));\n",
" out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 123
} | /*
* 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 { each, indexOf, curry, assert, map, createHashMap } from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as brushHelper from './brushHelper';
import {
BrushPanelConfig, BrushControllerEvents, BrushType,
BrushAreaRange, BrushDimensionMinMax
} from './BrushController';
import ExtensionAPI from '../../core/ExtensionAPI';
import GridModel from '../../coord/cartesian/GridModel';
import GeoModel from '../../coord/geo/GeoModel';
import { CoordinateSystemMaster } from '../../coord/CoordinateSystem';
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Geo from '../../coord/geo/Geo';
import GlobalModel from '../../model/Global';
import { BrushAreaParam, BrushAreaParamInternal } from '../brush/BrushModel';
import SeriesModel from '../../model/Series';
import { Dictionary } from '../../util/types';
import {
ModelFinderObject, ParsedModelFinder, ModelFinder,
parseFinder as modelUtilParseFinder,
ParsedModelFinderKnown
} from '../../util/model';
const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;
type COORD_CONVERTS_INDEX = 0 | 1;
// FIXME
// how to genarialize to more coordinate systems.
const INCLUDE_FINDER_MAIN_TYPES = [
'grid', 'xAxis', 'yAxis', 'geo', 'graph',
'polar', 'radiusAxis', 'angleAxis', 'bmap'
];
type BrushableCoordinateSystem = Cartesian2D | Geo;
type BrushTargetBuilderKey = 'grid' | 'geo';
/**
* There can be multiple axes in a single targetInfo. Consider the case
* of `grid` component, a targetInfo represents a grid which contains one or more
* cartesian and one or more axes. And consider the case of parallel system,
* which has multiple axes in a coordinate system.
*/
interface BrushTargetInfo {
panelId: string;
coordSysModel: CoordinateSystemMaster['model'];
// Use the first one as the representitive coordSys.
// A representitive cartesian in grid (first cartesian by default).
coordSys: BrushableCoordinateSystem;
// All cartesians.
coordSyses: BrushableCoordinateSystem[];
getPanelRect: GetPanelRect,
}
export interface BrushTargetInfoCartesian2D extends BrushTargetInfo {
gridModel: GridModel;
coordSys: Cartesian2D;
coordSyses: Cartesian2D[];
xAxisDeclared: boolean;
yAxisDeclared: boolean;
}
export interface BrushTargetInfoGeo extends BrushTargetInfo {
geoModel: GeoModel,
coordSysModel: GeoModel,
coordSys: Geo,
coordSyses: Geo[],
}
type GetPanelRect = () => graphic.BoundingRect;
class BrushTargetManager {
private _targetInfoList: BrushTargetInfo[] = [];
/**
* @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
* Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
* @param opt.include include coordinate system types.
*/
constructor(
finder: ModelFinderObject,
ecModel: GlobalModel,
opt?: {include?: BrushTargetBuilderKey[]}
) {
const foundCpts = parseFinder(ecModel, finder);
each(targetInfoBuilders, (builder, type) => {
if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
builder(foundCpts, this._targetInfoList);
}
});
}
setOutputRanges(
areas: BrushControllerEvents['brush']['areas'],
ecModel: GlobalModel
): BrushAreaParam[] {
this.matchOutputRanges(areas, ecModel, function (
area: BrushAreaParam,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem
) {
(area.coordRanges || (area.coordRanges = [])).push(coordRange);
// area.coordRange is the first of area.coordRanges
if (!area.coordRange) {
area.coordRange = coordRange;
// In 'category' axis, coord to pixel is not reversible, so we can not
// rebuild range by coordRange accrately, which may bring trouble when
// brushing only one item. So we use __rangeOffset to rebuilding range
// by coordRange. And this it only used in brush component so it is no
// need to be adapted to coordRanges.
const result = coordConvert[area.brushType](0, coordSys, coordRange);
area.__rangeOffset = {
offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
xyMinMax: result.xyMinMax
};
}
});
return areas;
}
matchOutputRanges<T extends (
Parameters<BrushTargetManager['findTargetInfo']>[0] & {
brushType: BrushType;
range: BrushAreaRange;
}
)>(
areas: T[],
ecModel: GlobalModel,
cb: (
area: T,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem,
ecModel: GlobalModel
) => void
) {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (targetInfo && targetInfo !== true) {
each(
targetInfo.coordSyses,
function (coordSys) {
const result = coordConvert[area.brushType](1, coordSys, area.range, true);
cb(area, result.values, coordSys, ecModel);
}
);
}
}, this);
}
/**
* the `areas` is `BrushModel.areas`.
* Called in layout stage.
* convert `area.coordRange` to global range and set panelId to `area.range`.
*/
setInputRanges(
areas: BrushAreaParamInternal[],
ecModel: GlobalModel
): void {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (__DEV__) {
assert(
!targetInfo || targetInfo === true || area.coordRange,
'coordRange must be specified when coord index specified.'
);
assert(
!targetInfo || targetInfo !== true || area.range,
'range must be specified in global brush.'
);
}
area.range = area.range || [];
// convert coordRange to global range and set panelId.
if (targetInfo && targetInfo !== true) {
area.panelId = targetInfo.panelId;
// (1) area.range shoule always be calculate from coordRange but does
// not keep its original value, for the sake of the dataZoom scenario,
// where area.coordRange remains unchanged but area.range may be changed.
// (2) Only support converting one coordRange to pixel range in brush
// component. So do not consider `coordRanges`.
// (3) About __rangeOffset, see comment above.
const result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
const rangeOffset = area.__rangeOffset;
area.range = rangeOffset
? diffProcessor[area.brushType](
result.values,
rangeOffset.offset,
getScales(result.xyMinMax, rangeOffset.xyMinMax)
)
: result.values;
}
}, this);
}
makePanelOpts(
api: ExtensionAPI,
getDefaultBrushType?: (targetInfo: BrushTargetInfo) => BrushType
): BrushPanelConfig[] {
return map(this._targetInfoList, function (targetInfo) {
const rect = targetInfo.getPanelRect();
return {
panelId: targetInfo.panelId,
defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
clipPath: brushHelper.makeRectPanelClipPath(rect),
isTargetByCursor: brushHelper.makeRectIsTargetByCursor(
rect, api, targetInfo.coordSysModel
),
getLinearBrushOtherExtent: brushHelper.makeLinearBrushOtherExtent(rect)
};
});
}
controlSeries(area: BrushAreaParamInternal, seriesModel: SeriesModel, ecModel: GlobalModel): boolean {
// Check whether area is bound in coord, and series do not belong to that coord.
// If do not do this check, some brush (like lineX) will controll all axes.
const targetInfo = this.findTargetInfo(area, ecModel);
return targetInfo === true || (
targetInfo && indexOf(
targetInfo.coordSyses, seriesModel.coordinateSystem as BrushableCoordinateSystem
) >= 0
);
}
/**
* If return Object, a coord found.
* If reutrn true, global found.
* Otherwise nothing found.
*/
findTargetInfo(
area: ModelFinderObject & {
panelId?: string
},
ecModel: GlobalModel
): BrushTargetInfo | true {
const targetInfoList = this._targetInfoList;
const foundCpts = parseFinder(ecModel, area);
for (let i = 0; i < targetInfoList.length; i++) {
const targetInfo = targetInfoList[i];
const areaPanelId = area.panelId;
if (areaPanelId) {
if (targetInfo.panelId === areaPanelId) {
return targetInfo;
}
}
else {
for (let j = 0; j < targetInfoMatchers.length; j++) {
if (targetInfoMatchers[j](foundCpts, targetInfo)) {
return targetInfo;
}
}
}
}
return true;
}
}
function formatMinMax(minMax: BrushDimensionMinMax): BrushDimensionMinMax {
minMax[0] > minMax[1] && minMax.reverse();
return minMax;
}
function parseFinder(
ecModel: GlobalModel, finder: ModelFinder
): ParsedModelFinderKnown {
return modelUtilParseFinder(
ecModel, finder, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
);
}
type TargetInfoBuilder = (
foundCpts: ParsedModelFinderKnown, targetInfoList: BrushTargetInfo[]
) => void;
const targetInfoBuilders: Record<BrushTargetBuilderKey, TargetInfoBuilder> = {
grid: function (foundCpts, targetInfoList) {
const xAxisModels = foundCpts.xAxisModels;
const yAxisModels = foundCpts.yAxisModels;
const gridModels = foundCpts.gridModels;
// Remove duplicated.
const gridModelMap = createHashMap<GridModel>();
const xAxesHas = {} as Dictionary<boolean>;
const yAxesHas = {} as Dictionary<boolean>;
if (!xAxisModels && !yAxisModels && !gridModels) {
return;
}
each(xAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
});
each(yAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
yAxesHas[gridModel.id] = true;
});
each(gridModels, function (gridModel) {
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
yAxesHas[gridModel.id] = true;
});
gridModelMap.each(function (gridModel) {
const grid = gridModel.coordinateSystem;
const cartesians = [] as Cartesian2D[];
each(grid.getCartesians(), function (cartesian, index) {
if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0
|| indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0
) {
cartesians.push(cartesian);
}
});
targetInfoList.push({
panelId: 'grid--' + gridModel.id,
gridModel: gridModel,
coordSysModel: gridModel,
// Use the first one as the representitive coordSys.
coordSys: cartesians[0],
coordSyses: cartesians,
getPanelRect: panelRectBuilders.grid,
xAxisDeclared: xAxesHas[gridModel.id],
yAxisDeclared: yAxesHas[gridModel.id]
} as BrushTargetInfoCartesian2D);
});
},
geo: function (foundCpts, targetInfoList) {
each(foundCpts.geoModels, function (geoModel: GeoModel) {
const coordSys = geoModel.coordinateSystem;
targetInfoList.push({
panelId: 'geo--' + geoModel.id,
geoModel: geoModel,
coordSysModel: geoModel,
coordSys: coordSys,
coordSyses: [coordSys],
getPanelRect: panelRectBuilders.geo
} as BrushTargetInfoGeo);
});
}
};
type TargetInfoMatcher = (
foundCpts: ParsedModelFinderKnown, targetInfo: BrushTargetInfo
) => boolean;
const targetInfoMatchers: TargetInfoMatcher[] = [
// grid
function (foundCpts, targetInfo) {
const xAxisModel = foundCpts.xAxisModel;
const yAxisModel = foundCpts.yAxisModel;
let gridModel = foundCpts.gridModel;
!gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
!gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
return gridModel && gridModel === (targetInfo as BrushTargetInfoCartesian2D).gridModel;
},
// geo
function (foundCpts, targetInfo) {
const geoModel = foundCpts.geoModel;
return geoModel && geoModel === (targetInfo as BrushTargetInfoGeo).geoModel;
}
];
type PanelRectBuilder = (this: BrushTargetInfo) => graphic.BoundingRect;
const panelRectBuilders: Record<BrushTargetBuilderKey, PanelRectBuilder> = {
grid: function (this: BrushTargetInfoCartesian2D) {
// grid is not Transformable.
return this.coordSys.master.getRect().clone();
},
geo: function (this: BrushTargetInfoGeo) {
const coordSys = this.coordSys;
const rect = coordSys.getBoundingRect().clone();
// geo roam and zoom transform
rect.applyTransform(graphic.getTransform(coordSys));
return rect;
}
};
type ConvertCoord = (
to: COORD_CONVERTS_INDEX,
coordSys: BrushableCoordinateSystem,
rangeOrCoordRange: BrushAreaRange,
clamp?: boolean
) => {
values: BrushAreaRange,
xyMinMax: BrushDimensionMinMax[]
};
const coordConvert: Record<BrushType, ConvertCoord> = {
lineX: curry(axisConvert, 0),
lineY: curry(axisConvert, 1),
rect: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xminymin = to
? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
const xmaxymax = to
? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
const values = [
formatMinMax([xminymin[0], xmaxymax[0]]),
formatMinMax([xminymin[1], xmaxymax[1]])
];
return {values: values, xyMinMax: values};
},
polygon: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
const values = map(rangeOrCoordRange, function (item) {
const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);
xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
return p;
});
return {values: values, xyMinMax: xyMinMax};
}
};
function axisConvert(
axisNameIndex: 0 | 1,
to: COORD_CONVERTS_INDEX,
coordSys: Cartesian2D,
rangeOrCoordRange: BrushDimensionMinMax
): {
values: BrushDimensionMinMax,
xyMinMax: BrushDimensionMinMax[]
} {
if (__DEV__) {
assert(
coordSys.type === 'cartesian2d',
'lineX/lineY brush is available only in cartesian2d.'
);
}
const axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
const values = formatMinMax(map([0, 1], function (i) {
return to
? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true)
: axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
}));
const xyMinMax = [];
xyMinMax[axisNameIndex] = values;
xyMinMax[1 - axisNameIndex] = [NaN, NaN];
return {values: values, xyMinMax: xyMinMax};
}
type DiffProcess = (
values: BrushDimensionMinMax | BrushDimensionMinMax[],
refer: BrushDimensionMinMax | BrushDimensionMinMax[],
scales: ReturnType<typeof getScales>
) => BrushDimensionMinMax | BrushDimensionMinMax[];
const diffProcessor: Record<BrushType, DiffProcess> = {
lineX: curry(axisDiffProcessor, 0),
lineY: curry(axisDiffProcessor, 1),
rect: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return [
[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
[values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
];
},
polygon: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return map(values, function (item, idx) {
return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
});
}
};
function axisDiffProcessor(
axisNameIndex: 0 | 1,
values: BrushDimensionMinMax,
refer: BrushDimensionMinMax,
scales: ReturnType<typeof getScales>
): BrushDimensionMinMax {
return [
values[0] - scales[axisNameIndex] * refer[0],
values[1] - scales[axisNameIndex] * refer[1]
];
}
// We have to process scale caused by dataZoom manually,
// although it might be not accurate.
// Return [0~1, 0~1]
function getScales(xyMinMaxCurr: BrushDimensionMinMax[], xyMinMaxOrigin: BrushDimensionMinMax[]): number[] {
const sizeCurr = getSize(xyMinMaxCurr);
const sizeOrigin = getSize(xyMinMaxOrigin);
const scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
function getSize(xyMinMax: BrushDimensionMinMax[]): number[] {
return xyMinMax
? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
: [NaN, NaN];
}
export default BrushTargetManager;
| src/component/helper/BrushTargetManager.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0003665400727186352,
0.00018357062072027475,
0.00016292877262458205,
0.00017140174168162048,
0.000041841438360279426
] |
{
"id": 8,
"code_window": [
" return applyTransform(out, data as number[], this._transform);\n",
" }\n",
" const xAxis = this.getAxis('x');\n",
" const yAxis = this.getAxis('y');\n",
" out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));\n",
" out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));\n",
" return out;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));\n",
" out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 123
} | /*
* 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.
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory);
} else if (
typeof exports === 'object' &&
typeof exports.nodeName !== 'string'
) {
// CommonJS
factory(exports, require('echarts/lib/echarts'));
} else {
// Browser globals
factory({}, root.echarts);
}
})(this, function(exports, echarts) {
var log = function(msg) {
if (typeof console !== 'undefined') {
console && console.error && console.error(msg);
}
};
if (!echarts) {
log('ECharts is not Loaded');
return;
}
var colorPalette = [
'#c12e34',
'#e6b600',
'#0098d9',
'#2b821d',
'#005eaa',
'#339ca8',
'#cda819',
'#32a487'
];
var theme = {
color: colorPalette,
title: {
textStyle: {
fontWeight: 'normal'
}
},
visualMap: {
color: ['#1790cf', '#a2d4e6']
},
toolbox: {
iconStyle: {
normal: {
borderColor: '#06467c'
}
}
},
tooltip: {
backgroundColor: 'rgba(0,0,0,0.6)'
},
dataZoom: {
dataBackgroundColor: '#dedede',
fillerColor: 'rgba(154,217,247,0.2)',
handleColor: '#005eaa'
},
timeline: {
lineStyle: {
color: '#005eaa'
},
controlStyle: {
color: '#005eaa',
borderColor: '#005eaa'
}
},
candlestick: {
itemStyle: {
color: '#c12e34',
color0: '#2b821d'
},
lineStyle: {
width: 1,
color: '#c12e34',
color0: '#2b821d'
},
areaStyle: {
color: '#e6b600',
color0: '#005eaa'
}
},
graph: {
itemStyle: {
color: '#e6b600'
},
linkStyle: {
color: '#005eaa'
}
},
map: {
itemStyle: {
color: '#f2385a',
borderColor: '#eee',
areaColor: '#ddd'
},
areaStyle: {
color: '#ddd'
},
label: {
color: '#c12e34'
}
},
gauge: {
axisLine: {
show: true,
lineStyle: {
color: [
[0.2, '#2b821d'],
[0.8, '#005eaa'],
[1, '#c12e34']
],
width: 5
}
},
axisTick: {
splitNumber: 10,
length: 8,
lineStyle: {
color: 'auto'
}
},
axisLabel: {
color: 'auto'
},
splitLine: {
length: 12,
lineStyle: {
color: 'auto'
}
},
pointer: {
length: '90%',
width: 3,
color: 'auto'
},
title: {
color: '#333'
},
detail: {
color: 'auto'
}
}
};
echarts.registerTheme('shine', theme);
});
| theme/shine.js | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0001772237301338464,
0.0001716752740321681,
0.00016411907563451678,
0.0001716824626782909,
0.0000029764585178782
] |
{
"id": 8,
"code_window": [
" return applyTransform(out, data as number[], this._transform);\n",
" }\n",
" const xAxis = this.getAxis('x');\n",
" const yAxis = this.getAxis('y');\n",
" out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));\n",
" out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));\n",
" return out;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));\n",
" out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 123
} | <!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<script src="lib/jquery.min.js"></script>
<script src="lib/facePrint.js"></script>
<script src="lib/testHelper.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="lib/reset.css">
</head>
<body>
<style>
.chart {
position: relative;
height: 500px;
max-width: 1000px;
margin: 0 auto;
}
h2 {
text-align: center;
font-size: 16px;
line-height: 40px;
font-weight: normal;
background: #078302;
color: #eee;
}
</style>
<h2>scatter</h2>
<div class="chart" id="main1"></div>
<h2>Test: (1) click zoom btn (2) select (3) click zoom btn, expect: not change</h2>
<div class="chart" id="main-test-y-range"></div>
<h2>Multiple Y axis (default)</h2>
<div class="chart" id="main-multiple-y-axis-default"></div>
<h2>Specify Y axis (yAxisIndex: [1, 2, 4], xAxisIndex: false, should be 'lineY' brush)</h2>
<div class="chart" id="main-specify-y-axis"></div>
<h2>Specify Y axis (yAxisIndex: false, should be 'lineX' brush)</h2>
<div class="chart" id="main-specify-x-axis"></div>
<div id="main0"></div>
<div id="main-refer-by-axis-id"></div>
<script>
var lastChart;
var globalColor = ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'];
function makeChart(id, option, cb) {
require([
'echarts'
// 'echarts/model/globalDefault',
// 'echarts/chart/scatter',
// 'echarts/chart/line',
// 'echarts/chart/bar',
// 'echarts/chart/scatter',
// 'echarts/component/grid',
// 'echarts/component/markLine',
// 'echarts/component/legend',
// 'echarts/component/tooltip',
// 'echarts/component/toolbox',
// 'echarts/component/dataZoom'
], function (echarts, globalDefault) {
var main = document.getElementById(id);
if (main) {
var chartMain = document.createElement('div');
chartMain.style.cssText = 'height:100%';
main.appendChild(chartMain);
var chart = lastChart = echarts.init(chartMain);
if (typeof option === 'function') {
option = option(echarts, globalDefault);
}
chart.setOption(option);
window.addEventListener('resize', chart.resize);
cb && cb(echarts, chart);
}
});
}
</script>
<script>
var data1 = [];
var data2 = [];
var data3 = [];
function random(max) {
return (Math.random() * max).toFixed(3);
};
for (var i = 0; i < 100; i++) {
data1.push([random(15), random(10), random(1)]);
// data1.push([i, 10, i]);
data2.push([random(10), random(10), random(1)]);
data3.push([random(15), random(10), random(1)]);
}
makeChart('main1', {
legend: {
data: ['scatter', 'scatter2', 'scatter3']
},
animationDuration: 1000,
animationDurationUpdate: 1000,
toolbox: {
feature: {
dataView: {},
dataZoom: {
show: true,
yAxisIndex: null,
// brushStyle: {
// borderWidth: 2,
// color: 'blue',
// opacity: 0.1,
// borderColor: '#596A76',
// }
},
restore: {show: true},
saveAsImage: {}
}
},
tooltip: {
},
xAxis: {
type: 'value',
min: 'dataMin',
max: 'dataMax',
splitLine: {
show: true
}
},
yAxis: {
type: 'value',
min: 'dataMin',
max: 'dataMax',
splitLine: {
show: true
}
},
dataZoom: [
{
show: true,
xAxisIndex: [0],
start: 10,
end: 70
},
{
show: true,
yAxisIndex: [0],
start: 0,
end: 20
},
{
type: 'inside',
xAxisIndex: [0],
start: 10,
end: 70
},
{
type: 'inside',
yAxisIndex: [0],
start: 0,
end: 20
}
],
series: [
{
name: 'scatter',
type: 'scatter',
itemStyle: {
normal: {
opacity: 0.8,
}
},
symbolSize: function (val) {
return val[2] * 40;
},
data: data1
},
{
name: 'scatter2',
type: 'scatter',
itemStyle: {
normal: {
opacity: 0.8
}
},
symbolSize: function (val) {
return val[2] * 40;
},
data: data2
},
{
name: 'scatter3',
type: 'scatter',
itemStyle: {
normal: {
opacity: 0.8,
}
},
symbolSize: function (val) {
return val[2] * 40;
},
data: data3
}
]
});
</script>
<script>
makeChart('main-test-y-range', function (echarts, globalDefault) {
return {
tooltip: {},
toolbox: {
feature: {
dataZoom: {},
restore: {}
}
},
legend: {
data: ['A1', 'A2', 'A3', 'B1', 'B2']
},
grid: [{
left: 40,
width: 300,
}],
xAxis: [{
data: ['z', 'y', 'x', 'w', 'v', 'u']
}],
yAxis: [{
type: 'value',
position: 'left',
axisLine: {
lineStyle: {
color: globalColor[0]
}
}
}, {
type: 'value',
position: 'right',
axisLine: {
lineStyle: {
color: globalColor[1]
}
}
}, {
type: 'value',
position: 'right',
offset: 80,
axisLine: {
lineStyle: {
color: globalColor[2]
}
}
}],
dataZoom: [{
type: 'slider',
height: 20
}, {
type: 'slider',
yAxisIndex: 1,
orient: 'vertical',
left: 365,
width: 20
}, {
type: 'slider',
yAxisIndex: 2,
orient: 'vertical',
left: 445,
width: 20
}],
series: [{
name: 'A1',
type: 'line',
data: [5, 1, 5, 1, 5, 10]
}, {
name: 'A2',
type: 'line',
yAxisIndex: 1,
data: [1, 5, 1, 5, 1, 10]
}, {
name: 'A3',
type: 'line',
yAxisIndex: 2,
data: [3, 8, 1, 4, 2, 5]
}]
};
});
</script>
<script>
makeChart('main-multiple-y-axis-default', function (echarts, globalDefault) {
return {
tooltip: {},
toolbox: {
feature: {
dataZoom: {},
restore: {}
}
},
legend: {
data: ['A1', 'A2', 'A3', 'B1', 'B2']
},
grid: [{
left: 40,
width: 300,
}, {
left: 550,
right: 40
}],
xAxis: [{
data: ['z', 'y', 'x', 'w', 'v', 'u']
}, {
data: ['z', 'y', 'x', 'w', 'v', 'u'],
gridIndex: 1
}],
yAxis: [{
type: 'value',
position: 'left',
axisLine: {
lineStyle: {
color: globalColor[0]
}
}
}, {
type: 'value',
position: 'right',
axisLine: {
lineStyle: {
color: globalColor[1]
}
}
}, {
type: 'value',
position: 'right',
offset: 80,
axisLine: {
lineStyle: {
color: globalColor[2]
}
}
}, {
type: 'value',
position: 'left',
gridIndex: 1,
boundaryGap: ['20%', '20%'],
axisLine: {
lineStyle: {
color: globalColor[3]
}
}
}, {
type: 'value',
position: 'right',
gridIndex: 1,
boundaryGap: ['20%', '20%'],
axisLine: {
lineStyle: {
color: globalColor[4]
}
}
}],
dataZoom: [{
type: 'slider',
height: 20
}, {
type: 'slider',
yAxisIndex: 1,
orient: 'vertical',
left: 365,
width: 20
}, {
type: 'slider',
yAxisIndex: 2,
orient: 'vertical',
left: 445,
width: 20
}],
series: [{
name: 'A1',
type: 'line',
data: [5, 1, 5, 1, 5, 10]
}, {
name: 'A2',
type: 'line',
yAxisIndex: 1,
data: [1, 5, 1, 5, 1, 10]
}, {
name: 'A3',
type: 'line',
yAxisIndex: 2,
data: [3, 8, 1, 4, 2, 5]
}, {
name: 'B1',
type: 'line',
xAxisIndex: 1,
yAxisIndex: 3,
data: [5, 1, 5, 1, 5, 3]
}, {
name: 'B2',
type: 'line',
xAxisIndex: 1,
yAxisIndex: 4,
data: [1, 5, 1, 5, 1, 10]
}]
};
});
</script>
<script>
makeChart('main-specify-y-axis', function (echarts, globalDefault) {
return {
tooltip: {},
toolbox: {
feature: {
dataZoom: {
yAxisIndex: [1, 2, 4],
xAxisIndex: false
},
restore: {}
}
},
legend: {
data: ['A1', 'A2', 'A3', 'B1', 'B2']
},
grid: [{
left: 40,
width: 300,
}, {
left: 550,
right: 40
}],
xAxis: [{
data: ['z', 'y', 'x', 'w', 'v', 'u']
}, {
data: ['z', 'y', 'x', 'w', 'v', 'u'],
gridIndex: 1
}],
yAxis: [{
type: 'value',
position: 'left',
axisLine: {
lineStyle: {
color: globalColor[0]
}
}
}, {
type: 'value',
position: 'right',
axisLine: {
lineStyle: {
color: globalColor[1]
}
}
}, {
type: 'value',
position: 'right',
offset: 80,
axisLine: {
lineStyle: {
color: globalColor[2]
}
}
}, {
type: 'value',
position: 'left',
gridIndex: 1,
boundaryGap: ['20%', '20%'],
axisLine: {
lineStyle: {
color: globalColor[3]
}
}
}, {
type: 'value',
position: 'right',
gridIndex: 1,
boundaryGap: ['20%', '20%'],
axisLine: {
lineStyle: {
color: globalColor[4]
}
}
}],
series: [{
name: 'A1',
type: 'line',
data: [5, 1, 5, 1, 5, 10]
}, {
name: 'A2',
type: 'line',
yAxisIndex: 1,
data: [1, 5, 1, 5, 1, 10]
}, {
name: 'A3',
type: 'line',
yAxisIndex: 2,
data: [3, 8, 1, 4, 2, 5]
}, {
name: 'B1',
type: 'line',
xAxisIndex: 1,
yAxisIndex: 3,
data: [5, 1, 5, 1, 5, 10]
}, {
name: 'B2',
type: 'line',
xAxisIndex: 1,
yAxisIndex: 4,
data: [1, 5, 1, 5, 1, 10]
}]
};
});
</script>
<script>
makeChart('main-specify-x-axis', function (echarts, globalDefault) {
return {
tooltip: {},
toolbox: {
feature: {
dataZoom: {
yAxisIndex: false
},
restore: {}
}
},
legend: {
data: ['A1', 'A2', 'A3', 'B1', 'B2']
},
grid: [{
left: 40,
width: 300,
}, {
left: 550,
right: 40
}],
xAxis: [{
data: ['z', 'y', 'x', 'w', 'v', 'u']
}, {
data: ['z', 'y', 'x', 'w', 'v', 'u'],
gridIndex: 1
}],
yAxis: [{
type: 'value',
position: 'left',
axisLine: {
lineStyle: {
color: globalColor[0]
}
}
}, {
type: 'value',
position: 'right',
axisLine: {
lineStyle: {
color: globalColor[1]
}
}
}, {
type: 'value',
position: 'right',
offset: 80,
axisLine: {
lineStyle: {
color: globalColor[2]
}
}
}, {
type: 'value',
position: 'left',
gridIndex: 1,
boundaryGap: ['20%', '20%'],
axisLine: {
lineStyle: {
color: globalColor[3]
}
}
}, {
type: 'value',
position: 'right',
gridIndex: 1,
boundaryGap: ['20%', '20%'],
axisLine: {
lineStyle: {
color: globalColor[4]
}
}
}],
series: [{
name: 'A1',
type: 'line',
data: [5, 1, 5, 1, 5, 10]
}, {
name: 'A2',
type: 'line',
yAxisIndex: 1,
data: [1, 5, 1, 5, 1, 10]
}, {
name: 'A3',
type: 'line',
yAxisIndex: 2,
data: [3, 8, 1, 4, 2, 5]
}, {
name: 'B1',
type: 'line',
xAxisIndex: 1,
yAxisIndex: 3,
data: [5, 1, 5, 1, 5, 10]
}, {
name: 'B2',
type: 'line',
xAxisIndex: 1,
yAxisIndex: 4,
data: [1, 5, 1, 5, 1, 10]
}]
};
});
</script>
<script>
require(['echarts'/*, 'map/js/china' */], function (echarts) {
var option;
option = {
toolbox: {
feature: {
dataZoom: {
// yAxisIndex: false
}
}
},
legend: {},
xAxis: {
data: ['I', 'II', 'III']
},
yAxis: {},
series: [{
name: 'x',
type: 'bar',
stack: 'a',
data: [11, 22, 33]
}, {
name: 'y',
type: 'bar',
stack: 'a',
data: [44, 33, 22]
}]
};
var chart = testHelper.create(echarts, 'main0', {
title: [
'(1) Use toolbox.dataZoom to brush a small rect in grid.',
'(2) Click a legend item to disappear a series and click again to show the series.',
'[Check]: the extent of yAxis: should be able to return to **the previous state after (1) did**.',
'(3) Click "back" in toolbox.dataZoom',
'[Check]: Back normally.'
],
option: option
// height: 300,
// buttons: [{text: 'btn-txt', onclick: function () {}}],
// recordCanvas: true,
});
});
</script>
<script>
require(['echarts'/*, 'map/js/china' */], function (echarts) {
var option;
option = {
toolbox: {
feature: {
dataZoom: {
xAxisId: 'xr',
yAxisId: ['yl0', 'yl1']
}
}
},
legend: {},
grid: [{
right: '60%',
bottom: '60%',
}, {
id: 'gr',
left: '60%',
bottom: '60%',
}, {
id: 'gb',
top: '60%',
}],
xAxis: [{
}, {
id: 'xr',
gridId: 'gr'
}, {
id: 'xb',
gridId: 'gb'
}],
yAxis: [{
id: 'yl0'
}, {
id: 'yl1'
}, {
id: 'yr',
gridId: 'gr'
}, {
id: 'yb',
gridId: 'gb'
}],
series: [{
type: 'line',
yAxisId: 'yl0',
data: [[11, 12], [22, 45], [33, 76]]
}, {
type: 'line',
yAxisId: 'yl1',
data: [[11, 2212], [22, 3345], [33, 4476]]
}, {
type: 'line',
xAxisId: 'xr',
yAxisId: 'yr',
data: [[45, 65], [13, 25], [56, 71]]
}, {
type: 'line',
xAxisId: 'xb',
yAxisId: 'yb',
data: [[123, 654], [234, 321], [345, 812]]
}]
};
var chart = testHelper.create(echarts, 'main-refer-by-axis-id', {
title: [
'Test toolbox datazoom refer with axis id',
'left grid: toolbox only work **on two yAxis**',
'right grid: toolbox only work **on xAxis**',
'bottom grid: toolbox **does not work**'
],
option: option
// height: 300,
// buttons: [{text: 'btn-txt', onclick: function () {}}],
// recordCanvas: true,
});
});
</script>
</body>
</html> | test/dataZoom-toolbox.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.86236172914505,
0.01134820468723774,
0.00016363499162252992,
0.00016930786659941077,
0.09364820271730423
] |
{
"id": 8,
"code_window": [
" return applyTransform(out, data as number[], this._transform);\n",
" }\n",
" const xAxis = this.getAxis('x');\n",
" const yAxis = this.getAxis('y');\n",
" out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));\n",
" out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));\n",
" return out;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));\n",
" out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 123
} | [{"name":"Action 1","ops":[{"type":"mousedown","time":774,"x":777,"y":159},{"type":"mousemove","time":901,"x":777,"y":161},{"type":"mousemove","time":1107,"x":768,"y":209},{"type":"mousemove","time":1307,"x":765,"y":272},{"type":"mousemove","time":1513,"x":764,"y":343},{"type":"mousemove","time":1722,"x":763,"y":370},{"type":"mousemove","time":1928,"x":763,"y":370},{"type":"mouseup","time":1935,"x":763,"y":370},{"time":1936,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":2128,"x":692,"y":445},{"type":"mousemove","time":2335,"x":652,"y":521},{"type":"mousemove","time":2539,"x":638,"y":584},{"type":"mousemove","time":2768,"x":638,"y":584},{"type":"mousemove","time":2969,"x":642,"y":580},{"type":"mousedown","time":3035,"x":642,"y":580},{"type":"mousemove","time":3172,"x":615,"y":580},{"type":"mousemove","time":3372,"x":526,"y":578},{"type":"mousemove","time":3573,"x":464,"y":582},{"type":"mousemove","time":3773,"x":412,"y":586},{"type":"mousemove","time":3975,"x":403,"y":587},{"type":"mouseup","time":4405,"x":403,"y":587},{"time":4406,"delay":400,"type":"screenshot-auto"}],"scrollY":9,"scrollX":0,"timestamp":1568037908913},{"name":"Action 2","ops":[{"type":"mousemove","time":406,"x":294,"y":15},{"type":"mousemove","time":606,"x":297,"y":13},{"type":"mousemove","time":819,"x":297,"y":13},{"type":"mousedown","time":918,"x":297,"y":13},{"type":"mouseup","time":1035,"x":297,"y":13},{"time":1036,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":2108,"x":298,"y":13},{"type":"mousemove","time":2309,"x":755,"y":202},{"type":"mousemove","time":2574,"x":784,"y":380},{"type":"mousemove","time":2774,"x":781,"y":396},{"type":"mousemove","time":2922,"x":781,"y":396},{"type":"mousedown","time":2977,"x":781,"y":396},{"type":"mousemove","time":3124,"x":778,"y":382},{"type":"mousemove","time":3326,"x":773,"y":322},{"type":"mousemove","time":3526,"x":767,"y":269},{"type":"mousemove","time":3732,"x":766,"y":256},{"type":"mousemove","time":3941,"x":766,"y":249},{"type":"mouseup","time":4359,"x":766,"y":249},{"time":4360,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":4463,"x":764,"y":253},{"type":"mousemove","time":4663,"x":523,"y":435},{"type":"mousemove","time":4865,"x":433,"y":504},{"type":"mousemove","time":5065,"x":454,"y":560},{"type":"mousemove","time":5265,"x":414,"y":568},{"type":"mousemove","time":5466,"x":381,"y":573},{"type":"mousedown","time":5656,"x":371,"y":572},{"type":"mousemove","time":5674,"x":371,"y":572},{"type":"mousemove","time":5749,"x":373,"y":572},{"type":"mousemove","time":5951,"x":469,"y":576},{"type":"mousemove","time":6152,"x":518,"y":575},{"type":"mousemove","time":6352,"x":541,"y":575},{"type":"mousemove","time":6552,"x":545,"y":575},{"type":"mouseup","time":6686,"x":545,"y":575},{"time":6687,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":6837,"x":545,"y":575}],"scrollY":9,"scrollX":0,"timestamp":1568037922834},{"name":"Action 3","ops":[{"type":"mousedown","time":683,"x":9,"y":10},{"type":"mouseup","time":767,"x":9,"y":10},{"time":768,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":1389,"x":10,"y":11},{"type":"mousemove","time":1593,"x":218,"y":278},{"type":"mousemove","time":1793,"x":301,"y":430},{"type":"mousemove","time":1994,"x":373,"y":517},{"type":"mousemove","time":2196,"x":384,"y":569},{"type":"mousemove","time":2396,"x":388,"y":574},{"type":"mousedown","time":2462,"x":388,"y":574},{"type":"mousemove","time":2469,"x":388,"y":574},{"type":"mousemove","time":2681,"x":296,"y":582},{"type":"mousemove","time":2881,"x":215,"y":580},{"type":"mousemove","time":3081,"x":209,"y":580},{"type":"mouseup","time":3297,"x":209,"y":580},{"time":3298,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":3385,"x":211,"y":580},{"type":"mousemove","time":3586,"x":706,"y":377},{"type":"mousemove","time":3803,"x":765,"y":321},{"type":"mousemove","time":4010,"x":766,"y":311},{"type":"mousemove","time":4210,"x":773,"y":302},{"type":"mousedown","time":4218,"x":773,"y":302},{"type":"mousemove","time":4414,"x":772,"y":344},{"type":"mousemove","time":4615,"x":776,"y":365},{"type":"mousemove","time":4849,"x":781,"y":394},{"type":"mouseup","time":5020,"x":781,"y":394},{"time":5021,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":5051,"x":781,"y":393},{"type":"mousemove","time":5251,"x":777,"y":340},{"type":"mousemove","time":5451,"x":774,"y":322},{"type":"mousemove","time":5651,"x":775,"y":314},{"type":"mousedown","time":5722,"x":775,"y":314},{"type":"mousemove","time":5851,"x":775,"y":313},{"type":"mousemove","time":6056,"x":772,"y":275},{"type":"mousemove","time":6271,"x":770,"y":236},{"type":"mousemove","time":6482,"x":770,"y":205},{"type":"mousemove","time":6690,"x":771,"y":177},{"type":"mousemove","time":6892,"x":772,"y":169},{"type":"mouseup","time":7068,"x":772,"y":169},{"time":7069,"delay":400,"type":"screenshot-auto"},{"type":"mousemove","time":7817,"x":772,"y":169},{"type":"mousemove","time":8017,"x":772,"y":170}],"scrollY":9,"scrollX":0,"timestamp":1568037935672}] | test/runTest/actions/dataZoom-scatter-hv-polar.json | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00016618608788121492,
0.00016618608788121492,
0.00016618608788121492,
0.00016618608788121492,
0
] |
{
"id": 9,
"code_window": [
" return out;\n",
" }\n",
"\n",
" pointToData(point: number[], out?: number[], reserved?: number[], clamp?: boolean): number[] {\n",
" out = out || [];\n",
" if (this._invTransform) {\n",
" return applyTransform(out, point, this._invTransform);\n",
" }\n",
" const xAxis = this.getAxis('x');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" pointToData(point: number[], clamp?: boolean): number[] {\n",
" const out: number[] = [];\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 148
} | /*
* 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 BoundingRect from 'zrender/src/core/BoundingRect';
import Cartesian from './Cartesian';
import { ScaleDataValue } from '../../util/types';
import Axis2D from './Axis2D';
import { CoordinateSystem } from '../CoordinateSystem';
import GridModel from './GridModel';
import Grid from './Grid';
import Scale from '../../scale/Scale';
import { invert } from 'zrender/src/core/matrix';
import { applyTransform } from 'zrender/src/core/vector';
export const cartesian2DDimensions = ['x', 'y'];
function canCalculateAffineTransform(scale: Scale) {
return scale.type === 'interval' || scale.type === 'time';
}
class Cartesian2D extends Cartesian<Axis2D> implements CoordinateSystem {
readonly type = 'cartesian2d';
readonly dimensions = cartesian2DDimensions;
model: GridModel;
master: Grid;
private _transform: number[];
private _invTransform: number[];
/**
* Calculate an affine transform matrix if two axes are time or value.
* It's mainly for accelartion on the large time series data.
*/
calcAffineTransform() {
this._transform = this._invTransform = null;
const xAxisScale = this.getAxis('x').scale;
const yAxisScale = this.getAxis('y').scale;
if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
return;
}
const xScaleExtent = xAxisScale.getExtent();
const yScaleExtent = yAxisScale.getExtent();
const start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
const end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
const xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
const yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
if (!xScaleSpan || !yScaleSpan) {
return;
}
// Accelerate data to point calculation on the special large time series data.
const scaleX = (end[0] - start[0]) / xScaleSpan;
const scaleY = (end[1] - start[1]) / yScaleSpan;
const translateX = start[0] - xScaleExtent[0] * scaleX;
const translateY = start[1] - yScaleExtent[0] * scaleY;
const m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
this._invTransform = invert([], m);
}
/**
* Base axis will be used on stacking.
*/
getBaseAxis(): Axis2D {
return this.getAxesByScale('ordinal')[0]
|| this.getAxesByScale('time')[0]
|| this.getAxis('x');
}
containPoint(point: number[]): boolean {
const axisX = this.getAxis('x');
const axisY = this.getAxis('y');
return axisX.contain(axisX.toLocalCoord(point[0]))
&& axisY.contain(axisY.toLocalCoord(point[1]));
}
containData(data: ScaleDataValue[]): boolean {
return this.getAxis('x').containData(data[0])
&& this.getAxis('y').containData(data[1]);
}
dataToPoint(data: ScaleDataValue[], reserved?: unknown, out?: number[]): number[] {
out = out || [];
const xVal = data[0];
const yVal = data[1];
// Fast path
if (this._transform
// It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
&& xVal != null
&& isFinite(xVal as number)
&& yVal != null
&& isFinite(yVal as number)
) {
return applyTransform(out, data as number[], this._transform);
}
const xAxis = this.getAxis('x');
const yAxis = this.getAxis('y');
out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));
out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));
return out;
}
clampData(data: ScaleDataValue[], out?: number[]): number[] {
const xScale = this.getAxis('x').scale;
const yScale = this.getAxis('y').scale;
const xAxisExtent = xScale.getExtent();
const yAxisExtent = yScale.getExtent();
const x = xScale.parse(data[0]);
const y = yScale.parse(data[1]);
out = out || [];
out[0] = Math.min(
Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
Math.max(xAxisExtent[0], xAxisExtent[1])
);
out[1] = Math.min(
Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
Math.max(yAxisExtent[0], yAxisExtent[1])
);
return out;
}
pointToData(point: number[], out?: number[], reserved?: number[], clamp?: boolean): number[] {
out = out || [];
if (this._invTransform) {
return applyTransform(out, point, this._invTransform);
}
const xAxis = this.getAxis('x');
const yAxis = this.getAxis('y');
out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
return out;
}
getOtherAxis(axis: Axis2D): Axis2D {
return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
}
/**
* Get rect area of cartesian.
* Area will have a contain function to determine if a point is in the coordinate system.
*/
getArea(): Cartesian2DArea {
const xExtent = this.getAxis('x').getGlobalExtent();
const yExtent = this.getAxis('y').getGlobalExtent();
const x = Math.min(xExtent[0], xExtent[1]);
const y = Math.min(yExtent[0], yExtent[1]);
const width = Math.max(xExtent[0], xExtent[1]) - x;
const height = Math.max(yExtent[0], yExtent[1]) - y;
return new BoundingRect(x, y, width, height);
}
};
interface Cartesian2DArea extends BoundingRect {}
export default Cartesian2D;
| src/coord/cartesian/Cartesian2D.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.9978652596473694,
0.26543617248535156,
0.00016738455451559275,
0.0067757912911474705,
0.41121798753738403
] |
{
"id": 9,
"code_window": [
" return out;\n",
" }\n",
"\n",
" pointToData(point: number[], out?: number[], reserved?: number[], clamp?: boolean): number[] {\n",
" out = out || [];\n",
" if (this._invTransform) {\n",
" return applyTransform(out, point, this._invTransform);\n",
" }\n",
" const xAxis = this.getAxis('x');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" pointToData(point: number[], clamp?: boolean): number[] {\n",
" const out: number[] = [];\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 148
} | /*
* 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 * as zrUtil from 'zrender/src/core/util';
import { AxisBaseOption } from './axisCommonTypes';
const defaultOption: AxisBaseOption = {
show: true,
zlevel: 0,
z: 0,
// Inverse the axis.
inverse: false,
// Axis name displayed.
name: '',
// 'start' | 'middle' | 'end'
nameLocation: 'end',
// By degree. By default auto rotate by nameLocation.
nameRotate: null,
nameTruncate: {
maxWidth: null,
ellipsis: '...',
placeholder: '.'
},
// Use global text style by default.
nameTextStyle: {},
// The gap between axisName and axisLine.
nameGap: 15,
// Default `false` to support tooltip.
silent: false,
// Default `false` to avoid legacy user event listener fail.
triggerEvent: false,
tooltip: {
show: false
},
axisPointer: {},
axisLine: {
show: true,
onZero: true,
onZeroAxisIndex: null,
lineStyle: {
color: '#6E7079',
width: 1,
type: 'solid'
},
// The arrow at both ends the the axis.
symbol: ['none', 'none'],
symbolSize: [10, 15]
},
axisTick: {
show: true,
// Whether axisTick is inside the grid or outside the grid.
inside: false,
// The length of axisTick.
length: 5,
lineStyle: {
width: 1
}
},
axisLabel: {
show: true,
// Whether axisLabel is inside the grid or outside the grid.
inside: false,
rotate: 0,
// true | false | null/undefined (auto)
showMinLabel: null,
// true | false | null/undefined (auto)
showMaxLabel: null,
margin: 8,
// formatter: null,
fontSize: 12
},
splitLine: {
show: true,
lineStyle: {
color: ['#E0E6F1'],
width: 1,
type: 'solid'
}
},
splitArea: {
show: false,
areaStyle: {
color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
}
}
};
const categoryAxis: AxisBaseOption = zrUtil.merge({
// The gap at both ends of the axis. For categoryAxis, boolean.
boundaryGap: true,
// Set false to faster category collection.
deduplication: null,
// splitArea: {
// show: false
// },
splitLine: {
show: false
},
axisTick: {
// If tick is align with label when boundaryGap is true
alignWithLabel: false,
interval: 'auto'
},
axisLabel: {
interval: 'auto'
}
}, defaultOption);
const valueAxis: AxisBaseOption = zrUtil.merge({
boundaryGap: [0, 0],
axisLine: {
// Not shown when other axis is categoryAxis in cartesian
show: 'auto'
},
axisTick: {
// Not shown when other axis is categoryAxis in cartesian
show: 'auto'
},
// TODO
// min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
splitNumber: 5,
minorTick: {
// Minor tick, not available for cateogry axis.
show: false,
// Split number of minor ticks. The value should be in range of (0, 100)
splitNumber: 5,
// Lenght of minor tick
length: 3,
// Line style
lineStyle: {
// Default to be same with axisTick
}
},
minorSplitLine: {
show: false,
lineStyle: {
color: '#F4F7FD',
width: 1
}
}
}, defaultOption);
const timeAxis: AxisBaseOption = zrUtil.merge({
scale: true,
splitNumber: 6,
axisLabel: {
// To eliminate labels that are not nice
showMinLabel: false,
showMaxLabel: false,
rich: {
primary: {
fontWeight: 'bold'
}
}
},
splitLine: {
show: false
}
}, valueAxis);
const logAxis: AxisBaseOption = zrUtil.defaults({
scale: true,
logBase: 10
}, valueAxis);
export default {
category: categoryAxis,
value: valueAxis,
time: timeAxis,
log: logAxis
};
| src/coord/axisDefault.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00019894832803402096,
0.0001722377201076597,
0.00016510652494616807,
0.00017126636521425098,
0.00000663518903820659
] |
{
"id": 9,
"code_window": [
" return out;\n",
" }\n",
"\n",
" pointToData(point: number[], out?: number[], reserved?: number[], clamp?: boolean): number[] {\n",
" out = out || [];\n",
" if (this._invTransform) {\n",
" return applyTransform(out, point, this._invTransform);\n",
" }\n",
" const xAxis = this.getAxis('x');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" pointToData(point: number[], clamp?: boolean): number[] {\n",
" const out: number[] = [];\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 148
} | /*
* 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.
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
factory(exports, require('echarts'));
} else {
// Browser globals
factory({}, root.echarts);
}
}(this, function (exports, echarts) {
var log = function (msg) {
if (typeof console !== 'undefined') {
console && console.error && console.error(msg);
}
}
if (!echarts) {
log('ECharts is not Loaded');
return;
}
if (!echarts.registerMap) {
log('ECharts Map is not loaded')
return;
}
echarts.registerMap('香港', {"type":"FeatureCollection","features":[{"id":"810001","type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[["@@D@bKBoCWKACBGCI@CJSVGFIBKCM@ABAF@LFHPFJJPFVB"],["@@ABD@@AA@"],["@@AAEAAB@DDBFC"]],"encodeOffsets":[[[116895,22829]],[[116861,22818]],[[116860,22817]]]},"properties":{"cp":[114.154334,22.281931],"name":"中西区","childNum":3}},{"id":"810002","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@BMHBBGD@BAHBD@HKDEF@FHDEDECCGCIAAQWCUBSBDXApREHD"],"encodeOffsets":[[116927,22822]]},"properties":{"cp":[114.18299,22.276345],"name":"湾仔区","childNum":1}},{"id":"810003","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@rWAGBEJKRO@ACCBEAIAEGEACKPA@MDICIDOBKDGAIBIABRNDHFEHADEGE@CFGLC@GAABC@AHECABAN|TTI"],"encodeOffsets":[[116967,22827]]},"properties":{"cp":[114.225965,22.279779],"name":"东区","childNum":1}},{"id":"810004","type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[["@@JBJAHBLCPAJCJDPCLOJM@IBAFBBA@CE@AAE@AAFIBQBADAFECCBEA@GFCAYBABIRC@QEGEACBEHMACECQACFE`A@GCK@AFFHADMJBBF@BB@FBHCFI@KLEBCAGWAAQDGCGJQHOPOHS`KLN@LDJAHETUDIJ@HDxCZD"],["@@ACCBFB"],["@@D@@ACCCB@CC@CFBDJA"],["@@BA@AG@@B@BF@"],["@@DABAGCADADBBDA"],["@@BAEBD@"]],"encodeOffsets":[[[116946,22787]],[[116886,22776]],[[116934,22767]],[[117006,22758]],[[116932,22748]],[[116970,22738]]]},"properties":{"cp":[114.160023,22.245811],"name":"南区","childNum":6}},{"id":"810005","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@AIBINQNIHU]IsRC@AvFBHFDCLDV@"],"encodeOffsets":[[116920,22860]]},"properties":{"cp":[114.173347,22.311632],"name":"油尖旺区","childNum":1}},{"id":"810006","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@H[@EEGU@KCCDGEEABQi@AHCF@B^P@BABOFCFBFF@FDNADADHJDjB"],"encodeOffsets":[[116919,22881]]},"properties":{"cp":[114.163349,22.333775],"name":"深水埗区","childNum":1}},{"id":"810007","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@DEBEFC@CJKD@DCHDLDBMEG@CFCLICETSDQSJeMGVKHGJIR@HFJBFG^FDF@"],"encodeOffsets":[[116925,22883]]},"properties":{"cp":[114.193047,22.312373],"name":"九龙城区","childNum":1}},{"id":"810008","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@AC@IH_BAYCEDIAGDICGCCDC@IL@DEDAFCFNDVD@BADBBHCFDJA^D"],"encodeOffsets":[[116970,22892]]},"properties":{"cp":[114.203985,22.336112],"name":"黄大仙区","childNum":1}},{"id":"810009","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@F@HWF@DABD@IHBB@GOAENMBE@AEAGOBCFE@CqXCRSTDFKJED@DFHANFCJBFCZD"],"encodeOffsets":[[116974,22868]]},"properties":{"cp":[114.214083,22.320679],"name":"观塘区","childNum":1}},{"id":"810010","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@AEDQ@WQACIKIGCQCABAHC@]I@ADC@ECICCKEGA@NuASIHyO@IEQW@CÙF~bNJFL@D@FLBBNPJJFIDAHEDBDHBDDBBTCB@AHDB^@@JHHF@DDLFJFDBHCD@PPD@L@RLLBDHVBNAHBBABGhB"],"encodeOffsets":[[116914,22950]]},"properties":{"cp":[114.121234,22.368458],"name":"荃湾区","childNum":1}},{"id":"810011","type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[["@@AC@G]@CABGA@SDAACCGAACFCBGJCIEOIAMKAEHGFgFgPS@E@MEGEEGCAO@E@SLUNCH@DDH@H@JEHAJCHQFAB\\`ZHTCFKBAHFFJFJBBZ@FC^CND@AEINGXA@OL@@U@@HN@BEE@@KTA@G"],["@@BAFADAAC@AACDACGEBBHAFGFBDD@"],["@@B@B@@CA@AD"],["@@BAB@CCA@ABDD"],["@@D@CGABAFD@"],["@@@ACICABJFD"],["@@DA@ACCC@ADBFBBBC"],["@@@A@@ABB@"]],"encodeOffsets":[[[116810,22924]],[[116618,22917]],[[116612,22891]],[[116626,22888]],[[116629,22880]],[[116725,22874]],[[116708,22866]],[[116720,22861]]]},"properties":{"cp":[113.976308,22.393896],"name":"屯门区","childNum":8}},{"id":"810012","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@BMDIEK@CDCAMHG@C@MCG@YBAZHZDLIJA[gAGBEHMTO@EAIKAQKK@C@OOC@GDCAIEKECCE@EE@HSB@LF@AFM@@G@@VK@@PWBMHFJ@BMC]DEDY@AAEIEIGEABELSDVHNRJPHJLHXHFBP^ZVBRB@\\CJIDEH@DDAJHDFF@DGL@FFB^CRED@JFDPJHPBHED@HFFF"],"encodeOffsets":[[116828,23059]]},"properties":{"cp":[114.032528,22.44132],"name":"元朗区","childNum":1}},{"id":"810013","type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[["@@A@@HIEK@EA@BDH@BBBD@BBBAB@MN@DH@@BEFBDFBDA@C@@VABBDAJ@B@D@D@@CC@ECGB@ACACCA@IFEBAC@CFABEHGF@BACGGB"],["@@DC@CEDAFB@BA"],["@@AABB"],["@@@AC@DB"],["@@AABB"],["@@BAAAEABDDB"],["@@@A@CEDBBD@"],["@@@AABB@"],["@@DA@CIE@JFB"],["@@@@@@@@"],["@@DCD@BNDBDIAE@I@EE@ABABOHAJDDFABC"],["@@@A@B"],["@@B@B@ECAFB@BA"],["@@AA@BB@"],["@@@@A@B@"],["@@A@B@@@"],["@@@A@B"],["@@BCAB@B"],["@@@A@B"],["@@@FBCDBDABBBBBABCB@ABDBBDB@DH@JABBDNEBE@CD@FCKKG@AEC@EBA@ACIEA@EDBB@DB@ED"],["@@A@B@"],["@@D@BCG@ADBBBA"],["@@@@@@"],["@@BAAB"],["@@A@B@"],["@@@@AABB"],["@@QCKMECAKH@FDD@FFDABAFBBHJBPZBDJ@BCD@BBHA@DF@HAAAEEDA@EF@DGF@BC@CGE@GFBLABBADBBDAH@D@@AEIBAFF@ADBDAGGAEA@EIBCLBBA@CDBBCHBBABCTKLFZHRJH@DASMQGGIOEGAGBaNM@eEK@EDKLGBCFEBAAAGGGEEEIIGAEIDU@GBK@IDUAIAEEEGCIEBEAAHM@AABC@EKCWOMEIBKJYCYGAB@ZDH@N@DGHBNCFFNEN@JBFMJBDNDFHFBHEDALDFAFD@KFAFDBFH@FHDBF@DFHAHDLABAFBBDFF@BAAA@@D@DD@@HH@LLDCJFFCJ@BABEFABBJAB@DADDH@BBB@FBDCPBFEJBFC@AFADC@IDA"]],"encodeOffsets":[[[117049,23071]],[[117017,23092]],[[117013,23092]],[[117010,23091]],[[117004,23090]],[[117009,23086]],[[117081,23081]],[[117014,23081]],[[117057,23081]],[[117015,23077]],[[117062,23071]],[[117020,23075]],[[117024,23072]],[[117021,23072]],[[117029,23071]],[[117037,23071]],[[116974,23071]],[[116957,23067]],[[117036,23065]],[[117043,23049]],[[117033,23064]],[[117035,23059]],[[117043,23052]],[[117049,23053]],[[117040,23048]],[[117054,23039]],[[116975,23082]]]},"properties":{"cp":[114.147404,22.496143],"name":"北区","childNum":27}},{"id":"810014","type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[["@@HGNA@ACGC@G@OFADCL@FDDJDBA@M"],["@@@EACUMIMGGGCE@@CACIEMCMISGG@CESIGKGEQGG@CBABALQTCDABC@GCK@EBCACAAKBAHABAB@HA@AE@@ENADBDLFBFABACGEEICG@ICQB@B@J@@GBAAEEAODERKMIGMAAUAAAUA@ACAAA[ASAAHABGAMBUAAA@D@FSPIRBJ\\hNFXPLD@FADBBN@BGFBFAHPDFHD\\BJCL@HAV@JCBFJHFJFFHHBHDBHGHALKFCL@fFN@bMLATHHJRHTN"],["@@CIEAEJBBBDBBBBHAFBEG"],["@@@CFABAAGCC@ECCEACB@HAJAB@FEDJJDBHABA@CAC"],["@@BAEBBBBA"],["@@^DLCFBBBBJFJNLH@DHN@NXJFFHPHDABABKDAFDDABGAEBCDBFFALDDBFDBDADIBIFOCCICAAAI@CDG@KJ@HEBBDJCBALDBFBBBDB@HBHHALEDE@IEG@EGA@EDIBYEGAIEEICADMFOLA@KEE@OHKHYDAC@KCECAS@CCAEBGGOK@CACIYCEAGEBLCH@JGJ@FBXCHDL@P"],["@@AEA@ABB@@FB@BA"],["@@@CABBB"],["@@BAAAABBB"],["@@BACDBA"],["@@@A@B"],["@@@DHBAEC@A@"],["@@AA@BB@"],["@@BB@CAA@D"]],"encodeOffsets":[[[117183,23086]],[[117087,23049]],[[117113,23039]],[[117114,23018]],[[117122,23021]],[[116998,22974]],[[117082,23017]],[[117084,23018]],[[117081,23013]],[[117180,23003]],[[117039,23001]],[[116966,22997]],[[117006,22983]],[[116968,22976]]]},"properties":{"cp":[114.171713,22.44573],"name":"大埔区","childNum":14}},{"id":"810015","type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[["@@B@@@C@BB@A"],["@@FIJBFCF@JDF@DDBEDBDEHACGDK@EFEFK@EGAI@CDILEBEAIG@C@EECCKBCJEFGFAJGAGDKEGDG@GCCC@CBCFC@AIGAACFEEACC@CEAGB@EC@@AID@KBC@CACCGE@ABALGLBFA@GGEAE@GJAFBFIFCJHN@JOFGFG@@DBHABCFKAAEDCACI@GBGAAFI@GJEBE@ECAEBICCCU@KJI@IGKIBAAHcDEFENAFADE@CDGDET@BCBEJGDKAIKEEEGAACBCF@DA@MHI@CACCAE@AGE@OLEHGBAA@CECCGEAEBITGDANHRGLCDG@QSEG@DEDADHPFB@BEJIJBFHPA@GA@JACCBEBGVE@ABG`@JBDB@ADBFPBPJLLBJRDAJHFFBZDFLN@HPAHBFDDT@DBDF@LBDZCLGPGF@LFB@PKNEBCJDFFBJFHAZCJ@FHB"],["@@A@@@B@"],["@@@@@@"],["@@AABB"],["@@BAC@@DBA"],["@@BAA@ABB@"],["@@@AABB@"],["@@@AABB@"],["@@B@BACEC@@DDD"],["@@A@B@"],["@@@AADBA"],["@@DC@CA@ADA@ADD@"],["@@DBFADBLC@MDEBIA@@GJAHGCCBEAA@CCA@CAEKBEBGACBEDEJAFHHAB@LABBDA@@AA@CBBB@DD@@DCDCB@JBBHA"],["@@@AAAAD@@D@"],["@@@A@B@@"],["@@HE@C@ICAA@AHAHCEEFBF@BD@FA"],["@@BACA@CC@@DFD"],["@@@AA@BB"],["@@BCFE@ACCDQCACB@FCBCLGHFFBHFDB@DE@AEBBE"],["@@@ACAAFFA"],["@@BA@@CBB@"],["@@B@C@BB@A"],["@@@AABB@"],["@@@AA@@DBB@C"],["@@ACABDB"],["@@BAAB"],["@@@@@@"],["@@BACA@BBB"],["@@A@BB@A"],["@@FADIFEAICAACC@ABI@CFBDCD@BCHFFLB"],["@@CEBEBACA@AA@KD@JBHH@@BF@BE"],["@@@@A@B@"],["@@@CE@BFB@BA"],["@@AB@FDC@AAA"],["@@DHFEDAFGACBCMBEJ@D"],["@@BADABAB@BCKBCFDB"],["@@B@B@C@"],["@@A@@BB@@A"],["@@D@C@@@"],["@@BAAB"],["@@@AA@BB"],["@@BAAB@@"],["@@@AADBA"],["@@@@@@"],["@@@A@B"],["@@AA@DBA"],["@@@A@B"],["@@@A@B"],["@@@AABB@"],["@@BAEBBBBA"],["@@@@@@"],["@@A@B@"],["@@BC@AAAEDBDD@"],["@@B@@AAB"],["@@BACKAAC@@JDDBBB@"],["@@AA@B@@B@"],["@@BCA@@D"],["@@@@@@"],["@@@A@B"],["@@@EAABAE@AAA@@JF@@FBBBA@C"],["@@@CCB@BD@"],["@@AA@GAAEAAE@@E@AJFLDDFADFF@@EEC"],["@@AFDBJBAADCDEACFEGA@EEB@FEDAH"],["@@JDB@ACDC@AA@ACB@@ADA@EC@@EAEC@E@AECAABBFIBED@F@DFHFDDAFF"]],"encodeOffsets":[[[117146,22985]],[[117119,22980]],[[117154,22972]],[[117153,22970]],[[117139,22942]],[[117137,22939]],[[117137,22938]],[[117033,22925]],[[117063,22925]],[[117066,22923]],[[117031,22921]],[[117064,22919]],[[117029,22917]],[[117054,22915]],[[117038,22915]],[[117048,22915]],[[117075,22911]],[[117036,22912]],[[117039,22911]],[[117043,22905]],[[117051,22909]],[[117044,22906]],[[117050,22906]],[[117074,22902]],[[117143,22898]],[[117036,22899]],[[117076,22898]],[[117116,22882]],[[117120,22880]],[[117102,22876]],[[117073,22876]],[[117119,22871]],[[117126,22873]],[[117085,22870]],[[117121,22865]],[[117041,22863]],[[117123,22866]],[[117118,22860]],[[117118,22859]],[[117118,22859]],[[117069,22860]],[[117077,22857]],[[117116,22856]],[[117068,22845]],[[117059,22840]],[[117059,22838]],[[117061,22837]],[[117066,22837]],[[117066,22837]],[[117061,22835]],[[117070,22834]],[[117061,22834]],[[117068,22833]],[[117064,22810]],[[117100,22804]],[[117100,22803]],[[117118,22799]],[[117120,22799]],[[117028,22798]],[[117095,22795]],[[117103,22791]],[[117097,22787]],[[117105,22856]],[[117111,22850]],[[117039,22789]]]},"properties":{"cp":[114.264813,22.314203],"name":"西贡区","childNum":65}},{"id":"810016","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@PGJAVDFD@HDBJBPA@OCKDGAYHM@IDGAKBIQCAIKKOIMACEBC_CIBECGDAABC@AUCKCG@ICeAICAAGHAL@FFJCP@FDHADLBFDLJDJRB@XCRBFHBBBDB@BVBBBXBHPNJ"],"encodeOffsets":[[116956,22970]]},"properties":{"cp":[114.195126,22.379715],"name":"沙田区","childNum":1}},{"id":"810017","type":"Feature","geometry":{"type":"Polygon","coordinates":["@@AECBMBECGA@CDEPEBA]QDGBGj@@cUADF@F@DCFIFSJQTQBaASPEBGzTJvB@MHBLFDDDJ@FCD@@ZJHBBIJBBCCI@GDKEI@EBKHG"],"encodeOffsets":[[116892,22877]]},"properties":{"cp":[114.13918,22.363908],"name":"葵青区","childNum":1}},{"id":"810018","type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[["@@AIIGQCQ@GE@G@ICCGAAABCBA@GBGCA@ADOAGO@KBMLC@ACAEFARSDEACSGCEACLIL@DEPCBACEAECCE@AACEIECCKCMGI@KJGJEJ@FDLIBSGUAOOSEAABE@ECG_CSBUPAHGBICEOUMGCKBC@GCGGMCABDRGDAF@HBFEHAP@JJJH@BNRFDDBHEBICAH@DPHF@DAFFFNLBRFBHNNBD@HEJJVED@DBDZD@DEPFBAFCBAI[@CFGF@~dÚE"],["@@DC@AKE@ABADDF@BCFCAAIEG@CBAB@DABAFGDBBXF"],["@@BAAAC@ADDBBA"],["@@BCAAIBA@BDBDJB@CAA"],["@@BCCGGCGBABBHFDL@"],["@@J@FC@AAKFGCIC@EDADAD@B@BCBAAEHI@AF@BB@@DT@"],["@@CEMI@ABEHHFBHBHAFDFBF@BCLBDC@AGIK@OMDKJM@CAAC@YP@AHKAGAACBGHEGC@GBMDCD@HBDFDDDBXCFBNAHEBA@@IEAGCK@CNBDLHHD@BEBDFGD@DVJBBBBBCF@BECGACLGBEAADEDADFF@DE@E"],["@@@CEA@DDDBA"],["@@FEFBD@DEC@@CCAACGF@AE@CCBAC@CCCCCBBBG@AHH@DHH@DFADABE@CD@BD@DF@BABBDDBH@DBDB@E@AEAFABAKCAA@EDA"],["@@D@ACAACD@B@BDA"],["@@BAC@BB"],["@@B@BBBA@EACGAEFA@GDBHJJFA@CB@BCAA@C"],["@@D@BCBEAECCGC@BIB@CAA@FA@@PTD"],["@@DE@KG@CBAHBDDABFB@"],["@@BB@CAB"],["@@BHBB@CAEA@"],["@@BADBDABAD@BAAABAAAABABAA@CA@ADAAAB@DABCACCC@BRHCBC"],["@@@A@ACA@DDB"],["@@DAAC@@CD@BB@"],["@@ABBA"],["@@BAC@BB"],["@@AAA@BDBA"],["@@A@B@"],["@@BBBAAAABCAA@FB"],["@@@BD@DDCDBDDBDAB@FCAAE@@EBABEE@CAI@AACAGF@DFDF@DA"],["@@@A@A@D"],["@@BACA@BBB"],["@@B@@AEABBBB"],["@@DFPFBFF@BCFCFICCDEBIQA@DA@EC@ECCEAE@FJIBABD@@DCAABBJDF"]],"encodeOffsets":[[[116799,22849]],[[116787,22826]],[[116803,22822]],[[116823,22817]],[[116799,22797]],[[116780,22791]],[[116882,22747]],[[116881,22757]],[[116774,22741]],[[116575,22748]],[[116686,22746]],[[116733,22725]],[[117001,22721]],[[117036,22720]],[[117038,22719]],[[117053,22714]],[[116651,22714]],[[117053,22714]],[[116664,22710]],[[116665,22706]],[[116984,22706]],[[116645,22704]],[[116647,22703]],[[116640,22702]],[[116646,22692]],[[116656,22693]],[[116663,22685]],[[116998,22691]],[[117001,22702]]]},"properties":{"cp":[113.946059,22.286371],"name":"离岛区","childNum":29}}],"UTF8Encoding":true});
})); | test/data/map/js/province/xianggang.js | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0001769216760294512,
0.0001710942160570994,
0.00016330314974766225,
0.00017027798458002508,
0.0000049945656428462826
] |
{
"id": 9,
"code_window": [
" return out;\n",
" }\n",
"\n",
" pointToData(point: number[], out?: number[], reserved?: number[], clamp?: boolean): number[] {\n",
" out = out || [];\n",
" if (this._invTransform) {\n",
" return applyTransform(out, point, this._invTransform);\n",
" }\n",
" const xAxis = this.getAxis('x');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" pointToData(point: number[], clamp?: boolean): number[] {\n",
" const out: number[] = [];\n"
],
"file_path": "src/coord/cartesian/Cartesian2D.ts",
"type": "replace",
"edit_start_line_idx": 148
} | /*
* 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 * as zrUtil from 'zrender/src/core/util';
import { ECUnitOption, AriaOptionMixin } from '../../util/types';
export default function ariaPreprocessor(option: ECUnitOption & AriaOptionMixin) {
if (!option || !option.aria) {
return;
}
const aria = option.aria;
// aria.show is deprecated and should use aria.enabled instead
if ((aria as any).show != null) {
aria.enabled = (aria as any).show;
}
aria.label = aria.label || {};
// move description, general, series, data to be under aria.label
zrUtil.each(['description', 'general', 'series', 'data'], name => {
if ((aria as any)[name] != null) {
(aria.label as any)[name] = (aria as any)[name];
}
});
}
| src/component/aria/preprocessor.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.000176425208337605,
0.00017190948710776865,
0.00016649553435854614,
0.00017149531049653888,
0.0000038760649658797774
] |
{
"id": 10,
"code_window": [
" valuePair[valueDimIdx] = data.get(valueDim, dataIndex);\n",
" valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);\n",
"\n",
" coord = cartesian.dataToPoint(valuePair, null, coord);\n",
" // Data index might not be in order, depends on `progressiveChunkMode`.\n",
" largeBackgroundPoints[pointsOffset] =\n",
" valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];\n",
" largePoints[pointsOffset++] = coord[0];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" coord = cartesian.dataToPoint(valuePair, null);\n"
],
"file_path": "src/layout/barGrid.ts",
"type": "replace",
"edit_start_line_idx": 593
} | /*
* 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 { each, indexOf, curry, assert, map, createHashMap } from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as brushHelper from './brushHelper';
import {
BrushPanelConfig, BrushControllerEvents, BrushType,
BrushAreaRange, BrushDimensionMinMax
} from './BrushController';
import ExtensionAPI from '../../core/ExtensionAPI';
import GridModel from '../../coord/cartesian/GridModel';
import GeoModel from '../../coord/geo/GeoModel';
import { CoordinateSystemMaster } from '../../coord/CoordinateSystem';
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Geo from '../../coord/geo/Geo';
import GlobalModel from '../../model/Global';
import { BrushAreaParam, BrushAreaParamInternal } from '../brush/BrushModel';
import SeriesModel from '../../model/Series';
import { Dictionary } from '../../util/types';
import {
ModelFinderObject, ParsedModelFinder, ModelFinder,
parseFinder as modelUtilParseFinder,
ParsedModelFinderKnown
} from '../../util/model';
const COORD_CONVERTS = ['dataToPoint', 'pointToData'] as const;
type COORD_CONVERTS_INDEX = 0 | 1;
// FIXME
// how to genarialize to more coordinate systems.
const INCLUDE_FINDER_MAIN_TYPES = [
'grid', 'xAxis', 'yAxis', 'geo', 'graph',
'polar', 'radiusAxis', 'angleAxis', 'bmap'
];
type BrushableCoordinateSystem = Cartesian2D | Geo;
type BrushTargetBuilderKey = 'grid' | 'geo';
/**
* There can be multiple axes in a single targetInfo. Consider the case
* of `grid` component, a targetInfo represents a grid which contains one or more
* cartesian and one or more axes. And consider the case of parallel system,
* which has multiple axes in a coordinate system.
*/
interface BrushTargetInfo {
panelId: string;
coordSysModel: CoordinateSystemMaster['model'];
// Use the first one as the representitive coordSys.
// A representitive cartesian in grid (first cartesian by default).
coordSys: BrushableCoordinateSystem;
// All cartesians.
coordSyses: BrushableCoordinateSystem[];
getPanelRect: GetPanelRect,
}
export interface BrushTargetInfoCartesian2D extends BrushTargetInfo {
gridModel: GridModel;
coordSys: Cartesian2D;
coordSyses: Cartesian2D[];
xAxisDeclared: boolean;
yAxisDeclared: boolean;
}
export interface BrushTargetInfoGeo extends BrushTargetInfo {
geoModel: GeoModel,
coordSysModel: GeoModel,
coordSys: Geo,
coordSyses: Geo[],
}
type GetPanelRect = () => graphic.BoundingRect;
class BrushTargetManager {
private _targetInfoList: BrushTargetInfo[] = [];
/**
* @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
* Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
* @param opt.include include coordinate system types.
*/
constructor(
finder: ModelFinderObject,
ecModel: GlobalModel,
opt?: {include?: BrushTargetBuilderKey[]}
) {
const foundCpts = parseFinder(ecModel, finder);
each(targetInfoBuilders, (builder, type) => {
if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
builder(foundCpts, this._targetInfoList);
}
});
}
setOutputRanges(
areas: BrushControllerEvents['brush']['areas'],
ecModel: GlobalModel
): BrushAreaParam[] {
this.matchOutputRanges(areas, ecModel, function (
area: BrushAreaParam,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem
) {
(area.coordRanges || (area.coordRanges = [])).push(coordRange);
// area.coordRange is the first of area.coordRanges
if (!area.coordRange) {
area.coordRange = coordRange;
// In 'category' axis, coord to pixel is not reversible, so we can not
// rebuild range by coordRange accrately, which may bring trouble when
// brushing only one item. So we use __rangeOffset to rebuilding range
// by coordRange. And this it only used in brush component so it is no
// need to be adapted to coordRanges.
const result = coordConvert[area.brushType](0, coordSys, coordRange);
area.__rangeOffset = {
offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
xyMinMax: result.xyMinMax
};
}
});
return areas;
}
matchOutputRanges<T extends (
Parameters<BrushTargetManager['findTargetInfo']>[0] & {
brushType: BrushType;
range: BrushAreaRange;
}
)>(
areas: T[],
ecModel: GlobalModel,
cb: (
area: T,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem,
ecModel: GlobalModel
) => void
) {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (targetInfo && targetInfo !== true) {
each(
targetInfo.coordSyses,
function (coordSys) {
const result = coordConvert[area.brushType](1, coordSys, area.range, true);
cb(area, result.values, coordSys, ecModel);
}
);
}
}, this);
}
/**
* the `areas` is `BrushModel.areas`.
* Called in layout stage.
* convert `area.coordRange` to global range and set panelId to `area.range`.
*/
setInputRanges(
areas: BrushAreaParamInternal[],
ecModel: GlobalModel
): void {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (__DEV__) {
assert(
!targetInfo || targetInfo === true || area.coordRange,
'coordRange must be specified when coord index specified.'
);
assert(
!targetInfo || targetInfo !== true || area.range,
'range must be specified in global brush.'
);
}
area.range = area.range || [];
// convert coordRange to global range and set panelId.
if (targetInfo && targetInfo !== true) {
area.panelId = targetInfo.panelId;
// (1) area.range shoule always be calculate from coordRange but does
// not keep its original value, for the sake of the dataZoom scenario,
// where area.coordRange remains unchanged but area.range may be changed.
// (2) Only support converting one coordRange to pixel range in brush
// component. So do not consider `coordRanges`.
// (3) About __rangeOffset, see comment above.
const result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
const rangeOffset = area.__rangeOffset;
area.range = rangeOffset
? diffProcessor[area.brushType](
result.values,
rangeOffset.offset,
getScales(result.xyMinMax, rangeOffset.xyMinMax)
)
: result.values;
}
}, this);
}
makePanelOpts(
api: ExtensionAPI,
getDefaultBrushType?: (targetInfo: BrushTargetInfo) => BrushType
): BrushPanelConfig[] {
return map(this._targetInfoList, function (targetInfo) {
const rect = targetInfo.getPanelRect();
return {
panelId: targetInfo.panelId,
defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
clipPath: brushHelper.makeRectPanelClipPath(rect),
isTargetByCursor: brushHelper.makeRectIsTargetByCursor(
rect, api, targetInfo.coordSysModel
),
getLinearBrushOtherExtent: brushHelper.makeLinearBrushOtherExtent(rect)
};
});
}
controlSeries(area: BrushAreaParamInternal, seriesModel: SeriesModel, ecModel: GlobalModel): boolean {
// Check whether area is bound in coord, and series do not belong to that coord.
// If do not do this check, some brush (like lineX) will controll all axes.
const targetInfo = this.findTargetInfo(area, ecModel);
return targetInfo === true || (
targetInfo && indexOf(
targetInfo.coordSyses, seriesModel.coordinateSystem as BrushableCoordinateSystem
) >= 0
);
}
/**
* If return Object, a coord found.
* If reutrn true, global found.
* Otherwise nothing found.
*/
findTargetInfo(
area: ModelFinderObject & {
panelId?: string
},
ecModel: GlobalModel
): BrushTargetInfo | true {
const targetInfoList = this._targetInfoList;
const foundCpts = parseFinder(ecModel, area);
for (let i = 0; i < targetInfoList.length; i++) {
const targetInfo = targetInfoList[i];
const areaPanelId = area.panelId;
if (areaPanelId) {
if (targetInfo.panelId === areaPanelId) {
return targetInfo;
}
}
else {
for (let j = 0; j < targetInfoMatchers.length; j++) {
if (targetInfoMatchers[j](foundCpts, targetInfo)) {
return targetInfo;
}
}
}
}
return true;
}
}
function formatMinMax(minMax: BrushDimensionMinMax): BrushDimensionMinMax {
minMax[0] > minMax[1] && minMax.reverse();
return minMax;
}
function parseFinder(
ecModel: GlobalModel, finder: ModelFinder
): ParsedModelFinderKnown {
return modelUtilParseFinder(
ecModel, finder, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
);
}
type TargetInfoBuilder = (
foundCpts: ParsedModelFinderKnown, targetInfoList: BrushTargetInfo[]
) => void;
const targetInfoBuilders: Record<BrushTargetBuilderKey, TargetInfoBuilder> = {
grid: function (foundCpts, targetInfoList) {
const xAxisModels = foundCpts.xAxisModels;
const yAxisModels = foundCpts.yAxisModels;
const gridModels = foundCpts.gridModels;
// Remove duplicated.
const gridModelMap = createHashMap<GridModel>();
const xAxesHas = {} as Dictionary<boolean>;
const yAxesHas = {} as Dictionary<boolean>;
if (!xAxisModels && !yAxisModels && !gridModels) {
return;
}
each(xAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
});
each(yAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
yAxesHas[gridModel.id] = true;
});
each(gridModels, function (gridModel) {
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
yAxesHas[gridModel.id] = true;
});
gridModelMap.each(function (gridModel) {
const grid = gridModel.coordinateSystem;
const cartesians = [] as Cartesian2D[];
each(grid.getCartesians(), function (cartesian, index) {
if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0
|| indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0
) {
cartesians.push(cartesian);
}
});
targetInfoList.push({
panelId: 'grid--' + gridModel.id,
gridModel: gridModel,
coordSysModel: gridModel,
// Use the first one as the representitive coordSys.
coordSys: cartesians[0],
coordSyses: cartesians,
getPanelRect: panelRectBuilders.grid,
xAxisDeclared: xAxesHas[gridModel.id],
yAxisDeclared: yAxesHas[gridModel.id]
} as BrushTargetInfoCartesian2D);
});
},
geo: function (foundCpts, targetInfoList) {
each(foundCpts.geoModels, function (geoModel: GeoModel) {
const coordSys = geoModel.coordinateSystem;
targetInfoList.push({
panelId: 'geo--' + geoModel.id,
geoModel: geoModel,
coordSysModel: geoModel,
coordSys: coordSys,
coordSyses: [coordSys],
getPanelRect: panelRectBuilders.geo
} as BrushTargetInfoGeo);
});
}
};
type TargetInfoMatcher = (
foundCpts: ParsedModelFinderKnown, targetInfo: BrushTargetInfo
) => boolean;
const targetInfoMatchers: TargetInfoMatcher[] = [
// grid
function (foundCpts, targetInfo) {
const xAxisModel = foundCpts.xAxisModel;
const yAxisModel = foundCpts.yAxisModel;
let gridModel = foundCpts.gridModel;
!gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
!gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
return gridModel && gridModel === (targetInfo as BrushTargetInfoCartesian2D).gridModel;
},
// geo
function (foundCpts, targetInfo) {
const geoModel = foundCpts.geoModel;
return geoModel && geoModel === (targetInfo as BrushTargetInfoGeo).geoModel;
}
];
type PanelRectBuilder = (this: BrushTargetInfo) => graphic.BoundingRect;
const panelRectBuilders: Record<BrushTargetBuilderKey, PanelRectBuilder> = {
grid: function (this: BrushTargetInfoCartesian2D) {
// grid is not Transformable.
return this.coordSys.master.getRect().clone();
},
geo: function (this: BrushTargetInfoGeo) {
const coordSys = this.coordSys;
const rect = coordSys.getBoundingRect().clone();
// geo roam and zoom transform
rect.applyTransform(graphic.getTransform(coordSys));
return rect;
}
};
type ConvertCoord = (
to: COORD_CONVERTS_INDEX,
coordSys: BrushableCoordinateSystem,
rangeOrCoordRange: BrushAreaRange,
clamp?: boolean
) => {
values: BrushAreaRange,
xyMinMax: BrushDimensionMinMax[]
};
const coordConvert: Record<BrushType, ConvertCoord> = {
lineX: curry(axisConvert, 0),
lineY: curry(axisConvert, 1),
rect: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xminymin = to
? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
const xmaxymax = to
? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], [], [], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
const values = [
formatMinMax([xminymin[0], xmaxymax[0]]),
formatMinMax([xminymin[1], xmaxymax[1]])
];
return {values: values, xyMinMax: values};
},
polygon: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
const values = map(rangeOrCoordRange, function (item) {
const p = to ? coordSys.pointToData(item, [], [], clamp) : coordSys.dataToPoint(item);
xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
return p;
});
return {values: values, xyMinMax: xyMinMax};
}
};
function axisConvert(
axisNameIndex: 0 | 1,
to: COORD_CONVERTS_INDEX,
coordSys: Cartesian2D,
rangeOrCoordRange: BrushDimensionMinMax
): {
values: BrushDimensionMinMax,
xyMinMax: BrushDimensionMinMax[]
} {
if (__DEV__) {
assert(
coordSys.type === 'cartesian2d',
'lineX/lineY brush is available only in cartesian2d.'
);
}
const axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
const values = formatMinMax(map([0, 1], function (i) {
return to
? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true)
: axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
}));
const xyMinMax = [];
xyMinMax[axisNameIndex] = values;
xyMinMax[1 - axisNameIndex] = [NaN, NaN];
return {values: values, xyMinMax: xyMinMax};
}
type DiffProcess = (
values: BrushDimensionMinMax | BrushDimensionMinMax[],
refer: BrushDimensionMinMax | BrushDimensionMinMax[],
scales: ReturnType<typeof getScales>
) => BrushDimensionMinMax | BrushDimensionMinMax[];
const diffProcessor: Record<BrushType, DiffProcess> = {
lineX: curry(axisDiffProcessor, 0),
lineY: curry(axisDiffProcessor, 1),
rect: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return [
[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
[values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
];
},
polygon: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return map(values, function (item, idx) {
return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
});
}
};
function axisDiffProcessor(
axisNameIndex: 0 | 1,
values: BrushDimensionMinMax,
refer: BrushDimensionMinMax,
scales: ReturnType<typeof getScales>
): BrushDimensionMinMax {
return [
values[0] - scales[axisNameIndex] * refer[0],
values[1] - scales[axisNameIndex] * refer[1]
];
}
// We have to process scale caused by dataZoom manually,
// although it might be not accurate.
// Return [0~1, 0~1]
function getScales(xyMinMaxCurr: BrushDimensionMinMax[], xyMinMaxOrigin: BrushDimensionMinMax[]): number[] {
const sizeCurr = getSize(xyMinMaxCurr);
const sizeOrigin = getSize(xyMinMaxOrigin);
const scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
function getSize(xyMinMax: BrushDimensionMinMax[]): number[] {
return xyMinMax
? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
: [NaN, NaN];
}
export default BrushTargetManager;
| src/component/helper/BrushTargetManager.ts | 1 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0006352956988848746,
0.00018490008369553834,
0.0001618906098883599,
0.00016784615581855178,
0.00008655158308101818
] |
{
"id": 10,
"code_window": [
" valuePair[valueDimIdx] = data.get(valueDim, dataIndex);\n",
" valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);\n",
"\n",
" coord = cartesian.dataToPoint(valuePair, null, coord);\n",
" // Data index might not be in order, depends on `progressiveChunkMode`.\n",
" largeBackgroundPoints[pointsOffset] =\n",
" valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];\n",
" largePoints[pointsOffset++] = coord[0];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" coord = cartesian.dataToPoint(valuePair, null);\n"
],
"file_path": "src/layout/barGrid.ts",
"type": "replace",
"edit_start_line_idx": 593
} | /*
* 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 {isDimensionStacked} from '../../data/helper/dataStackHelper';
import {map} from 'zrender/src/core/util';
import type Polar from '../../coord/polar/Polar';
import type Cartesian2D from '../../coord/cartesian/Cartesian2D';
import List from '../../data/List';
import Axis from '../../coord/Axis';
import type { LineSeriesOption } from './LineSeries';
interface CoordInfo {
dataDimsForPoint: string[]
valueStart: number
valueAxisDim: string
baseAxisDim: string
stacked: boolean
valueDim: string
baseDim: string
baseDataOffset: number
stackedOverDimension: string
}
export function prepareDataCoordInfo(
coordSys: Cartesian2D | Polar,
data: List,
valueOrigin?: LineSeriesOption['areaStyle']['origin']
): CoordInfo {
const baseAxis = coordSys.getBaseAxis();
const valueAxis = coordSys.getOtherAxis(baseAxis as any);
const valueStart = getValueStart(valueAxis, valueOrigin);
const baseAxisDim = baseAxis.dim;
const valueAxisDim = valueAxis.dim;
const valueDim = data.mapDimension(valueAxisDim);
const baseDim = data.mapDimension(baseAxisDim);
const baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
const dims = map(coordSys.dimensions, function (coordDim) {
return data.mapDimension(coordDim);
});
let stacked = false;
const stackResultDim = data.getCalculationInfo('stackResultDimension');
if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
stacked = true;
dims[0] = stackResultDim;
}
if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
stacked = true;
dims[1] = stackResultDim;
}
return {
dataDimsForPoint: dims,
valueStart: valueStart,
valueAxisDim: valueAxisDim,
baseAxisDim: baseAxisDim,
stacked: !!stacked,
valueDim: valueDim,
baseDim: baseDim,
baseDataOffset: baseDataOffset,
stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
};
}
function getValueStart(valueAxis: Axis, valueOrigin: LineSeriesOption['areaStyle']['origin']) {
let valueStart = 0;
const extent = valueAxis.scale.getExtent();
if (valueOrigin === 'start') {
valueStart = extent[0];
}
else if (valueOrigin === 'end') {
valueStart = extent[1];
}
// auto
else {
// Both positive
if (extent[0] > 0) {
valueStart = extent[0];
}
// Both negative
else if (extent[1] < 0) {
valueStart = extent[1];
}
// If is one positive, and one negative, onZero shall be true
}
return valueStart;
}
export function getStackedOnPoint(
dataCoordInfo: CoordInfo,
coordSys: Cartesian2D | Polar,
data: List,
idx: number
) {
let value = NaN;
if (dataCoordInfo.stacked) {
value = data.get(data.getCalculationInfo('stackedOverDimension'), idx) as number;
}
if (isNaN(value)) {
value = dataCoordInfo.valueStart;
}
const baseDataOffset = dataCoordInfo.baseDataOffset;
const stackedData = [];
stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
stackedData[1 - baseDataOffset] = value;
return coordSys.dataToPoint(stackedData);
}
| src/chart/line/helper.ts | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.004981589037925005,
0.0007007063250057399,
0.00016434240387752652,
0.00017691189714241773,
0.001269686152227223
] |
{
"id": 10,
"code_window": [
" valuePair[valueDimIdx] = data.get(valueDim, dataIndex);\n",
" valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);\n",
"\n",
" coord = cartesian.dataToPoint(valuePair, null, coord);\n",
" // Data index might not be in order, depends on `progressiveChunkMode`.\n",
" largeBackgroundPoints[pointsOffset] =\n",
" valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];\n",
" largePoints[pointsOffset++] = coord[0];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" coord = cartesian.dataToPoint(valuePair, null);\n"
],
"file_path": "src/layout/barGrid.ts",
"type": "replace",
"edit_start_line_idx": 593
} |
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
</head>
<body>
<style>
html, body, #main {
width: 100%;
height: 100%;
}
</style>
<div id="main"></div>
<script>
require([
'echarts'
// 'echarts/chart/scatter',
// 'echarts/component/legend',
// 'echarts/component/grid',
// 'echarts/component/tooltip',
// 'echarts/component/toolbox'
], function (echarts) {
var chart = echarts.init(document.getElementById('main'));
var data1 = [];
var data2 = [];
var data3 = [];
var names = [
'diamond, red, show inside label only on hover',
'green, show top label only on hover',
'indigo, show inside label on normal'
];
var random = function (max) {
return (Math.random() * max).toFixed(3);
}
for (var i = 0; i < 50; i++) {
data1.push([random(5), random(5), random(2)]);
data2.push([random(10), random(10), random(2)]);
data3.push([random(15), random(10), random(2)]);
}
chart.setOption({
aria: {
show: true
},
legend: {
data: names.slice()
},
toolbox: {
left: 'left',
feature: {
dataView: {},
saveAsImage: {},
dataZoom: {}
}
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
}
},
xAxis: {
type: 'value',
splitLine: {
show: false
},
min: 0,
max: 15,
splitNumber: 30
},
yAxis: {
type: 'value',
splitLine: {
show: false
}
},
series: [{
name: names[0],
type: 'scatter',
label: {
emphasis: {
show: true
}
},
symbol: 'diamond',
symbolSize: function (val) {
return val[2] * 40;
},
data: data1
},
{
name: names[1],
type: 'scatter',
emphasis: {
label: {
show: true,
position: 'top',
formatter: function (params) {
return params.value;
}
}
},
symbolSize: function (val) {
return val[2] * 40;
},
itemStyle: {
color: function (params) {
return 'rgba(30, 70, 50, ' + (params.value ? params.value[2] : 0) + ')';
}
},
data: data2
},
{
name: names[2],
type: 'scatter',
label: {
show: true
},
symbolSize: function (val) {
return val[2] * 40;
},
data: data3
}],
animationDelay: function (idx) {
return idx * 20;
},
animationDelayUpdate: function (idx) {
return idx * 20;
}
});
chart.on('click', function (params) {
console.log(params.data);
});
})
</script>
</body>
</html> | test/scatter.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.00018165730580221862,
0.00017006898997351527,
0.00016377172141801566,
0.00016884422802831978,
0.000004425343831826467
] |
{
"id": 10,
"code_window": [
" valuePair[valueDimIdx] = data.get(valueDim, dataIndex);\n",
" valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);\n",
"\n",
" coord = cartesian.dataToPoint(valuePair, null, coord);\n",
" // Data index might not be in order, depends on `progressiveChunkMode`.\n",
" largeBackgroundPoints[pointsOffset] =\n",
" valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];\n",
" largePoints[pointsOffset++] = coord[0];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" coord = cartesian.dataToPoint(valuePair, null);\n"
],
"file_path": "src/layout/barGrid.ts",
"type": "replace",
"edit_start_line_idx": 593
} |
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="lib/esl.js"></script>
<script src="lib/config.js"></script>
<script src="lib/facePrint.js"></script>
</head>
<body>
<style>
html, body, #main {
width: 100%;
height: 100%;
}
</style>
<div id="info"></div>
<div id="main"></div>
<script>
/**
* @see <https://en.wikipedia.org/wiki/Michelson%E2%80%93Morley_experiment>
* @see <http://bl.ocks.org/mbostock/4061502>
*/
var chart;
var data;
require([
'echarts'
// 'echarts/chart/candlestick',
// 'echarts/chart/line',
// 'echarts/component/title',
// 'echarts/component/legend',
// 'echarts/component/grid',
// 'echarts/component/tooltip',
// 'echarts/component/dataZoom',
// 'echarts/component/markPoint',
// 'echarts/component/markLine'
], function (echarts) {
chart = echarts.init(document.getElementById('main'), null, {
});
var data0 = splitData([
['2013/1/24'],
['2013/1/25', 2300,2291.3,2288.26,2308.38],
['2013/1/28'],
['2013/1/29', 2347.22,2358.98,2337.35,2363.8],
['2013/1/30'],
['2013/1/31', 2383.43,2385.42,2371.23,2391.82],
['2013/2/1', 2377.41,2419.02,2369.57,2421.15],
['2013/2/4', 2425.92,2428.15,2417.58,2440.38],
['2013/2/5', 2411,2433.13,2403.3,2437.42],
['2013/2/6', 2432.68,2434.48,2427.7,2441.73],
['2013/2/7', 2430.69,2418.53,2394.22,2433.89],
['2013/2/8', 2416.62,2432.4,2414.4,2443.03],
['2013/2/18', 2441.91,2421.56,2415.43,2444.8],
['2013/2/19', 2420.26,2382.91,2373.53,2427.07],
['2013/2/20', 2383.49,2397.18,2370.61,2397.94],
['2013/2/21', 2378.82,2325.95,2309.17,2378.82],
['2013/2/22', 2322.94,2314.16,2308.76,2330.88]
]);
option = {
title: {
text: '上证指数',
left: 0
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
}
},
legend: {
data: ['日K', '日K 空']
},
grid: {
left: '10%',
right: '10%',
bottom: '15%'
},
xAxis: {
type: 'category',
data: data0.categoryData,
scale: true,
boundaryGap : false,
axisLine: {onZero: false},
splitLine: {show: false},
splitNumber: 20,
min: 'dataMin',
max: 'dataMax'
},
yAxis: {
scale: true,
splitArea: {
show: true
}
},
dataZoom: [
{
type: 'inside'
},
{
show: true,
type: 'slider',
y: '90%'
}
],
series: [
{
name: '日K',
type: 'candlestick',
data: data0.values
},
// {
// name: '日K 空',
// type: 'candlestick',
// data: []
// },
]
};
chart.setOption(option);
});
function splitData(rawData) {
var categoryData = [];
var values = []
for (var i = 0; i < rawData.length; i++) {
categoryData.push(rawData[i].splice(0, 1)[0]);
values.push(rawData[i])
}
return {
categoryData: categoryData,
values: values
};
}
</script>
</body>
</html> | test/candlestick-empty.html | 0 | https://github.com/apache/echarts/commit/f0368aeb1747087bde61a222398b71ab9347b6f6 | [
0.0007185859722085297,
0.00020173750817775726,
0.00016174971824511886,
0.00016880495240911841,
0.00012929471267852932
] |
{
"id": 0,
"code_window": [
" }\n",
"\n",
" &-disabled &-selection {\n",
" &:hover,\n",
" &:active {\n",
" border-color: @border-color-base;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" background: #f4f4f4;\n",
" cursor: not-allowed;\n"
],
"file_path": "style/components/select.less",
"type": "add",
"edit_start_line_idx": 71
} | @tree-select-tree-prefix-cls: ant-tree-select-tree;
.antCheckboxFn(@checkbox-prefix-cls: ant-tree-select-tree-checkbox);
@import "../mixins/iconfont";
.@{tree-select-tree-prefix-cls} {
margin: 0;
padding: 8px;
font-size: 12px;
li {
padding: 0;
margin: 8px 0;
list-style: none;
white-space: nowrap;
outline: 0;
&.filter-node {
> a {
color: @error-color!important;
font-weight: bold!important;
}
}
ul {
margin: 0;
padding: 0 0 0 18px;
}
a {
display: inline-block;
padding: 1px 5px;
border-radius: 2px;
margin: 0;
cursor: pointer;
text-decoration: none;
vertical-align: top;
color: #666;
transition: all 0.3s ease;
&:hover {
background-color: tint(@primary-color, 90%);
}
&.@{tree-select-tree-prefix-cls}-node-selected {
background-color: tint(@primary-color, 80%);
}
}
span {
&.@{tree-select-tree-prefix-cls}-checkbox {
margin: 2px 4px 0 0;
}
&.@{tree-select-tree-prefix-cls}-switcher,
&.@{tree-select-tree-prefix-cls}-iconEle {
margin: 0;
width: 16px;
height: 16px;
line-height: 16px;
display: inline-block;
vertical-align: middle;
border: 0 none;
cursor: pointer;
outline: none;
}
&.@{tree-select-tree-prefix-cls}-icon_loading {
&:after {
content: '\e6a1';
display: inline-block;
font-family: 'anticon';
font-weight: bold;
.animation(loadingCircle 1s infinite linear);
margin-top: 8px;
}
}
&.@{tree-select-tree-prefix-cls}-switcher {
&.@{tree-select-tree-prefix-cls}-roots_open,
&.@{tree-select-tree-prefix-cls}-center_open,
&.@{tree-select-tree-prefix-cls}-bottom_open,
&.@{tree-select-tree-prefix-cls}-noline_open {
.antTreeSwitcherIcon();
}
&.@{tree-select-tree-prefix-cls}-roots_close,
&.@{tree-select-tree-prefix-cls}-center_close,
&.@{tree-select-tree-prefix-cls}-bottom_close,
&.@{tree-select-tree-prefix-cls}-noline_close {
.antTreeSwitcherIcon();
.ie-rotate(3);
&:after {
transform: rotate(270deg) scale(0.5);
}
}
}
}
}
&-child-tree {
display: none;
&-open {
display: block;
}
}
&-treenode-disabled {
>span,
>a,
>a span {
color: #ccc;
cursor: not-allowed;
}
}
&-icon__open {
margin-right: 2px;
vertical-align: top;
}
&-icon__close {
margin-right: 2px;
vertical-align: top;
}
}
@tree-select-prefix-cls: ant-tree-select;
@duration: .3s;
@import "../mixins/iconfont";
//mixin
.selection__clear() {
cursor: pointer;
float: right;
font-weight: bold;
}
.@{tree-select-prefix-cls} {
box-sizing: border-box;
display: inline-block;
margin: 0;
position: relative;
vertical-align: middle;
color: #666;
font-size: @font-size-base;
> ul > li > a {
padding: 0;
background-color: #fff;
}
// arrow
&-arrow {
.iconfont-mixin();
position: absolute;
top: 50%;
right: 8px;
line-height: 1;
margin-top: -5px;
.iconfont-size-under-12px(8px);
* {
display: none;
}
&:before {
content: '\e603';
transition: transform 0.2s ease;
}
}
&-selection {
outline: none;
user-select: none;
box-sizing: border-box;
display: block;
background-color: #fff;
border-radius: @border-radius-base;
border: 1px solid @border-color-base;
.transition(all .3s @ease-in-out);
&:hover {
.hover;
}
&:active {
.active;
}
}
&-disabled {
color: #ccc;
}
&-disabled &-selection {
&:hover,
&:active {
border-color: @border-color-base;
}
}
&-disabled &-selection--single {
background: #f4f4f4;
cursor: not-allowed;
}
&-selection--single {
height: 28px;
cursor: pointer;
.@{tree-select-prefix-cls}-selection__rendered {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding-left: 8px;
padding-right: 24px;
line-height: 26px;
}
.@{tree-select-prefix-cls}-selection__clear {
.selection__clear();
}
.@{tree-select-prefix-cls}-selection__placeholder {
color: #ccc;
}
}
&-lg {
.@{tree-select-prefix-cls}-selection--single {
height: 32px;
.@{tree-select-prefix-cls}-selection__rendered {
line-height: 30px;
}
}
.@{tree-select-prefix-cls}-selection--multiple {
min-height: 32px;
.@{tree-select-prefix-cls}-selection__rendered {
li {
height: 24px;
.@{tree-select-prefix-cls}-selection__choice__content {
font-size: 14px;
line-height: 24px;
}
}
}
}
}
&-sm {
.@{tree-select-prefix-cls}-selection {
border-radius: @border-radius-sm;
}
.@{tree-select-prefix-cls}-selection--single {
height: 22px;
.@{tree-select-prefix-cls}-selection__rendered {
line-height: 20px;
}
}
.@{tree-select-prefix-cls}-selection--multiple {
min-height: 22px;
.@{tree-select-prefix-cls}-selection__rendered {
li {
height: 14px;
.@{tree-select-prefix-cls}-selection__choice__content {
line-height: 14px;
position: relative;
top: -3px;
}
.@{tree-select-prefix-cls}-selection__choice__remove {
position: relative;
top: -4px;
}
}
}
}
}
&-disabled &-selection__choice__remove {
color: #ccc;
cursor: default;
&:hover {
color: #ccc;
}
}
&-search__field__wrap {
display: inline-block;
position: relative;
}
&-search__field__placeholder {
position: absolute;
top: 0;
left: 3px;
color: #aaa;
}
&-search--inline {
float: left;
.@{tree-select-prefix-cls}-search__field__wrap {
width: 100%;
}
.@{tree-select-prefix-cls}-search__field {
border: 0;
font-size: 100%;
background: transparent;
outline: 0;
}
> i {
float: right;
}
}
&-selection--multiple {
min-height: 28px;
cursor: text;
.@{tree-select-prefix-cls}-search__field__placeholder {
top: 6px;
left: 10px;
}
.@{tree-select-prefix-cls}-search--inline {
width: auto;
.@{tree-select-prefix-cls}-search__field {
width: 0.75em;
}
}
.@{tree-select-prefix-cls}-selection__rendered {
overflow: hidden;
text-overflow: ellipsis;
padding-left: 6px;
padding-bottom: 4px;
}
.@{tree-select-prefix-cls}-selection__clear {
.selection__clear();
margin-top: 5px;
margin-right: 10px;
}
> ul > li {
margin-top: 4px;
height: 20px;
line-height: 20px;
}
.@{tree-select-prefix-cls}-selection__choice {
background-color: #f3f3f3;
border-radius: 4px;
cursor: default;
float: left;
padding: 0 15px;
margin-right: 4px;
max-width: 99%;
position: relative;
overflow: hidden;
transition: padding @duration @ease-in-out;
padding: 0 20px 0 10px;
}
.@{tree-select-prefix-cls}-selection__choice__content {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
transition: margin @duration @ease-in-out;
}
.@{tree-select-prefix-cls}-selection__choice__remove {
.iconfont-mixin();
color: #999;
line-height: 20px;
cursor: pointer;
display: inline-block;
font-weight: bold;
transition: all 0.3s @ease-in-out;
.iconfont-size-under-12px(8px);
position: absolute;
right: 4px;
padding: 0 0 0 8px;
&:hover {
color: #404040;
}
&:before {
content: "\e62d";
}
}
}
&-open {
.@{tree-select-prefix-cls}-arrow {
.ie-rotate(2);
-ms-transform: rotate(180deg);
&:before {
.rotate(180deg);
}
}
.@{tree-select-prefix-cls}-selection {
.active();
}
}
&-combobox {
.@{tree-select-prefix-cls}-arrow {
display: none;
}
.@{tree-select-prefix-cls}-search--inline {
height: 100%;
float: none;
}
.@{tree-select-prefix-cls}-search__field__placeholder {
left: 10px;
cursor: text;
}
.@{tree-select-prefix-cls}-search__field__wrap {
width: 100%;
height: 100%;
}
.@{tree-select-prefix-cls}-search__field {
padding: 0 10px;
width: 100%;
height: 100%;
position: relative;
z-index: 1;
}
.@{tree-select-prefix-cls}-selection__rendered {
padding: 0;
height: 100%;
}
}
}
.@{tree-select-prefix-cls}-dropdown {
&.slide-up-enter.slide-up-enter-active&-placement-bottomLeft,
&.slide-up-appear.slide-up-appear-active&-placement-bottomLeft {
animation-name: antSlideUpIn;
}
&.slide-up-enter.slide-up-enter-active&-placement-topLeft,
&.slide-up-appear.slide-up-appear-active&-placement-topLeft {
animation-name: antSlideDownIn;
}
&.slide-up-leave.slide-up-leave-active&-placement-bottomLeft {
animation-name: antSlideUpOut;
}
&.slide-up-leave.slide-up-leave-active&-placement-topLeft {
animation-name: antSlideDownOut;
}
&-hidden {
display: none;
}
background-color: white;
border: 1px solid @border-color-base;
box-shadow: @box-shadow-base;
border-radius: @border-radius-base;
box-sizing: border-box;
z-index: 1070;
left: -9999px;
top: -9999px;
position: absolute;
outline: none;
overflow: hidden;
font-size: @font-size-base;
&-menu {
outline: none;
margin-bottom: 0;
padding-left: 0; // Override default ul/ol
list-style: none;
max-height: 250px;
overflow: auto;
&-item-group-list {
margin: 0;
padding: 0;
> .@{tree-select-prefix-cls}-dropdown-menu-item {
padding-left: 24px;
}
}
&-item-group-title {
color: #999;
line-height: 1.5;
padding: 8px 15px;
}
&-item {
position: relative;
display: block;
padding: 7px 15px;
font-weight: normal;
color: #666;
white-space: nowrap;
cursor: pointer;
overflow: hidden;
transition: background 0.3s ease;
&:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
&:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
&:hover,
&-active {
background-color: tint(@primary-color, 90%);
}
&-selected {
background-color: tint(@primary-color, 80%);
&:hover {
background-color: tint(@primary-color, 80%);
}
}
&-disabled {
color: #ccc;
cursor: not-allowed;
&:hover {
color: #ccc;
background-color: #fff;
cursor: not-allowed;
}
}
&-divider {
height: 1px;
margin: 1px 0;
overflow: hidden;
background-color: #e5e5e5;
line-height: 0;
}
}
}
&-container-open,
&-open {
.@{tree-select-prefix-cls}-dropdown {
display: block;
}
}
.@{tree-select-prefix-cls}-dropdown-search {
display: block;
padding: 4px;
.@{tree-select-prefix-cls}-search__field__placeholder {
left: 7px;
top: 5px;
}
.@{tree-select-prefix-cls}-search__field__wrap {
width: 100%;
}
.@{tree-select-prefix-cls}-search__field {
padding: 4px 7px;
width: 100%;
box-sizing: border-box;
border: 1px solid @border-color-base;
border-radius: 4px;
outline: none;
}
&.@{tree-select-prefix-cls}-search--hide {
display: none;
}
}
}
| style/components/treeSelect.less | 1 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.9753205180168152,
0.020248524844646454,
0.00016344756295438856,
0.00017067753651645035,
0.128325417637825
] |
{
"id": 0,
"code_window": [
" }\n",
"\n",
" &-disabled &-selection {\n",
" &:hover,\n",
" &:active {\n",
" border-color: @border-color-base;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" background: #f4f4f4;\n",
" cursor: not-allowed;\n"
],
"file_path": "style/components/select.less",
"type": "add",
"edit_start_line_idx": 71
} | # 表单
- category: 2
- order: 2
---
作为获取用户输入的重要交互方式,表单也承担将问题和答案进行配对的角色。
设计者进行表单设计时,应当注意这几点:
1. 确保用户了解要提供什么信息,以及为什么要提供这些信息。
为初级用户/偶尔访问的用户提供白话作为『标签』;为领域专家提供专业术语作为『标签』。当需要用户提供敏感信息时,通过『输入提示』来说明系统为什么要这么做,eg:需要获取身份证号码、手机号码时。
2. 让用户能在上下文中获取信息,帮助他完成输入。
使用『良好的默认值』、『结构化的格式』、『输入提示』、『输入提醒』等方式,避免让用户在空白中完成输入。
3. 对错误敏感,并尽可能宽容。
通过不同的『校验』规则和形式进行反馈,避免用户在点击提交后才刚刚开始『校验』,让用户提前纠正错误;依据『容错格式』,允许用户以多种格式和语法输入,eg:用户在电话号码输入框中多输入了一个空格,系统存储时可以主动删掉空格,但是不需要告诉用户这是一个错误。
4. 不要提出不必要的问题。
## 内容
<img class="preview-img" align="right" alt="结构示例" src="https://os.alipayobjects.com/rmsportal/mLkQbODgVsdGUTe.png">
通常表单会有四个部分组成。
1. 标签
2. 输入框
3. 校验反馈
4. 动作
> 注:`*` 表明该项为必填项。
## 交互
### 填空
<img class="preview-img" align="right" alt="填空示例" src="https://os.alipayobjects.com/rmsportal/SdzCTaevNMvJFBR.png">
在一种描述性的上下文中出现输入项,可以帮助用户理解当前的状况,以及需要提供什么数据。
### 组合输入框
<img class="preview-img" align="right" alt="组合输入框示例" src="https://os.alipayobjects.com/rmsportal/waStvhMnuoqqsCE.png">
当两个输入框关联性很强时,可以前后拼接,减少页面空间。
### 对齐方式
<img class="preview-img" align="right" alt="对齐方式示例" src="https://os.alipayobjects.com/rmsportal/cjHTEtXFxUSdHnE.png">
在页面设计表单时,按钮组必须和输入框左对齐。
### 禁用主按钮
当输入框非常少时(一般少于 3 个),如果用户没有在必填项中输入内容,可禁用『提交』等主按钮;当输入框非常多时(超过 5 项以上),不建议禁用主按钮。
<br>
<img class="preview-img" align="right" alt="未达字符标准时,主按钮禁用状态" src="https://os.alipayobjects.com/rmsportal/VabHKlbouFxSQXz.png">
<img class="preview-img" align="right" alt="达到字符标准时,主按钮可用状态" src="https://os.alipayobjects.com/rmsportal/usdFxJmWDawqUuq.png">
当输入框非常少时,用户一输入就会有反馈,因而主按钮的禁用规则非常清晰,容易被用户理解。
<br>
<img class="preview-img" align="right" alt="不禁用示例" src="https://os.alipayobjects.com/rmsportal/GwZhvOuXmwqUIUW.png">
当输入框非常多时(尤其是输入项中交叉了必填项和非必填项),整个反馈链路冗长又复杂,禁用规则难以被识别,容易引起困惑。
### 结构化的格式
<img class="preview-img" align="right" alt="结构化的格式示例" src="https://os.alipayobjects.com/rmsportal/SQgGfreRAqPZPsm.png">
用户对输入的内容很熟悉,且系统不希望接受任何偏离期望的格式。
### 输入提示 & 输入提醒
<img class="preview-img" align="right" alt="输入提示示例" description="在输入框激活后,输入提示一直出现至该输入框失去焦点。" src="https://os.alipayobjects.com/rmsportal/cTlmdEprGSzMZfs.png">
<img class="preview-img" align="right" alt="输入提醒示例" description="在输入框激活后,输入提醒不要马上消失,等用户完成第一个词输入后再消失。" src="https://os.alipayobjects.com/rmsportal/QPhvLWfMbLTvjRw.png">
输入提示:不希望在标签上放置太多文字进行解释,同时只有标签又会引起误解。
输入提醒:提醒用户该控件的目的或所需格式,由于在用户输入后提醒就会消失,所以适用在用户对内容比较熟悉时。
### 密码加强计
<img class="preview-img" align="right" alt="密码强度示例" src="https://os.alipayobjects.com/rmsportal/wKpOgeyyoOUeCrk.png">
提供关于密码强度和有效性的及时反馈,适用在注册页面时的密码输入框。
### 校验
<img class="preview-img" align="right" description="输入时的实时校验。" src="https://os.alipayobjects.com/rmsportal/urCdIJFuNYCenqH.png">
<img class="preview-img" align="right" description="输入框失去焦点后的校验。" src="https://os.alipayobjects.com/rmsportal/KkcSBkbTJirIxCw.png">
<img class="preview-img" align="right" description="点击『提交』后,系统将处理结果直接在页面上进行反馈(统计错误数量和标记错误内容)。" src="https://os.alipayobjects.com/rmsportal/PLdlPvaebRdJOgu.png">
通过不同的『校验』规则和形式进行反馈,避免用户在点击提交后才刚刚开始『校验』,让用户提前纠正错误。
### 字数校验框
<img class="preview-img" align="right" alt="字数校验框示例" src="https://os.alipayobjects.com/rmsportal/ziTMevqClLTYagX.png">
用于统计当前输入长度,以及是否超过系统阈值。
## 规格
### 间距
<img class="preview-img" align="right" alt="间隔示例" src="https://os.alipayobjects.com/rmsportal/dlTiHzZvCGRbMzL.png">
典型表单的间隔规范。
### 输入框宽度
<img class="preview-img" align="right" alt="正确示例" src="https://os.alipayobjects.com/rmsportal/vypllNQZsEHRszB.png" good>
<img class="preview-img" align="right" alt="错误示例" src="https://os.alipayobjects.com/rmsportal/XSLwnrlLbKFjiNj.png" bad>
当内容可预知,可以根据内容长短进行定义其落在多少个栅格上。
<br>
### 对齐方式
无论左对齐、右对齐还是顶部对齐,都有其优缺点和应用场景,所以正确的解决方案取决于具体目标和制约因素,诸如:希望用户加快或者降低填写速度(有时设计者希望用户深思熟虑每个输入)、屏幕显示的限制、本地化考虑等多种因素。
<br>
<img class="preview-img" align="right" alt="右对齐(推荐)" src="https://os.alipayobjects.com/rmsportal/UxGJfenYBKvkEEB.png">
右对齐(推荐)。
- 优点:节约垂直空间。
- 缺点:降低可读性;标签长度和输入框弹性小。
- 场景:既要减少垂直空间,又要加快填写速度。
<br>
<img class="preview-img" align="right" alt="顶部对齐" src="https://os.alipayobjects.com/rmsportal/AsyyNKormNdEMLi.png">
顶部对齐。
- 优点:有最快的浏览和处理速度;标签长度弹性大。
- 缺点:非常占垂直空间。
- 场景:希望用户快速填写表单,完成任务。
<br>
<img class="preview-img" align="right" alt="左对齐" src="https://os.alipayobjects.com/rmsportal/eqUyDExbRlAQoas.png">
左对齐。
- 优点:文字开头按阅读视线对齐,方便阅读;节约垂直空间。
- 缺点:填写速度慢;标签长度和输入框弹性小。
- 场景:希望用户放慢速度,仔细思考表单中的每个输入框。
| docs/pattern/form.md | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.0031831644009798765,
0.0004581052344292402,
0.00016364218026865274,
0.00016578550275880843,
0.0007882543723098934
] |
{
"id": 0,
"code_window": [
" }\n",
"\n",
" &-disabled &-selection {\n",
" &:hover,\n",
" &:active {\n",
" border-color: @border-color-base;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" background: #f4f4f4;\n",
" cursor: not-allowed;\n"
],
"file_path": "style/components/select.less",
"type": "add",
"edit_start_line_idx": 71
} | # QueueAnim
- category: Components
- chinese: 进出场动画
---
通过简单的配置对一组元素添加串行的进场动画效果。
## 何时使用
- 从内容A到内容B的转变过程时能有效的吸引用户注意力,突出视觉中心,提高整体视觉效果。
- 小的信息元素排布或块状较多的情况下,根据一定的路径层次依次进场,区分维度层级,来凸显量级,使页面转场更加流畅和舒适,提高整体视觉效果和产品的质感。
- 特别适合首页和需要视觉展示效果的宣传页,以及单页应用的切换页面动效。
## API
> 此组件取代了 0.9.x 版本的 [enter-animation](http://09x.ant.design/components/enter-animation/)。
元素依次进场。
```html
<QueueAnim>
<div key='demo1'>依次进场</div>
<div key='demo2'>依次进场</div>
<div key='demo3'>依次进场</div>
<div key='demo4'>依次进场</div>
</QueueAnim>
```
> 每个子标签必须带 key,如果未设置 key 将不执行动画。
|参数 |类型 |默认 |详细 |
|------------|----------------|---------|----------------|
| type | string / array | `right` | 动画内置参数 <br/> `left` `right` `top` `bottom` `scale` `scaleBig` `scaleX` `scaleY`|
| animConfig | object / array | null | 配置动画参数 <br/> 如 `{opacity:[1, 0],translateY:[0, -30]}` 具体参考 [velocity](http://julian.com/research/velocity) 的写法|
| delay | number / array | 0 | 整个动画的延时,以毫秒为单位 |
| duration | number / array | 500 | 每个动画的时间,以毫秒为单位 |
| interval | number / array | 100 | 每个动画的间隔时间,以毫秒为单位 |
| leaveReverse | boolean | false | 出场时是否倒放,从最后一个 dom 开始往上播放 |
| ease | string / array | `easeOutQuart` | 动画的缓动函数,[查看详细](http://julian.com/research/velocity/#easing) |
| animatingClassName | array | `['queue-anim-entering', 'queue-anim-leaving']` | 进出场动画进行中的类名 |
| component | string | `div` | QueueAnim 替换的标签名 |
> 当以上数据类型为 Array 时,`['left', 'top']` 第一个为进场动画属性, 第二个为离场属性。
<style>
.code-box-demo .demo-header {
width: 100%;
background: #ebedee;
height: 30px;
}
.code-box-demo .demo-header ul {
float: right;
margin-right: 5px;
}
.code-box-demo .demo-header ul li {
width: 50px;
height: 30px;
float: left;
background: #e4e4e4;
margin-left: 5px;
}
.code-box-demo .demo-header ul li:before {
margin: 10px auto;
width: 20px;
height: 10px;
background: #ebeded;
}
.code-box-demo .demo-header .logo {
float: left;
margin: 0px auto 0 10px;
line-height: 32px;
}
.code-box-demo .demo-header .logo img{
margin:auto
}
.code-box-demo .demo-header .logo span {
display: block;
float: right;
}
.code-box-demo .demo-content {
width: 80%;
margin: 10px auto;
}
.code-box-demo .demo-content .demo-title {
text-align:left;
background: #a4a4a4;
width: 40%;
height: 20px;
line-height: 20px;
color: #ebeded;
text-indent:10px
}
.code-box-demo .demo-content .demo-listBox {
margin-top: 10px;
}
.code-box-demo .demo-content .demo-listBox .demo-list .title {
height: 30px;
background: #cacaca;
overflow: hidden;
}
.code-box-demo .demo-content .demo-listBox .demo-list .title:before,.code-box-demo .demo-content .demo-listBox .demo-list .title:after{
width: 30%;
height: 5px;
background: #ebeded;
float:left;
margin:12px 35px 0;
}
.code-box-demo .demo-content .demo-listBox .demo-list .title:after{
width:15%;
float:right;
margin:12px 10px 0;
}
.code-box-demo .demo-content .demo-listBox .demo-list ul li {
height: 25px;
background: #ebeded;
border-bottom: 1px solid #cacaca;
overflow: hidden;
padding: 5px 15px;
}
.code-box-demo .demo-content .demo-listBox .demo-list ul li:before {
width: 10px;
height: 5px;
background: #cacaca;
float: left;
margin-top:4px
}
.code-box-demo .demo-content .demo-listBox .demo-list ul li:after {
width: 50%;
height: 5px;
background: #cacaca;
float: left;
margin-left: 10px;
margin-top: 4px;
}
.code-box-demo .demo-content .demo-kp {
margin: 10px auto;
}
.code-box-demo .demo-content .demo-kp ul li {
display: inline-block;
width: 32%;
height: 40px;
background: #cacaca;
color: #ebeded;
text-align: left;
padding: 10px;
margin-right: calc(2%);
}
.code-box-demo .demo-content .demo-kp ul li:last-child {
margin-right: 0%;
}
.code-box-demo .demo-content .demo-kp ul li:after {
width: 60%;
height: 5px;
background: #ebeded;
float: left;
margin-top: 7px;
}
.code-box-demo .demo-content .demo-kp ul li:before {
background: #ebeded;
float: left;
width: 15px;
height: 15px;
margin:2px 10% 0 0;
}
.code-box-demo .demo-footer {
margin-top: 10px;
background: #cacaca;
height: 40px;
float: left;
width: 100%;
display: table;
}
.code-box-demo .demo-footer:before {
width: 60%;
height: 5px;
background: #ededed;
margin: 10px auto 0;
}
.code-box-demo .demo-footer:after {
width: 30%;
height: 5px;
background: #ededed;
margin: 5px auto;
}
.code-box-demo .demo-header ul li:before,
.code-box-demo .demo-content .demo-kp ul li:before,
.code-box-demo .demo-content .demo-kp ul li:after,
.code-box-demo .demo-content .demo-listBox .demo-list .title:before,
.code-box-demo .demo-content .demo-listBox .demo-list .title:after,
.code-box-demo .demo-content .demo-listBox .demo-list ul li:before,
.code-box-demo .demo-content .demo-listBox .demo-list ul li:after,
.code-box-demo .demo-footer:before,
.code-box-demo .demo-footer:after {
display: block;
content: "";
}
</style>
| components/queue-anim/index.md | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.00018426885071676224,
0.0001693000376690179,
0.00016401834727730602,
0.00016970757860690355,
0.000004063831511302851
] |
{
"id": 0,
"code_window": [
" }\n",
"\n",
" &-disabled &-selection {\n",
" &:hover,\n",
" &:active {\n",
" border-color: @border-color-base;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" background: #f4f4f4;\n",
" cursor: not-allowed;\n"
],
"file_path": "style/components/select.less",
"type": "add",
"edit_start_line_idx": 71
} | # 条件触发
- order: 3
可以判断是否需要弹出。
---
````jsx
import { Popconfirm, Switch, message } from 'antd';
let App = React.createClass({
getInitialState() {
return {
visible: false,
condition: true, // 是否满足条件,不满足则弹出确认框
};
},
changeCondition(value) {
this.setState({ condition: value });
},
confirm() {
this.setState({ visible: false });
message.success('进行下一步操作. next step.');
},
cancel() {
this.setState({ visible: false });
message.error('点击了取消');
},
handleVisibleChange(visible) {
if (!visible) {
this.setState({ visible });
return;
}
// 打开前进行判断
console.log(this.state.condition);
if (this.state.condition) {
this.confirm(); // 直接执行下一步
} else {
this.setState({ visible }); // 进行确认
}
},
render() {
return (
<div>
<Popconfirm title="确定要删除这个任务吗?"
visible={this.state.visible} onVisibleChange={this.handleVisibleChange}
onConfirm={this.confirm} onCancel={this.cancel}>
<a href="#">删除某任务</a>
</Popconfirm>
<br />
<br />
点击是否直接执行:<Switch defaultChecked onChange={this.changeCondition} />
</div>
);
}
});
ReactDOM.render(<App />, mountNode);
````
| components/popconfirm/demo/dynamic-trigger.md | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.00017597933765500784,
0.00016941582725849003,
0.00016424573550466448,
0.00016838761803228408,
0.0000036833616832154803
] |
{
"id": 1,
"code_window": [
" &:active {\n",
" border-color: @border-color-base;\n",
" }\n",
" }\n",
"\n",
" &-disabled &-selection--single {\n",
" background: #f4f4f4;\n",
" cursor: not-allowed;\n",
" }\n",
"\n",
" &-disabled &-selection--multiple &-selection__choice__remove {\n",
" display: none;\n",
" }\n",
"\n",
" &-selection--single {\n",
" height: 28px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-disabled &-selection--multiple &-selection__choice {\n",
" background: #e9e9e9;\n",
" color: #aaa;\n",
" padding-right: 10px;\n",
" &__remove {\n",
" display: none;\n",
" }\n"
],
"file_path": "style/components/select.less",
"type": "replace",
"edit_start_line_idx": 77
} | @tree-select-tree-prefix-cls: ant-tree-select-tree;
.antCheckboxFn(@checkbox-prefix-cls: ant-tree-select-tree-checkbox);
@import "../mixins/iconfont";
.@{tree-select-tree-prefix-cls} {
margin: 0;
padding: 8px;
font-size: 12px;
li {
padding: 0;
margin: 8px 0;
list-style: none;
white-space: nowrap;
outline: 0;
&.filter-node {
> a {
color: @error-color!important;
font-weight: bold!important;
}
}
ul {
margin: 0;
padding: 0 0 0 18px;
}
a {
display: inline-block;
padding: 1px 5px;
border-radius: 2px;
margin: 0;
cursor: pointer;
text-decoration: none;
vertical-align: top;
color: #666;
transition: all 0.3s ease;
&:hover {
background-color: tint(@primary-color, 90%);
}
&.@{tree-select-tree-prefix-cls}-node-selected {
background-color: tint(@primary-color, 80%);
}
}
span {
&.@{tree-select-tree-prefix-cls}-checkbox {
margin: 2px 4px 0 0;
}
&.@{tree-select-tree-prefix-cls}-switcher,
&.@{tree-select-tree-prefix-cls}-iconEle {
margin: 0;
width: 16px;
height: 16px;
line-height: 16px;
display: inline-block;
vertical-align: middle;
border: 0 none;
cursor: pointer;
outline: none;
}
&.@{tree-select-tree-prefix-cls}-icon_loading {
&:after {
content: '\e6a1';
display: inline-block;
font-family: 'anticon';
font-weight: bold;
.animation(loadingCircle 1s infinite linear);
margin-top: 8px;
}
}
&.@{tree-select-tree-prefix-cls}-switcher {
&.@{tree-select-tree-prefix-cls}-roots_open,
&.@{tree-select-tree-prefix-cls}-center_open,
&.@{tree-select-tree-prefix-cls}-bottom_open,
&.@{tree-select-tree-prefix-cls}-noline_open {
.antTreeSwitcherIcon();
}
&.@{tree-select-tree-prefix-cls}-roots_close,
&.@{tree-select-tree-prefix-cls}-center_close,
&.@{tree-select-tree-prefix-cls}-bottom_close,
&.@{tree-select-tree-prefix-cls}-noline_close {
.antTreeSwitcherIcon();
.ie-rotate(3);
&:after {
transform: rotate(270deg) scale(0.5);
}
}
}
}
}
&-child-tree {
display: none;
&-open {
display: block;
}
}
&-treenode-disabled {
>span,
>a,
>a span {
color: #ccc;
cursor: not-allowed;
}
}
&-icon__open {
margin-right: 2px;
vertical-align: top;
}
&-icon__close {
margin-right: 2px;
vertical-align: top;
}
}
@tree-select-prefix-cls: ant-tree-select;
@duration: .3s;
@import "../mixins/iconfont";
//mixin
.selection__clear() {
cursor: pointer;
float: right;
font-weight: bold;
}
.@{tree-select-prefix-cls} {
box-sizing: border-box;
display: inline-block;
margin: 0;
position: relative;
vertical-align: middle;
color: #666;
font-size: @font-size-base;
> ul > li > a {
padding: 0;
background-color: #fff;
}
// arrow
&-arrow {
.iconfont-mixin();
position: absolute;
top: 50%;
right: 8px;
line-height: 1;
margin-top: -5px;
.iconfont-size-under-12px(8px);
* {
display: none;
}
&:before {
content: '\e603';
transition: transform 0.2s ease;
}
}
&-selection {
outline: none;
user-select: none;
box-sizing: border-box;
display: block;
background-color: #fff;
border-radius: @border-radius-base;
border: 1px solid @border-color-base;
.transition(all .3s @ease-in-out);
&:hover {
.hover;
}
&:active {
.active;
}
}
&-disabled {
color: #ccc;
}
&-disabled &-selection {
&:hover,
&:active {
border-color: @border-color-base;
}
}
&-disabled &-selection--single {
background: #f4f4f4;
cursor: not-allowed;
}
&-selection--single {
height: 28px;
cursor: pointer;
.@{tree-select-prefix-cls}-selection__rendered {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding-left: 8px;
padding-right: 24px;
line-height: 26px;
}
.@{tree-select-prefix-cls}-selection__clear {
.selection__clear();
}
.@{tree-select-prefix-cls}-selection__placeholder {
color: #ccc;
}
}
&-lg {
.@{tree-select-prefix-cls}-selection--single {
height: 32px;
.@{tree-select-prefix-cls}-selection__rendered {
line-height: 30px;
}
}
.@{tree-select-prefix-cls}-selection--multiple {
min-height: 32px;
.@{tree-select-prefix-cls}-selection__rendered {
li {
height: 24px;
.@{tree-select-prefix-cls}-selection__choice__content {
font-size: 14px;
line-height: 24px;
}
}
}
}
}
&-sm {
.@{tree-select-prefix-cls}-selection {
border-radius: @border-radius-sm;
}
.@{tree-select-prefix-cls}-selection--single {
height: 22px;
.@{tree-select-prefix-cls}-selection__rendered {
line-height: 20px;
}
}
.@{tree-select-prefix-cls}-selection--multiple {
min-height: 22px;
.@{tree-select-prefix-cls}-selection__rendered {
li {
height: 14px;
.@{tree-select-prefix-cls}-selection__choice__content {
line-height: 14px;
position: relative;
top: -3px;
}
.@{tree-select-prefix-cls}-selection__choice__remove {
position: relative;
top: -4px;
}
}
}
}
}
&-disabled &-selection__choice__remove {
color: #ccc;
cursor: default;
&:hover {
color: #ccc;
}
}
&-search__field__wrap {
display: inline-block;
position: relative;
}
&-search__field__placeholder {
position: absolute;
top: 0;
left: 3px;
color: #aaa;
}
&-search--inline {
float: left;
.@{tree-select-prefix-cls}-search__field__wrap {
width: 100%;
}
.@{tree-select-prefix-cls}-search__field {
border: 0;
font-size: 100%;
background: transparent;
outline: 0;
}
> i {
float: right;
}
}
&-selection--multiple {
min-height: 28px;
cursor: text;
.@{tree-select-prefix-cls}-search__field__placeholder {
top: 6px;
left: 10px;
}
.@{tree-select-prefix-cls}-search--inline {
width: auto;
.@{tree-select-prefix-cls}-search__field {
width: 0.75em;
}
}
.@{tree-select-prefix-cls}-selection__rendered {
overflow: hidden;
text-overflow: ellipsis;
padding-left: 6px;
padding-bottom: 4px;
}
.@{tree-select-prefix-cls}-selection__clear {
.selection__clear();
margin-top: 5px;
margin-right: 10px;
}
> ul > li {
margin-top: 4px;
height: 20px;
line-height: 20px;
}
.@{tree-select-prefix-cls}-selection__choice {
background-color: #f3f3f3;
border-radius: 4px;
cursor: default;
float: left;
padding: 0 15px;
margin-right: 4px;
max-width: 99%;
position: relative;
overflow: hidden;
transition: padding @duration @ease-in-out;
padding: 0 20px 0 10px;
}
.@{tree-select-prefix-cls}-selection__choice__content {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
transition: margin @duration @ease-in-out;
}
.@{tree-select-prefix-cls}-selection__choice__remove {
.iconfont-mixin();
color: #999;
line-height: 20px;
cursor: pointer;
display: inline-block;
font-weight: bold;
transition: all 0.3s @ease-in-out;
.iconfont-size-under-12px(8px);
position: absolute;
right: 4px;
padding: 0 0 0 8px;
&:hover {
color: #404040;
}
&:before {
content: "\e62d";
}
}
}
&-open {
.@{tree-select-prefix-cls}-arrow {
.ie-rotate(2);
-ms-transform: rotate(180deg);
&:before {
.rotate(180deg);
}
}
.@{tree-select-prefix-cls}-selection {
.active();
}
}
&-combobox {
.@{tree-select-prefix-cls}-arrow {
display: none;
}
.@{tree-select-prefix-cls}-search--inline {
height: 100%;
float: none;
}
.@{tree-select-prefix-cls}-search__field__placeholder {
left: 10px;
cursor: text;
}
.@{tree-select-prefix-cls}-search__field__wrap {
width: 100%;
height: 100%;
}
.@{tree-select-prefix-cls}-search__field {
padding: 0 10px;
width: 100%;
height: 100%;
position: relative;
z-index: 1;
}
.@{tree-select-prefix-cls}-selection__rendered {
padding: 0;
height: 100%;
}
}
}
.@{tree-select-prefix-cls}-dropdown {
&.slide-up-enter.slide-up-enter-active&-placement-bottomLeft,
&.slide-up-appear.slide-up-appear-active&-placement-bottomLeft {
animation-name: antSlideUpIn;
}
&.slide-up-enter.slide-up-enter-active&-placement-topLeft,
&.slide-up-appear.slide-up-appear-active&-placement-topLeft {
animation-name: antSlideDownIn;
}
&.slide-up-leave.slide-up-leave-active&-placement-bottomLeft {
animation-name: antSlideUpOut;
}
&.slide-up-leave.slide-up-leave-active&-placement-topLeft {
animation-name: antSlideDownOut;
}
&-hidden {
display: none;
}
background-color: white;
border: 1px solid @border-color-base;
box-shadow: @box-shadow-base;
border-radius: @border-radius-base;
box-sizing: border-box;
z-index: 1070;
left: -9999px;
top: -9999px;
position: absolute;
outline: none;
overflow: hidden;
font-size: @font-size-base;
&-menu {
outline: none;
margin-bottom: 0;
padding-left: 0; // Override default ul/ol
list-style: none;
max-height: 250px;
overflow: auto;
&-item-group-list {
margin: 0;
padding: 0;
> .@{tree-select-prefix-cls}-dropdown-menu-item {
padding-left: 24px;
}
}
&-item-group-title {
color: #999;
line-height: 1.5;
padding: 8px 15px;
}
&-item {
position: relative;
display: block;
padding: 7px 15px;
font-weight: normal;
color: #666;
white-space: nowrap;
cursor: pointer;
overflow: hidden;
transition: background 0.3s ease;
&:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
&:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
&:hover,
&-active {
background-color: tint(@primary-color, 90%);
}
&-selected {
background-color: tint(@primary-color, 80%);
&:hover {
background-color: tint(@primary-color, 80%);
}
}
&-disabled {
color: #ccc;
cursor: not-allowed;
&:hover {
color: #ccc;
background-color: #fff;
cursor: not-allowed;
}
}
&-divider {
height: 1px;
margin: 1px 0;
overflow: hidden;
background-color: #e5e5e5;
line-height: 0;
}
}
}
&-container-open,
&-open {
.@{tree-select-prefix-cls}-dropdown {
display: block;
}
}
.@{tree-select-prefix-cls}-dropdown-search {
display: block;
padding: 4px;
.@{tree-select-prefix-cls}-search__field__placeholder {
left: 7px;
top: 5px;
}
.@{tree-select-prefix-cls}-search__field__wrap {
width: 100%;
}
.@{tree-select-prefix-cls}-search__field {
padding: 4px 7px;
width: 100%;
box-sizing: border-box;
border: 1px solid @border-color-base;
border-radius: 4px;
outline: none;
}
&.@{tree-select-prefix-cls}-search--hide {
display: none;
}
}
}
| style/components/treeSelect.less | 1 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.4466603398323059,
0.010238910093903542,
0.00016615296772215515,
0.00017384407692588866,
0.058792851865291595
] |
{
"id": 1,
"code_window": [
" &:active {\n",
" border-color: @border-color-base;\n",
" }\n",
" }\n",
"\n",
" &-disabled &-selection--single {\n",
" background: #f4f4f4;\n",
" cursor: not-allowed;\n",
" }\n",
"\n",
" &-disabled &-selection--multiple &-selection__choice__remove {\n",
" display: none;\n",
" }\n",
"\n",
" &-selection--single {\n",
" height: 28px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-disabled &-selection--multiple &-selection__choice {\n",
" background: #e9e9e9;\n",
" color: #aaa;\n",
" padding-right: 10px;\n",
" &__remove {\n",
" display: none;\n",
" }\n"
],
"file_path": "style/components/select.less",
"type": "replace",
"edit_start_line_idx": 77
} | # Checkbox
- category: Components
- chinese: 多选框
- type: 表单
---
多选框。
## 何时使用
- 在一组可选项中进行多项选择时;
- 单独使用可以表示两种状态之间的切换,和 `switch` 类似。区别在于切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。
## API
### Checkbox
| 参数 | 说明 | 类型 | 可选值 |默认值 |
|-----------|------------------------------------------|------------|-------|--------|
| checked | 指定当前是否选中 | boolean | | false |
| defaultChecked | 初始是否选中 | boolean | | false |
| onChange | 变化时回调函数 | Function(e:Event) | | | |
### Checkbox Group
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|-----------|------------------------------------------|------------|---------|--------|
| defaultValue | 默认选中的选项 | array | | [] |
| value | 指定选中的选项| array | | [] |
| options | 指定可选项 | array | | [] |
| onChange | 变化时回调函数 | Function(checkedValue) | | | |
| components/checkbox/index.md | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.00017585066962055862,
0.0001729558571241796,
0.000169850216479972,
0.00017306125664617866,
0.000002708042529775412
] |
{
"id": 1,
"code_window": [
" &:active {\n",
" border-color: @border-color-base;\n",
" }\n",
" }\n",
"\n",
" &-disabled &-selection--single {\n",
" background: #f4f4f4;\n",
" cursor: not-allowed;\n",
" }\n",
"\n",
" &-disabled &-selection--multiple &-selection__choice__remove {\n",
" display: none;\n",
" }\n",
"\n",
" &-selection--single {\n",
" height: 28px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-disabled &-selection--multiple &-selection__choice {\n",
" background: #e9e9e9;\n",
" color: #aaa;\n",
" padding-right: 10px;\n",
" &__remove {\n",
" display: none;\n",
" }\n"
],
"file_path": "style/components/select.less",
"type": "replace",
"edit_start_line_idx": 77
} | @message-prefix-cls: ant-message;
.@{message-prefix-cls} {
font-size: 12px;
position: fixed;
z-index: 1050;
width: 100%;
top: 16px;
&-notice {
width: auto;
vertical-align: middle;
position: absolute;
left: 50%;
}
&-notice-content {
position: relative;
right: 50%;
padding: 8px 16px;
border-radius: @border-radius-base;
border: 1px solid @border-color-base;
box-shadow: @box-shadow-base;
background: #fff;
display: block;
}
&-success.anticon {
color: @success-color;
}
&-error.anticon {
color: @error-color;
}
&-warn.anticon {
color: @warning-color;
}
&-info.anticon,
&-loading.anticon {
color: @primary-color;
}
.anticon {
margin-right: 8px;
font-size: 14px;
top: 1px;
position: relative;
}
}
| style/components/message.less | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.00017799800843931735,
0.00017455896886531264,
0.00016530453285668045,
0.0001760569284670055,
0.000004290256583772134
] |
{
"id": 1,
"code_window": [
" &:active {\n",
" border-color: @border-color-base;\n",
" }\n",
" }\n",
"\n",
" &-disabled &-selection--single {\n",
" background: #f4f4f4;\n",
" cursor: not-allowed;\n",
" }\n",
"\n",
" &-disabled &-selection--multiple &-selection__choice__remove {\n",
" display: none;\n",
" }\n",
"\n",
" &-selection--single {\n",
" height: 28px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-disabled &-selection--multiple &-selection__choice {\n",
" background: #e9e9e9;\n",
" color: #aaa;\n",
" padding-right: 10px;\n",
" &__remove {\n",
" display: none;\n",
" }\n"
],
"file_path": "style/components/select.less",
"type": "replace",
"edit_start_line_idx": 77
} | {%- set categories = resource.pages|get_categories(post) %}
<aside class="aside-container">
<ul>
{%- for category in categories %}
{%- if category.pages.length === 1 %}
{%- for item in category.pages|splitComponentsByType(category.name) %}
<li class="{%- if item.title === post.title %}current{%- endif %}">
<a href="{%- if item.meta.link %}{{item.meta.link}}{%- else %}{{permalink_url(item)}}{%- endif %}"
{%- if item.meta.link %}target="_blank"{%- endif %}
class="{%- if item.meta.disabled %}nav-link-disabled{%- endif %}">
{{item.title}}
<span class="chinese">{{item.meta.chinese}}</span>
</a>
</li>
{%- endfor %}
{%- else %}
<li open="open">
<h4>{{category.name}}</h4>
<ul class="{%- if category === post.meta.category %}aside-list-show{%- endif %}">
{%- for item in category.pages|splitComponentsByType(category.name) %}
{%- if item.divider === true %}
<li class="type-divider">{{item.name}}</li>
{%- else %}
<li class="{%- if item.title === post.title %}current{%- endif %}">
<a href="{{permalink_url(item)}}"
class="{%- if item.meta.disabled %}nav-link-disabled{%- endif %}"
{%- if item.meta.noinstant %}data-no-instant{%- endif %}>
{{item.title}}
<span class="chinese">{{item.meta.chinese}}</span>
</a>
</li>
{%- endif %}
{%- endfor %}
</ul>
</li>
{%- endif %}
{%- endfor %}
</ul>
</aside>
| site/templates/aside.html | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.0001757201098371297,
0.0001716944098006934,
0.00016407166549470276,
0.0001734929101075977,
0.000004512686700763879
] |
{
"id": 2,
"code_window": [
" }\n",
"\n",
" &-disabled &-selection {\n",
" &:hover,\n",
" &:active {\n",
" border-color: @border-color-base;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" background: #f4f4f4;\n",
" cursor: not-allowed;\n"
],
"file_path": "style/components/treeSelect.less",
"type": "add",
"edit_start_line_idx": 183
} | @tree-select-tree-prefix-cls: ant-tree-select-tree;
.antCheckboxFn(@checkbox-prefix-cls: ant-tree-select-tree-checkbox);
@import "../mixins/iconfont";
.@{tree-select-tree-prefix-cls} {
margin: 0;
padding: 8px;
font-size: 12px;
li {
padding: 0;
margin: 8px 0;
list-style: none;
white-space: nowrap;
outline: 0;
&.filter-node {
> a {
color: @error-color!important;
font-weight: bold!important;
}
}
ul {
margin: 0;
padding: 0 0 0 18px;
}
a {
display: inline-block;
padding: 1px 5px;
border-radius: 2px;
margin: 0;
cursor: pointer;
text-decoration: none;
vertical-align: top;
color: #666;
transition: all 0.3s ease;
&:hover {
background-color: tint(@primary-color, 90%);
}
&.@{tree-select-tree-prefix-cls}-node-selected {
background-color: tint(@primary-color, 80%);
}
}
span {
&.@{tree-select-tree-prefix-cls}-checkbox {
margin: 2px 4px 0 0;
}
&.@{tree-select-tree-prefix-cls}-switcher,
&.@{tree-select-tree-prefix-cls}-iconEle {
margin: 0;
width: 16px;
height: 16px;
line-height: 16px;
display: inline-block;
vertical-align: middle;
border: 0 none;
cursor: pointer;
outline: none;
}
&.@{tree-select-tree-prefix-cls}-icon_loading {
&:after {
content: '\e6a1';
display: inline-block;
font-family: 'anticon';
font-weight: bold;
.animation(loadingCircle 1s infinite linear);
margin-top: 8px;
}
}
&.@{tree-select-tree-prefix-cls}-switcher {
&.@{tree-select-tree-prefix-cls}-roots_open,
&.@{tree-select-tree-prefix-cls}-center_open,
&.@{tree-select-tree-prefix-cls}-bottom_open,
&.@{tree-select-tree-prefix-cls}-noline_open {
.antTreeSwitcherIcon();
}
&.@{tree-select-tree-prefix-cls}-roots_close,
&.@{tree-select-tree-prefix-cls}-center_close,
&.@{tree-select-tree-prefix-cls}-bottom_close,
&.@{tree-select-tree-prefix-cls}-noline_close {
.antTreeSwitcherIcon();
.ie-rotate(3);
&:after {
transform: rotate(270deg) scale(0.5);
}
}
}
}
}
&-child-tree {
display: none;
&-open {
display: block;
}
}
&-treenode-disabled {
>span,
>a,
>a span {
color: #ccc;
cursor: not-allowed;
}
}
&-icon__open {
margin-right: 2px;
vertical-align: top;
}
&-icon__close {
margin-right: 2px;
vertical-align: top;
}
}
@tree-select-prefix-cls: ant-tree-select;
@duration: .3s;
@import "../mixins/iconfont";
//mixin
.selection__clear() {
cursor: pointer;
float: right;
font-weight: bold;
}
.@{tree-select-prefix-cls} {
box-sizing: border-box;
display: inline-block;
margin: 0;
position: relative;
vertical-align: middle;
color: #666;
font-size: @font-size-base;
> ul > li > a {
padding: 0;
background-color: #fff;
}
// arrow
&-arrow {
.iconfont-mixin();
position: absolute;
top: 50%;
right: 8px;
line-height: 1;
margin-top: -5px;
.iconfont-size-under-12px(8px);
* {
display: none;
}
&:before {
content: '\e603';
transition: transform 0.2s ease;
}
}
&-selection {
outline: none;
user-select: none;
box-sizing: border-box;
display: block;
background-color: #fff;
border-radius: @border-radius-base;
border: 1px solid @border-color-base;
.transition(all .3s @ease-in-out);
&:hover {
.hover;
}
&:active {
.active;
}
}
&-disabled {
color: #ccc;
}
&-disabled &-selection {
&:hover,
&:active {
border-color: @border-color-base;
}
}
&-disabled &-selection--single {
background: #f4f4f4;
cursor: not-allowed;
}
&-selection--single {
height: 28px;
cursor: pointer;
.@{tree-select-prefix-cls}-selection__rendered {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding-left: 8px;
padding-right: 24px;
line-height: 26px;
}
.@{tree-select-prefix-cls}-selection__clear {
.selection__clear();
}
.@{tree-select-prefix-cls}-selection__placeholder {
color: #ccc;
}
}
&-lg {
.@{tree-select-prefix-cls}-selection--single {
height: 32px;
.@{tree-select-prefix-cls}-selection__rendered {
line-height: 30px;
}
}
.@{tree-select-prefix-cls}-selection--multiple {
min-height: 32px;
.@{tree-select-prefix-cls}-selection__rendered {
li {
height: 24px;
.@{tree-select-prefix-cls}-selection__choice__content {
font-size: 14px;
line-height: 24px;
}
}
}
}
}
&-sm {
.@{tree-select-prefix-cls}-selection {
border-radius: @border-radius-sm;
}
.@{tree-select-prefix-cls}-selection--single {
height: 22px;
.@{tree-select-prefix-cls}-selection__rendered {
line-height: 20px;
}
}
.@{tree-select-prefix-cls}-selection--multiple {
min-height: 22px;
.@{tree-select-prefix-cls}-selection__rendered {
li {
height: 14px;
.@{tree-select-prefix-cls}-selection__choice__content {
line-height: 14px;
position: relative;
top: -3px;
}
.@{tree-select-prefix-cls}-selection__choice__remove {
position: relative;
top: -4px;
}
}
}
}
}
&-disabled &-selection__choice__remove {
color: #ccc;
cursor: default;
&:hover {
color: #ccc;
}
}
&-search__field__wrap {
display: inline-block;
position: relative;
}
&-search__field__placeholder {
position: absolute;
top: 0;
left: 3px;
color: #aaa;
}
&-search--inline {
float: left;
.@{tree-select-prefix-cls}-search__field__wrap {
width: 100%;
}
.@{tree-select-prefix-cls}-search__field {
border: 0;
font-size: 100%;
background: transparent;
outline: 0;
}
> i {
float: right;
}
}
&-selection--multiple {
min-height: 28px;
cursor: text;
.@{tree-select-prefix-cls}-search__field__placeholder {
top: 6px;
left: 10px;
}
.@{tree-select-prefix-cls}-search--inline {
width: auto;
.@{tree-select-prefix-cls}-search__field {
width: 0.75em;
}
}
.@{tree-select-prefix-cls}-selection__rendered {
overflow: hidden;
text-overflow: ellipsis;
padding-left: 6px;
padding-bottom: 4px;
}
.@{tree-select-prefix-cls}-selection__clear {
.selection__clear();
margin-top: 5px;
margin-right: 10px;
}
> ul > li {
margin-top: 4px;
height: 20px;
line-height: 20px;
}
.@{tree-select-prefix-cls}-selection__choice {
background-color: #f3f3f3;
border-radius: 4px;
cursor: default;
float: left;
padding: 0 15px;
margin-right: 4px;
max-width: 99%;
position: relative;
overflow: hidden;
transition: padding @duration @ease-in-out;
padding: 0 20px 0 10px;
}
.@{tree-select-prefix-cls}-selection__choice__content {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
transition: margin @duration @ease-in-out;
}
.@{tree-select-prefix-cls}-selection__choice__remove {
.iconfont-mixin();
color: #999;
line-height: 20px;
cursor: pointer;
display: inline-block;
font-weight: bold;
transition: all 0.3s @ease-in-out;
.iconfont-size-under-12px(8px);
position: absolute;
right: 4px;
padding: 0 0 0 8px;
&:hover {
color: #404040;
}
&:before {
content: "\e62d";
}
}
}
&-open {
.@{tree-select-prefix-cls}-arrow {
.ie-rotate(2);
-ms-transform: rotate(180deg);
&:before {
.rotate(180deg);
}
}
.@{tree-select-prefix-cls}-selection {
.active();
}
}
&-combobox {
.@{tree-select-prefix-cls}-arrow {
display: none;
}
.@{tree-select-prefix-cls}-search--inline {
height: 100%;
float: none;
}
.@{tree-select-prefix-cls}-search__field__placeholder {
left: 10px;
cursor: text;
}
.@{tree-select-prefix-cls}-search__field__wrap {
width: 100%;
height: 100%;
}
.@{tree-select-prefix-cls}-search__field {
padding: 0 10px;
width: 100%;
height: 100%;
position: relative;
z-index: 1;
}
.@{tree-select-prefix-cls}-selection__rendered {
padding: 0;
height: 100%;
}
}
}
.@{tree-select-prefix-cls}-dropdown {
&.slide-up-enter.slide-up-enter-active&-placement-bottomLeft,
&.slide-up-appear.slide-up-appear-active&-placement-bottomLeft {
animation-name: antSlideUpIn;
}
&.slide-up-enter.slide-up-enter-active&-placement-topLeft,
&.slide-up-appear.slide-up-appear-active&-placement-topLeft {
animation-name: antSlideDownIn;
}
&.slide-up-leave.slide-up-leave-active&-placement-bottomLeft {
animation-name: antSlideUpOut;
}
&.slide-up-leave.slide-up-leave-active&-placement-topLeft {
animation-name: antSlideDownOut;
}
&-hidden {
display: none;
}
background-color: white;
border: 1px solid @border-color-base;
box-shadow: @box-shadow-base;
border-radius: @border-radius-base;
box-sizing: border-box;
z-index: 1070;
left: -9999px;
top: -9999px;
position: absolute;
outline: none;
overflow: hidden;
font-size: @font-size-base;
&-menu {
outline: none;
margin-bottom: 0;
padding-left: 0; // Override default ul/ol
list-style: none;
max-height: 250px;
overflow: auto;
&-item-group-list {
margin: 0;
padding: 0;
> .@{tree-select-prefix-cls}-dropdown-menu-item {
padding-left: 24px;
}
}
&-item-group-title {
color: #999;
line-height: 1.5;
padding: 8px 15px;
}
&-item {
position: relative;
display: block;
padding: 7px 15px;
font-weight: normal;
color: #666;
white-space: nowrap;
cursor: pointer;
overflow: hidden;
transition: background 0.3s ease;
&:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
&:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
&:hover,
&-active {
background-color: tint(@primary-color, 90%);
}
&-selected {
background-color: tint(@primary-color, 80%);
&:hover {
background-color: tint(@primary-color, 80%);
}
}
&-disabled {
color: #ccc;
cursor: not-allowed;
&:hover {
color: #ccc;
background-color: #fff;
cursor: not-allowed;
}
}
&-divider {
height: 1px;
margin: 1px 0;
overflow: hidden;
background-color: #e5e5e5;
line-height: 0;
}
}
}
&-container-open,
&-open {
.@{tree-select-prefix-cls}-dropdown {
display: block;
}
}
.@{tree-select-prefix-cls}-dropdown-search {
display: block;
padding: 4px;
.@{tree-select-prefix-cls}-search__field__placeholder {
left: 7px;
top: 5px;
}
.@{tree-select-prefix-cls}-search__field__wrap {
width: 100%;
}
.@{tree-select-prefix-cls}-search__field {
padding: 4px 7px;
width: 100%;
box-sizing: border-box;
border: 1px solid @border-color-base;
border-radius: 4px;
outline: none;
}
&.@{tree-select-prefix-cls}-search--hide {
display: none;
}
}
}
| style/components/treeSelect.less | 1 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.9753205180168152,
0.020248524844646454,
0.00016344756295438856,
0.00017067753651645035,
0.128325417637825
] |
{
"id": 2,
"code_window": [
" }\n",
"\n",
" &-disabled &-selection {\n",
" &:hover,\n",
" &:active {\n",
" border-color: @border-color-base;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" background: #f4f4f4;\n",
" cursor: not-allowed;\n"
],
"file_path": "style/components/treeSelect.less",
"type": "add",
"edit_start_line_idx": 183
} | # Ant Design
- category: 0
- order: 0
---
Ant Design 是一个 UI 设计语言,是一套提炼和应用于企业级中后台产品的交互语言和视觉体系。
<img width="300" src="https://t.alipayobjects.com/images/rmsweb/T1B9hfXcdvXXXXXXXX.svg">
Ant Design 源自蚂蚁金服体验技术部的后台产品开发。在中后台产品设计中,通常有很多类似的页面和控件,不同的产品会出现不同的规范和实现,给设计师和工程师带来很多困扰和重复建设,降低企业后台的整体研发效率。我们的设计师和前端工程师经过大量的项目实践和总结,希望能沉淀出一套企业级的交互视觉规范,统一中后台项目的前端 UI 设计,屏蔽各种不必要的设计差异和前端实现成本,解放设计和前端开发资源。
整套设计规范还在持续整理和完善中。
## 谁在使用
- 蚂蚁金服
- 口碑
> 如果你的公司和产品使用了 Ant Design,欢迎到 [这里](https://github.com/ant-design/ant-design/issues/477) 留言。
## 前端实现
我们采用 [React](http://facebook.github.io/react/) 封装了一套 Ant Design 的组件库,也欢迎社区其他框架的实现版本。
- [Ant Design of React](/docs/react/introduce)(官方实现)
- [vue-antd](https://github.com/okoala/vue-antd)
## 如何贡献
我们欢迎任何形式的贡献,有任何建议或意见您可以进行 [Pull Request](https://github.com/ant-design/ant-design/pulls),或者给我们[提问](https://github.com/ant-design/ant-design/issues)。
| docs/spec/introduce.md | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.0006859664572402835,
0.0002989284403156489,
0.0001664125156821683,
0.00017166743054986,
0.00022346782498061657
] |
{
"id": 2,
"code_window": [
" }\n",
"\n",
" &-disabled &-selection {\n",
" &:hover,\n",
" &:active {\n",
" border-color: @border-color-base;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" background: #f4f4f4;\n",
" cursor: not-allowed;\n"
],
"file_path": "style/components/treeSelect.less",
"type": "add",
"edit_start_line_idx": 183
} | # 高级搜索
- category: 6
- order: 6
---
借助『高级搜索』,用户可以缩小复杂列表/表格等的展示范围。
## 常规型
### 交互
<img class="preview-img" align="right" alt="交互示例" description="在收起状态时,用户点击『高级搜索』展开;如果此前用户已经输入过文案,需要将值带到对应的输入框中。" src="https://os.alipayobjects.com/rmsportal/NpRKspdYRDwsKnw.png">
常规型常和表格搭配使用,适合在搜索条件多以及搜索值个数不确定的场景中。
『高级搜索』功能一般开放给中间用户/专家用户使用,一般通过点击『高级搜索』触发;如果非常高频使用,可以默认展开『高级搜索』。
<br>
<img class="preview-img" align="right" alt="交互示例" description="在『高级搜索』顶部放置 Alert ,用于展现已经输入的值;用户点击『清空』可以清空所有输入值;点击『高级搜索』可以再次展开『高级搜索』。" src="https://os.alipayobjects.com/rmsportal/gKiZtjopvLufqSP.png">
当已经输入了值的『高级搜索』被隐藏时,需要展示检索条件和值。
### 排列规则
<img class="preview-img" align="right" alt="排列示例" src="https://os.alipayobjects.com/rmsportal/TsdXCWLPIETykye.png">
搜索条件的排布顺序需要和表格中的标题顺序,尽可能保持一致;如果非常高频使用的搜索条件,可以放在最前面。
### 规格
<img class="preview-img" align="right" alt="规格示例" src="https://os.alipayobjects.com/rmsportal/fuPcwZCYiohhdSt.png">
<img class="preview-img" align="right" alt="规格示例" src="https://os.alipayobjects.com/rmsportal/bFLUSbwoNoakKYS.png">
- 横向排版
在一行不要放置 3 列以上的输入框;标签和输入框应该落在栅格上。
- 纵向排版
使用 `16px` 作为间距。
## 字段型
### 交互
<img class="preview-img" align="right" alt="交互示例" src="https://os.alipayobjects.com/rmsportal/TUxfnHjfTJeKaDq.png">
字段型一般会出现在主搜索框底部,适合搜索条件和值都比较少的场景中。
## 案例(敬请期待)
| docs/pattern/advanced-search.md | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.00086539814947173,
0.00039900271804071963,
0.00016484335355926305,
0.0001683437149040401,
0.0003280853561591357
] |
{
"id": 2,
"code_window": [
" }\n",
"\n",
" &-disabled &-selection {\n",
" &:hover,\n",
" &:active {\n",
" border-color: @border-color-base;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" background: #f4f4f4;\n",
" cursor: not-allowed;\n"
],
"file_path": "style/components/treeSelect.less",
"type": "add",
"edit_start_line_idx": 183
} | # 基本
- order: 0
默认选中第一项。
---
````jsx
import { Tabs } from 'antd';
const TabPane = Tabs.TabPane;
function callback(key) {
console.log(key);
}
ReactDOM.render(
<Tabs defaultActiveKey="1" onChange={callback}>
<TabPane tab="选项卡一" key="1">选项卡一内容</TabPane>
<TabPane tab="选项卡二" key="2">选项卡二内容</TabPane>
<TabPane tab="选项卡三" key="3">选项卡三内容</TabPane>
</Tabs>
, mountNode);
````
| components/tabs/demo/basic.md | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.0001700170832918957,
0.00016824759950395674,
0.00016732596850488335,
0.0001673997176112607,
0.0000012515830576376175
] |
{
"id": 3,
"code_window": [
" border-color: @border-color-base;\n",
" }\n",
" }\n",
"\n",
" &-disabled &-selection--single {\n",
" background: #f4f4f4;\n",
" cursor: not-allowed;\n",
" }\n",
"\n",
" &-selection--single {\n",
" height: 28px;\n",
" cursor: pointer;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-disabled &-selection--multiple &-selection__choice {\n",
" background: #e9e9e9;\n",
" color: #999;\n",
" padding-right: 10px;\n",
" &__remove {\n",
" display: none;\n",
" }\n"
],
"file_path": "style/components/treeSelect.less",
"type": "replace",
"edit_start_line_idx": 189
} | @select-prefix-cls: ant-select;
@duration: .3s;
@import "../mixins/iconfont";
//mixin
.selection__clear() {
cursor: pointer;
float: right;
font-weight: bold;
}
.@{select-prefix-cls} {
box-sizing: border-box;
display: inline-block;
margin: 0;
position: relative;
vertical-align: middle;
color: #666;
font-size: @font-size-base;
> ul > li > a {
padding: 0;
background-color: #fff;
}
// arrow
&-arrow {
.iconfont-mixin();
position: absolute;
top: 50%;
right: 8px;
line-height: 1;
margin-top: -5px;
.iconfont-size-under-12px(8px);
* {
display: none;
}
&:before {
content: '\e603';
transition: transform 0.2s ease;
}
}
&-selection {
outline: none;
user-select: none;
box-sizing: border-box;
display: block;
background-color: #fff;
border-radius: @border-radius-base;
border: 1px solid @border-color-base;
.transition(all .3s @ease-in-out);
&:hover {
.hover;
}
&:active {
.active;
}
}
&-disabled {
color: #ccc;
}
&-disabled &-selection {
&:hover,
&:active {
border-color: @border-color-base;
}
}
&-disabled &-selection--single {
background: #f4f4f4;
cursor: not-allowed;
}
&-disabled &-selection--multiple &-selection__choice__remove {
display: none;
}
&-selection--single {
height: 28px;
cursor: pointer;
.@{select-prefix-cls}-selection__rendered {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding-left: 8px;
padding-right: 24px;
line-height: 26px;
}
.@{select-prefix-cls}-selection__clear {
.selection__clear();
}
.@{select-prefix-cls}-selection__placeholder {
color: #ccc;
}
}
&-lg {
.ant-select-selection--single {
height: 32px;
.ant-select-selection__rendered {
line-height: 30px;
}
}
.ant-select-selection--multiple {
min-height: 32px;
.ant-select-selection__rendered {
li {
height: 24px;
.ant-select-selection__choice__content {
font-size: 14px;
line-height: 24px;
}
}
}
}
}
&-sm {
.ant-select-selection {
border-radius: @border-radius-sm;
}
.ant-select-selection--single {
height: 22px;
.ant-select-selection__rendered {
line-height: 20px;
}
}
.ant-select-selection--multiple {
min-height: 22px;
.ant-select-selection__rendered {
li {
height: 14px;
.ant-select-selection__choice__content {
line-height: 14px;
position: relative;
top: -3px;
}
.ant-select-selection__choice__remove {
position: relative;
top: -4px;
}
}
}
}
}
&-disabled &-selection__choice__remove {
color: #ccc;
cursor: default;
&:hover {
color: #ccc;
}
}
&-search__field__wrap {
display: inline-block;
position: relative;
}
&-search__field__placeholder {
position: absolute;
top: 0;
left: 3px;
color: #aaa;
}
&-search--inline {
float: left;
.@{select-prefix-cls}-search__field__wrap {
width: 100%;
}
.@{select-prefix-cls}-search__field {
border: 0;
font-size: 100%;
background: transparent;
outline: 0;
border-radius: @border-radius-base;
}
> i {
float: right;
}
}
&-selection--multiple {
min-height: 28px;
cursor: text;
.@{select-prefix-cls}-search__field__placeholder {
top: 6px;
left: 10px;
}
.@{select-prefix-cls}-search--inline {
width: auto;
.@{select-prefix-cls}-search__field {
width: 0.75em;
}
}
.@{select-prefix-cls}-selection__rendered {
overflow: hidden;
text-overflow: ellipsis;
padding-left: 6px;
padding-bottom: 4px;
}
.@{select-prefix-cls}-selection__clear {
.selection__clear();
margin-top: 5px;
margin-right: 10px;
}
> ul > li {
margin-top: 4px;
height: 20px;
line-height: 20px;
}
.@{select-prefix-cls}-selection__choice {
background-color: #f3f3f3;
border-radius: 4px;
cursor: default;
float: left;
padding: 0 15px;
margin-right: 4px;
max-width: 99%;
position: relative;
overflow: hidden;
transition: padding @duration @ease-in-out;
padding: 0 20px 0 10px;
}
.@{select-prefix-cls}-selection__choice__content {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
transition: margin @duration @ease-in-out;
}
.@{select-prefix-cls}-selection__choice__remove {
.iconfont-mixin();
color: #999;
line-height: 20px;
cursor: pointer;
display: inline-block;
font-weight: bold;
transition: all 0.3s @ease-in-out;
.iconfont-size-under-12px(8px);
position: absolute;
right: 4px;
padding: 0 0 0 8px;
&:hover {
color: #404040;
}
&:before {
content: "\e62d";
}
}
}
&-open {
.@{select-prefix-cls}-arrow {
.ie-rotate(2);
-ms-transform: rotate(180deg);
&:before {
.rotate(180deg);
}
}
.@{select-prefix-cls}-selection {
.active();
}
}
&-combobox {
.@{select-prefix-cls}-arrow {
display: none;
}
.@{select-prefix-cls}-search--inline {
height: 100%;
float: none;
}
.@{select-prefix-cls}-search__field__placeholder {
left: 10px;
cursor: text;
}
.@{select-prefix-cls}-search__field__wrap {
width: 100%;
height: 100%;
}
.@{select-prefix-cls}-search__field {
padding: 0 10px;
width: 100%;
height: 100%;
position: relative;
z-index: 1;
transition: all .3s @ease-in-out;
&:focus {
box-shadow: 0 0 0 1px tint(@primary-color, 20%), 0 0 0 3px tint(@primary-color, 80%);
}
}
.@{select-prefix-cls}-selection__rendered {
padding: 0;
height: 100%;
overflow: visible;
}
}
}
.@{select-prefix-cls}-dropdown {
&.slide-up-enter.slide-up-enter-active&-placement-bottomLeft,
&.slide-up-appear.slide-up-appear-active&-placement-bottomLeft {
animation-name: antSlideUpIn;
}
&.slide-up-enter.slide-up-enter-active&-placement-topLeft,
&.slide-up-appear.slide-up-appear-active&-placement-topLeft {
animation-name: antSlideDownIn;
}
&.slide-up-leave.slide-up-leave-active&-placement-bottomLeft {
animation-name: antSlideUpOut;
}
&.slide-up-leave.slide-up-leave-active&-placement-topLeft {
animation-name: antSlideDownOut;
}
&-hidden {
display: none;
}
background-color: white;
border: 1px solid @border-color-base;
box-shadow: @box-shadow-base;
border-radius: @border-radius-base;
box-sizing: border-box;
z-index: 1070;
left: -9999px;
top: -9999px;
position: absolute;
outline: none;
overflow: hidden;
font-size: @font-size-base;
&-menu {
outline: none;
margin-bottom: 0;
padding-left: 0; // Override default ul/ol
list-style: none;
max-height: 250px;
overflow: auto;
&-item-group-list {
margin: 0;
padding: 0;
> .@{select-prefix-cls}-dropdown-menu-item {
padding-left: 24px;
}
}
&-item-group-title {
color: #999;
line-height: 1.5;
padding: 8px 15px;
}
&-item {
position: relative;
display: block;
padding: 7px 15px;
font-weight: normal;
color: #666;
white-space: nowrap;
cursor: pointer;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
transition: background 0.3s ease;
&:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
&:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
&:hover,
&-active {
background-color: tint(@primary-color, 90%);
}
&-selected {
background-color: tint(@primary-color, 80%);
&:hover {
background-color: tint(@primary-color, 80%);
}
}
&-disabled {
color: #ccc;
cursor: not-allowed;
&:hover {
color: #ccc;
background-color: #fff;
cursor: not-allowed;
}
}
&-divider {
height: 1px;
margin: 1px 0;
overflow: hidden;
background-color: #e5e5e5;
line-height: 0;
}
}
}
&-container-open,
&-open {
.@{select-prefix-cls}-dropdown {
display: block;
}
}
.@{select-prefix-cls}-dropdown-search {
display: block;
padding: 4px;
.@{select-prefix-cls}-search__field__placeholder {
left: 7px;
top: 5px;
}
.@{select-prefix-cls}-search__field__wrap {
width: 100%;
}
.@{select-prefix-cls}-search__field {
padding: 4px 7px;
width: 100%;
box-sizing: border-box;
border: 1px solid @border-color-base;
border-radius: 4px;
outline: none;
}
&.@{select-prefix-cls}-search--hide {
display: none;
}
}
}
| style/components/select.less | 1 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.9928868412971497,
0.0222462210804224,
0.000166104975505732,
0.00017409501015208662,
0.14182645082473755
] |
{
"id": 3,
"code_window": [
" border-color: @border-color-base;\n",
" }\n",
" }\n",
"\n",
" &-disabled &-selection--single {\n",
" background: #f4f4f4;\n",
" cursor: not-allowed;\n",
" }\n",
"\n",
" &-selection--single {\n",
" height: 28px;\n",
" cursor: pointer;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-disabled &-selection--multiple &-selection__choice {\n",
" background: #e9e9e9;\n",
" color: #999;\n",
" padding-right: 10px;\n",
" &__remove {\n",
" display: none;\n",
" }\n"
],
"file_path": "style/components/treeSelect.less",
"type": "replace",
"edit_start_line_idx": 189
} | # Cascader
- category: Components
- chinese: 级联选择
- type: 表单
---
级联选择框。
## 何时使用
- 需要从一组相关联的数据集合进行选择,例如省市区,公司层级,事物分类等。
- 从一个较大的数据集合中进行选择时,用多级分类进行分隔,方便选择。
- 比起 Select 组件,可以在同一个浮层中完成选择,有较好的体验。
## API
```html
<Cascader options={options} onChange={onChange} />
```
| 参数 | 说明 | 类型 | 默认值 |
|------|------|------|--------|
| options | 可选项数据源 | object | - |
| defaultValue | 默认的选中项 | array |[] |
| value | 指定选中项 | array | - |
| onChange | 选择完成后的回调 | `function(value, selectedOptions)` | - |
| displayRender | 选择后展示的渲染函数 | `function(label)`` | `function(label) { return label.join(' / ') }` |
| style | 自定义样式 | string | - |
| className | 自定义类名 | string | - |
| popupClassName | 自定义浮层类名 | string | - |
| placeholder | 输入框占位文本 | string | '请选择' |
| size | 输入框大小,可选 `large` `default` `small` | string | `default` |
| disabled | 禁用 | boolean | false |
| components/cascader/index.md | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.00017159836716018617,
0.0001694037055131048,
0.00016685438458807766,
0.00016958103515207767,
0.000001731827978801448
] |
{
"id": 3,
"code_window": [
" border-color: @border-color-base;\n",
" }\n",
" }\n",
"\n",
" &-disabled &-selection--single {\n",
" background: #f4f4f4;\n",
" cursor: not-allowed;\n",
" }\n",
"\n",
" &-selection--single {\n",
" height: 28px;\n",
" cursor: pointer;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-disabled &-selection--multiple &-selection__choice {\n",
" background: #e9e9e9;\n",
" color: #999;\n",
" padding-right: 10px;\n",
" &__remove {\n",
" display: none;\n",
" }\n"
],
"file_path": "style/components/treeSelect.less",
"type": "replace",
"edit_start_line_idx": 189
} | import React from 'react';
import Animate from 'rc-animate';
import Icon from '../icon';
const prefixCls = 'ant-upload';
import { Line } from '../progress';
import classNames from 'classnames';
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
const previewFile = function (file, callback) {
const reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
};
reader.readAsDataURL(file);
};
export default React.createClass({
getDefaultProps() {
return {
listType: 'text', // or picture
items: [],
progressAttr: {
strokeWidth: 3,
showInfo: false
}
};
},
handleClose(file) {
this.props.onRemove(file);
},
componentDidUpdate() {
if (this.props.listType !== 'picture' && this.props.listType !== 'picture-card') {
return;
}
this.props.items.forEach(file => {
if (typeof document === 'undefined' ||
typeof window === 'undefined' ||
!window.FileReader || !window.File ||
!(file.originFileObj instanceof File) ||
file.thumbUrl !== undefined) {
return;
}
/*eslint-disable */
file.thumbUrl = '';
/*eslint-enable */
previewFile(file.originFileObj, (previewDataUrl) => {
/*eslint-disable */
file.thumbUrl = previewDataUrl;
/*eslint-enable */
this.forceUpdate();
});
});
},
render() {
let list = this.props.items.map(file => {
let progress;
let icon = <Icon type="paper-clip" />;
if (this.props.listType === 'picture' || this.props.listType === 'picture-card') {
if (file.status === 'uploading' || (!file.thumbUrl && !file.url)) {
if (this.props.listType === 'picture-card') {
icon = <div className={prefixCls + '-list-item-uploading-text'}>文件上传中</div>;
} else {
icon = <Icon className={prefixCls + '-list-item-thumbnail'} type="picture" />;
}
} else {
icon = (<a className={prefixCls + '-list-item-thumbnail'}
href={file.url}
target="_blank"><img src={file.thumbUrl || file.url} alt={file.name} /></a>
);
}
}
if (file.status === 'uploading') {
progress = (
<div className={prefixCls + '-list-item-progress'}>
<Line {...this.props.progressAttr} percent={file.percent} />
</div>
);
}
const infoUploadingClass = classNames({
[`${prefixCls}-list-item`]: true,
[`${prefixCls}-list-item-${file.status}`]: true,
});
return (
<div className={infoUploadingClass} key={file.uid}>
<div className={prefixCls + '-list-item-info'}>
{icon}
<span className={prefixCls + '-list-item-name'}>{file.name}</span>
{
this.props.listType === 'picture-card' && file.status !== 'uploading'
? (
<span>
<a href={file.url} target="_blank" style={{ pointerEvents: file.url ? '' : 'none' }}><Icon type="eye-o" /></a>
<Icon type="delete" onClick={this.handleClose.bind(this, file)} />
</span>
) : <Icon type="cross" onClick={this.handleClose.bind(this, file)} />
}
</div>
{ progress }
</div>
);
});
const listClassNames = classNames({
[`${prefixCls}-list`]: true,
[`${prefixCls}-list-${this.props.listType}`]: true,
});
return (
<div className={listClassNames}>
<Animate transitionName={prefixCls + '-margin-top'}>
{list}
</Animate>
</div>
);
}
});
| components/upload/uploadList.jsx | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.0001788353401934728,
0.0001745484332786873,
0.00016434099234174937,
0.00017459510127082467,
0.0000034541353670647368
] |
{
"id": 3,
"code_window": [
" border-color: @border-color-base;\n",
" }\n",
" }\n",
"\n",
" &-disabled &-selection--single {\n",
" background: #f4f4f4;\n",
" cursor: not-allowed;\n",
" }\n",
"\n",
" &-selection--single {\n",
" height: 28px;\n",
" cursor: pointer;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-disabled &-selection--multiple &-selection__choice {\n",
" background: #e9e9e9;\n",
" color: #999;\n",
" padding-right: 10px;\n",
" &__remove {\n",
" display: none;\n",
" }\n"
],
"file_path": "style/components/treeSelect.less",
"type": "replace",
"edit_start_line_idx": 189
} | // mixins for button
// ------------------------
.button-size(@padding; @font-size; @border-radius) {
padding: @padding;
font-size: @font-size;
border-radius: @border-radius;
}
.button-variant(@color; @background; @border) {
.button-color(@color; @background; @border);
&:hover {
.button-color(tint(@color, 20%); tint(@background, 20%); tint(@border, 20%));
}
&:active,
&.active {
.button-color(shade(@color, 5%); shade(@background, 5%); shade(@background, 5%));
}
&:active,
&.active {
background-image: none;
}
&.disabled,
&[disabled],
fieldset[disabled] & {
&,
&:hover,
&:active,
&.active {
.button-color(@btn-disable-color; @btn-disable-bg; @btn-disable-border);
}
}
}
.button-color(@color; @background; @border) {
color: @color;
background-color: @background;
border-color: @border;
}
.button-group-base(@btnClassName) {
position: relative;
display: inline-block;
vertical-align: middle;
> .@{btnClassName} {
position: relative;
float: left;
&:hover,
&:focus,
&:active,
&.active {
z-index: 2;
}
}
// size
&-lg > .@{btnClassName} {
.button-size(@btn-padding-lg; @btn-font-size-lg; @border-radius-base);
}
&-sm > .@{btnClassName} {
.button-size(@btn-padding-sm; @font-size-base; @border-radius-sm);
> .@{iconfont-css-prefix} {
font-size: @font-size-base;
}
}
}
// Base styles of buttons
// --------------------------------------------------
.btn() {
display: inline-block;
margin-bottom: 0;
font-weight: @btn-font-weight;
text-align: center;
vertical-align: middle;
touch-action: manipulation;
cursor: pointer;
background-image: none;
border: 1px solid transparent;
// outline: none;
white-space: nowrap;
line-height: @line-height-base;
.button-size(@btn-padding-base; @font-size-base; @border-radius-base);
.user-select(none);
.transition(all .3s @ease-in-out);
transform: translate3d(0, 0, 0);
// Fix for ie8 border-radius
// http://css3pie.com/documentation/known-issues/#z-index
position: relative\0;
> .@{iconfont-css-prefix} {
line-height: 1;
}
&,
&:active,
&:focus {
outline: 0;
}
&:not([disabled]):hover {
text-decoration: none;
}
&:not([disabled]):active {
outline: 0;
.transition(none);
}
&.disabled,
&[disabled] {
cursor: @cursor-disabled;
}
&-lg {
.button-size(@btn-padding-lg; @btn-font-size-lg; @border-radius-base);
}
&-sm {
.button-size(@btn-padding-sm; @font-size-base; @border-radius-sm);
}
}
// primary button style
.btn-primary() {
.button-variant(@btn-primary-color; @btn-primary-bg; @primary-color);
&:hover,
&:active,
&.active {
color: @btn-primary-color;
}
}
// default button style
.btn-default() {
.button-variant(@btn-default-color; @btn-default-bg; @btn-default-border);
&:hover {
.button-color(tint(@primary-color, 20%); white; tint(@primary-color, 20%));
}
&:active,
&.active {
.button-color(shade(@primary-color, 5%); white; shade(@primary-color, 5%));
}
}
// ghost button style
.btn-ghost() {
.button-variant(@btn-ghost-color, @btn-ghost-bg, @btn-ghost-border);
&:hover {
.button-color(tint(@primary-color, 20%); white; tint(@primary-color, 20%));
}
&:active,
&.active {
.button-color(shade(@primary-color, 5%); white; shade(@primary-color, 5%));
}
}
// ghost button style
.btn-dashed() {
.button-variant(@btn-ghost-color, @btn-ghost-bg, @btn-ghost-border);
border-style: dashed;
&:hover {
.button-color(tint(@primary-color, 20%); white; tint(@primary-color, 20%));
}
&:active,
&.active {
.button-color(shade(@primary-color, 5%); white; shade(@primary-color, 5%));
}
}
// circle button: the content only contains icon
.btn-circle(@btnClassName: btn) {
.square(@btn-circle-size);
.button-size(0; @font-size-base + 2; 50%);
&.@{btnClassName}-lg {
.square(@btn-circle-size-lg);
.button-size(0; @btn-font-size-lg + 2; 50%);
}
&.@{btnClassName}-sm {
.square(@btn-circle-size-sm);
.button-size(0; @font-size-base; 50%);
}
}
// circle button with stroke border
.btn-circle-outline() {
position: relative;
&:not([disabled]):before {
position: absolute;
top: 0;
left: 0;
display: inline-block;
.opacity(0);
width: 100%;
height: 100%;
border-radius: 50% 50%;
content: " ";
.scale(0, 0);
.transition(all .3s @ease-in-out);
z-index: 0;
background-color: @primary-color;
}
&:not([disabled]):hover,
&:not([disabled]):active,
&:not([disabled]).active {
> .@{iconfont-css-prefix} {
color: @btn-primary-color;
position: relative;
}
}
&:not([disabled]):hover:before,
&:not([disabled]):active:before,
&:not([disabled]).active:before {
.opacity(1);
.scale(1, 1);
}
&:not([disabled]):active:before,
&:not([disabled]).active:before {
background-color: tint(@primary-color, 20%);
}
}
// Horizontal button groups styl
// --------------------------------------------------
.btn-group(@btnClassName: btn) {
.button-group-base(@btnClassName);
.@{btnClassName} + .@{btnClassName},
.@{btnClassName} + &,
& + .@{btnClassName},
& + & {
margin-left: -1px;
}
.@{btnClassName}:not(:first-child):not(:last-child) {
border-radius: 0;
padding-left: 7px;
padding-right: 7px;
}
> .@{btnClassName}:first-child {
margin-left: 0;
&:not(:last-child) {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
padding-right: 7px;
}
}
> .@{btnClassName}:last-child:not(:first-child) {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
padding-left: 7px;
}
& > & {
float: left;
}
& > &:not(:first-child):not(:last-child) > .@{btnClassName} {
border-radius: 0;
}
& > &:first-child:not(:last-child) {
> .@{btnClassName}:last-child {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
padding-right: 7px;
}
}
& > &:last-child:not(:first-child) > .@{btnClassName}:first-child {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
padding-left: 7px;
}
}
| style/mixins/button.less | 0 | https://github.com/ant-design/ant-design/commit/7c7e8beed2224acab850864e741ade43057b7352 | [
0.0009853462688624859,
0.00020428044081199914,
0.0001658767432672903,
0.00016999845684040338,
0.00014914812345523387
] |
{
"id": 0,
"code_window": [
" os: linux\n",
"services: []\n",
"steps:\n",
"- commands:\n",
" - mkdir -p bin\n",
" - curl -fL -o bin/grabpl https://grafana-downloads.storage.googleapis.com/grafana-build-pipeline/v3.0.17/grabpl\n",
" - chmod +x bin/grabpl\n",
" image: byrnedo/alpine-curl:0.1.8\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- commands:\n",
" - echo $DRONE_RUNNER_NAME\n",
" image: alpine:3.15.6\n",
" name: identify-runner\n"
],
"file_path": ".drone.yml",
"type": "add",
"edit_start_line_idx": 1000
} | load(
'scripts/drone/steps/lib.star',
'download_grabpl_step',
'publish_images_step',
'compile_build_cmd',
'fetch_images_step',
)
load(
'scripts/drone/utils/utils.star',
'pipeline',
)
def publish_image_steps(edition, mode, docker_repo):
additional_docker_repo = ""
if edition == 'oss':
additional_docker_repo='grafana/grafana-oss'
steps = [
download_grabpl_step(),
compile_build_cmd(),
fetch_images_step(edition),
publish_images_step(edition, 'release', mode, docker_repo),
]
if additional_docker_repo != "":
steps.extend([publish_images_step(edition, 'release', mode, additional_docker_repo)])
return steps
def publish_image_pipelines_public():
mode='public'
trigger = {
'event': ['promote'],
'target': [mode],
}
return [pipeline(
name='publish-docker-oss-{}'.format(mode), trigger=trigger, steps=publish_image_steps(edition='oss', mode=mode, docker_repo='grafana'), edition="", environment = {'EDITION': 'oss'}
), pipeline(
name='publish-docker-enterprise-{}'.format(mode), trigger=trigger, steps=publish_image_steps(edition='enterprise', mode=mode, docker_repo='grafana-enterprise'), edition="", environment = {'EDITION': 'enterprise'}
),]
def publish_image_pipelines_security():
mode='security'
trigger = {
'event': ['promote'],
'target': [mode],
}
return [pipeline(
name='publish-docker-enterprise-{}'.format(mode), trigger=trigger, steps=publish_image_steps(edition='enterprise', mode=mode, docker_repo='grafana-enterprise'), edition="", environment = {'EDITION': 'enterprise'}
),]
| scripts/drone/pipelines/publish_images.star | 1 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.17396292090415955,
0.02971358597278595,
0.00016802466416265815,
0.000924639287404716,
0.06451421976089478
] |
{
"id": 0,
"code_window": [
" os: linux\n",
"services: []\n",
"steps:\n",
"- commands:\n",
" - mkdir -p bin\n",
" - curl -fL -o bin/grabpl https://grafana-downloads.storage.googleapis.com/grafana-build-pipeline/v3.0.17/grabpl\n",
" - chmod +x bin/grabpl\n",
" image: byrnedo/alpine-curl:0.1.8\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- commands:\n",
" - echo $DRONE_RUNNER_NAME\n",
" image: alpine:3.15.6\n",
" name: identify-runner\n"
],
"file_path": ".drone.yml",
"type": "add",
"edit_start_line_idx": 1000
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12,1A7,7,0,0,0,7,12.89V22a1,1,0,0,0,1.45.89L12,21.12l3.55,1.77A1,1,0,0,0,16,23a1,1,0,0,0,.53-.15A1,1,0,0,0,17,22V12.89A7,7,0,0,0,12,1Zm3,19.38-2.55-1.27a1,1,0,0,0-.9,0L9,20.38V14.32a7,7,0,0,0,2,.6V16a1,1,0,0,0,2,0V14.92a7,7,0,0,0,2-.6ZM12,13a5,5,0,1,1,5-5A5,5,0,0,1,12,13Z"/></svg> | public/img/icons/unicons/award-alt.svg | 0 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.00017001548258122057,
0.00017001548258122057,
0.00017001548258122057,
0.00017001548258122057,
0
] |
{
"id": 0,
"code_window": [
" os: linux\n",
"services: []\n",
"steps:\n",
"- commands:\n",
" - mkdir -p bin\n",
" - curl -fL -o bin/grabpl https://grafana-downloads.storage.googleapis.com/grafana-build-pipeline/v3.0.17/grabpl\n",
" - chmod +x bin/grabpl\n",
" image: byrnedo/alpine-curl:0.1.8\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- commands:\n",
" - echo $DRONE_RUNNER_NAME\n",
" image: alpine:3.15.6\n",
" name: identify-runner\n"
],
"file_path": ".drone.yml",
"type": "add",
"edit_start_line_idx": 1000
} | import { getBackendSrv, isFetchError, locationService } from '@grafana/runtime';
import { notifyApp } from 'app/core/actions';
import { createErrorNotification, createSuccessNotification } from 'app/core/copy/appNotification';
import { AlertRuleDTO, NotifierDTO, ThunkResult } from 'app/types';
import { loadAlertRules, loadedAlertRules, notificationChannelLoaded, setNotificationChannels } from './reducers';
export function getAlertRulesAsync(options: { state: string }): ThunkResult<void> {
return async (dispatch) => {
dispatch(loadAlertRules());
const rules: AlertRuleDTO[] = await getBackendSrv().get('/api/alerts', options);
dispatch(loadedAlertRules(rules));
};
}
export function togglePauseAlertRule(id: number, options: { paused: boolean }): ThunkResult<void> {
return async (dispatch) => {
await getBackendSrv().post(`/api/alerts/${id}/pause`, options);
const stateFilter = locationService.getSearchObject().state || 'all';
dispatch(getAlertRulesAsync({ state: stateFilter.toString() }));
};
}
export function createNotificationChannel(data: any): ThunkResult<Promise<void>> {
return async (dispatch) => {
try {
await getBackendSrv().post(`/api/alert-notifications`, data);
dispatch(notifyApp(createSuccessNotification('Notification created')));
locationService.push('/alerting/notifications');
} catch (error) {
if (isFetchError(error)) {
dispatch(notifyApp(createErrorNotification(error.data.error)));
}
}
};
}
export function updateNotificationChannel(data: any): ThunkResult<void> {
return async (dispatch) => {
try {
await getBackendSrv().put(`/api/alert-notifications/${data.id}`, data);
dispatch(notifyApp(createSuccessNotification('Notification updated')));
} catch (error) {
if (isFetchError(error)) {
dispatch(notifyApp(createErrorNotification(error.data.error)));
}
}
};
}
export function testNotificationChannel(data: any): ThunkResult<void> {
return async (dispatch, getState) => {
const channel = getState().notificationChannel.notificationChannel;
await getBackendSrv().post('/api/alert-notifications/test', { id: channel.id, ...data });
};
}
export function loadNotificationTypes(): ThunkResult<void> {
return async (dispatch) => {
const alertNotifiers: NotifierDTO[] = await getBackendSrv().get(`/api/alert-notifiers`);
const notificationTypes = alertNotifiers.sort((o1, o2) => {
if (o1.name > o2.name) {
return 1;
}
return -1;
});
dispatch(setNotificationChannels(notificationTypes));
};
}
export function loadNotificationChannel(id: number): ThunkResult<void> {
return async (dispatch) => {
await dispatch(loadNotificationTypes());
const notificationChannel = await getBackendSrv().get(`/api/alert-notifications/${id}`);
dispatch(notificationChannelLoaded(notificationChannel));
};
}
| public/app/features/alerting/state/actions.ts | 0 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.00020279717864468694,
0.0001757618156261742,
0.00016531746950931847,
0.00017299558385275304,
0.00001056106157193426
] |
{
"id": 0,
"code_window": [
" os: linux\n",
"services: []\n",
"steps:\n",
"- commands:\n",
" - mkdir -p bin\n",
" - curl -fL -o bin/grabpl https://grafana-downloads.storage.googleapis.com/grafana-build-pipeline/v3.0.17/grabpl\n",
" - chmod +x bin/grabpl\n",
" image: byrnedo/alpine-curl:0.1.8\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- commands:\n",
" - echo $DRONE_RUNNER_NAME\n",
" image: alpine:3.15.6\n",
" name: identify-runner\n"
],
"file_path": ".drone.yml",
"type": "add",
"edit_start_line_idx": 1000
} | import { ReducerID } from '@grafana/data';
import { ExpressionQuery, ExpressionQueryType } from 'app/features/expressions/types';
import { defaultCondition } from 'app/features/expressions/utils/expressionTypes';
import { AlertQuery } from 'app/types/unified-alerting-dto';
import { getTimeRangeForExpression } from './timeRange';
describe('timeRange', () => {
describe('getTimeRangeForExpression', () => {
describe('classic condition', () => {
it('should return referenced query timeRange for classic condition', () => {
const expressionQuery: AlertQuery = {
refId: 'B',
queryType: 'expression',
datasourceUid: '-100',
model: {
queryType: 'query',
datasource: '__expr__',
refId: 'B',
conditions: [{ ...defaultCondition, query: { params: ['A'] } }],
type: ExpressionQueryType.classic,
} as ExpressionQuery,
};
const query: AlertQuery = {
refId: 'A',
relativeTimeRange: { from: 300, to: 0 },
queryType: 'query',
datasourceUid: 'dsuid',
model: { refId: 'A' },
};
const queries: AlertQuery[] = [query, expressionQuery];
expect(getTimeRangeForExpression(expressionQuery.model as ExpressionQuery, queries)).toEqual({
from: 300,
to: 0,
});
});
it('should return the min and max time range', () => {
const expressionQuery: AlertQuery = {
refId: 'C',
queryType: 'expression',
datasourceUid: '-100',
model: {
queryType: 'query',
datasource: '__expr__',
refId: 'C',
conditions: [
{ ...defaultCondition, query: { params: ['A'] } },
{ ...defaultCondition, query: { params: ['B'] } },
],
type: ExpressionQueryType.classic,
} as ExpressionQuery,
};
const queryA: AlertQuery = {
refId: 'A',
relativeTimeRange: { from: 300, to: 0 },
datasourceUid: 'dsuid',
model: { refId: 'A' },
queryType: 'query',
};
const queryB: AlertQuery = {
refId: 'B',
relativeTimeRange: { from: 600, to: 300 },
datasourceUid: 'dsuid',
model: { refId: 'B' },
queryType: 'query',
};
const queries: AlertQuery[] = [queryA, queryB, expressionQuery];
expect(getTimeRangeForExpression(expressionQuery.model as ExpressionQuery, queries)).toEqual({
from: 600,
to: 0,
});
});
});
});
describe('math', () => {
it('should get timerange for referenced query', () => {
const expressionQuery: AlertQuery = {
refId: 'B',
queryType: 'expression',
datasourceUid: '-100',
model: {
queryType: 'query',
datasource: '__expr__',
refId: 'B',
expression: '$A > 10',
type: ExpressionQueryType.math,
} as ExpressionQuery,
};
const query: AlertQuery = {
refId: 'A',
datasourceUid: 'dsuid',
relativeTimeRange: { from: 300, to: 0 },
model: { refId: 'A' },
queryType: 'query',
};
expect(getTimeRangeForExpression(expressionQuery.model as ExpressionQuery, [expressionQuery, query]));
});
it('should get time ranges for multiple referenced queries', () => {
const expressionQuery: AlertQuery = {
refId: 'C',
queryType: 'expression',
datasourceUid: '-100',
model: {
queryType: 'query',
datasource: '__expr__',
refId: 'C',
expression: '$A > 10 && $queryB > 20',
type: ExpressionQueryType.math,
} as ExpressionQuery,
};
const queryA: AlertQuery = {
refId: 'A',
relativeTimeRange: { from: 300, to: 0 },
datasourceUid: 'dsuid',
model: { refId: 'A' },
queryType: 'query',
};
const queryB: AlertQuery = {
refId: 'queryB',
relativeTimeRange: { from: 600, to: 300 },
datasourceUid: 'dsuid',
model: { refId: 'queryB' },
queryType: 'query',
};
expect(
getTimeRangeForExpression(expressionQuery.model as ExpressionQuery, [expressionQuery, queryA, queryB])
).toEqual({ from: 600, to: 0 });
});
});
describe('resample', () => {
it('should get referenced timerange for resample expression', () => {
const expressionQuery: AlertQuery = {
refId: 'B',
queryType: 'expression',
datasourceUid: '-100',
model: {
queryType: 'query',
datasource: '__expr__',
refId: 'B',
expression: 'A',
type: ExpressionQueryType.resample,
window: '10s',
} as ExpressionQuery,
};
const queryA: AlertQuery = {
refId: 'A',
relativeTimeRange: { from: 300, to: 0 },
datasourceUid: 'dsuid',
model: { refId: 'A' },
queryType: 'query',
};
const queries = [queryA, expressionQuery];
expect(getTimeRangeForExpression(expressionQuery.model as ExpressionQuery, queries)).toEqual({
from: 300,
to: 0,
});
});
});
describe('reduce', () => {
it('should get referenced timerange for reduce expression', () => {
const expressionQuery: AlertQuery = {
refId: 'B',
queryType: 'expression',
datasourceUid: '-100',
model: {
queryType: 'query',
datasource: '__expr__',
refId: 'B',
expression: 'A',
type: ExpressionQueryType.reduce,
reducer: ReducerID.max,
} as ExpressionQuery,
};
const queryA: AlertQuery = {
refId: 'A',
relativeTimeRange: { from: 300, to: 0 },
datasourceUid: 'dsuid',
model: { refId: 'A' },
queryType: 'query',
};
const queries = [queryA, expressionQuery];
expect(getTimeRangeForExpression(expressionQuery.model as ExpressionQuery, queries)).toEqual({
from: 300,
to: 0,
});
});
});
});
| public/app/features/alerting/unified/utils/timeRange.test.ts | 0 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.00021343732078094035,
0.00017342666978947818,
0.00016782659804448485,
0.00017116940580308437,
0.000009335324648418464
] |
{
"id": 2,
"code_window": [
"platform:\n",
" arch: amd64\n",
" os: linux\n",
"services: []\n",
"steps:\n",
"- commands:\n",
" - mkdir -p bin\n",
" - curl -fL -o bin/grabpl https://grafana-downloads.storage.googleapis.com/grafana-build-pipeline/v3.0.17/grabpl\n",
" - chmod +x bin/grabpl\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- commands:\n",
" - echo $DRONE_RUNNER_NAME\n",
" image: alpine:3.15.6\n",
" name: identify-runner\n"
],
"file_path": ".drone.yml",
"type": "add",
"edit_start_line_idx": 1167
} | load(
'scripts/drone/steps/lib.star',
'download_grabpl_step',
'publish_images_step',
'compile_build_cmd',
'fetch_images_step',
)
load(
'scripts/drone/utils/utils.star',
'pipeline',
)
def publish_image_steps(edition, mode, docker_repo):
additional_docker_repo = ""
if edition == 'oss':
additional_docker_repo='grafana/grafana-oss'
steps = [
download_grabpl_step(),
compile_build_cmd(),
fetch_images_step(edition),
publish_images_step(edition, 'release', mode, docker_repo),
]
if additional_docker_repo != "":
steps.extend([publish_images_step(edition, 'release', mode, additional_docker_repo)])
return steps
def publish_image_pipelines_public():
mode='public'
trigger = {
'event': ['promote'],
'target': [mode],
}
return [pipeline(
name='publish-docker-oss-{}'.format(mode), trigger=trigger, steps=publish_image_steps(edition='oss', mode=mode, docker_repo='grafana'), edition="", environment = {'EDITION': 'oss'}
), pipeline(
name='publish-docker-enterprise-{}'.format(mode), trigger=trigger, steps=publish_image_steps(edition='enterprise', mode=mode, docker_repo='grafana-enterprise'), edition="", environment = {'EDITION': 'enterprise'}
),]
def publish_image_pipelines_security():
mode='security'
trigger = {
'event': ['promote'],
'target': [mode],
}
return [pipeline(
name='publish-docker-enterprise-{}'.format(mode), trigger=trigger, steps=publish_image_steps(edition='enterprise', mode=mode, docker_repo='grafana-enterprise'), edition="", environment = {'EDITION': 'enterprise'}
),]
| scripts/drone/pipelines/publish_images.star | 1 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.012772546149790287,
0.0034664582926779985,
0.00016769814828876406,
0.002008771291002631,
0.0043501476757228374
] |
{
"id": 2,
"code_window": [
"platform:\n",
" arch: amd64\n",
" os: linux\n",
"services: []\n",
"steps:\n",
"- commands:\n",
" - mkdir -p bin\n",
" - curl -fL -o bin/grabpl https://grafana-downloads.storage.googleapis.com/grafana-build-pipeline/v3.0.17/grabpl\n",
" - chmod +x bin/grabpl\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- commands:\n",
" - echo $DRONE_RUNNER_NAME\n",
" image: alpine:3.15.6\n",
" name: identify-runner\n"
],
"file_path": ".drone.yml",
"type": "add",
"edit_start_line_idx": 1167
} | // 🌟 This was machine generated. Do not edit. 🌟
//
// Frame[0] {
// "custom": {
// "resultType": "exemplar"
// },
// "executedQueryString": "Expr: histogram_quantile(0.99, sum(rate(traces_spanmetrics_duration_seconds_bucket[15s])) by (le))\nStep: 15s"
// }
// Name: exemplar
// Dimensions: 14 Fields by 62 Rows
// +-----------------------------------+-----------------+--------------------------------------------+----------------+-------------------+-------------------+----------------+----------------+--------------------+----------------+------------------+-----------------+-------------------+----------------------------------+
// | Name: Time | Name: Value | Name: __name__ | Name: group | Name: http_method | Name: http_target | Name: instance | Name: le | Name: service | Name: source | Name: span_kind | Name: span_name | Name: span_status | Name: traceID |
// | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: | Labels: |
// | Type: []time.Time | Type: []float64 | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string | Type: []string |
// +-----------------------------------+-----------------+--------------------------------------------+----------------+-------------------+-------------------+----------------+----------------+--------------------+----------------+------------------+-----------------+-------------------+----------------------------------+
// | 2022-06-01 12:28:31.809 +0000 UTC | 0.001162 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.002 | mythical-server | tempo | SPAN_KIND_CLIENT | pg.query:INSERT | STATUS_CODE_ERROR | 94809f37ec6cc984f2eb2b14a9f8036e |
// | 2022-06-01 12:28:36.81 +0000 UTC | 0.134971 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.256 | mythical-requester | tempo | SPAN_KIND_CLIENT | requester | STATUS_CODE_OK | 46e15ae41852149068aeb26c64643c29 |
// | 2022-06-01 12:28:36.81 +0000 UTC | 0.090381 | traces_spanmetrics_duration_seconds_bucket | mythical | POST | /loki/api/v1/push | f1c32fe505c3 | 0.128 | mythical-server | tempo | SPAN_KIND_CLIENT | HTTP POST | STATUS_CODE_OK | 46e15ae41852149068aeb26c64643c29 |
// | 2022-06-01 12:28:36.81 +0000 UTC | 0.029188 | traces_spanmetrics_duration_seconds_bucket | mythical | GET | /manticore | f1c32fe505c3 | 0.032 | mythical-server | tempo | SPAN_KIND_SERVER | GET /:endpoint | STATUS_CODE_OK | 1e58dc2083eceb454846f9ab343a79ff |
// | 2022-06-01 12:28:41.809 +0000 UTC | 0.05719 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.064 | mythical-requester | tempo | SPAN_KIND_CLIENT | requester | STATUS_CODE_OK | d6ff032e85e6e5719a1f6b923042765f |
// | 2022-06-01 12:28:46.809 +0000 UTC | 0.071953 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.128 | mythical-requester | tempo | SPAN_KIND_CLIENT | requester | STATUS_CODE_OK | b12280a11924d98f7001f9b03779c6bc |
// | 2022-06-01 12:28:46.809 +0000 UTC | 0.041812 | traces_spanmetrics_duration_seconds_bucket | mythical | GET | /unicorn | f1c32fe505c3 | 0.064 | mythical-server | tempo | SPAN_KIND_SERVER | GET /:endpoint | STATUS_CODE_OK | b12280a11924d98f7001f9b03779c6bc |
// | 2022-06-01 12:28:56.809 +0000 UTC | 0.013244 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.016 | mythical-requester | tempo | SPAN_KIND_CLIENT | log_to_loki | STATUS_CODE_OK | 43cd491719146ad9c706d73b4870512c |
// | 2022-06-01 12:29:06.809 +0000 UTC | 0.070504 | traces_spanmetrics_duration_seconds_bucket | mythical | | | f1c32fe505c3 | 0.128 | mythical-requester | tempo | SPAN_KIND_CLIENT | requester | STATUS_CODE_OK | e08c737b2dc96959a8dda2cb76c91de7 |
// | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
// +-----------------------------------+-----------------+--------------------------------------------+----------------+-------------------+-------------------+----------------+----------------+--------------------+----------------+------------------+-----------------+-------------------+----------------------------------+
//
//
// 🌟 This was machine generated. Do not edit. 🌟
{
"status": 200,
"frames": [
{
"schema": {
"name": "exemplar",
"meta": {
"custom": {
"resultType": "exemplar"
},
"executedQueryString": "Expr: histogram_quantile(0.99, sum(rate(traces_spanmetrics_duration_seconds_bucket[15s])) by (le))\nStep: 15s"
},
"fields": [
{
"name": "Time",
"type": "time",
"typeInfo": {
"frame": "time.Time"
}
},
{
"name": "Value",
"type": "number",
"typeInfo": {
"frame": "float64"
}
},
{
"name": "__name__",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "group",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "http_method",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "http_target",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "instance",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "le",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "service",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "source",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "span_kind",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "span_name",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "span_status",
"type": "string",
"typeInfo": {
"frame": "string"
}
},
{
"name": "traceID",
"type": "string",
"typeInfo": {
"frame": "string"
}
}
]
},
"data": {
"values": [
[
1654086511809,
1654086516810,
1654086516810,
1654086516810,
1654086521809,
1654086526809,
1654086526809,
1654086536809,
1654086546809,
1654086546809,
1654086546809,
1654086561810,
1654086566809,
1654086566809,
1654086571809,
1654086576810,
1654086576810,
1654086586809,
1654086591809,
1654086591809,
1654086601809,
1654086606809,
1654086616810,
1654086621809,
1654086626810,
1654086631809,
1654086636809,
1654086641809,
1654086646809,
1654086651809,
1654086651809,
1654086661809,
1654086666809,
1654086666809,
1654086676809,
1654086676809,
1654086686809,
1654086696809,
1654086701809,
1654086701809,
1654086706809,
1654086716809,
1654086716809,
1654086721809,
1654086721809,
1654086731809,
1654086731809,
1654086741809,
1654086741809,
1654086746809,
1654086751809,
1654086761809,
1654086761809,
1654086766809,
1654086766809,
1654086776809,
1654086786809,
1654086786809,
1654086791809,
1654086796809,
1654086801809,
1654086801809
],
[
0.001162,
0.134971,
0.090381,
0.029188,
0.05719,
0.071953,
0.041812,
0.013244,
0.070504,
0.038753,
0.010491,
0.01785,
0.074616,
0.046192,
0.067413,
0.038985,
0.010387,
0.055778,
0.090068,
0.026474,
0.020916,
0.051105,
0.010103,
0.038904,
0.069116,
0.036012,
0.06704,
0.007759,
0.046809,
0.076668,
0.01864,
0.037142,
0.066299,
0.008877,
0.072569,
0.038946,
0.010457,
0.021391,
0.089991,
0.049446,
0.011579,
0.068599,
0.039792,
0.067805,
0.010759,
0.099291,
0.039441,
0.06673,
0.03671,
0.008554,
0.039395,
0.071128,
0.010549,
0.043282,
0.014027,
0.072983,
0.070787,
0.009928,
0.037937,
0.010333,
0.067877,
0.038846
],
[
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket",
"traces_spanmetrics_duration_seconds_bucket"
],
[
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical",
"mythical"
],
[
"",
"",
"POST",
"GET",
"",
"",
"GET",
"",
"",
"GET",
"",
"",
"",
"",
"",
"GET",
"",
"",
"",
"GET",
"",
"",
"",
"GET",
"",
"GET",
"",
"",
"GET",
"",
"",
"",
"",
"",
"",
"POST",
"",
"POST",
"",
"",
"POST",
"",
"GET",
"",
"",
"",
"",
"",
"GET",
"POST",
"GET",
"",
"",
"POST",
"",
"",
"",
"",
"GET",
"",
"",
""
],
[
"",
"",
"/loki/api/v1/push",
"/manticore",
"",
"",
"/unicorn",
"",
"",
"/manticore",
"",
"",
"",
"",
"",
"/manticore",
"",
"",
"",
"/manticore",
"",
"",
"",
"/manticore",
"",
"/unicorn",
"",
"",
"/unicorn",
"",
"",
"",
"",
"",
"",
"/loki/api/v1/push",
"",
"/loki/api/v1/push",
"",
"",
"/beholder",
"",
"/manticore",
"",
"",
"",
"",
"",
"/manticore",
"/loki/api/v1/push",
"/manticore",
"",
"",
"/loki/api/v1/push",
"",
"",
"",
"",
"/manticore",
"",
"",
""
],
[
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3",
"f1c32fe505c3"
],
[
"0.002",
"0.256",
"0.128",
"0.032",
"0.064",
"0.128",
"0.064",
"0.016",
"0.128",
"0.064",
"0.016",
"0.032",
"0.128",
"0.064",
"0.128",
"0.064",
"0.016",
"0.064",
"0.128",
"0.032",
"0.032",
"0.064",
"0.016",
"0.064",
"0.128",
"0.064",
"0.128",
"0.008",
"0.064",
"0.128",
"0.032",
"0.064",
"0.128",
"0.016",
"0.128",
"0.064",
"0.016",
"0.032",
"0.128",
"0.064",
"0.016",
"0.128",
"0.064",
"0.128",
"0.016",
"0.128",
"0.064",
"0.128",
"0.064",
"0.016",
"0.064",
"0.128",
"0.016",
"0.064",
"0.016",
"0.128",
"0.128",
"0.016",
"0.064",
"0.016",
"0.128",
"0.064"
],
[
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-requester",
"mythical-requester",
"mythical-requester",
"mythical-server",
"mythical-server",
"mythical-server",
"mythical-requester",
"mythical-server"
],
[
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo",
"tempo"
],
[
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_UNSPECIFIED",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_SERVER",
"SPAN_KIND_CLIENT",
"SPAN_KIND_CLIENT",
"SPAN_KIND_UNSPECIFIED"
],
[
"pg.query:INSERT",
"requester",
"HTTP POST",
"GET /:endpoint",
"requester",
"requester",
"GET /:endpoint",
"log_to_loki",
"requester",
"GET /:endpoint",
"pg.query:INSERT",
"log_to_loki",
"requester",
"dns.lookup",
"requester",
"GET /:endpoint",
"pg.query:DELETE",
"requester",
"requester",
"GET /:endpoint",
"requester",
"requester",
"log_to_loki",
"GET /:endpoint",
"requester",
"GET /:endpoint",
"requester",
"log_to_loki",
"GET /:endpoint",
"requester",
"dns.lookup",
"pg.query:INSERT",
"requester",
"tcp.connect",
"requester",
"HTTP POST",
"pg.query:INSERT",
"HTTP POST",
"requester",
"requester",
"POST /:endpoint",
"requester",
"GET /:endpoint",
"requester",
"requester",
"requester",
"pg.query:SELECT",
"requester",
"GET /:endpoint",
"HTTP POST",
"GET /:endpoint",
"requester",
"requester",
"HTTP POST",
"log_to_loki",
"requester",
"requester",
"pg.query:SELECT",
"GET /:endpoint",
"pg.query:DELETE",
"requester",
"tcp.connect"
],
[
"STATUS_CODE_ERROR",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET",
"STATUS_CODE_OK",
"STATUS_CODE_UNSET"
],
[
"94809f37ec6cc984f2eb2b14a9f8036e",
"46e15ae41852149068aeb26c64643c29",
"46e15ae41852149068aeb26c64643c29",
"1e58dc2083eceb454846f9ab343a79ff",
"d6ff032e85e6e5719a1f6b923042765f",
"b12280a11924d98f7001f9b03779c6bc",
"b12280a11924d98f7001f9b03779c6bc",
"43cd491719146ad9c706d73b4870512c",
"e08c737b2dc96959a8dda2cb76c91de7",
"654d578991bcc53c7de88912a8660488",
"8dec2e77ca64f1cc665afc43b3b1623f",
"e5f765faeb401c335355e0bb79e33b83",
"68d98aae947863f11a7863cd92421038",
"61386de633427db6bb2e5fd216518b3c",
"a17f9f61386f57e7ef85acedc120f82",
"3b4e33abe16c115448759924138cc775",
"ccfb65171f9957871c792f9e7ba4caf0",
"62110ace7888d4e116a0d6182e3ef880",
"1c5d32e0675734a7d86c6146cfef54e1",
"ee885d6d0fa1949978667532d7b50b40",
"45128087f18fb412c24394ed10826446",
"3855df04789862c55b23ca3726fd700a",
"ff6a99aa5fd60f6fbcf0f838164f87ea",
"ca2f23783ee1c390e446f02f7a27cf4",
"2699255777b784b20c8e42bb7889f607",
"72c7ff318a7bb17b6e38aa0f4e94c955",
"78b31a3856158fb296920170f15b2663",
"e81a28f6ee9b468cdac757b825b17623",
"a5277cb54e46140aa3ae489109e1ebc8",
"9ed79aa36a4c6b4c53c7f54e77e6489c",
"9ed79aa36a4c6b4c53c7f54e77e6489c",
"5ec0bc7cc644f654c04190b1cc16d39",
"2d6bde392e5b69cb55588219ce605cbc",
"7c42490bd4361a83bb8ee827b89387ae",
"1b9024f2c2042d52b82d22c36597ec3f",
"1b9024f2c2042d52b82d22c36597ec3f",
"da0d4ef26ef65b5d9c446a51b8662895",
"b1a28a72cc2a4991b2cec793530d605",
"c642d0d7df516be0390080402991b79f",
"a05d1517c61ea0c4ab76b39ab645c9b6",
"2dc68b746bbd6c6958f25c3dbb1ea110",
"ec7dc9dd4096d36ebf564427bf30abc8",
"da805bfda5683c80b9a5538c17346217",
"3835f629b97ac7869de9a839b1e2bf2a",
"1f2e6add2566d120c876e5e4f4602432",
"efa3c8aa7380ae77e734f6f655d9c782",
"312e6ef8f9d9b4ffbb4470e772f43660",
"135989a5bb785b94d339caf672590634",
"a58a30a5caee0a451e7b1ae24bc1e33e",
"d4c096aa222e1016b67de881f80978d8",
"3eefbe3d5fb80a96325688a69c5597e3",
"5384591d9cd576d73f86cbe1803d2a46",
"4f1660168b2dcf5a40474d08a587e8dd",
"bd11e06766d5a045d69b201a9c442258",
"60d05233bc4ccb745055ef19af359686",
"a3374ca45cd256cc5bdb6f482c0a2856",
"a30c5021f274710636e84eca64343b4",
"54b4e0377ac7c101278b68134853562a",
"32dfe6e357ffbb98e7148104e2d660a4",
"a11a727138a3de7ca030687340bd19b0",
"a11c1d3d300f07b1e5d688e96069f76b",
"83bf586cc62842c3187106bb40a6793d"
]
]
}
}
]
} | pkg/tsdb/prometheus/testdata/exemplar.result.streaming-wide.golden.jsonc | 0 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.00030068427440710366,
0.00017244562332052737,
0.0001655314990784973,
0.0001686273462837562,
0.000019598559447331354
] |
{
"id": 2,
"code_window": [
"platform:\n",
" arch: amd64\n",
" os: linux\n",
"services: []\n",
"steps:\n",
"- commands:\n",
" - mkdir -p bin\n",
" - curl -fL -o bin/grabpl https://grafana-downloads.storage.googleapis.com/grafana-build-pipeline/v3.0.17/grabpl\n",
" - chmod +x bin/grabpl\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- commands:\n",
" - echo $DRONE_RUNNER_NAME\n",
" image: alpine:3.15.6\n",
" name: identify-runner\n"
],
"file_path": ".drone.yml",
"type": "add",
"edit_start_line_idx": 1167
} | import { css } from '@emotion/css';
import Prism from 'prismjs';
import React, { useCallback, useState, useEffect, useMemo } from 'react';
import { Node } from 'slate';
import { GrafanaTheme2, isValidGoDuration, SelectableValue, toOption } from '@grafana/data';
import { FetchError, getTemplateSrv, isFetchError, TemplateSrv } from '@grafana/runtime';
import {
InlineFieldRow,
InlineField,
Input,
QueryField,
SlatePrism,
BracesPlugin,
TypeaheadInput,
TypeaheadOutput,
Alert,
useStyles2,
fuzzyMatch,
Select,
} from '@grafana/ui';
import { notifyApp } from 'app/core/actions';
import { createErrorNotification } from 'app/core/copy/appNotification';
import { dispatch } from 'app/store/store';
import { DEFAULT_LIMIT, TempoDatasource } from '../datasource';
import TempoLanguageProvider from '../language_provider';
import { tokenizer } from '../syntax';
import { TempoQuery } from '../types';
interface Props {
datasource: TempoDatasource;
query: TempoQuery;
onChange: (value: TempoQuery) => void;
onBlur?: () => void;
onRunQuery: () => void;
}
const PRISM_LANGUAGE = 'tempo';
const durationPlaceholder = 'e.g. 1.2s, 100ms';
const plugins = [
BracesPlugin(),
SlatePrism({
onlyIn: (node: Node) => node.object === 'block' && node.type === 'code_block',
getSyntax: () => PRISM_LANGUAGE,
}),
];
Prism.languages[PRISM_LANGUAGE] = tokenizer;
const NativeSearch = ({ datasource, query, onChange, onBlur, onRunQuery }: Props) => {
const styles = useStyles2(getStyles);
const languageProvider = useMemo(() => new TempoLanguageProvider(datasource), [datasource]);
const [hasSyntaxLoaded, setHasSyntaxLoaded] = useState(false);
const [serviceOptions, setServiceOptions] = useState<Array<SelectableValue<string>>>();
const [spanOptions, setSpanOptions] = useState<Array<SelectableValue<string>>>();
const [error, setError] = useState<Error | FetchError | null>(null);
const [inputErrors, setInputErrors] = useState<{ [key: string]: boolean }>({});
const [isLoading, setIsLoading] = useState<{
serviceName: boolean;
spanName: boolean;
}>({
serviceName: false,
spanName: false,
});
const loadOptions = useCallback(
async (name: string, query = '') => {
const lpName = name === 'serviceName' ? 'service.name' : 'name';
setIsLoading((prevValue) => ({ ...prevValue, [name]: true }));
try {
const options = await languageProvider.getOptions(lpName);
const filteredOptions = options.filter((item) => (item.value ? fuzzyMatch(item.value, query).found : false));
return filteredOptions;
} catch (error) {
if (isFetchError(error) && error?.status === 404) {
setError(error);
} else if (error instanceof Error) {
dispatch(notifyApp(createErrorNotification('Error', error)));
}
return [];
} finally {
setIsLoading((prevValue) => ({ ...prevValue, [name]: false }));
}
},
[languageProvider]
);
useEffect(() => {
const fetchOptions = async () => {
try {
const [services, spans] = await Promise.all([loadOptions('serviceName'), loadOptions('spanName')]);
if (query.serviceName && getTemplateSrv().containsTemplate(query.serviceName)) {
services.push(toOption(query.serviceName));
}
setServiceOptions(services);
if (query.spanName && getTemplateSrv().containsTemplate(query.spanName)) {
spans.push(toOption(query.spanName));
}
setSpanOptions(spans);
} catch (error) {
// Display message if Tempo is connected but search 404's
if (isFetchError(error) && error?.status === 404) {
setError(error);
} else if (error instanceof Error) {
dispatch(notifyApp(createErrorNotification('Error', error)));
}
}
};
fetchOptions();
}, [languageProvider, loadOptions, query.serviceName, query.spanName]);
useEffect(() => {
const fetchTags = async () => {
try {
await languageProvider.start();
setHasSyntaxLoaded(true);
} catch (error) {
if (error instanceof Error) {
dispatch(notifyApp(createErrorNotification('Error', error)));
}
}
};
fetchTags();
}, [languageProvider]);
const onTypeahead = useCallback(
async (typeahead: TypeaheadInput): Promise<TypeaheadOutput> => {
return await languageProvider.provideCompletionItems(typeahead);
},
[languageProvider]
);
const cleanText = useCallback((text: string) => {
const splittedText = text.split(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g);
if (splittedText.length > 1) {
return splittedText[splittedText.length - 1];
}
return text;
}, []);
const onKeyDown = (keyEvent: React.KeyboardEvent) => {
if (keyEvent.key === 'Enter' && (keyEvent.shiftKey || keyEvent.ctrlKey)) {
onRunQuery();
}
};
const onSpanNameChange = (v: SelectableValue<string>) => {
// If the 'x' icon is clicked to clear the selected span name, remove spanName from the query object.
if (!v) {
delete query.spanName;
return;
}
if (spanOptions?.find((obj) => obj.value === v.value)) {
onChange({
...query,
spanName: v.value,
});
}
};
const handleOnChange = useCallback(
(value) => {
onChange({
...query,
search: value,
});
},
[onChange, query]
);
const templateSrv: TemplateSrv = getTemplateSrv();
return (
<>
<div className={styles.container}>
<InlineFieldRow>
<InlineField label="Service Name" labelWidth={14} grow>
<Select
inputId="service"
options={serviceOptions}
onOpenMenu={() => {
loadOptions('serviceName');
}}
isLoading={isLoading.serviceName}
value={serviceOptions?.find((v) => v?.value === query.serviceName) || undefined}
onChange={(v) => {
onChange({
...query,
serviceName: v?.value || undefined,
});
}}
placeholder="Select a service"
isClearable
onKeyDown={onKeyDown}
aria-label={'select-service-name'}
allowCustomValue={true}
/>
</InlineField>
</InlineFieldRow>
<InlineFieldRow>
<InlineField label="Span Name" labelWidth={14} grow>
<Select
inputId="spanName"
options={spanOptions}
onOpenMenu={() => {
loadOptions('spanName');
}}
isLoading={isLoading.spanName}
onChange={onSpanNameChange}
placeholder="Select a span"
isClearable
onKeyDown={onKeyDown}
aria-label={'select-span-name'}
allowCustomValue={true}
/>
</InlineField>
</InlineFieldRow>
<InlineFieldRow>
<InlineField label="Tags" labelWidth={14} grow tooltip="Values should be in logfmt.">
<QueryField
additionalPlugins={plugins}
query={query.search}
onTypeahead={onTypeahead}
onBlur={onBlur}
onChange={handleOnChange}
cleanText={cleanText}
placeholder="http.status_code=200 error=true"
onRunQuery={onRunQuery}
syntaxLoaded={hasSyntaxLoaded}
portalOrigin="tempo"
/>
</InlineField>
</InlineFieldRow>
<InlineFieldRow>
<InlineField label="Min Duration" invalid={!!inputErrors.minDuration} labelWidth={14} grow>
<Input
id="minDuration"
value={query.minDuration || ''}
placeholder={durationPlaceholder}
onBlur={() => {
const templatedMinDuration = templateSrv.replace(query.minDuration ?? '');
if (query.minDuration && !isValidGoDuration(templatedMinDuration)) {
setInputErrors({ ...inputErrors, minDuration: true });
} else {
setInputErrors({ ...inputErrors, minDuration: false });
}
}}
onChange={(v) =>
onChange({
...query,
minDuration: v.currentTarget.value,
})
}
onKeyDown={onKeyDown}
/>
</InlineField>
</InlineFieldRow>
<InlineFieldRow>
<InlineField label="Max Duration" invalid={!!inputErrors.maxDuration} labelWidth={14} grow>
<Input
id="maxDuration"
value={query.maxDuration || ''}
placeholder={durationPlaceholder}
onBlur={() => {
const templatedMaxDuration = templateSrv.replace(query.maxDuration ?? '');
if (query.maxDuration && !isValidGoDuration(templatedMaxDuration)) {
setInputErrors({ ...inputErrors, maxDuration: true });
} else {
setInputErrors({ ...inputErrors, maxDuration: false });
}
}}
onChange={(v) =>
onChange({
...query,
maxDuration: v.currentTarget.value,
})
}
onKeyDown={onKeyDown}
/>
</InlineField>
</InlineFieldRow>
<InlineFieldRow>
<InlineField
label="Limit"
invalid={!!inputErrors.limit}
labelWidth={14}
grow
tooltip="Maximum number of returned results"
>
<Input
id="limit"
value={query.limit || ''}
placeholder={`Default: ${DEFAULT_LIMIT}`}
type="number"
onChange={(v) => {
let limit = v.currentTarget.value ? parseInt(v.currentTarget.value, 10) : undefined;
if (limit && (!Number.isInteger(limit) || limit <= 0)) {
setInputErrors({ ...inputErrors, limit: true });
} else {
setInputErrors({ ...inputErrors, limit: false });
}
onChange({
...query,
limit: v.currentTarget.value ? parseInt(v.currentTarget.value, 10) : undefined,
});
}}
onKeyDown={onKeyDown}
/>
</InlineField>
</InlineFieldRow>
</div>
{error ? (
<Alert title="Unable to connect to Tempo search" severity="info" className={styles.alert}>
Please ensure that Tempo is configured with search enabled. If you would like to hide this tab, you can
configure it in the <a href={`/datasources/edit/${datasource.uid}`}>datasource settings</a>.
</Alert>
) : null}
</>
);
};
export default NativeSearch;
const getStyles = (theme: GrafanaTheme2) => ({
container: css`
max-width: 500px;
`,
alert: css`
max-width: 75ch;
margin-top: ${theme.spacing(2)};
`,
});
| public/app/plugins/datasource/tempo/QueryEditor/NativeSearch.tsx | 0 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.0005252014962024987,
0.00018842316057998687,
0.00016544722893740982,
0.0001699102285783738,
0.00007144178380258381
] |
{
"id": 2,
"code_window": [
"platform:\n",
" arch: amd64\n",
" os: linux\n",
"services: []\n",
"steps:\n",
"- commands:\n",
" - mkdir -p bin\n",
" - curl -fL -o bin/grabpl https://grafana-downloads.storage.googleapis.com/grafana-build-pipeline/v3.0.17/grabpl\n",
" - chmod +x bin/grabpl\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- commands:\n",
" - echo $DRONE_RUNNER_NAME\n",
" image: alpine:3.15.6\n",
" name: identify-runner\n"
],
"file_path": ".drone.yml",
"type": "add",
"edit_start_line_idx": 1167
} | import React from 'react';
import { AnnotationQuery, getDataSourceRef, NavModelItem } from '@grafana/data';
import { getDataSourceSrv, locationService } from '@grafana/runtime';
import { Page } from 'app/core/components/PageNew/Page';
import { DashboardModel } from '../../state';
import { AnnotationSettingsEdit, AnnotationSettingsList, newAnnotationName } from '../AnnotationSettings';
import { SettingsPageProps } from './types';
export function AnnotationsSettings({ dashboard, editIndex, sectionNav }: SettingsPageProps) {
const onNew = () => {
const newAnnotation: AnnotationQuery = {
name: newAnnotationName,
enable: true,
datasource: getDataSourceRef(getDataSourceSrv().getInstanceSettings(null)!),
iconColor: 'red',
};
dashboard.annotations.list = [...dashboard.annotations.list, { ...newAnnotation }];
locationService.partial({ editIndex: dashboard.annotations.list.length - 1 });
};
const onEdit = (idx: number) => {
locationService.partial({ editIndex: idx });
};
const isEditing = editIndex != null && editIndex < dashboard.annotations.list.length;
return (
<Page navModel={sectionNav} pageNav={getSubPageNav(dashboard, editIndex)}>
{!isEditing && <AnnotationSettingsList dashboard={dashboard} onNew={onNew} onEdit={onEdit} />}
{isEditing && <AnnotationSettingsEdit dashboard={dashboard} editIdx={editIndex!} />}
</Page>
);
}
function getSubPageNav(dashboard: DashboardModel, editIndex: number | undefined): NavModelItem | undefined {
if (editIndex == null) {
return undefined;
}
const editItem = dashboard.annotations.list[editIndex];
if (editItem) {
return {
text: editItem.name,
};
}
return undefined;
}
| public/app/features/dashboard/components/DashboardSettings/AnnotationsSettings.tsx | 0 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.0001722772722132504,
0.0001689979835646227,
0.00016666979354340583,
0.00016879801114555448,
0.0000017777784933059593
] |
{
"id": 3,
"code_window": [
"name: packages_secret_access_key\n",
"---\n",
"kind: signature\n",
"hmac: e7746a4b35fba9e1a7cb3096b947a874786b082f41e4252448ac6acde7ee3ccf\n",
"\n",
"..."
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"hmac: efffc2eb55bbfa1cebe950585df1f3f81d2f2a38311e2854f3ce08d1eec16fe3\n"
],
"file_path": ".drone.yml",
"type": "replace",
"edit_start_line_idx": 3167
} | load(
'scripts/drone/steps/lib.star',
'download_grabpl_step',
'publish_images_step',
'compile_build_cmd',
'fetch_images_step',
)
load(
'scripts/drone/utils/utils.star',
'pipeline',
)
def publish_image_steps(edition, mode, docker_repo):
additional_docker_repo = ""
if edition == 'oss':
additional_docker_repo='grafana/grafana-oss'
steps = [
download_grabpl_step(),
compile_build_cmd(),
fetch_images_step(edition),
publish_images_step(edition, 'release', mode, docker_repo),
]
if additional_docker_repo != "":
steps.extend([publish_images_step(edition, 'release', mode, additional_docker_repo)])
return steps
def publish_image_pipelines_public():
mode='public'
trigger = {
'event': ['promote'],
'target': [mode],
}
return [pipeline(
name='publish-docker-oss-{}'.format(mode), trigger=trigger, steps=publish_image_steps(edition='oss', mode=mode, docker_repo='grafana'), edition="", environment = {'EDITION': 'oss'}
), pipeline(
name='publish-docker-enterprise-{}'.format(mode), trigger=trigger, steps=publish_image_steps(edition='enterprise', mode=mode, docker_repo='grafana-enterprise'), edition="", environment = {'EDITION': 'enterprise'}
),]
def publish_image_pipelines_security():
mode='security'
trigger = {
'event': ['promote'],
'target': [mode],
}
return [pipeline(
name='publish-docker-enterprise-{}'.format(mode), trigger=trigger, steps=publish_image_steps(edition='enterprise', mode=mode, docker_repo='grafana-enterprise'), edition="", environment = {'EDITION': 'enterprise'}
),]
| scripts/drone/pipelines/publish_images.star | 1 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.00017466519784647971,
0.0001701044966466725,
0.00016670887998770922,
0.00016971517470665276,
0.0000025151052795990836
] |
{
"id": 3,
"code_window": [
"name: packages_secret_access_key\n",
"---\n",
"kind: signature\n",
"hmac: e7746a4b35fba9e1a7cb3096b947a874786b082f41e4252448ac6acde7ee3ccf\n",
"\n",
"..."
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"hmac: efffc2eb55bbfa1cebe950585df1f3f81d2f2a38311e2854f3ce08d1eec16fe3\n"
],
"file_path": ".drone.yml",
"type": "replace",
"edit_start_line_idx": 3167
} | import { render, RenderResult } from '@testing-library/react';
import { noop } from 'lodash';
import React from 'react';
import { CoreApp } from '@grafana/data';
import { PrometheusDatasource } from '../datasource';
import { testIds as regularTestIds } from './PromQueryEditor';
import { PromQueryEditorByApp } from './PromQueryEditorByApp';
import { testIds as alertingTestIds } from './PromQueryEditorForAlerting';
// the monaco-based editor uses lazy-loading and that does not work
// well with this test, and we do not need the monaco-related
// functionality in this test anyway, so we mock it out.
jest.mock('./monaco-query-field/MonacoQueryFieldLazy', () => {
const fakeQueryField = (props: any) => {
return <input onBlur={props.onBlur} data-testid={'dummy-code-input'} type={'text'} />;
};
return {
MonacoQueryFieldLazy: fakeQueryField,
};
});
jest.mock('@grafana/runtime', () => {
const runtime = jest.requireActual('@grafana/runtime');
return {
__esModule: true,
...runtime,
config: {
...runtime.config,
featureToggles: {
...runtime.config.featureToggles,
promQueryBuilder: true,
},
},
};
});
function setup(app: CoreApp): RenderResult & { onRunQuery: jest.Mock } {
const dataSource = {
createQuery: jest.fn((q) => q),
getInitHints: () => [],
getPrometheusTime: jest.fn((date, roundup) => 123),
getQueryHints: jest.fn(() => []),
languageProvider: {
start: () => Promise.resolve([]),
syntax: () => {},
getLabelKeys: () => [],
metrics: [],
},
} as unknown as PrometheusDatasource;
const onRunQuery = jest.fn();
const renderOutput = render(
<PromQueryEditorByApp
app={app}
onChange={noop}
onRunQuery={onRunQuery}
datasource={dataSource}
query={{ refId: 'A', expr: '' }}
/>
);
return {
...renderOutput,
onRunQuery,
};
}
describe('PromQueryEditorByApp', () => {
it('should render simplified query editor for cloud alerting', () => {
const { getByTestId, queryByTestId } = setup(CoreApp.CloudAlerting);
expect(getByTestId(alertingTestIds.editor)).toBeInTheDocument();
expect(queryByTestId(regularTestIds.editor)).toBeNull();
});
it('should render editor selector for unkown apps', () => {
const { getByTestId, queryByTestId } = setup(CoreApp.Unknown);
expect(getByTestId('QueryEditorModeToggle')).toBeInTheDocument();
expect(queryByTestId(alertingTestIds.editor)).toBeNull();
});
it('should render editor selector for explore', () => {
const { getByTestId, queryByTestId } = setup(CoreApp.Explore);
expect(getByTestId('QueryEditorModeToggle')).toBeInTheDocument();
expect(queryByTestId(alertingTestIds.editor)).toBeNull();
});
it('should render editor selector for dashboard', () => {
const { getByTestId, queryByTestId } = setup(CoreApp.Dashboard);
expect(getByTestId('QueryEditorModeToggle')).toBeInTheDocument();
expect(queryByTestId(alertingTestIds.editor)).toBeNull();
});
});
| public/app/plugins/datasource/prometheus/components/PromQueryEditorByApp.test.tsx | 0 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.00017362076323479414,
0.00016975037578959018,
0.00016667328600306064,
0.0001697815314400941,
0.0000020434349607967306
] |
{
"id": 3,
"code_window": [
"name: packages_secret_access_key\n",
"---\n",
"kind: signature\n",
"hmac: e7746a4b35fba9e1a7cb3096b947a874786b082f41e4252448ac6acde7ee3ccf\n",
"\n",
"..."
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"hmac: efffc2eb55bbfa1cebe950585df1f3f81d2f2a38311e2854f3ce08d1eec16fe3\n"
],
"file_path": ".drone.yml",
"type": "replace",
"edit_start_line_idx": 3167
} | import { of } from 'rxjs';
import { DataQueryRequest, dateTime } from '@grafana/data';
import { backendSrv } from 'app/core/services/backend_srv'; // will use the version in __mocks__
import { createFetchResponse } from '../../../../../test/helpers/createFetchResponse';
import OpenTsDatasource from '../datasource';
import { OpenTsdbQuery } from '../types';
jest.mock('@grafana/runtime', () => ({
...(jest.requireActual('@grafana/runtime') as unknown as object),
getBackendSrv: () => backendSrv,
}));
const metricFindQueryData = [
{
target: 'prod1.count',
datapoints: [
[10, 1],
[12, 1],
],
},
];
describe('opentsdb', () => {
function getTestcontext({ data = metricFindQueryData }: { data?: any } = {}) {
jest.clearAllMocks();
const fetchMock = jest.spyOn(backendSrv, 'fetch');
fetchMock.mockImplementation(() => of(createFetchResponse(data)));
const instanceSettings = { url: '', jsonData: { tsdbVersion: 1 } };
const replace = jest.fn((value) => value);
const templateSrv: any = {
replace,
};
const ds = new OpenTsDatasource(instanceSettings, templateSrv);
return { ds, templateSrv, fetchMock };
}
describe('When performing metricFindQuery', () => {
it('metrics() should generate api suggest query', async () => {
const { ds, fetchMock } = getTestcontext();
const results = await ds.metricFindQuery('metrics(pew)');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0].url).toBe('/api/suggest');
expect(fetchMock.mock.calls[0][0].params?.type).toBe('metrics');
expect(fetchMock.mock.calls[0][0].params?.q).toBe('pew');
expect(results).not.toBe(null);
});
it('tag_names(cpu) should generate lookup query', async () => {
const { ds, fetchMock } = getTestcontext();
const results = await ds.metricFindQuery('tag_names(cpu)');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0].url).toBe('/api/search/lookup');
expect(fetchMock.mock.calls[0][0].params?.m).toBe('cpu');
expect(results).not.toBe(null);
});
it('tag_values(cpu, test) should generate lookup query', async () => {
const { ds, fetchMock } = getTestcontext();
const results = await ds.metricFindQuery('tag_values(cpu, hostname)');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0].url).toBe('/api/search/lookup');
expect(fetchMock.mock.calls[0][0].params?.m).toBe('cpu{hostname=*}');
expect(results).not.toBe(null);
});
it('tag_values(cpu, test) should generate lookup query', async () => {
const { ds, fetchMock } = getTestcontext();
const results = await ds.metricFindQuery('tag_values(cpu, hostname, env=$env)');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0].url).toBe('/api/search/lookup');
expect(fetchMock.mock.calls[0][0].params?.m).toBe('cpu{hostname=*,env=$env}');
expect(results).not.toBe(null);
});
it('tag_values(cpu, test) should generate lookup query', async () => {
const { ds, fetchMock } = getTestcontext();
const results = await ds.metricFindQuery('tag_values(cpu, hostname, env=$env, region=$region)');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0].url).toBe('/api/search/lookup');
expect(fetchMock.mock.calls[0][0].params?.m).toBe('cpu{hostname=*,env=$env,region=$region}');
expect(results).not.toBe(null);
});
it('suggest_tagk() should generate api suggest query', async () => {
const { ds, fetchMock } = getTestcontext();
const results = await ds.metricFindQuery('suggest_tagk(foo)');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0].url).toBe('/api/suggest');
expect(fetchMock.mock.calls[0][0].params?.type).toBe('tagk');
expect(fetchMock.mock.calls[0][0].params?.q).toBe('foo');
expect(results).not.toBe(null);
});
it('suggest_tagv() should generate api suggest query', async () => {
const { ds, fetchMock } = getTestcontext();
const results = await ds.metricFindQuery('suggest_tagv(bar)');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0].url).toBe('/api/suggest');
expect(fetchMock.mock.calls[0][0].params?.type).toBe('tagv');
expect(fetchMock.mock.calls[0][0].params?.q).toBe('bar');
expect(results).not.toBe(null);
});
});
describe('When interpolating variables', () => {
it('should return an empty array if no queries are provided', () => {
const { ds } = getTestcontext();
expect(ds.interpolateVariablesInQueries([], {})).toHaveLength(0);
});
it('should replace metric variable', () => {
const { ds, templateSrv } = getTestcontext();
const logQuery: OpenTsdbQuery = {
refId: 'someRefId',
metric: '$someVar',
filters: [
{
type: 'type',
tagk: 'someTagk',
filter: 'someTagv',
groupBy: true,
},
],
};
ds.interpolateVariablesInQueries([logQuery], {});
expect(templateSrv.replace).toHaveBeenCalledWith('$someVar', {});
expect(templateSrv.replace).toHaveBeenCalledTimes(1);
});
it('should replace filter tag key and value', () => {
const { ds, templateSrv } = getTestcontext();
let logQuery: OpenTsdbQuery = {
refId: 'A',
datasource: {
type: 'opentsdb',
uid: 'P311D5F9D9B165031',
},
aggregator: 'sum',
downsampleAggregator: 'avg',
downsampleFillPolicy: 'none',
metric: 'logins.count',
filters: [
{
type: 'iliteral_or',
tagk: '$someTagk',
filter: '$someTagv',
groupBy: false,
},
],
};
const scopedVars = {
__interval: {
text: '20s',
value: '20s',
},
__interval_ms: {
text: '20000',
value: 20000,
},
};
const dataQR: DataQueryRequest<OpenTsdbQuery> = {
app: 'dashboard',
requestId: 'Q103',
timezone: 'browser',
panelId: 2,
dashboardId: 189,
dashboardUID: 'tyzmfPIVz',
publicDashboardAccessToken: '',
range: {
from: dateTime('2022-10-19T08:55:18.430Z'),
to: dateTime('2022-10-19T14:55:18.431Z'),
raw: {
from: 'now-6h',
to: 'now',
},
},
timeInfo: '',
interval: '20s',
intervalMs: 20000,
targets: [logQuery],
maxDataPoints: 909,
scopedVars: scopedVars,
startTime: 1666191318431,
rangeRaw: {
from: 'now-6h',
to: 'now',
},
};
ds.interpolateVariablesInFilters(logQuery, dataQR);
expect(templateSrv.replace).toHaveBeenCalledWith('$someTagk', scopedVars, 'pipe');
expect(templateSrv.replace).toHaveBeenCalledWith('$someTagv', scopedVars, 'pipe');
expect(templateSrv.replace).toHaveBeenCalledTimes(2);
});
});
});
| public/app/plugins/datasource/opentsdb/specs/datasource.test.ts | 0 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.00020990989287383854,
0.00017157378897536546,
0.00016477059398312122,
0.00017036973440553993,
0.000008490547770634294
] |
{
"id": 3,
"code_window": [
"name: packages_secret_access_key\n",
"---\n",
"kind: signature\n",
"hmac: e7746a4b35fba9e1a7cb3096b947a874786b082f41e4252448ac6acde7ee3ccf\n",
"\n",
"..."
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"hmac: efffc2eb55bbfa1cebe950585df1f3f81d2f2a38311e2854f3ce08d1eec16fe3\n"
],
"file_path": ".drone.yml",
"type": "replace",
"edit_start_line_idx": 3167
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2,13.5v2a1,1,0,0,0,1,1H13a3,3,0,0,0,6,0h2a1,1,0,0,0,1-1v-8a3,3,0,0,0-3-3H9a3,3,0,0,0-3,3v7H4v-1a1,1,0,0,0-2,0Zm13,3a1,1,0,1,1,1,1A1,1,0,0,1,15,16.5Zm-7-6H20v4H18.22a3,3,0,0,0-4.44,0H8Zm0-3a1,1,0,0,1,1-1H19a1,1,0,0,1,1,1v1H8Z"/></svg> | public/img/icons/unicons/luggage-cart.svg | 0 | https://github.com/grafana/grafana/commit/7deaeb0f9e6578f378d922b2290bfa4bdfa42466 | [
0.00016739476996008307,
0.00016739476996008307,
0.00016739476996008307,
0.00016739476996008307,
0
] |
{
"id": 0,
"code_window": [
"import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';\n",
"import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';\n",
"import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';\n",
"import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';\n",
"import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';\n",
"import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n",
"import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 31
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event';
import { dispose } from 'vs/base/common/lifecycle';
import * as UUID from 'vs/base/common/uuid';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { PrefixSumComputer } from 'vs/editor/common/model/prefixSumComputer';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { CellEditState, CellFindMatch, CodeCellLayoutChangeEvent, CodeCellLayoutInfo, CellLayoutState, ICellOutputViewModel, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CellOutputViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/cellOutputViewModel';
import { ViewContext } from 'vs/workbench/contrib/notebook/browser/viewModel/viewContext';
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { CellKind, INotebookSearchOptions, NotebookCellOutputsSplice } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptionsChangeEvent } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { BaseCellViewModel } from './baseCellViewModel';
import { NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
export class CodeCellViewModel extends BaseCellViewModel implements ICellViewModel {
readonly cellKind = CellKind.Code;
protected readonly _onLayoutInfoRead = this._register(new Emitter<void>());
readonly onLayoutInfoRead = this._onLayoutInfoRead.event;
protected readonly _onDidChangeOutputs = this._register(new Emitter<NotebookCellOutputsSplice>());
readonly onDidChangeOutputs = this._onDidChangeOutputs.event;
private readonly _onDidRemoveOutputs = this._register(new Emitter<readonly ICellOutputViewModel[]>());
readonly onDidRemoveOutputs = this._onDidRemoveOutputs.event;
private _outputCollection: number[] = [];
private _outputsTop: PrefixSumComputer | null = null;
protected _pauseableEmitter = this._register(new PauseableEmitter<CodeCellLayoutChangeEvent>());
readonly onDidChangeLayout = this._pauseableEmitter.event;
private _editorHeight = 0;
set editorHeight(height: number) {
this._editorHeight = height;
this.layoutChange({ editorHeight: true }, 'CodeCellViewModel#editorHeight');
}
get editorHeight() {
throw new Error('editorHeight is write-only');
}
private _commentHeight = 0;
set commentHeight(height: number) {
if (this._commentHeight === height) {
return;
}
this._commentHeight = height;
this.layoutChange({ commentHeight: true }, 'CodeCellViewModel#commentHeight');
}
private _hoveringOutput: boolean = false;
public get outputIsHovered(): boolean {
return this._hoveringOutput;
}
public set outputIsHovered(v: boolean) {
this._hoveringOutput = v;
this._onDidChangeState.fire({ outputIsHoveredChanged: true });
}
private _focusOnOutput: boolean = false;
public get outputIsFocused(): boolean {
return this._focusOnOutput;
}
public set outputIsFocused(v: boolean) {
this._focusOnOutput = v;
this._onDidChangeState.fire({ outputIsFocusedChanged: true });
}
private _outputMinHeight: number = 0;
private get outputMinHeight() {
return this._outputMinHeight;
}
/**
* The minimum height of the output region. It's only set to non-zero temporarily when replacing an output with a new one.
* It's reset to 0 when the new output is rendered, or in one second.
*/
private set outputMinHeight(newMin: number) {
this._outputMinHeight = newMin;
}
private _layoutInfo: CodeCellLayoutInfo;
get layoutInfo() {
return this._layoutInfo;
}
private _outputViewModels: ICellOutputViewModel[];
get outputsViewModels() {
return this._outputViewModels;
}
constructor(
viewType: string,
model: NotebookCellTextModel,
initialNotebookLayoutInfo: NotebookLayoutInfo | null,
readonly viewContext: ViewContext,
@IConfigurationService configurationService: IConfigurationService,
@INotebookService private readonly _notebookService: INotebookService,
@ITextModelService modelService: ITextModelService,
@IUndoRedoService undoRedoService: IUndoRedoService,
@ICodeEditorService codeEditorService: ICodeEditorService
) {
super(viewType, model, UUID.generateUuid(), viewContext, configurationService, modelService, undoRedoService, codeEditorService);
this._outputViewModels = this.model.outputs.map(output => new CellOutputViewModel(this, output, this._notebookService));
this._register(this.model.onDidChangeOutputs((splice) => {
const removedOutputs: ICellOutputViewModel[] = [];
let outputLayoutChange = false;
for (let i = splice.start; i < splice.start + splice.deleteCount; i++) {
if (this._outputCollection[i] !== undefined && this._outputCollection[i] !== 0) {
outputLayoutChange = true;
}
}
this._outputCollection.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(() => 0));
removedOutputs.push(...this._outputViewModels.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(output => new CellOutputViewModel(this, output, this._notebookService))));
this._outputsTop = null;
this._onDidChangeOutputs.fire(splice);
this._onDidRemoveOutputs.fire(removedOutputs);
if (outputLayoutChange) {
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#model.onDidChangeOutputs');
}
dispose(removedOutputs);
}));
this._outputCollection = new Array(this.model.outputs.length);
this._layoutInfo = {
fontInfo: initialNotebookLayoutInfo?.fontInfo || null,
editorHeight: 0,
editorWidth: initialNotebookLayoutInfo
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(initialNotebookLayoutInfo.width)
: 0,
statusBarHeight: 0,
commentHeight: 0,
outputContainerOffset: 0,
outputTotalHeight: 0,
outputShowMoreContainerHeight: 0,
outputShowMoreContainerOffset: 0,
totalHeight: this.computeTotalHeight(17, 0, 0),
codeIndicatorHeight: 0,
outputIndicatorHeight: 0,
bottomToolbarOffset: 0,
layoutState: CellLayoutState.Uninitialized,
estimatedHasHorizontalScrolling: false
};
}
updateOptions(e: NotebookOptionsChangeEvent) {
if (e.cellStatusBarVisibility || e.insertToolbarPosition || e.cellToolbarLocation) {
this.layoutChange({});
}
}
pauseLayout() {
this._pauseableEmitter.pause();
}
resumeLayout() {
this._pauseableEmitter.resume();
}
layoutChange(state: CodeCellLayoutChangeEvent, source?: string) {
// recompute
this._ensureOutputsTop();
const notebookLayoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const bottomToolbarDimensions = this.viewContext.notebookOptions.computeBottomToolbarDimensions();
const outputShowMoreContainerHeight = state.outputShowMoreContainerHeight ? state.outputShowMoreContainerHeight : this._layoutInfo.outputShowMoreContainerHeight;
const outputTotalHeight = Math.max(this._outputMinHeight, this.isOutputCollapsed ? notebookLayoutConfiguration.collapsedIndicatorHeight : this._outputsTop!.getTotalSum());
const commentHeight = state.commentHeight ? this._commentHeight : this._layoutInfo.commentHeight;
const originalLayout = this.layoutInfo;
if (!this.isInputCollapsed) {
let newState: CellLayoutState;
let editorHeight: number;
let totalHeight: number;
let hasHorizontalScrolling = false;
if (!state.editorHeight && this._layoutInfo.layoutState === CellLayoutState.FromCache && !state.outputHeight) {
// No new editorHeight info - keep cached totalHeight and estimate editorHeight
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this._layoutInfo.totalHeight;
newState = CellLayoutState.FromCache;
} else if (state.editorHeight || this._layoutInfo.layoutState === CellLayoutState.Measured) {
// Editor has been measured
editorHeight = this._editorHeight;
totalHeight = this.computeTotalHeight(this._editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Measured;
hasHorizontalScrolling = this._layoutInfo.estimatedHasHorizontalScrolling;
} else {
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this.computeTotalHeight(editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Estimated;
}
const statusBarHeight = this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri);
const codeIndicatorHeight = editorHeight + statusBarHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.editorToolbarHeight
+ notebookLayoutConfiguration.cellTopMargin // CELL_TOP_MARGIN
+ editorHeight
+ statusBarHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight,
editorWidth,
statusBarHeight,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: newState,
estimatedHasHorizontalScrolling: hasHorizontalScrolling
};
} else {
const codeIndicatorHeight = notebookLayoutConfiguration.collapsedIndicatorHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.cellTopMargin + notebookLayoutConfiguration.collapsedIndicatorHeight;
const totalHeight =
notebookLayoutConfiguration.cellTopMargin
+ notebookLayoutConfiguration.collapsedIndicatorHeight
+ notebookLayoutConfiguration.cellBottomMargin //CELL_BOTTOM_MARGIN
+ bottomToolbarDimensions.bottomToolbarGap //BOTTOM_CELL_TOOLBAR_GAP
+ commentHeight
+ outputTotalHeight + outputShowMoreContainerHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight: this._layoutInfo.editorHeight,
editorWidth,
statusBarHeight: 0,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: this._layoutInfo.layoutState,
estimatedHasHorizontalScrolling: false
};
}
this._fireOnDidChangeLayout({
...state,
totalHeight: this.layoutInfo.totalHeight !== originalLayout.totalHeight,
source,
});
}
private _fireOnDidChangeLayout(state: CodeCellLayoutChangeEvent) {
this._pauseableEmitter.fire(state);
}
override restoreEditorViewState(editorViewStates: editorCommon.ICodeEditorViewState | null, totalHeight?: number) {
super.restoreEditorViewState(editorViewStates);
if (totalHeight !== undefined && this._layoutInfo.layoutState !== CellLayoutState.Measured) {
this._layoutInfo = {
fontInfo: this._layoutInfo.fontInfo,
editorHeight: this._layoutInfo.editorHeight,
editorWidth: this._layoutInfo.editorWidth,
statusBarHeight: this.layoutInfo.statusBarHeight,
commentHeight: this.layoutInfo.commentHeight,
outputContainerOffset: this._layoutInfo.outputContainerOffset,
outputTotalHeight: this._layoutInfo.outputTotalHeight,
outputShowMoreContainerHeight: this._layoutInfo.outputShowMoreContainerHeight,
outputShowMoreContainerOffset: this._layoutInfo.outputShowMoreContainerOffset,
totalHeight: totalHeight,
codeIndicatorHeight: this._layoutInfo.codeIndicatorHeight,
outputIndicatorHeight: this._layoutInfo.outputIndicatorHeight,
bottomToolbarOffset: this._layoutInfo.bottomToolbarOffset,
layoutState: CellLayoutState.FromCache,
estimatedHasHorizontalScrolling: this._layoutInfo.estimatedHasHorizontalScrolling
};
}
}
hasDynamicHeight() {
// CodeCellVM always measures itself and controls its cell's height
return false;
}
getDynamicHeight() {
this._onLayoutInfoRead.fire();
return this._layoutInfo.totalHeight;
}
getHeight(lineHeight: number) {
if (this._layoutInfo.layoutState === CellLayoutState.Uninitialized) {
const estimate = this.estimateEditorHeight(lineHeight);
return this.computeTotalHeight(estimate.editorHeight, 0, 0);
} else {
return this._layoutInfo.totalHeight;
}
}
private estimateEditorHeight(lineHeight: number | undefined = 20): { editorHeight: number; hasHorizontalScrolling: boolean } {
let hasHorizontalScrolling = false;
const cellEditorOptions = this.viewContext.getBaseCellEditorOptions(this.language);
if (this.layoutInfo.fontInfo && cellEditorOptions.value.wordWrap === 'off') {
for (let i = 0; i < this.lineCount; i++) {
const max = this.textBuffer.getLineLastNonWhitespaceColumn(i + 1);
const estimatedWidth = max * (this.layoutInfo.fontInfo.typicalHalfwidthCharacterWidth + this.layoutInfo.fontInfo.letterSpacing);
if (estimatedWidth > this.layoutInfo.editorWidth) {
hasHorizontalScrolling = true;
break;
}
}
}
const verticalScrollbarHeight = hasHorizontalScrolling ? 12 : 0; // take zoom level into account
const editorPadding = this.viewContext.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
const editorHeight = this.lineCount * lineHeight
+ editorPadding.top
+ editorPadding.bottom // EDITOR_BOTTOM_PADDING
+ verticalScrollbarHeight;
return {
editorHeight,
hasHorizontalScrolling
};
}
private computeTotalHeight(editorHeight: number, outputsTotalHeight: number, outputShowMoreContainerHeight: number): number {
const layoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const { bottomToolbarGap } = this.viewContext.notebookOptions.computeBottomToolbarDimensions(this.viewType);
return layoutConfiguration.editorToolbarHeight
+ layoutConfiguration.cellTopMargin
+ editorHeight
+ this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri)
+ this._commentHeight
+ outputsTotalHeight
+ outputShowMoreContainerHeight
+ bottomToolbarGap
+ layoutConfiguration.cellBottomMargin;
}
protected onDidChangeTextModelContent(): void {
if (this.getEditState() !== CellEditState.Editing) {
this.updateEditState(CellEditState.Editing, 'onDidChangeTextModelContent');
this._onDidChangeState.fire({ contentChanged: true });
}
}
onDeselect() {
this.updateEditState(CellEditState.Preview, 'onDeselect');
}
updateOutputShowMoreContainerHeight(height: number) {
this.layoutChange({ outputShowMoreContainerHeight: height }, 'CodeCellViewModel#updateOutputShowMoreContainerHeight');
}
updateOutputMinHeight(height: number) {
this.outputMinHeight = height;
}
unlockOutputHeight() {
this.outputMinHeight = 0;
this.layoutChange({ outputHeight: true });
}
updateOutputHeight(index: number, height: number, source?: string) {
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
this._ensureOutputsTop();
if (height < 28 && this._outputViewModels[index].hasMultiMimeType()) {
height = 28;
}
this._outputCollection[index] = height;
if (this._outputsTop!.setValue(index, height)) {
this.layoutChange({ outputHeight: true }, source);
}
}
getOutputOffsetInContainer(index: number) {
this._ensureOutputsTop();
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
return this._outputsTop!.getPrefixSum(index - 1);
}
getOutputOffset(index: number): number {
return this.layoutInfo.outputContainerOffset + this.getOutputOffsetInContainer(index);
}
spliceOutputHeights(start: number, deleteCnt: number, heights: number[]) {
this._ensureOutputsTop();
this._outputsTop!.removeValues(start, deleteCnt);
if (heights.length) {
const values = new Uint32Array(heights.length);
for (let i = 0; i < heights.length; i++) {
values[i] = heights[i];
}
this._outputsTop!.insertValues(start, values);
}
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#spliceOutputs');
}
private _ensureOutputsTop(): void {
if (!this._outputsTop) {
const values = new Uint32Array(this._outputCollection.length);
for (let i = 0; i < this._outputCollection.length; i++) {
values[i] = this._outputCollection[i];
}
this._outputsTop = new PrefixSumComputer(values);
}
}
private readonly _hasFindResult = this._register(new Emitter<boolean>());
public readonly hasFindResult: Event<boolean> = this._hasFindResult.event;
startFind(value: string, options: INotebookSearchOptions): CellFindMatch | null {
const matches = super.cellStartFind(value, options);
if (matches === null) {
return null;
}
return {
cell: this,
contentMatches: matches
};
}
override dispose() {
super.dispose();
this._outputCollection = [];
this._outputsTop = null;
dispose(this._outputViewModels);
}
}
| src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.007524452172219753,
0.00036547667696140707,
0.00016256302478723228,
0.0001716901024337858,
0.0010430008405819535
] |
{
"id": 0,
"code_window": [
"import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';\n",
"import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';\n",
"import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';\n",
"import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';\n",
"import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';\n",
"import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n",
"import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 31
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { IContextMenuProvider } from 'vs/base/browser/contextmenu';
import { $, addDisposableListener, append, EventType, h } from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IActionViewItemProvider } from 'vs/base/browser/ui/actionbar/actionbar';
import { ActionViewItem, BaseActionViewItem, IActionViewItemOptions, IBaseActionViewItemOptions } from 'vs/base/browser/ui/actionbar/actionViewItems';
import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview';
import { DropdownMenu, IActionProvider, IDropdownMenuOptions, ILabelRenderer } from 'vs/base/browser/ui/dropdown/dropdown';
import { Action, IAction, IActionRunner } from 'vs/base/common/actions';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { ResolvedKeybinding } from 'vs/base/common/keybindings';
import { IDisposable } from 'vs/base/common/lifecycle';
import 'vs/css!./dropdown';
export interface IKeybindingProvider {
(action: IAction): ResolvedKeybinding | undefined;
}
export interface IAnchorAlignmentProvider {
(): AnchorAlignment;
}
export interface IDropdownMenuActionViewItemOptions extends IBaseActionViewItemOptions {
readonly actionViewItemProvider?: IActionViewItemProvider;
readonly keybindingProvider?: IKeybindingProvider;
readonly actionRunner?: IActionRunner;
readonly classNames?: string[] | string;
readonly anchorAlignmentProvider?: IAnchorAlignmentProvider;
readonly menuAsChild?: boolean;
}
export class DropdownMenuActionViewItem extends BaseActionViewItem {
private menuActionsOrProvider: readonly IAction[] | IActionProvider;
private dropdownMenu: DropdownMenu | undefined;
private contextMenuProvider: IContextMenuProvider;
private actionItem: HTMLElement | null = null;
private _onDidChangeVisibility = this._register(new Emitter<boolean>());
readonly onDidChangeVisibility = this._onDidChangeVisibility.event;
protected override readonly options: IDropdownMenuActionViewItemOptions;
constructor(
action: IAction,
menuActionsOrProvider: readonly IAction[] | IActionProvider,
contextMenuProvider: IContextMenuProvider,
options: IDropdownMenuActionViewItemOptions = Object.create(null)
) {
super(null, action, options);
this.menuActionsOrProvider = menuActionsOrProvider;
this.contextMenuProvider = contextMenuProvider;
this.options = options;
if (this.options.actionRunner) {
this.actionRunner = this.options.actionRunner;
}
}
override render(container: HTMLElement): void {
this.actionItem = container;
const labelRenderer: ILabelRenderer = (el: HTMLElement): IDisposable | null => {
this.element = append(el, $('a.action-label'));
let classNames: string[] = [];
if (typeof this.options.classNames === 'string') {
classNames = this.options.classNames.split(/\s+/g).filter(s => !!s);
} else if (this.options.classNames) {
classNames = this.options.classNames;
}
// todo@aeschli: remove codicon, should come through `this.options.classNames`
if (!classNames.find(c => c === 'icon')) {
classNames.push('codicon');
}
this.element.classList.add(...classNames);
this.element.setAttribute('role', 'button');
this.element.setAttribute('aria-haspopup', 'true');
this.element.setAttribute('aria-expanded', 'false');
this.element.title = this._action.label || '';
this.element.ariaLabel = this._action.label || '';
return null;
};
const isActionsArray = Array.isArray(this.menuActionsOrProvider);
const options: IDropdownMenuOptions = {
contextMenuProvider: this.contextMenuProvider,
labelRenderer: labelRenderer,
menuAsChild: this.options.menuAsChild,
actions: isActionsArray ? this.menuActionsOrProvider as IAction[] : undefined,
actionProvider: isActionsArray ? undefined : this.menuActionsOrProvider as IActionProvider
};
this.dropdownMenu = this._register(new DropdownMenu(container, options));
this._register(this.dropdownMenu.onDidChangeVisibility(visible => {
this.element?.setAttribute('aria-expanded', `${visible}`);
this._onDidChangeVisibility.fire(visible);
}));
this.dropdownMenu.menuOptions = {
actionViewItemProvider: this.options.actionViewItemProvider,
actionRunner: this.actionRunner,
getKeyBinding: this.options.keybindingProvider,
context: this._context
};
if (this.options.anchorAlignmentProvider) {
const that = this;
this.dropdownMenu.menuOptions = {
...this.dropdownMenu.menuOptions,
get anchorAlignment(): AnchorAlignment {
return that.options.anchorAlignmentProvider!();
}
};
}
this.updateTooltip();
this.updateEnabled();
}
protected override getTooltip(): string | undefined {
let title: string | null = null;
if (this.action.tooltip) {
title = this.action.tooltip;
} else if (this.action.label) {
title = this.action.label;
}
return title ?? undefined;
}
override setActionContext(newContext: unknown): void {
super.setActionContext(newContext);
if (this.dropdownMenu) {
if (this.dropdownMenu.menuOptions) {
this.dropdownMenu.menuOptions.context = newContext;
} else {
this.dropdownMenu.menuOptions = { context: newContext };
}
}
}
show(): void {
this.dropdownMenu?.show();
}
protected override updateEnabled(): void {
const disabled = !this.action.enabled;
this.actionItem?.classList.toggle('disabled', disabled);
this.element?.classList.toggle('disabled', disabled);
}
}
export interface IActionWithDropdownActionViewItemOptions extends IActionViewItemOptions {
readonly menuActionsOrProvider: readonly IAction[] | IActionProvider;
readonly menuActionClassNames?: string[];
}
export class ActionWithDropdownActionViewItem extends ActionViewItem {
protected dropdownMenuActionViewItem: DropdownMenuActionViewItem | undefined;
constructor(
context: unknown,
action: IAction,
options: IActionWithDropdownActionViewItemOptions,
private readonly contextMenuProvider: IContextMenuProvider
) {
super(context, action, options);
}
override render(container: HTMLElement): void {
super.render(container);
if (this.element) {
this.element.classList.add('action-dropdown-item');
const menuActionsProvider = {
getActions: () => {
const actionsProvider = (<IActionWithDropdownActionViewItemOptions>this.options).menuActionsOrProvider;
return Array.isArray(actionsProvider) ? actionsProvider : (actionsProvider as IActionProvider).getActions(); // TODO: microsoft/TypeScript#42768
}
};
const menuActionClassNames = (<IActionWithDropdownActionViewItemOptions>this.options).menuActionClassNames || [];
const separator = h('div.action-dropdown-item-separator', [h('div', {})]).root;
separator.classList.toggle('prominent', menuActionClassNames.includes('prominent'));
append(this.element, separator);
this.dropdownMenuActionViewItem = new DropdownMenuActionViewItem(this._register(new Action('dropdownAction', nls.localize('moreActions', "More Actions..."))), menuActionsProvider, this.contextMenuProvider, { classNames: ['dropdown', ...Codicon.dropDownButton.classNamesArray, ...menuActionClassNames] });
this.dropdownMenuActionViewItem.render(this.element);
this._register(addDisposableListener(this.element, EventType.KEY_DOWN, e => {
const event = new StandardKeyboardEvent(e);
let handled: boolean = false;
if (this.dropdownMenuActionViewItem?.isFocused() && event.equals(KeyCode.LeftArrow)) {
handled = true;
this.dropdownMenuActionViewItem?.blur();
this.focus();
} else if (this.isFocused() && event.equals(KeyCode.RightArrow)) {
handled = true;
this.blur();
this.dropdownMenuActionViewItem?.focus();
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
}));
}
}
override blur(): void {
super.blur();
this.dropdownMenuActionViewItem?.blur();
}
override setFocusable(focusable: boolean): void {
super.setFocusable(focusable);
this.dropdownMenuActionViewItem?.setFocusable(focusable);
}
}
| src/vs/base/browser/ui/dropdown/dropdownActionViewItem.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.000174552493263036,
0.00016991824668366462,
0.0001644472504267469,
0.00017025934357661754,
0.0000026053371584566776
] |
{
"id": 0,
"code_window": [
"import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';\n",
"import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';\n",
"import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';\n",
"import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';\n",
"import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';\n",
"import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n",
"import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 31
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import * as json from 'vs/base/common/json';
import { setProperty } from 'vs/base/common/jsonEdit';
import { Queue } from 'vs/base/common/async';
import { Edit } from 'vs/base/common/jsonFormatter';
import { IReference } from 'vs/base/common/lifecycle';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService } from 'vs/platform/files/common/files';
import { ITextModelService, IResolvedTextEditorModel } from 'vs/editor/common/services/resolverService';
import { IJSONEditingService, IJSONValue, JSONEditingError, JSONEditingErrorCode } from 'vs/workbench/services/configuration/common/jsonEditing';
import { ITextModel } from 'vs/editor/common/model';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
export class JSONEditingService implements IJSONEditingService {
public _serviceBrand: undefined;
private queue: Queue<void>;
constructor(
@IFileService private readonly fileService: IFileService,
@ITextModelService private readonly textModelResolverService: ITextModelService,
@ITextFileService private readonly textFileService: ITextFileService
) {
this.queue = new Queue<void>();
}
write(resource: URI, values: IJSONValue[]): Promise<void> {
return Promise.resolve(this.queue.queue(() => this.doWriteConfiguration(resource, values))); // queue up writes to prevent race conditions
}
private async doWriteConfiguration(resource: URI, values: IJSONValue[]): Promise<void> {
const reference = await this.resolveAndValidate(resource, true);
try {
await this.writeToBuffer(reference.object.textEditorModel, values);
} finally {
reference.dispose();
}
}
private async writeToBuffer(model: ITextModel, values: IJSONValue[]): Promise<any> {
let hasEdits: boolean = false;
for (const value of values) {
const edit = this.getEdits(model, value)[0];
hasEdits = !!edit && this.applyEditsToBuffer(edit, model);
}
if (hasEdits) {
return this.textFileService.save(model.uri);
}
}
private applyEditsToBuffer(edit: Edit, model: ITextModel): boolean {
const startPosition = model.getPositionAt(edit.offset);
const endPosition = model.getPositionAt(edit.offset + edit.length);
const range = new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
const currentText = model.getValueInRange(range);
if (edit.content !== currentText) {
const editOperation = currentText ? EditOperation.replace(range, edit.content) : EditOperation.insert(startPosition, edit.content);
model.pushEditOperations([new Selection(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column)], [editOperation], () => []);
return true;
}
return false;
}
private getEdits(model: ITextModel, configurationValue: IJSONValue): Edit[] {
const { tabSize, insertSpaces } = model.getOptions();
const eol = model.getEOL();
const { path, value } = configurationValue;
// With empty path the entire file is being replaced, so we just use JSON.stringify
if (!path.length) {
const content = JSON.stringify(value, null, insertSpaces ? ' '.repeat(tabSize) : '\t');
return [{
content,
length: content.length,
offset: 0
}];
}
return setProperty(model.getValue(), path, value, { tabSize, insertSpaces, eol });
}
private async resolveModelReference(resource: URI): Promise<IReference<IResolvedTextEditorModel>> {
const exists = await this.fileService.exists(resource);
if (!exists) {
await this.textFileService.write(resource, '{}', { encoding: 'utf8' });
}
return this.textModelResolverService.createModelReference(resource);
}
private hasParseErrors(model: ITextModel): boolean {
const parseErrors: json.ParseError[] = [];
json.parse(model.getValue(), parseErrors, { allowTrailingComma: true, allowEmptyContent: true });
return parseErrors.length > 0;
}
private async resolveAndValidate(resource: URI, checkDirty: boolean): Promise<IReference<IResolvedTextEditorModel>> {
const reference = await this.resolveModelReference(resource);
const model = reference.object.textEditorModel;
if (this.hasParseErrors(model)) {
reference.dispose();
return this.reject<IReference<IResolvedTextEditorModel>>(JSONEditingErrorCode.ERROR_INVALID_FILE);
}
return reference;
}
private reject<T>(code: JSONEditingErrorCode): Promise<T> {
const message = this.toErrorMessage(code);
return Promise.reject(new JSONEditingError(message, code));
}
private toErrorMessage(error: JSONEditingErrorCode): string {
switch (error) {
// User issues
case JSONEditingErrorCode.ERROR_INVALID_FILE: {
return nls.localize('errorInvalidFile', "Unable to write into the file. Please open the file to correct errors/warnings in the file and try again.");
}
}
}
}
registerSingleton(IJSONEditingService, JSONEditingService, InstantiationType.Delayed);
| src/vs/workbench/services/configuration/common/jsonEditingService.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017358583863824606,
0.00017024227418005466,
0.00016196069191209972,
0.0001709117495920509,
0.0000032394020763604203
] |
{
"id": 0,
"code_window": [
"import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';\n",
"import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';\n",
"import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';\n",
"import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';\n",
"import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';\n",
"import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n",
"import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 31
} | [
{
"c": "<",
"t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.begin.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080",
"dark_plus_experimental": "punctuation.definition.tag: #808080",
"hc_light": "punctuation.definition.tag: #0F4A85",
"light_plus_experimental": "punctuation.definition.tag: #800000"
}
},
{
"c": "script",
"t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.start.html entity.name.tag.html",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6",
"dark_plus_experimental": "entity.name.tag: #569CD6",
"hc_light": "entity.name.tag: #0F4A85",
"light_plus_experimental": "entity.name.tag: #800000"
}
},
{
"c": ">",
"t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.end.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080",
"dark_plus_experimental": "punctuation.definition.tag: #808080",
"hc_light": "punctuation.definition.tag: #0F4A85",
"light_plus_experimental": "punctuation.definition.tag: #800000"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "...",
"t": "text.html.php meta.embedded.block.html source.js keyword.operator.spread.js",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_plus_experimental": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_plus_experimental": "keyword.operator: #000000"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "<?php",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php punctuation.section.embedded.begin.php",
"r": {
"dark_plus": "punctuation.section.embedded.begin.php: #569CD6",
"light_plus": "punctuation.section.embedded.begin.php: #800000",
"dark_vs": "punctuation.section.embedded.begin.php: #569CD6",
"light_vs": "punctuation.section.embedded.begin.php: #800000",
"hc_black": "punctuation.section.embedded: #569CD6",
"dark_plus_experimental": "punctuation.section.embedded.begin.php: #569CD6",
"hc_light": "punctuation.section.embedded.begin.php: #0F4A85",
"light_plus_experimental": "punctuation.section.embedded.begin.php: #800000"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "foreach",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php keyword.control.foreach.php",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0",
"dark_plus_experimental": "keyword.control: #C586C0",
"hc_light": "keyword.control: #B5200D",
"light_plus_experimental": "keyword.control: #AF00DB"
}
},
{
"c": "(",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.definition.begin.bracket.round.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "$",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php punctuation.definition.variable.php",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "variable: #9CDCFE",
"dark_plus_experimental": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_plus_experimental": "variable: #001080"
}
},
{
"c": "actID",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "variable: #9CDCFE",
"dark_plus_experimental": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_plus_experimental": "variable: #001080"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "AS",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php keyword.operator.logical.php",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_plus_experimental": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_plus_experimental": "keyword.operator: #000000"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "$",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php punctuation.definition.variable.php",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "variable: #9CDCFE",
"dark_plus_experimental": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_plus_experimental": "variable: #001080"
}
},
{
"c": "act",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "variable: #9CDCFE",
"dark_plus_experimental": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_plus_experimental": "variable: #001080"
}
},
{
"c": ")",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.definition.end.bracket.round.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "{",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.definition.begin.bracket.curly.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "echo",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php support.function.construct.output.php",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "support.function: #DCDCAA",
"dark_plus_experimental": "support.function: #DCDCAA",
"hc_light": "support.function: #5E2CBC",
"light_plus_experimental": "support.function: #795E26"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "'",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php punctuation.definition.string.begin.php",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_plus_experimental": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_plus_experimental": "string: #A31515"
}
},
{
"c": "divNames.push(",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_plus_experimental": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_plus_experimental": "string: #A31515"
}
},
{
"c": "\\'",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php constant.character.escape.php",
"r": {
"dark_plus": "constant.character.escape: #D7BA7D",
"light_plus": "constant.character.escape: #EE0000",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "constant.character: #569CD6",
"dark_plus_experimental": "constant.character.escape: #D7BA7D",
"hc_light": "constant.character.escape: #EE0000",
"light_plus_experimental": "constant.character.escape: #EE0000"
}
},
{
"c": "[nid=",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_plus_experimental": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_plus_experimental": "string: #A31515"
}
},
{
"c": "'",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php punctuation.definition.string.end.php",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_plus_experimental": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_plus_experimental": "string: #A31515"
}
},
{
"c": ".",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php keyword.operator.string.php",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_plus_experimental": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_plus_experimental": "keyword.operator: #000000"
}
},
{
"c": "$",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php punctuation.definition.variable.php",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "variable: #9CDCFE",
"dark_plus_experimental": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_plus_experimental": "variable: #001080"
}
},
{
"c": "act",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "variable: #9CDCFE",
"dark_plus_experimental": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_plus_experimental": "variable: #001080"
}
},
{
"c": ".",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php keyword.operator.string.php",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_plus_experimental": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_plus_experimental": "keyword.operator: #000000"
}
},
{
"c": "'",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php punctuation.definition.string.begin.php",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_plus_experimental": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_plus_experimental": "string: #A31515"
}
},
{
"c": "]",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_plus_experimental": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_plus_experimental": "string: #A31515"
}
},
{
"c": "\\'",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php constant.character.escape.php",
"r": {
"dark_plus": "constant.character.escape: #D7BA7D",
"light_plus": "constant.character.escape: #EE0000",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "constant.character: #569CD6",
"dark_plus_experimental": "constant.character.escape: #D7BA7D",
"hc_light": "constant.character.escape: #EE0000",
"light_plus_experimental": "constant.character.escape: #EE0000"
}
},
{
"c": ");",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_plus_experimental": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_plus_experimental": "string: #A31515"
}
},
{
"c": "'",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php punctuation.definition.string.end.php",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_plus_experimental": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_plus_experimental": "string: #A31515"
}
},
{
"c": ";",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.terminator.expression.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "}",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.definition.end.bracket.curly.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "?",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php punctuation.section.embedded.end.php source.php",
"r": {
"dark_plus": "punctuation.section.embedded.end.php: #569CD6",
"light_plus": "punctuation.section.embedded.end.php: #800000",
"dark_vs": "punctuation.section.embedded.end.php: #569CD6",
"light_vs": "punctuation.section.embedded.end.php: #800000",
"hc_black": "punctuation.section.embedded: #569CD6",
"dark_plus_experimental": "punctuation.section.embedded.end.php: #569CD6",
"hc_light": "punctuation.section.embedded.end.php: #0F4A85",
"light_plus_experimental": "punctuation.section.embedded.end.php: #800000"
}
},
{
"c": ">",
"t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php punctuation.section.embedded.end.php",
"r": {
"dark_plus": "punctuation.section.embedded.end.php: #569CD6",
"light_plus": "punctuation.section.embedded.end.php: #800000",
"dark_vs": "punctuation.section.embedded.end.php: #569CD6",
"light_vs": "punctuation.section.embedded.end.php: #800000",
"hc_black": "punctuation.section.embedded: #569CD6",
"dark_plus_experimental": "punctuation.section.embedded.end.php: #569CD6",
"hc_light": "punctuation.section.embedded.end.php: #0F4A85",
"light_plus_experimental": "punctuation.section.embedded.end.php: #800000"
}
},
{
"c": " ",
"t": "text.html.php meta.embedded.block.html source.js",
"r": {
"dark_plus": "meta.embedded: #D4D4D4",
"light_plus": "meta.embedded: #000000",
"dark_vs": "meta.embedded: #D4D4D4",
"light_vs": "meta.embedded: #000000",
"hc_black": "meta.embedded: #FFFFFF",
"dark_plus_experimental": "meta.embedded: #D4D4D4",
"hc_light": "meta.embedded: #292929",
"light_plus_experimental": "meta.embedded: #000000"
}
},
{
"c": "...",
"t": "text.html.php meta.embedded.block.html source.js keyword.operator.spread.js",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_plus_experimental": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_plus_experimental": "keyword.operator: #000000"
}
},
{
"c": "<",
"t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html source.js-ignored-vscode",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080",
"dark_plus_experimental": "punctuation.definition.tag: #808080",
"hc_light": "punctuation.definition.tag: #0F4A85",
"light_plus_experimental": "punctuation.definition.tag: #800000"
}
},
{
"c": "/",
"t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080",
"dark_plus_experimental": "punctuation.definition.tag: #808080",
"hc_light": "punctuation.definition.tag: #0F4A85",
"light_plus_experimental": "punctuation.definition.tag: #800000"
}
},
{
"c": "script",
"t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.end.html entity.name.tag.html",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6",
"dark_plus_experimental": "entity.name.tag: #569CD6",
"hc_light": "entity.name.tag: #0F4A85",
"light_plus_experimental": "entity.name.tag: #800000"
}
},
{
"c": ">",
"t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.end.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080",
"dark_plus_experimental": "punctuation.definition.tag: #808080",
"hc_light": "punctuation.definition.tag: #0F4A85",
"light_plus_experimental": "punctuation.definition.tag: #800000"
}
}
] | extensions/vscode-colorize-tests/test/colorize-results/issue-28354_php.json | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017730772378854454,
0.0001748984504956752,
0.0001726806949591264,
0.00017475933418609202,
0.0000010436802995172911
] |
{
"id": 1,
"code_window": [
"\t}\n",
"}\n",
"\n",
"export class CellOutputContainer extends CellContentPart {\n",
"\tprivate _outputEntries: OutputEntryViewHandler[] = [];\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const enum CellOutputUpdateContext {\n",
"\tExecution = 1,\n",
"\tOther = 2\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 433
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event';
import { dispose } from 'vs/base/common/lifecycle';
import * as UUID from 'vs/base/common/uuid';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { PrefixSumComputer } from 'vs/editor/common/model/prefixSumComputer';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { CellEditState, CellFindMatch, CodeCellLayoutChangeEvent, CodeCellLayoutInfo, CellLayoutState, ICellOutputViewModel, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CellOutputViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/cellOutputViewModel';
import { ViewContext } from 'vs/workbench/contrib/notebook/browser/viewModel/viewContext';
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { CellKind, INotebookSearchOptions, NotebookCellOutputsSplice } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptionsChangeEvent } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { BaseCellViewModel } from './baseCellViewModel';
import { NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
export class CodeCellViewModel extends BaseCellViewModel implements ICellViewModel {
readonly cellKind = CellKind.Code;
protected readonly _onLayoutInfoRead = this._register(new Emitter<void>());
readonly onLayoutInfoRead = this._onLayoutInfoRead.event;
protected readonly _onDidChangeOutputs = this._register(new Emitter<NotebookCellOutputsSplice>());
readonly onDidChangeOutputs = this._onDidChangeOutputs.event;
private readonly _onDidRemoveOutputs = this._register(new Emitter<readonly ICellOutputViewModel[]>());
readonly onDidRemoveOutputs = this._onDidRemoveOutputs.event;
private _outputCollection: number[] = [];
private _outputsTop: PrefixSumComputer | null = null;
protected _pauseableEmitter = this._register(new PauseableEmitter<CodeCellLayoutChangeEvent>());
readonly onDidChangeLayout = this._pauseableEmitter.event;
private _editorHeight = 0;
set editorHeight(height: number) {
this._editorHeight = height;
this.layoutChange({ editorHeight: true }, 'CodeCellViewModel#editorHeight');
}
get editorHeight() {
throw new Error('editorHeight is write-only');
}
private _commentHeight = 0;
set commentHeight(height: number) {
if (this._commentHeight === height) {
return;
}
this._commentHeight = height;
this.layoutChange({ commentHeight: true }, 'CodeCellViewModel#commentHeight');
}
private _hoveringOutput: boolean = false;
public get outputIsHovered(): boolean {
return this._hoveringOutput;
}
public set outputIsHovered(v: boolean) {
this._hoveringOutput = v;
this._onDidChangeState.fire({ outputIsHoveredChanged: true });
}
private _focusOnOutput: boolean = false;
public get outputIsFocused(): boolean {
return this._focusOnOutput;
}
public set outputIsFocused(v: boolean) {
this._focusOnOutput = v;
this._onDidChangeState.fire({ outputIsFocusedChanged: true });
}
private _outputMinHeight: number = 0;
private get outputMinHeight() {
return this._outputMinHeight;
}
/**
* The minimum height of the output region. It's only set to non-zero temporarily when replacing an output with a new one.
* It's reset to 0 when the new output is rendered, or in one second.
*/
private set outputMinHeight(newMin: number) {
this._outputMinHeight = newMin;
}
private _layoutInfo: CodeCellLayoutInfo;
get layoutInfo() {
return this._layoutInfo;
}
private _outputViewModels: ICellOutputViewModel[];
get outputsViewModels() {
return this._outputViewModels;
}
constructor(
viewType: string,
model: NotebookCellTextModel,
initialNotebookLayoutInfo: NotebookLayoutInfo | null,
readonly viewContext: ViewContext,
@IConfigurationService configurationService: IConfigurationService,
@INotebookService private readonly _notebookService: INotebookService,
@ITextModelService modelService: ITextModelService,
@IUndoRedoService undoRedoService: IUndoRedoService,
@ICodeEditorService codeEditorService: ICodeEditorService
) {
super(viewType, model, UUID.generateUuid(), viewContext, configurationService, modelService, undoRedoService, codeEditorService);
this._outputViewModels = this.model.outputs.map(output => new CellOutputViewModel(this, output, this._notebookService));
this._register(this.model.onDidChangeOutputs((splice) => {
const removedOutputs: ICellOutputViewModel[] = [];
let outputLayoutChange = false;
for (let i = splice.start; i < splice.start + splice.deleteCount; i++) {
if (this._outputCollection[i] !== undefined && this._outputCollection[i] !== 0) {
outputLayoutChange = true;
}
}
this._outputCollection.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(() => 0));
removedOutputs.push(...this._outputViewModels.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(output => new CellOutputViewModel(this, output, this._notebookService))));
this._outputsTop = null;
this._onDidChangeOutputs.fire(splice);
this._onDidRemoveOutputs.fire(removedOutputs);
if (outputLayoutChange) {
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#model.onDidChangeOutputs');
}
dispose(removedOutputs);
}));
this._outputCollection = new Array(this.model.outputs.length);
this._layoutInfo = {
fontInfo: initialNotebookLayoutInfo?.fontInfo || null,
editorHeight: 0,
editorWidth: initialNotebookLayoutInfo
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(initialNotebookLayoutInfo.width)
: 0,
statusBarHeight: 0,
commentHeight: 0,
outputContainerOffset: 0,
outputTotalHeight: 0,
outputShowMoreContainerHeight: 0,
outputShowMoreContainerOffset: 0,
totalHeight: this.computeTotalHeight(17, 0, 0),
codeIndicatorHeight: 0,
outputIndicatorHeight: 0,
bottomToolbarOffset: 0,
layoutState: CellLayoutState.Uninitialized,
estimatedHasHorizontalScrolling: false
};
}
updateOptions(e: NotebookOptionsChangeEvent) {
if (e.cellStatusBarVisibility || e.insertToolbarPosition || e.cellToolbarLocation) {
this.layoutChange({});
}
}
pauseLayout() {
this._pauseableEmitter.pause();
}
resumeLayout() {
this._pauseableEmitter.resume();
}
layoutChange(state: CodeCellLayoutChangeEvent, source?: string) {
// recompute
this._ensureOutputsTop();
const notebookLayoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const bottomToolbarDimensions = this.viewContext.notebookOptions.computeBottomToolbarDimensions();
const outputShowMoreContainerHeight = state.outputShowMoreContainerHeight ? state.outputShowMoreContainerHeight : this._layoutInfo.outputShowMoreContainerHeight;
const outputTotalHeight = Math.max(this._outputMinHeight, this.isOutputCollapsed ? notebookLayoutConfiguration.collapsedIndicatorHeight : this._outputsTop!.getTotalSum());
const commentHeight = state.commentHeight ? this._commentHeight : this._layoutInfo.commentHeight;
const originalLayout = this.layoutInfo;
if (!this.isInputCollapsed) {
let newState: CellLayoutState;
let editorHeight: number;
let totalHeight: number;
let hasHorizontalScrolling = false;
if (!state.editorHeight && this._layoutInfo.layoutState === CellLayoutState.FromCache && !state.outputHeight) {
// No new editorHeight info - keep cached totalHeight and estimate editorHeight
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this._layoutInfo.totalHeight;
newState = CellLayoutState.FromCache;
} else if (state.editorHeight || this._layoutInfo.layoutState === CellLayoutState.Measured) {
// Editor has been measured
editorHeight = this._editorHeight;
totalHeight = this.computeTotalHeight(this._editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Measured;
hasHorizontalScrolling = this._layoutInfo.estimatedHasHorizontalScrolling;
} else {
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this.computeTotalHeight(editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Estimated;
}
const statusBarHeight = this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri);
const codeIndicatorHeight = editorHeight + statusBarHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.editorToolbarHeight
+ notebookLayoutConfiguration.cellTopMargin // CELL_TOP_MARGIN
+ editorHeight
+ statusBarHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight,
editorWidth,
statusBarHeight,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: newState,
estimatedHasHorizontalScrolling: hasHorizontalScrolling
};
} else {
const codeIndicatorHeight = notebookLayoutConfiguration.collapsedIndicatorHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.cellTopMargin + notebookLayoutConfiguration.collapsedIndicatorHeight;
const totalHeight =
notebookLayoutConfiguration.cellTopMargin
+ notebookLayoutConfiguration.collapsedIndicatorHeight
+ notebookLayoutConfiguration.cellBottomMargin //CELL_BOTTOM_MARGIN
+ bottomToolbarDimensions.bottomToolbarGap //BOTTOM_CELL_TOOLBAR_GAP
+ commentHeight
+ outputTotalHeight + outputShowMoreContainerHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight: this._layoutInfo.editorHeight,
editorWidth,
statusBarHeight: 0,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: this._layoutInfo.layoutState,
estimatedHasHorizontalScrolling: false
};
}
this._fireOnDidChangeLayout({
...state,
totalHeight: this.layoutInfo.totalHeight !== originalLayout.totalHeight,
source,
});
}
private _fireOnDidChangeLayout(state: CodeCellLayoutChangeEvent) {
this._pauseableEmitter.fire(state);
}
override restoreEditorViewState(editorViewStates: editorCommon.ICodeEditorViewState | null, totalHeight?: number) {
super.restoreEditorViewState(editorViewStates);
if (totalHeight !== undefined && this._layoutInfo.layoutState !== CellLayoutState.Measured) {
this._layoutInfo = {
fontInfo: this._layoutInfo.fontInfo,
editorHeight: this._layoutInfo.editorHeight,
editorWidth: this._layoutInfo.editorWidth,
statusBarHeight: this.layoutInfo.statusBarHeight,
commentHeight: this.layoutInfo.commentHeight,
outputContainerOffset: this._layoutInfo.outputContainerOffset,
outputTotalHeight: this._layoutInfo.outputTotalHeight,
outputShowMoreContainerHeight: this._layoutInfo.outputShowMoreContainerHeight,
outputShowMoreContainerOffset: this._layoutInfo.outputShowMoreContainerOffset,
totalHeight: totalHeight,
codeIndicatorHeight: this._layoutInfo.codeIndicatorHeight,
outputIndicatorHeight: this._layoutInfo.outputIndicatorHeight,
bottomToolbarOffset: this._layoutInfo.bottomToolbarOffset,
layoutState: CellLayoutState.FromCache,
estimatedHasHorizontalScrolling: this._layoutInfo.estimatedHasHorizontalScrolling
};
}
}
hasDynamicHeight() {
// CodeCellVM always measures itself and controls its cell's height
return false;
}
getDynamicHeight() {
this._onLayoutInfoRead.fire();
return this._layoutInfo.totalHeight;
}
getHeight(lineHeight: number) {
if (this._layoutInfo.layoutState === CellLayoutState.Uninitialized) {
const estimate = this.estimateEditorHeight(lineHeight);
return this.computeTotalHeight(estimate.editorHeight, 0, 0);
} else {
return this._layoutInfo.totalHeight;
}
}
private estimateEditorHeight(lineHeight: number | undefined = 20): { editorHeight: number; hasHorizontalScrolling: boolean } {
let hasHorizontalScrolling = false;
const cellEditorOptions = this.viewContext.getBaseCellEditorOptions(this.language);
if (this.layoutInfo.fontInfo && cellEditorOptions.value.wordWrap === 'off') {
for (let i = 0; i < this.lineCount; i++) {
const max = this.textBuffer.getLineLastNonWhitespaceColumn(i + 1);
const estimatedWidth = max * (this.layoutInfo.fontInfo.typicalHalfwidthCharacterWidth + this.layoutInfo.fontInfo.letterSpacing);
if (estimatedWidth > this.layoutInfo.editorWidth) {
hasHorizontalScrolling = true;
break;
}
}
}
const verticalScrollbarHeight = hasHorizontalScrolling ? 12 : 0; // take zoom level into account
const editorPadding = this.viewContext.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
const editorHeight = this.lineCount * lineHeight
+ editorPadding.top
+ editorPadding.bottom // EDITOR_BOTTOM_PADDING
+ verticalScrollbarHeight;
return {
editorHeight,
hasHorizontalScrolling
};
}
private computeTotalHeight(editorHeight: number, outputsTotalHeight: number, outputShowMoreContainerHeight: number): number {
const layoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const { bottomToolbarGap } = this.viewContext.notebookOptions.computeBottomToolbarDimensions(this.viewType);
return layoutConfiguration.editorToolbarHeight
+ layoutConfiguration.cellTopMargin
+ editorHeight
+ this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri)
+ this._commentHeight
+ outputsTotalHeight
+ outputShowMoreContainerHeight
+ bottomToolbarGap
+ layoutConfiguration.cellBottomMargin;
}
protected onDidChangeTextModelContent(): void {
if (this.getEditState() !== CellEditState.Editing) {
this.updateEditState(CellEditState.Editing, 'onDidChangeTextModelContent');
this._onDidChangeState.fire({ contentChanged: true });
}
}
onDeselect() {
this.updateEditState(CellEditState.Preview, 'onDeselect');
}
updateOutputShowMoreContainerHeight(height: number) {
this.layoutChange({ outputShowMoreContainerHeight: height }, 'CodeCellViewModel#updateOutputShowMoreContainerHeight');
}
updateOutputMinHeight(height: number) {
this.outputMinHeight = height;
}
unlockOutputHeight() {
this.outputMinHeight = 0;
this.layoutChange({ outputHeight: true });
}
updateOutputHeight(index: number, height: number, source?: string) {
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
this._ensureOutputsTop();
if (height < 28 && this._outputViewModels[index].hasMultiMimeType()) {
height = 28;
}
this._outputCollection[index] = height;
if (this._outputsTop!.setValue(index, height)) {
this.layoutChange({ outputHeight: true }, source);
}
}
getOutputOffsetInContainer(index: number) {
this._ensureOutputsTop();
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
return this._outputsTop!.getPrefixSum(index - 1);
}
getOutputOffset(index: number): number {
return this.layoutInfo.outputContainerOffset + this.getOutputOffsetInContainer(index);
}
spliceOutputHeights(start: number, deleteCnt: number, heights: number[]) {
this._ensureOutputsTop();
this._outputsTop!.removeValues(start, deleteCnt);
if (heights.length) {
const values = new Uint32Array(heights.length);
for (let i = 0; i < heights.length; i++) {
values[i] = heights[i];
}
this._outputsTop!.insertValues(start, values);
}
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#spliceOutputs');
}
private _ensureOutputsTop(): void {
if (!this._outputsTop) {
const values = new Uint32Array(this._outputCollection.length);
for (let i = 0; i < this._outputCollection.length; i++) {
values[i] = this._outputCollection[i];
}
this._outputsTop = new PrefixSumComputer(values);
}
}
private readonly _hasFindResult = this._register(new Emitter<boolean>());
public readonly hasFindResult: Event<boolean> = this._hasFindResult.event;
startFind(value: string, options: INotebookSearchOptions): CellFindMatch | null {
const matches = super.cellStartFind(value, options);
if (matches === null) {
return null;
}
return {
cell: this,
contentMatches: matches
};
}
override dispose() {
super.dispose();
this._outputCollection = [];
this._outputsTop = null;
dispose(this._outputViewModels);
}
}
| src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.9949560761451721,
0.16646042466163635,
0.00016772134404163808,
0.0009102600160986185,
0.3360966444015503
] |
{
"id": 1,
"code_window": [
"\t}\n",
"}\n",
"\n",
"export class CellOutputContainer extends CellContentPart {\n",
"\tprivate _outputEntries: OutputEntryViewHandler[] = [];\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const enum CellOutputUpdateContext {\n",
"\tExecution = 1,\n",
"\tOther = 2\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 433
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import * as sinon from 'sinon';
import { Emitter } from 'vs/base/common/event';
import { ExtHostTreeViews } from 'vs/workbench/api/common/extHostTreeViews';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { MainThreadTreeViewsShape, MainContext } from 'vs/workbench/api/common/extHost.protocol';
import { TreeDataProvider, TreeItem } from 'vscode';
import { TestRPCProtocol } from 'vs/workbench/api/test/common/testRPCProtocol';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { MainThreadCommands } from 'vs/workbench/api/browser/mainThreadCommands';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { mock } from 'vs/base/test/common/mock';
import { TreeItemCollapsibleState, ITreeItem, IRevealOptions } from 'vs/workbench/common/views';
import { NullLogService } from 'vs/platform/log/common/log';
import type { IDisposable } from 'vs/base/common/lifecycle';
import { nullExtensionDescription as extensionsDescription } from 'vs/workbench/services/extensions/common/extensions';
import { runWithFakedTimers } from 'vs/base/test/common/timeTravelScheduler';
suite('ExtHostTreeView', function () {
class RecordingShape extends mock<MainThreadTreeViewsShape>() {
onRefresh = new Emitter<{ [treeItemHandle: string]: ITreeItem }>();
override async $registerTreeViewDataProvider(treeViewId: string): Promise<void> {
}
override $refresh(viewId: string, itemsToRefresh: { [treeItemHandle: string]: ITreeItem }): Promise<void> {
return Promise.resolve(null).then(() => {
this.onRefresh.fire(itemsToRefresh);
});
}
override $reveal(treeViewId: string, itemInfo: { item: ITreeItem; parentChain: ITreeItem[] } | undefined, options: IRevealOptions): Promise<void> {
return Promise.resolve();
}
}
let testObject: ExtHostTreeViews;
let target: RecordingShape;
let onDidChangeTreeNode: Emitter<{ key: string } | undefined>;
let onDidChangeTreeNodeWithId: Emitter<{ key: string }>;
let tree: { [key: string]: any };
let labels: { [key: string]: string };
let nodes: { [key: string]: { key: string } };
setup(() => {
tree = {
'a': {
'aa': {},
'ab': {}
},
'b': {
'ba': {},
'bb': {}
}
};
labels = {};
nodes = {};
const rpcProtocol = new TestRPCProtocol();
// Use IInstantiationService to get typechecking when instantiating
let inst: IInstantiationService;
{
const instantiationService = new TestInstantiationService();
inst = instantiationService;
}
rpcProtocol.set(MainContext.MainThreadCommands, inst.createInstance(MainThreadCommands, rpcProtocol));
target = new RecordingShape();
testObject = new ExtHostTreeViews(target, new ExtHostCommands(
rpcProtocol,
new NullLogService()
), new NullLogService());
onDidChangeTreeNode = new Emitter<{ key: string } | undefined>();
onDidChangeTreeNodeWithId = new Emitter<{ key: string }>();
testObject.createTreeView('testNodeTreeProvider', { treeDataProvider: aNodeTreeDataProvider() }, extensionsDescription);
testObject.createTreeView('testNodeWithIdTreeProvider', { treeDataProvider: aNodeWithIdTreeDataProvider() }, extensionsDescription);
testObject.createTreeView('testNodeWithHighlightsTreeProvider', { treeDataProvider: aNodeWithHighlightedLabelTreeDataProvider() }, extensionsDescription);
return loadCompleteTree('testNodeTreeProvider');
});
test('construct node tree', () => {
return testObject.$getChildren('testNodeTreeProvider')
.then(elements => {
const actuals = elements?.map(e => e.handle);
assert.deepStrictEqual(actuals, ['0/0:a', '0/0:b']);
return Promise.all([
testObject.$getChildren('testNodeTreeProvider', '0/0:a')
.then(children => {
const actuals = children?.map(e => e.handle);
assert.deepStrictEqual(actuals, ['0/0:a/0:aa', '0/0:a/0:ab']);
return Promise.all([
testObject.$getChildren('testNodeTreeProvider', '0/0:a/0:aa').then(children => assert.strictEqual(children?.length, 0)),
testObject.$getChildren('testNodeTreeProvider', '0/0:a/0:ab').then(children => assert.strictEqual(children?.length, 0))
]);
}),
testObject.$getChildren('testNodeTreeProvider', '0/0:b')
.then(children => {
const actuals = children?.map(e => e.handle);
assert.deepStrictEqual(actuals, ['0/0:b/0:ba', '0/0:b/0:bb']);
return Promise.all([
testObject.$getChildren('testNodeTreeProvider', '0/0:b/0:ba').then(children => assert.strictEqual(children?.length, 0)),
testObject.$getChildren('testNodeTreeProvider', '0/0:b/0:bb').then(children => assert.strictEqual(children?.length, 0))
]);
})
]);
});
});
test('construct id tree', () => {
return testObject.$getChildren('testNodeWithIdTreeProvider')
.then(elements => {
const actuals = elements?.map(e => e.handle);
assert.deepStrictEqual(actuals, ['1/a', '1/b']);
return Promise.all([
testObject.$getChildren('testNodeWithIdTreeProvider', '1/a')
.then(children => {
const actuals = children?.map(e => e.handle);
assert.deepStrictEqual(actuals, ['1/aa', '1/ab']);
return Promise.all([
testObject.$getChildren('testNodeWithIdTreeProvider', '1/aa').then(children => assert.strictEqual(children?.length, 0)),
testObject.$getChildren('testNodeWithIdTreeProvider', '1/ab').then(children => assert.strictEqual(children?.length, 0))
]);
}),
testObject.$getChildren('testNodeWithIdTreeProvider', '1/b')
.then(children => {
const actuals = children?.map(e => e.handle);
assert.deepStrictEqual(actuals, ['1/ba', '1/bb']);
return Promise.all([
testObject.$getChildren('testNodeWithIdTreeProvider', '1/ba').then(children => assert.strictEqual(children?.length, 0)),
testObject.$getChildren('testNodeWithIdTreeProvider', '1/bb').then(children => assert.strictEqual(children?.length, 0))
]);
})
]);
});
});
test('construct highlights tree', () => {
return testObject.$getChildren('testNodeWithHighlightsTreeProvider')
.then(elements => {
assert.deepStrictEqual(removeUnsetKeys(elements), [{
handle: '1/a',
label: { label: 'a', highlights: [[0, 2], [3, 5]] },
collapsibleState: TreeItemCollapsibleState.Collapsed
}, {
handle: '1/b',
label: { label: 'b', highlights: [[0, 2], [3, 5]] },
collapsibleState: TreeItemCollapsibleState.Collapsed
}]);
return Promise.all([
testObject.$getChildren('testNodeWithHighlightsTreeProvider', '1/a')
.then(children => {
assert.deepStrictEqual(removeUnsetKeys(children), [{
handle: '1/aa',
parentHandle: '1/a',
label: { label: 'aa', highlights: [[0, 2], [3, 5]] },
collapsibleState: TreeItemCollapsibleState.None
}, {
handle: '1/ab',
parentHandle: '1/a',
label: { label: 'ab', highlights: [[0, 2], [3, 5]] },
collapsibleState: TreeItemCollapsibleState.None
}]);
}),
testObject.$getChildren('testNodeWithHighlightsTreeProvider', '1/b')
.then(children => {
assert.deepStrictEqual(removeUnsetKeys(children), [{
handle: '1/ba',
parentHandle: '1/b',
label: { label: 'ba', highlights: [[0, 2], [3, 5]] },
collapsibleState: TreeItemCollapsibleState.None
}, {
handle: '1/bb',
parentHandle: '1/b',
label: { label: 'bb', highlights: [[0, 2], [3, 5]] },
collapsibleState: TreeItemCollapsibleState.None
}]);
})
]);
});
});
test('error is thrown if id is not unique', (done) => {
tree['a'] = {
'aa': {},
};
tree['b'] = {
'aa': {},
'ba': {}
};
let caughtExpectedError = false;
target.onRefresh.event(() => {
testObject.$getChildren('testNodeWithIdTreeProvider')
.then(elements => {
const actuals = elements?.map(e => e.handle);
assert.deepStrictEqual(actuals, ['1/a', '1/b']);
return testObject.$getChildren('testNodeWithIdTreeProvider', '1/a')
.then(() => testObject.$getChildren('testNodeWithIdTreeProvider', '1/b'))
.then(() => assert.fail('Should fail with duplicate id'))
.catch(() => caughtExpectedError = true)
.finally(() => caughtExpectedError ? done() : assert.fail('Expected duplicate id error not thrown.'));
});
});
onDidChangeTreeNode.fire(undefined);
});
test('refresh root', function (done) {
target.onRefresh.event(actuals => {
assert.strictEqual(undefined, actuals);
done();
});
onDidChangeTreeNode.fire(undefined);
});
test('refresh a parent node', () => {
return new Promise((c, e) => {
target.onRefresh.event(actuals => {
assert.deepStrictEqual(['0/0:b'], Object.keys(actuals));
assert.deepStrictEqual(removeUnsetKeys(actuals['0/0:b']), {
handle: '0/0:b',
label: { label: 'b' },
collapsibleState: TreeItemCollapsibleState.Collapsed
});
c(undefined);
});
onDidChangeTreeNode.fire(getNode('b'));
});
});
test('refresh a leaf node', function (done) {
target.onRefresh.event(actuals => {
assert.deepStrictEqual(['0/0:b/0:bb'], Object.keys(actuals));
assert.deepStrictEqual(removeUnsetKeys(actuals['0/0:b/0:bb']), {
handle: '0/0:b/0:bb',
parentHandle: '0/0:b',
label: { label: 'bb' },
collapsibleState: TreeItemCollapsibleState.None
});
done();
});
onDidChangeTreeNode.fire(getNode('bb'));
});
async function runWithEventMerging(action: (resolve: () => void) => void) {
await runWithFakedTimers({}, async () => {
await new Promise<void>((resolve) => {
let subscription: IDisposable | undefined = undefined;
subscription = target.onRefresh.event(() => {
subscription!.dispose();
resolve();
});
onDidChangeTreeNode.fire(getNode('b'));
});
await new Promise<void>(action);
});
}
test('refresh parent and child node trigger refresh only on parent - scenario 1', async () => {
return runWithEventMerging((resolve) => {
target.onRefresh.event(actuals => {
assert.deepStrictEqual(['0/0:b', '0/0:a/0:aa'], Object.keys(actuals));
assert.deepStrictEqual(removeUnsetKeys(actuals['0/0:b']), {
handle: '0/0:b',
label: { label: 'b' },
collapsibleState: TreeItemCollapsibleState.Collapsed
});
assert.deepStrictEqual(removeUnsetKeys(actuals['0/0:a/0:aa']), {
handle: '0/0:a/0:aa',
parentHandle: '0/0:a',
label: { label: 'aa' },
collapsibleState: TreeItemCollapsibleState.None
});
resolve();
});
onDidChangeTreeNode.fire(getNode('b'));
onDidChangeTreeNode.fire(getNode('aa'));
onDidChangeTreeNode.fire(getNode('bb'));
});
});
test('refresh parent and child node trigger refresh only on parent - scenario 2', async () => {
return runWithEventMerging((resolve) => {
target.onRefresh.event(actuals => {
assert.deepStrictEqual(['0/0:a/0:aa', '0/0:b'], Object.keys(actuals));
assert.deepStrictEqual(removeUnsetKeys(actuals['0/0:b']), {
handle: '0/0:b',
label: { label: 'b' },
collapsibleState: TreeItemCollapsibleState.Collapsed
});
assert.deepStrictEqual(removeUnsetKeys(actuals['0/0:a/0:aa']), {
handle: '0/0:a/0:aa',
parentHandle: '0/0:a',
label: { label: 'aa' },
collapsibleState: TreeItemCollapsibleState.None
});
resolve();
});
onDidChangeTreeNode.fire(getNode('bb'));
onDidChangeTreeNode.fire(getNode('aa'));
onDidChangeTreeNode.fire(getNode('b'));
});
});
test('refresh an element for label change', function (done) {
labels['a'] = 'aa';
target.onRefresh.event(actuals => {
assert.deepStrictEqual(['0/0:a'], Object.keys(actuals));
assert.deepStrictEqual(removeUnsetKeys(actuals['0/0:a']), {
handle: '0/0:aa',
label: { label: 'aa' },
collapsibleState: TreeItemCollapsibleState.Collapsed
});
done();
});
onDidChangeTreeNode.fire(getNode('a'));
});
test('refresh calls are throttled on roots', () => {
return runWithEventMerging((resolve) => {
target.onRefresh.event(actuals => {
assert.strictEqual(undefined, actuals);
resolve();
});
onDidChangeTreeNode.fire(undefined);
onDidChangeTreeNode.fire(undefined);
onDidChangeTreeNode.fire(undefined);
onDidChangeTreeNode.fire(undefined);
});
});
test('refresh calls are throttled on elements', () => {
return runWithEventMerging((resolve) => {
target.onRefresh.event(actuals => {
assert.deepStrictEqual(['0/0:a', '0/0:b'], Object.keys(actuals));
resolve();
});
onDidChangeTreeNode.fire(getNode('a'));
onDidChangeTreeNode.fire(getNode('b'));
onDidChangeTreeNode.fire(getNode('b'));
onDidChangeTreeNode.fire(getNode('a'));
});
});
test('refresh calls are throttled on unknown elements', () => {
return runWithEventMerging((resolve) => {
target.onRefresh.event(actuals => {
assert.deepStrictEqual(['0/0:a', '0/0:b'], Object.keys(actuals));
resolve();
});
onDidChangeTreeNode.fire(getNode('a'));
onDidChangeTreeNode.fire(getNode('b'));
onDidChangeTreeNode.fire(getNode('g'));
onDidChangeTreeNode.fire(getNode('a'));
});
});
test('refresh calls are throttled on unknown elements and root', () => {
return runWithEventMerging((resolve) => {
target.onRefresh.event(actuals => {
assert.strictEqual(undefined, actuals);
resolve();
});
onDidChangeTreeNode.fire(getNode('a'));
onDidChangeTreeNode.fire(getNode('b'));
onDidChangeTreeNode.fire(getNode('g'));
onDidChangeTreeNode.fire(undefined);
});
});
test('refresh calls are throttled on elements and root', () => {
return runWithEventMerging((resolve) => {
target.onRefresh.event(actuals => {
assert.strictEqual(undefined, actuals);
resolve();
});
onDidChangeTreeNode.fire(getNode('a'));
onDidChangeTreeNode.fire(getNode('b'));
onDidChangeTreeNode.fire(undefined);
onDidChangeTreeNode.fire(getNode('a'));
});
});
test('generate unique handles from labels by escaping them', (done) => {
tree = {
'a/0:b': {}
};
target.onRefresh.event(() => {
testObject.$getChildren('testNodeTreeProvider')
.then(elements => {
assert.deepStrictEqual(elements?.map(e => e.handle), ['0/0:a//0:b']);
done();
});
});
onDidChangeTreeNode.fire(undefined);
});
test('tree with duplicate labels', (done) => {
const dupItems = {
'adup1': 'c',
'adup2': 'g',
'bdup1': 'e',
'hdup1': 'i',
'hdup2': 'l',
'jdup1': 'k'
};
labels['c'] = 'a';
labels['e'] = 'b';
labels['g'] = 'a';
labels['i'] = 'h';
labels['l'] = 'h';
labels['k'] = 'j';
tree[dupItems['adup1']] = {};
tree['d'] = {};
const bdup1Tree: { [key: string]: any } = {};
bdup1Tree['h'] = {};
bdup1Tree[dupItems['hdup1']] = {};
bdup1Tree['j'] = {};
bdup1Tree[dupItems['jdup1']] = {};
bdup1Tree[dupItems['hdup2']] = {};
tree[dupItems['bdup1']] = bdup1Tree;
tree['f'] = {};
tree[dupItems['adup2']] = {};
target.onRefresh.event(() => {
testObject.$getChildren('testNodeTreeProvider')
.then(elements => {
const actuals = elements?.map(e => e.handle);
assert.deepStrictEqual(actuals, ['0/0:a', '0/0:b', '0/1:a', '0/0:d', '0/1:b', '0/0:f', '0/2:a']);
return testObject.$getChildren('testNodeTreeProvider', '0/1:b')
.then(elements => {
const actuals = elements?.map(e => e.handle);
assert.deepStrictEqual(actuals, ['0/1:b/0:h', '0/1:b/1:h', '0/1:b/0:j', '0/1:b/1:j', '0/1:b/2:h']);
done();
});
});
});
onDidChangeTreeNode.fire(undefined);
});
test('getChildren is not returned from cache if refreshed', (done) => {
tree = {
'c': {}
};
target.onRefresh.event(() => {
testObject.$getChildren('testNodeTreeProvider')
.then(elements => {
assert.deepStrictEqual(elements?.map(e => e.handle), ['0/0:c']);
done();
});
});
onDidChangeTreeNode.fire(undefined);
});
test('getChildren is returned from cache if not refreshed', () => {
tree = {
'c': {}
};
return testObject.$getChildren('testNodeTreeProvider')
.then(elements => {
assert.deepStrictEqual(elements?.map(e => e.handle), ['0/0:a', '0/0:b']);
});
});
test('reveal will throw an error if getParent is not implemented', () => {
const treeView = testObject.createTreeView('treeDataProvider', { treeDataProvider: aNodeTreeDataProvider() }, extensionsDescription);
return treeView.reveal({ key: 'a' })
.then(() => assert.fail('Reveal should throw an error as getParent is not implemented'), () => null);
});
test('reveal will return empty array for root element', () => {
const revealTarget = sinon.spy(target, '$reveal');
const treeView = testObject.createTreeView('treeDataProvider', { treeDataProvider: aCompleteNodeTreeDataProvider() }, extensionsDescription);
const expected = {
item:
{ handle: '0/0:a', label: { label: 'a' }, collapsibleState: TreeItemCollapsibleState.Collapsed },
parentChain: []
};
return treeView.reveal({ key: 'a' })
.then(() => {
assert.ok(revealTarget.calledOnce);
assert.deepStrictEqual('treeDataProvider', revealTarget.args[0][0]);
assert.deepStrictEqual(expected, removeUnsetKeys(revealTarget.args[0][1]));
assert.deepStrictEqual({ select: true, focus: false, expand: false }, revealTarget.args[0][2]);
});
});
test('reveal will return parents array for an element when hierarchy is not loaded', () => {
const revealTarget = sinon.spy(target, '$reveal');
const treeView = testObject.createTreeView('treeDataProvider', { treeDataProvider: aCompleteNodeTreeDataProvider() }, extensionsDescription);
const expected = {
item: { handle: '0/0:a/0:aa', label: { label: 'aa' }, collapsibleState: TreeItemCollapsibleState.None, parentHandle: '0/0:a' },
parentChain: [{ handle: '0/0:a', label: { label: 'a' }, collapsibleState: TreeItemCollapsibleState.Collapsed }]
};
return treeView.reveal({ key: 'aa' })
.then(() => {
assert.ok(revealTarget.calledOnce);
assert.deepStrictEqual('treeDataProvider', revealTarget.args[0][0]);
assert.deepStrictEqual(expected.item, removeUnsetKeys(revealTarget.args[0][1]!.item));
assert.deepStrictEqual(expected.parentChain, (<Array<any>>(revealTarget.args[0][1]!.parentChain)).map(arg => removeUnsetKeys(arg)));
assert.deepStrictEqual({ select: true, focus: false, expand: false }, revealTarget.args[0][2]);
});
});
test('reveal will return parents array for an element when hierarchy is loaded', () => {
const revealTarget = sinon.spy(target, '$reveal');
const treeView = testObject.createTreeView('treeDataProvider', { treeDataProvider: aCompleteNodeTreeDataProvider() }, extensionsDescription);
const expected = {
item: { handle: '0/0:a/0:aa', label: { label: 'aa' }, collapsibleState: TreeItemCollapsibleState.None, parentHandle: '0/0:a' },
parentChain: [{ handle: '0/0:a', label: { label: 'a' }, collapsibleState: TreeItemCollapsibleState.Collapsed }]
};
return testObject.$getChildren('treeDataProvider')
.then(() => testObject.$getChildren('treeDataProvider', '0/0:a'))
.then(() => treeView.reveal({ key: 'aa' })
.then(() => {
assert.ok(revealTarget.calledOnce);
assert.deepStrictEqual('treeDataProvider', revealTarget.args[0][0]);
assert.deepStrictEqual(expected.item, removeUnsetKeys(revealTarget.args[0][1]!.item));
assert.deepStrictEqual(expected.parentChain, (<Array<any>>(revealTarget.args[0][1]!.parentChain)).map(arg => removeUnsetKeys(arg)));
assert.deepStrictEqual({ select: true, focus: false, expand: false }, revealTarget.args[0][2]);
}));
});
test('reveal will return parents array for deeper element with no selection', () => {
tree = {
'b': {
'ba': {
'bac': {}
}
}
};
const revealTarget = sinon.spy(target, '$reveal');
const treeView = testObject.createTreeView('treeDataProvider', { treeDataProvider: aCompleteNodeTreeDataProvider() }, extensionsDescription);
const expected = {
item: { handle: '0/0:b/0:ba/0:bac', label: { label: 'bac' }, collapsibleState: TreeItemCollapsibleState.None, parentHandle: '0/0:b/0:ba' },
parentChain: [
{ handle: '0/0:b', label: { label: 'b' }, collapsibleState: TreeItemCollapsibleState.Collapsed },
{ handle: '0/0:b/0:ba', label: { label: 'ba' }, collapsibleState: TreeItemCollapsibleState.Collapsed, parentHandle: '0/0:b' }
]
};
return treeView.reveal({ key: 'bac' }, { select: false, focus: false, expand: false })
.then(() => {
assert.ok(revealTarget.calledOnce);
assert.deepStrictEqual('treeDataProvider', revealTarget.args[0][0]);
assert.deepStrictEqual(expected.item, removeUnsetKeys(revealTarget.args[0][1]!.item));
assert.deepStrictEqual(expected.parentChain, (<Array<any>>(revealTarget.args[0][1]!.parentChain)).map(arg => removeUnsetKeys(arg)));
assert.deepStrictEqual({ select: false, focus: false, expand: false }, revealTarget.args[0][2]);
});
});
test('reveal after first udpate', () => {
const revealTarget = sinon.spy(target, '$reveal');
const treeView = testObject.createTreeView('treeDataProvider', { treeDataProvider: aCompleteNodeTreeDataProvider() }, extensionsDescription);
const expected = {
item: { handle: '0/0:a/0:ac', label: { label: 'ac' }, collapsibleState: TreeItemCollapsibleState.None, parentHandle: '0/0:a' },
parentChain: [{ handle: '0/0:a', label: { label: 'a' }, collapsibleState: TreeItemCollapsibleState.Collapsed }]
};
return loadCompleteTree('treeDataProvider')
.then(() => {
tree = {
'a': {
'aa': {},
'ac': {}
},
'b': {
'ba': {},
'bb': {}
}
};
onDidChangeTreeNode.fire(getNode('a'));
return treeView.reveal({ key: 'ac' })
.then(() => {
assert.ok(revealTarget.calledOnce);
assert.deepStrictEqual('treeDataProvider', revealTarget.args[0][0]);
assert.deepStrictEqual(expected.item, removeUnsetKeys(revealTarget.args[0][1]!.item));
assert.deepStrictEqual(expected.parentChain, (<Array<any>>(revealTarget.args[0][1]!.parentChain)).map(arg => removeUnsetKeys(arg)));
assert.deepStrictEqual({ select: true, focus: false, expand: false }, revealTarget.args[0][2]);
});
});
});
test('reveal after second udpate', () => {
const revealTarget = sinon.spy(target, '$reveal');
const treeView = testObject.createTreeView('treeDataProvider', { treeDataProvider: aCompleteNodeTreeDataProvider() }, extensionsDescription);
return loadCompleteTree('treeDataProvider')
.then(() => {
return runWithEventMerging((resolve) => {
tree = {
'a': {
'aa': {},
'ac': {}
},
'b': {
'ba': {},
'bb': {}
}
};
onDidChangeTreeNode.fire(getNode('a'));
tree = {
'a': {
'aa': {},
'ac': {}
},
'b': {
'ba': {},
'bc': {}
}
};
onDidChangeTreeNode.fire(getNode('b'));
resolve();
}).then(() => {
return treeView.reveal({ key: 'bc' })
.then(() => {
assert.ok(revealTarget.calledOnce);
assert.deepStrictEqual('treeDataProvider', revealTarget.args[0][0]);
assert.deepStrictEqual({ handle: '0/0:b/0:bc', label: { label: 'bc' }, collapsibleState: TreeItemCollapsibleState.None, parentHandle: '0/0:b' }, removeUnsetKeys(revealTarget.args[0][1]!.item));
assert.deepStrictEqual([{ handle: '0/0:b', label: { label: 'b' }, collapsibleState: TreeItemCollapsibleState.Collapsed }], (<Array<any>>revealTarget.args[0][1]!.parentChain).map(arg => removeUnsetKeys(arg)));
assert.deepStrictEqual({ select: true, focus: false, expand: false }, revealTarget.args[0][2]);
});
});
});
});
function loadCompleteTree(treeId: string, element?: string): Promise<null> {
return testObject.$getChildren(treeId, element)
.then(elements => elements?.map(e => loadCompleteTree(treeId, e.handle)))
.then(() => null);
}
function removeUnsetKeys(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(o => removeUnsetKeys(o));
}
if (typeof obj === 'object') {
const result: { [key: string]: any } = {};
for (const key of Object.keys(obj)) {
if (obj[key] !== undefined) {
result[key] = removeUnsetKeys(obj[key]);
}
}
return result;
}
return obj;
}
function aNodeTreeDataProvider(): TreeDataProvider<{ key: string }> {
return {
getChildren: (element: { key: string }): { key: string }[] => {
return getChildren(element ? element.key : undefined).map(key => getNode(key));
},
getTreeItem: (element: { key: string }): TreeItem => {
return getTreeItem(element.key);
},
onDidChangeTreeData: onDidChangeTreeNode.event
};
}
function aCompleteNodeTreeDataProvider(): TreeDataProvider<{ key: string }> {
return {
getChildren: (element: { key: string }): { key: string }[] => {
return getChildren(element ? element.key : undefined).map(key => getNode(key));
},
getTreeItem: (element: { key: string }): TreeItem => {
return getTreeItem(element.key);
},
getParent: ({ key }: { key: string }): { key: string } | undefined => {
const parentKey = key.substring(0, key.length - 1);
return parentKey ? new Key(parentKey) : undefined;
},
onDidChangeTreeData: onDidChangeTreeNode.event
};
}
function aNodeWithIdTreeDataProvider(): TreeDataProvider<{ key: string }> {
return {
getChildren: (element: { key: string }): { key: string }[] => {
return getChildren(element ? element.key : undefined).map(key => getNode(key));
},
getTreeItem: (element: { key: string }): TreeItem => {
const treeItem = getTreeItem(element.key);
treeItem.id = element.key;
return treeItem;
},
onDidChangeTreeData: onDidChangeTreeNodeWithId.event
};
}
function aNodeWithHighlightedLabelTreeDataProvider(): TreeDataProvider<{ key: string }> {
return {
getChildren: (element: { key: string }): { key: string }[] => {
return getChildren(element ? element.key : undefined).map(key => getNode(key));
},
getTreeItem: (element: { key: string }): TreeItem => {
const treeItem = getTreeItem(element.key, [[0, 2], [3, 5]]);
treeItem.id = element.key;
return treeItem;
},
onDidChangeTreeData: onDidChangeTreeNodeWithId.event
};
}
function getTreeElement(element: string): any {
let parent = tree;
for (let i = 0; i < element.length; i++) {
parent = parent[element.substring(0, i + 1)];
if (!parent) {
return null;
}
}
return parent;
}
function getChildren(key: string | undefined): string[] {
if (!key) {
return Object.keys(tree);
}
const treeElement = getTreeElement(key);
if (treeElement) {
return Object.keys(treeElement);
}
return [];
}
function getTreeItem(key: string, highlights?: [number, number][]): TreeItem {
const treeElement = getTreeElement(key);
return {
label: <any>{ label: labels[key] || key, highlights },
collapsibleState: treeElement && Object.keys(treeElement).length ? TreeItemCollapsibleState.Collapsed : TreeItemCollapsibleState.None
};
}
function getNode(key: string): { key: string } {
if (!nodes[key]) {
nodes[key] = new Key(key);
}
return nodes[key];
}
class Key {
constructor(readonly key: string) { }
}
});
| src/vs/workbench/api/test/browser/extHostTreeViews.test.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017884386761579663,
0.00017172236402984709,
0.00016721895372029394,
0.0001715198450256139,
0.000001804118824111356
] |
{
"id": 1,
"code_window": [
"\t}\n",
"}\n",
"\n",
"export class CellOutputContainer extends CellContentPart {\n",
"\tprivate _outputEntries: OutputEntryViewHandler[] = [];\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const enum CellOutputUpdateContext {\n",
"\tExecution = 1,\n",
"\tOther = 2\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 433
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/callHierarchy';
import * as peekView from 'vs/editor/contrib/peekView/browser/peekView';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { CallHierarchyDirection, CallHierarchyModel } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy';
import { WorkbenchAsyncDataTree, IWorkbenchAsyncDataTreeOptions } from 'vs/platform/list/browser/listService';
import { FuzzyScore } from 'vs/base/common/filters';
import * as callHTree from 'vs/workbench/contrib/callHierarchy/browser/callHierarchyTree';
import { IAsyncDataTreeViewState } from 'vs/base/browser/ui/tree/asyncDataTree';
import { localize } from 'vs/nls';
import { ScrollType } from 'vs/editor/common/editorCommon';
import { IRange, Range } from 'vs/editor/common/core/range';
import { SplitView, Orientation, Sizing } from 'vs/base/browser/ui/splitview/splitview';
import { Dimension } from 'vs/base/browser/dom';
import { Event } from 'vs/base/common/event';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EmbeddedCodeEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { TrackedRangeStickiness, IModelDeltaDecoration, IModelDecorationOptions, OverviewRulerLane } from 'vs/editor/common/model';
import { themeColorFromId, IThemeService, IColorTheme } from 'vs/platform/theme/common/themeService';
import { IPosition } from 'vs/editor/common/core/position';
import { IAction } from 'vs/base/common/actions';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { Color } from 'vs/base/common/color';
import { TreeMouseEventTarget, ITreeNode } from 'vs/base/browser/ui/tree/tree';
import { URI } from 'vs/base/common/uri';
import { MenuId, IMenuService } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
const enum State {
Loading = 'loading',
Message = 'message',
Data = 'data'
}
class LayoutInfo {
static store(info: LayoutInfo, storageService: IStorageService): void {
storageService.store('callHierarchyPeekLayout', JSON.stringify(info), StorageScope.PROFILE, StorageTarget.MACHINE);
}
static retrieve(storageService: IStorageService): LayoutInfo {
const value = storageService.get('callHierarchyPeekLayout', StorageScope.PROFILE, '{}');
const defaultInfo: LayoutInfo = { ratio: 0.7, height: 17 };
try {
return { ...defaultInfo, ...JSON.parse(value) };
} catch {
return defaultInfo;
}
}
constructor(
public ratio: number,
public height: number
) { }
}
class CallHierarchyTree extends WorkbenchAsyncDataTree<CallHierarchyModel, callHTree.Call, FuzzyScore>{ }
export class CallHierarchyTreePeekWidget extends peekView.PeekViewWidget {
static readonly TitleMenu = new MenuId('callhierarchy/title');
private _parent!: HTMLElement;
private _message!: HTMLElement;
private _splitView!: SplitView;
private _tree!: CallHierarchyTree;
private _treeViewStates = new Map<CallHierarchyDirection, IAsyncDataTreeViewState>();
private _editor!: EmbeddedCodeEditorWidget;
private _dim!: Dimension;
private _layoutInfo!: LayoutInfo;
private readonly _previewDisposable = new DisposableStore();
constructor(
editor: ICodeEditor,
private readonly _where: IPosition,
private _direction: CallHierarchyDirection,
@IThemeService themeService: IThemeService,
@peekView.IPeekViewService private readonly _peekViewService: peekView.IPeekViewService,
@IEditorService private readonly _editorService: IEditorService,
@ITextModelService private readonly _textModelService: ITextModelService,
@IStorageService private readonly _storageService: IStorageService,
@IMenuService private readonly _menuService: IMenuService,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
) {
super(editor, { showFrame: true, showArrow: true, isResizeable: true, isAccessible: true }, _instantiationService);
this.create();
this._peekViewService.addExclusiveWidget(editor, this);
this._applyTheme(themeService.getColorTheme());
this._disposables.add(themeService.onDidColorThemeChange(this._applyTheme, this));
this._disposables.add(this._previewDisposable);
}
override dispose(): void {
LayoutInfo.store(this._layoutInfo, this._storageService);
this._splitView.dispose();
this._tree.dispose();
this._editor.dispose();
super.dispose();
}
get direction(): CallHierarchyDirection {
return this._direction;
}
private _applyTheme(theme: IColorTheme) {
const borderColor = theme.getColor(peekView.peekViewBorder) || Color.transparent;
this.style({
arrowColor: borderColor,
frameColor: borderColor,
headerBackgroundColor: theme.getColor(peekView.peekViewTitleBackground) || Color.transparent,
primaryHeadingColor: theme.getColor(peekView.peekViewTitleForeground),
secondaryHeadingColor: theme.getColor(peekView.peekViewTitleInfoForeground)
});
}
protected override _fillHead(container: HTMLElement): void {
super._fillHead(container, true);
const menu = this._menuService.createMenu(CallHierarchyTreePeekWidget.TitleMenu, this._contextKeyService);
const updateToolbar = () => {
const actions: IAction[] = [];
createAndFillInActionBarActions(menu, undefined, actions);
this._actionbarWidget!.clear();
this._actionbarWidget!.push(actions, { label: false, icon: true });
};
this._disposables.add(menu);
this._disposables.add(menu.onDidChange(updateToolbar));
updateToolbar();
}
protected _fillBody(parent: HTMLElement): void {
this._layoutInfo = LayoutInfo.retrieve(this._storageService);
this._dim = new Dimension(0, 0);
this._parent = parent;
parent.classList.add('call-hierarchy');
const message = document.createElement('div');
message.classList.add('message');
parent.appendChild(message);
this._message = message;
this._message.tabIndex = 0;
const container = document.createElement('div');
container.classList.add('results');
parent.appendChild(container);
this._splitView = new SplitView(container, { orientation: Orientation.HORIZONTAL });
// editor stuff
const editorContainer = document.createElement('div');
editorContainer.classList.add('editor');
container.appendChild(editorContainer);
const editorOptions: IEditorOptions = {
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: 14,
horizontal: 'auto',
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
alwaysConsumeMouseWheel: false
},
overviewRulerLanes: 2,
fixedOverflowWidgets: true,
minimap: {
enabled: false
}
};
this._editor = this._instantiationService.createInstance(
EmbeddedCodeEditorWidget,
editorContainer,
editorOptions,
this.editor
);
// tree stuff
const treeContainer = document.createElement('div');
treeContainer.classList.add('tree');
container.appendChild(treeContainer);
const options: IWorkbenchAsyncDataTreeOptions<callHTree.Call, FuzzyScore> = {
sorter: new callHTree.Sorter(),
accessibilityProvider: new callHTree.AccessibilityProvider(() => this._direction),
identityProvider: new callHTree.IdentityProvider(() => this._direction),
expandOnlyOnTwistieClick: true,
overrideStyles: {
listBackground: peekView.peekViewResultsBackground
}
};
this._tree = this._instantiationService.createInstance(
CallHierarchyTree,
'CallHierarchyPeek',
treeContainer,
new callHTree.VirtualDelegate(),
[this._instantiationService.createInstance(callHTree.CallRenderer)],
this._instantiationService.createInstance(callHTree.DataSource, () => this._direction),
options
);
// split stuff
this._splitView.addView({
onDidChange: Event.None,
element: editorContainer,
minimumSize: 200,
maximumSize: Number.MAX_VALUE,
layout: (width) => {
if (this._dim.height) {
this._editor.layout({ height: this._dim.height, width });
}
}
}, Sizing.Distribute);
this._splitView.addView({
onDidChange: Event.None,
element: treeContainer,
minimumSize: 100,
maximumSize: Number.MAX_VALUE,
layout: (width) => {
if (this._dim.height) {
this._tree.layout(this._dim.height, width);
}
}
}, Sizing.Distribute);
this._disposables.add(this._splitView.onDidSashChange(() => {
if (this._dim.width) {
this._layoutInfo.ratio = this._splitView.getViewSize(0) / this._dim.width;
}
}));
// update editor
this._disposables.add(this._tree.onDidChangeFocus(this._updatePreview, this));
this._disposables.add(this._editor.onMouseDown(e => {
const { event, target } = e;
if (event.detail !== 2) {
return;
}
const [focus] = this._tree.getFocus();
if (!focus) {
return;
}
this.dispose();
this._editorService.openEditor({
resource: focus.item.uri,
options: { selection: target.range! }
});
}));
this._disposables.add(this._tree.onMouseDblClick(e => {
if (e.target === TreeMouseEventTarget.Twistie) {
return;
}
if (e.element) {
this.dispose();
this._editorService.openEditor({
resource: e.element.item.uri,
options: { selection: e.element.item.selectionRange, pinned: true }
});
}
}));
this._disposables.add(this._tree.onDidChangeSelection(e => {
const [element] = e.elements;
// don't close on click
if (element && e.browserEvent instanceof KeyboardEvent) {
this.dispose();
this._editorService.openEditor({
resource: element.item.uri,
options: { selection: element.item.selectionRange, pinned: true }
});
}
}));
}
private async _updatePreview() {
const [element] = this._tree.getFocus();
if (!element) {
return;
}
this._previewDisposable.clear();
// update: editor and editor highlights
const options: IModelDecorationOptions = {
description: 'call-hierarchy-decoration',
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'call-decoration',
overviewRuler: {
color: themeColorFromId(peekView.peekViewEditorMatchHighlight),
position: OverviewRulerLane.Center
},
};
let previewUri: URI;
if (this._direction === CallHierarchyDirection.CallsFrom) {
// outgoing calls: show caller and highlight focused calls
previewUri = element.parent ? element.parent.item.uri : element.model.root.uri;
} else {
// incoming calls: show caller and highlight focused calls
previewUri = element.item.uri;
}
const value = await this._textModelService.createModelReference(previewUri);
this._editor.setModel(value.object.textEditorModel);
// set decorations for caller ranges (if in the same file)
const decorations: IModelDeltaDecoration[] = [];
let fullRange: IRange | undefined;
let locations = element.locations;
if (!locations) {
locations = [{ uri: element.item.uri, range: element.item.selectionRange }];
}
for (const loc of locations) {
if (loc.uri.toString() === previewUri.toString()) {
decorations.push({ range: loc.range, options });
fullRange = !fullRange ? loc.range : Range.plusRange(loc.range, fullRange);
}
}
if (fullRange) {
this._editor.revealRangeInCenter(fullRange, ScrollType.Immediate);
const decorationsCollection = this._editor.createDecorationsCollection(decorations);
this._previewDisposable.add(toDisposable(() => decorationsCollection.clear()));
}
this._previewDisposable.add(value);
// update: title
const title = this._direction === CallHierarchyDirection.CallsFrom
? localize('callFrom', "Calls from '{0}'", element.model.root.name)
: localize('callsTo', "Callers of '{0}'", element.model.root.name);
this.setTitle(title);
}
showLoading(): void {
this._parent.dataset['state'] = State.Loading;
this.setTitle(localize('title.loading', "Loading..."));
this._show();
}
showMessage(message: string): void {
this._parent.dataset['state'] = State.Message;
this.setTitle('');
this.setMetaTitle('');
this._message.innerText = message;
this._show();
this._message.focus();
}
async showModel(model: CallHierarchyModel): Promise<void> {
this._show();
const viewState = this._treeViewStates.get(this._direction);
await this._tree.setInput(model, viewState);
const root = <ITreeNode<callHTree.Call, FuzzyScore>>this._tree.getNode(model).children[0];
await this._tree.expand(root.element);
if (root.children.length === 0) {
//
this.showMessage(this._direction === CallHierarchyDirection.CallsFrom
? localize('empt.callsFrom', "No calls from '{0}'", model.root.name)
: localize('empt.callsTo', "No callers of '{0}'", model.root.name));
} else {
this._parent.dataset['state'] = State.Data;
if (!viewState || this._tree.getFocus().length === 0) {
this._tree.setFocus([root.children[0].element]);
}
this._tree.domFocus();
this._updatePreview();
}
}
getModel(): CallHierarchyModel | undefined {
return this._tree.getInput();
}
getFocused(): callHTree.Call | undefined {
return this._tree.getFocus()[0];
}
async updateDirection(newDirection: CallHierarchyDirection): Promise<void> {
const model = this._tree.getInput();
if (model && newDirection !== this._direction) {
this._treeViewStates.set(this._direction, this._tree.getViewState());
this._direction = newDirection;
await this.showModel(model);
}
}
private _show() {
if (!this._isShowing) {
this.editor.revealLineInCenterIfOutsideViewport(this._where.lineNumber, ScrollType.Smooth);
super.show(Range.fromPositions(this._where), this._layoutInfo.height);
}
}
protected override _onWidth(width: number) {
if (this._dim) {
this._doLayoutBody(this._dim.height, width);
}
}
protected override _doLayoutBody(height: number, width: number): void {
if (this._dim.height !== height || this._dim.width !== width) {
super._doLayoutBody(height, width);
this._dim = new Dimension(width, height);
this._layoutInfo.height = this._viewZone ? this._viewZone.heightInLines : this._layoutInfo.height;
this._splitView.layout(width);
this._splitView.resizeView(0, width * this._layoutInfo.ratio);
}
}
}
| src/vs/workbench/contrib/callHierarchy/browser/callHierarchyPeek.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0001741289161145687,
0.00016925897216424346,
0.000162845230079256,
0.00016869457613211125,
0.0000024184332687582355
] |
{
"id": 1,
"code_window": [
"\t}\n",
"}\n",
"\n",
"export class CellOutputContainer extends CellContentPart {\n",
"\tprivate _outputEntries: OutputEntryViewHandler[] = [];\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const enum CellOutputUpdateContext {\n",
"\tExecution = 1,\n",
"\tOther = 2\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 433
} | {
"originalFileName": "./1.txt",
"modifiedFileName": "./2.txt",
"diffs": [
{
"originalRange": "[1,2)",
"modifiedRange": "[1,2)",
"innerChanges": null
}
]
} | src/vs/editor/test/node/diffing/fixtures/trivial/smart.expected.diff.json | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00018081745656672865,
0.00017749593826010823,
0.00017417440540157259,
0.00017749593826010823,
0.000003321525582578033
] |
{
"id": 2,
"code_window": [
"\t\tprivate readonly templateData: CodeCellRenderTemplate,\n",
"\t\tprivate options: { limit: number },\n",
"\t\t@IOpenerService private readonly openerService: IOpenerService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService,\n",
"\t) {\n",
"\t\tsuper();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 446
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
import { renderMarkdown } from 'vs/base/browser/markdownRenderer';
import { Action, IAction } from 'vs/base/common/actions';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import * as nls from 'vs/nls';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { WorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { IMenuService, MenuId } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSION_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellOutputViewModel, ICellViewModel, IInsetRenderOutput, INotebookEditorDelegate, JUPYTER_EXTENSION_ID, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { mimetypeIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';
import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
interface IRenderResult {
initRenderIsSynchronous: false;
}
// DOM structure
//
// #output
// |
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | | #output-element
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
class CellOutputElement extends Disposable {
private readonly _renderDisposableStore = this._register(new DisposableStore());
innerContainer?: HTMLElement;
renderedOutputContainer!: HTMLElement;
renderResult?: IInsetRenderOutput;
private readonly contextKeyService: IContextKeyService;
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private cellOutputContainer: CellOutputContainer,
private outputContainer: FastDomNode<HTMLElement>,
readonly output: ICellOutputViewModel,
@INotebookService private readonly notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@IContextKeyService parentContextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this.contextKeyService = parentContextKeyService;
this._register(this.output.model.onDidChangeData(() => {
this.rerender();
}));
this._register(this.output.onDidResetRenderer(() => {
this.rerender();
}));
}
detach() {
this.renderedOutputContainer?.parentElement?.removeChild(this.renderedOutputContainer);
let count = 0;
if (this.innerContainer) {
for (let i = 0; i < this.innerContainer.childNodes.length; i++) {
if ((this.innerContainer.childNodes[i] as HTMLElement).className === 'rendered-output') {
count++;
}
if (count > 1) {
break;
}
}
if (count === 0) {
this.innerContainer.parentElement?.removeChild(this.innerContainer);
}
}
this.notebookEditor.removeInset(this.output);
}
updateDOMTop(top: number) {
if (this.innerContainer) {
this.innerContainer.style.top = `${top}px`;
}
}
rerender() {
if (
this.notebookEditor.hasModel() &&
this.innerContainer &&
this.renderResult &&
this.renderResult.type === RenderOutputType.Extension
) {
// Output rendered by extension renderer got an update
const [mimeTypes, pick] = this.output.resolveMimeTypes(this.notebookEditor.textModel, this.notebookEditor.activeKernel?.preloadProvides);
const pickedMimeType = mimeTypes[pick];
if (pickedMimeType.mimeType === this.renderResult.mimeType && pickedMimeType.rendererId === this.renderResult.renderer.id) {
// Same mimetype, same renderer, call the extension renderer to update
const index = this.viewCell.outputsViewModels.indexOf(this.output);
this.notebookEditor.updateOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
return;
}
}
if (!this.innerContainer) {
// init rendering didn't happen
const currOutputIndex = this.cellOutputContainer.renderedOutputEntries.findIndex(entry => entry.element === this);
const previousSibling = currOutputIndex > 0 && !!(this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer?.parentElement)
? this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer
: undefined;
this.render(previousSibling);
} else {
// Another mimetype or renderer is picked, we need to clear the current output and re-render
const nextElement = this.innerContainer.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(this.output);
}
this.render(nextElement as HTMLElement);
}
this._relayoutCell();
}
// insert after previousSibling
private _generateInnerOutputContainer(previousSibling: HTMLElement | undefined, pickedMimeTypeRenderer: IOrderedMimeType) {
this.innerContainer = DOM.$('.output-inner-container');
if (previousSibling && previousSibling.nextElementSibling) {
this.outputContainer.domNode.insertBefore(this.innerContainer, previousSibling.nextElementSibling);
} else {
this.outputContainer.domNode.appendChild(this.innerContainer);
}
this.innerContainer.setAttribute('output-mime-type', pickedMimeTypeRenderer.mimeType);
return this.innerContainer;
}
render(previousSibling: HTMLElement | undefined): IRenderResult | undefined {
const index = this.viewCell.outputsViewModels.indexOf(this.output);
if (this.viewCell.isOutputCollapsed || !this.notebookEditor.hasModel()) {
return undefined;
}
const notebookUri = CellUri.parse(this.viewCell.uri)?.notebook;
if (!notebookUri) {
return undefined;
}
const notebookTextModel = this.notebookEditor.textModel;
const [mimeTypes, pick] = this.output.resolveMimeTypes(notebookTextModel, this.notebookEditor.activeKernel?.preloadProvides);
if (!mimeTypes.find(mimeType => mimeType.isTrusted) || mimeTypes.length === 0) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#noMimeType');
return undefined;
}
const pickedMimeTypeRenderer = mimeTypes[pick];
const innerContainer = this._generateInnerOutputContainer(previousSibling, pickedMimeTypeRenderer);
this._attachToolbar(innerContainer, notebookTextModel, this.notebookEditor.activeKernel, index, mimeTypes);
this.renderedOutputContainer = DOM.append(innerContainer, DOM.$('.rendered-output'));
const renderer = this.notebookService.getRendererInfo(pickedMimeTypeRenderer.rendererId);
this.renderResult = renderer
? { type: RenderOutputType.Extension, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType }
: this._renderMissingRenderer(this.output, pickedMimeTypeRenderer.mimeType);
this.output.pickedMimeType = pickedMimeTypeRenderer;
if (!this.renderResult) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#renderResultUndefined');
return undefined;
}
this.notebookEditor.createOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
innerContainer.classList.add('background');
return { initRenderIsSynchronous: false };
}
private _renderMissingRenderer(viewModel: ICellOutputViewModel, preferredMimeType: string | undefined): IInsetRenderOutput {
if (!viewModel.model.outputs.length) {
return this._renderMessage(viewModel, nls.localize('empty', "Cell has no output"));
}
if (!preferredMimeType) {
const mimeTypes = viewModel.model.outputs.map(op => op.mime);
const mimeTypesMessage = mimeTypes.join(', ');
return this._renderMessage(viewModel, nls.localize('noRenderer.2', "No renderer could be found for output. It has the following mimetypes: {0}", mimeTypesMessage));
}
return this._renderSearchForMimetype(viewModel, preferredMimeType);
}
private _renderSearchForMimetype(viewModel: ICellOutputViewModel, mimeType: string): IInsetRenderOutput {
const query = `@tag:notebookRenderer ${mimeType}`;
const p = DOM.$('p', undefined, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
const a = DOM.$('a', { href: `command:workbench.extensions.search?%22${query}%22`, class: 'monaco-button monaco-text-button', tabindex: 0, role: 'button', style: 'padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;' }, `Search Marketplace`);
return {
type: RenderOutputType.Html,
source: viewModel,
htmlContent: p.outerHTML + a.outerHTML
};
}
private _renderMessage(viewModel: ICellOutputViewModel, message: string): IInsetRenderOutput {
const el = DOM.$('p', undefined, message);
return { type: RenderOutputType.Html, source: viewModel, htmlContent: el.outerHTML };
}
private async _attachToolbar(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, index: number, mimeTypes: readonly IOrderedMimeType[]) {
const hasMultipleMimeTypes = mimeTypes.filter(mimeType => mimeType.isTrusted).length <= 1;
if (index > 0 && hasMultipleMimeTypes) {
return;
}
if (!this.notebookEditor.hasModel()) {
return;
}
const useConsolidatedButton = this.notebookEditor.notebookOptions.getLayoutConfiguration().consolidatedOutputButton;
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.cell-output-toolbar');
outputItemDiv.appendChild(mimeTypePicker);
const toolbar = this._renderDisposableStore.add(this.instantiationService.createInstance(WorkbenchToolBar, mimeTypePicker, {
renderDropdownAsChildElement: false
}));
toolbar.context = <INotebookCellActionContext>{
ui: true,
cell: this.output.cellViewModel as ICellViewModel,
notebookEditor: this.notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
};
// TODO: This could probably be a real registered action, but it has to talk to this output element
const pickAction = new Action('notebook.output.pickMimetype', nls.localize('pickMimeType', "Change Presentation"), ThemeIcon.asClassName(mimetypeIcon), undefined,
async _context => this._pickActiveMimeTypeRenderer(outputItemDiv, notebookTextModel, kernel, this.output));
if (index === 0 && useConsolidatedButton) {
const menu = this._renderDisposableStore.add(this.menuService.createMenu(MenuId.NotebookOutputToolbar, this.contextKeyService));
const updateMenuToolbar = () => {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, result, () => false);
toolbar.setActions([], [pickAction, ...secondary]);
};
updateMenuToolbar();
this._renderDisposableStore.add(menu.onDidChange(updateMenuToolbar));
} else {
toolbar.setActions([pickAction]);
}
}
private async _pickActiveMimeTypeRenderer(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, viewModel: ICellOutputViewModel) {
const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, kernel?.preloadProvides);
const items: IMimeTypeRenderer[] = [];
const unsupportedItems: IMimeTypeRenderer[] = [];
mimeTypes.forEach((mimeType, index) => {
if (mimeType.isTrusted) {
const arr = mimeType.rendererId === RENDERER_NOT_AVAILABLE ?
unsupportedItems :
items;
arr.push({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
detail: this._generateRendererInfo(mimeType.rendererId),
description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined
});
}
});
if (unsupportedItems.some(m => JUPYTER_RENDERER_MIMETYPES.includes(m.id!))) {
unsupportedItems.push({
label: nls.localize('installJupyterPrompt', "Install additional renderers from the marketplace"),
id: 'installRenderers',
index: mimeTypes.length
});
}
const picker = this.quickInputService.createQuickPick();
picker.items = [
...items,
{ type: 'separator' },
...unsupportedItems
];
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = items.length !== mimeTypes.length
? nls.localize('promptChooseMimeTypeInSecure.placeHolder', "Select mimetype to render for current output")
: nls.localize('promptChooseMimeType.placeHolder', "Select mimetype to render for current output");
const pick = await new Promise<IMimeTypeRenderer | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer) : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined || pick.index === currIndex) {
return;
}
if (pick.id === 'installRenderers') {
this._showJupyterExtension();
return;
}
// user chooses another mimetype
const nextElement = outputItemDiv.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(viewModel);
}
viewModel.pickedMimeType = mimeTypes[pick.index];
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
const { mimeType, rendererId } = mimeTypes[pick.index];
this.notebookService.updateMimePreferredRenderer(notebookTextModel.viewType, mimeType, rendererId, mimeTypes.map(m => m.mimeType));
this.render(nextElement as HTMLElement);
this._validateFinalOutputHeight(false);
this._relayoutCell();
}
private async _showJupyterExtension() {
const viewlet = await this.paneCompositeService.openPaneComposite(EXTENSION_VIEWLET_ID, ViewContainerLocation.Sidebar, true);
const view = viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer | undefined;
view?.search(`@id:${JUPYTER_EXTENSION_ID}`);
}
private _generateRendererInfo(renderId: string): string {
const renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
const displayName = renderInfo.displayName !== '' ? renderInfo.displayName : renderInfo.id;
return `${displayName} (${renderInfo.extensionId.value})`;
}
return nls.localize('unavailableRenderInfo', "renderer not available");
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
if (this._outputHeightTimer) {
this.viewCell.unlockOutputHeight();
clearTimeout(this._outputHeightTimer);
}
super.dispose();
}
}
class OutputEntryViewHandler {
constructor(
readonly model: ICellOutputViewModel,
readonly element: CellOutputElement
) {
}
}
export class CellOutputContainer extends CellContentPart {
private _outputEntries: OutputEntryViewHandler[] = [];
get renderedOutputEntries() {
return this._outputEntries;
}
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private readonly templateData: CodeCellRenderTemplate,
private options: { limit: number },
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._register(viewCell.onDidChangeOutputs(splice => {
this._updateOutputs(splice);
}));
this._register(viewCell.onDidChangeLayout(() => {
this.updateInternalLayoutNow(viewCell);
}));
}
override updateInternalLayoutNow(viewCell: CodeCellViewModel) {
this.templateData.outputContainer.setTop(viewCell.layoutInfo.outputContainerOffset);
this.templateData.outputShowMoreContainer.setTop(viewCell.layoutInfo.outputShowMoreContainerOffset);
this._outputEntries.forEach(entry => {
const index = this.viewCell.outputsViewModels.indexOf(entry.model);
if (index >= 0) {
const top = this.viewCell.getOutputOffsetInContainer(index);
entry.element.updateDOMTop(top);
}
});
}
render() {
if (this.viewCell.outputsViewModels.length > 0) {
if (this.viewCell.layoutInfo.outputTotalHeight !== 0) {
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
this._relayoutCell();
}
DOM.show(this.templateData.outputContainer.domNode);
for (let index = 0; index < Math.min(this.options.limit, this.viewCell.outputsViewModels.length); index++) {
const currOutput = this.viewCell.outputsViewModels[index];
const entry = this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, currOutput);
this._outputEntries.push(new OutputEntryViewHandler(currOutput, entry));
entry.render(undefined);
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(46);
}
this._relayoutCell();
this._validateFinalOutputHeight(false);
} else {
// noop
this._relayoutCell();
DOM.hide(this.templateData.outputContainer.domNode);
}
this.templateData.outputShowMoreContainer.domNode.innerText = '';
if (this.viewCell.outputsViewModels.length > this.options.limit) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(0);
}
}
viewUpdateShowOutputs(initRendering: boolean): void {
for (let index = 0; index < this._outputEntries.length; index++) {
const viewHandler = this._outputEntries[index];
const outputEntry = viewHandler.element;
if (outputEntry.renderResult) {
this.notebookEditor.createOutput(this.viewCell, outputEntry.renderResult as IInsetRenderOutput, this.viewCell.getOutputOffset(index));
} else {
outputEntry.render(undefined);
}
}
this._relayoutCell();
}
viewUpdateHideOuputs(): void {
for (let index = 0; index < this._outputEntries.length; index++) {
this.notebookEditor.hideInset(this._outputEntries[index].model);
}
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _updateOutputs(splice: NotebookCellOutputsSplice) {
const previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;
// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.
this.viewCell.updateOutputMinHeight(previousOutputHeight);
if (this.viewCell.outputsViewModels.length) {
DOM.show(this.templateData.outputContainer.domNode);
} else {
DOM.hide(this.templateData.outputContainer.domNode);
}
this.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));
this._renderNow(splice);
}
private _renderNow(splice: NotebookCellOutputsSplice) {
if (splice.start >= this.options.limit) {
// splice items out of limit
return;
}
const firstGroupEntries = this._outputEntries.slice(0, splice.start);
const deletedEntries = this._outputEntries.slice(splice.start, splice.start + splice.deleteCount);
const secondGroupEntries = this._outputEntries.slice(splice.start + splice.deleteCount);
let newlyInserted = this.viewCell.outputsViewModels.slice(splice.start, splice.start + splice.newOutputs.length);
// [...firstGroup, ...deletedEntries, ...secondGroupEntries] [...restInModel]
// [...firstGroup, ...newlyInserted, ...secondGroupEntries, restInModel]
if (firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length > this.options.limit) {
// exceeds limit again
if (firstGroupEntries.length + newlyInserted.length > this.options.limit) {
[...deletedEntries, ...secondGroupEntries].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
newlyInserted = newlyInserted.slice(0, this.options.limit - firstGroupEntries.length);
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries];
// render newly inserted outputs
for (let i = firstGroupEntries.length; i < this._outputEntries.length; i++) {
this._outputEntries[i].element.render(undefined);
}
} else {
// part of secondGroupEntries are pushed out of view
// now we have to be creative as secondGroupEntries might not use dedicated containers
const elementsPushedOutOfView = secondGroupEntries.slice(this.options.limit - firstGroupEntries.length - newlyInserted.length);
[...deletedEntries, ...elementsPushedOutOfView].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
// exclusive
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries.slice(0, this.options.limit - firstGroupEntries.length - newlyInserted.length)];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
}
} else {
// after splice, it doesn't exceed
deletedEntries.forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
let outputsNewlyAvailable: OutputEntryViewHandler[] = [];
if (firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length < this.viewCell.outputsViewModels.length) {
const last = Math.min(this.options.limit, this.viewCell.outputsViewModels.length);
outputsNewlyAvailable = this.viewCell.outputsViewModels.slice(firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length, last).map(output => {
return new OutputEntryViewHandler(output, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, output));
});
}
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries, ...outputsNewlyAvailable];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
for (let i = 0; i < outputsNewlyAvailable.length; i++) {
this._outputEntries[firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length + i].element.render(undefined);
}
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
if (!this.templateData.outputShowMoreContainer.domNode.hasChildNodes()) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
}
this.viewCell.updateOutputShowMoreContainerHeight(46);
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
}
const editorHeight = this.templateData.editor.getContentHeight();
this.viewCell.editorHeight = editorHeight;
this._relayoutCell();
// if it's clearing all outputs, or outputs are all rendered synchronously
// shrink immediately as the final output height will be zero.
this._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);
}
private _generateShowMoreElement(disposables: DisposableStore): HTMLElement {
const md: IMarkdownString = {
value: `There are more than ${this.options.limit} outputs, [show more (open the raw output data in a text editor) ...](command:workbench.action.openLargeOutput)`,
isTrusted: true,
supportThemeIcons: true
};
const rendered = renderMarkdown(md, {
actionHandler: {
callback: (content) => {
if (content === 'command:workbench.action.openLargeOutput') {
this.openerService.open(CellUri.generateCellOutputUri(this.notebookEditor.textModel!.uri));
}
return;
},
disposables
}
});
disposables.add(rendered);
rendered.element.classList.add('output-show-more');
return rendered.element;
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
this.viewCell.updateOutputMinHeight(0);
if (this._outputHeightTimer) {
clearTimeout(this._outputHeightTimer);
}
this._outputEntries.forEach(entry => {
entry.element.dispose();
});
super.dispose();
}
}
const JUPYTER_RENDERER_MIMETYPES = [
'application/geo+json',
'application/vdom.v1+json',
'application/vnd.dataresource+json',
'application/vnd.plotly.v1+json',
'application/vnd.vega.v2+json',
'application/vnd.vega.v3+json',
'application/vnd.vega.v4+json',
'application/vnd.vega.v5+json',
'application/vnd.vegalite.v1+json',
'application/vnd.vegalite.v2+json',
'application/vnd.vegalite.v3+json',
'application/vnd.vegalite.v4+json',
'application/x-nteract-model-debug+json',
'image/svg+xml',
'text/latex',
'text/vnd.plotly.v1+html',
'application/vnd.jupyter.widget-view+json',
'application/vnd.code.notebook.error'
];
| src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.9905617833137512,
0.07226692885160446,
0.00016002220218069851,
0.00017178313282784075,
0.24462027847766876
] |
{
"id": 2,
"code_window": [
"\t\tprivate readonly templateData: CodeCellRenderTemplate,\n",
"\t\tprivate options: { limit: number },\n",
"\t\t@IOpenerService private readonly openerService: IOpenerService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService,\n",
"\t) {\n",
"\t\tsuper();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 446
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { Position } from 'vs/editor/common/core/position';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ITextModel } from 'vs/editor/common/model';
import { SnippetController2 } from 'vs/editor/contrib/snippet/browser/snippetController2';
import { localize } from 'vs/nls';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { SnippetEditorAction } from 'vs/workbench/contrib/snippets/browser/commands/abstractSnippetsActions';
import { pickSnippet } from 'vs/workbench/contrib/snippets/browser/snippetPicker';
import { Snippet } from 'vs/workbench/contrib/snippets/browser/snippetsFile';
import { ISnippetsService } from '../snippets';
export async function getSurroundableSnippets(snippetsService: ISnippetsService, model: ITextModel, position: Position, includeDisabledSnippets: boolean): Promise<Snippet[]> {
const { lineNumber, column } = position;
model.tokenization.tokenizeIfCheap(lineNumber);
const languageId = model.getLanguageIdAtPosition(lineNumber, column);
const allSnippets = await snippetsService.getSnippets(languageId, { includeNoPrefixSnippets: true, includeDisabledSnippets });
return allSnippets.filter(snippet => snippet.usesSelection);
}
export class SurroundWithSnippetEditorAction extends SnippetEditorAction {
static readonly options = {
id: 'editor.action.surroundWithSnippet',
title: {
value: localize('label', 'Surround With Snippet...'),
original: 'Surround With Snippet...'
}
};
constructor() {
super({
...SurroundWithSnippetEditorAction.options,
precondition: ContextKeyExpr.and(
EditorContextKeys.writable,
EditorContextKeys.hasNonEmptySelection
),
f1: true,
});
}
async runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor) {
if (!editor.hasModel()) {
return;
}
const instaService = accessor.get(IInstantiationService);
const snippetsService = accessor.get(ISnippetsService);
const clipboardService = accessor.get(IClipboardService);
const snippets = await getSurroundableSnippets(snippetsService, editor.getModel(), editor.getPosition(), true);
if (!snippets.length) {
return;
}
const snippet = await instaService.invokeFunction(pickSnippet, snippets);
if (!snippet) {
return;
}
let clipboardText: string | undefined;
if (snippet.needsClipboard) {
clipboardText = await clipboardService.readText();
}
editor.focus();
SnippetController2.get(editor)?.insert(snippet.codeSnippet, { clipboardText });
snippetsService.updateUsageTimestamp(snippet);
}
}
| src/vs/workbench/contrib/snippets/browser/commands/surroundWithSnippet.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0009299216908402741,
0.00032813340658321977,
0.00016365527699235827,
0.00017422404198441654,
0.000279371248325333
] |
{
"id": 2,
"code_window": [
"\t\tprivate readonly templateData: CodeCellRenderTemplate,\n",
"\t\tprivate options: { limit: number },\n",
"\t\t@IOpenerService private readonly openerService: IOpenerService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService,\n",
"\t) {\n",
"\t\tsuper();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 446
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IMirrorModel, IWorkerContext } from 'vs/editor/common/services/editorSimpleWorker';
import { ILink } from 'vs/editor/common/languages';
import { URI } from 'vs/base/common/uri';
import * as extpath from 'vs/base/common/extpath';
import * as resources from 'vs/base/common/resources';
import * as strings from 'vs/base/common/strings';
import { Range } from 'vs/editor/common/core/range';
import { isWindows } from 'vs/base/common/platform';
import { Schemas } from 'vs/base/common/network';
export interface ICreateData {
workspaceFolders: string[];
}
export interface IResourceCreator {
toResource: (folderRelativePath: string) => URI | null;
}
export class OutputLinkComputer {
private patterns = new Map<URI /* folder uri */, RegExp[]>();
constructor(private ctx: IWorkerContext, createData: ICreateData) {
this.computePatterns(createData);
}
private computePatterns(createData: ICreateData): void {
// Produce patterns for each workspace root we are configured with
// This means that we will be able to detect links for paths that
// contain any of the workspace roots as segments.
const workspaceFolders = createData.workspaceFolders
.sort((resourceStrA, resourceStrB) => resourceStrB.length - resourceStrA.length) // longest paths first (for https://github.com/microsoft/vscode/issues/88121)
.map(resourceStr => URI.parse(resourceStr));
for (const workspaceFolder of workspaceFolders) {
const patterns = OutputLinkComputer.createPatterns(workspaceFolder);
this.patterns.set(workspaceFolder, patterns);
}
}
private getModel(uri: string): IMirrorModel | undefined {
const models = this.ctx.getMirrorModels();
return models.find(model => model.uri.toString() === uri);
}
computeLinks(uri: string): ILink[] {
const model = this.getModel(uri);
if (!model) {
return [];
}
const links: ILink[] = [];
const lines = strings.splitLines(model.getValue());
// For each workspace root patterns
for (const [folderUri, folderPatterns] of this.patterns) {
const resourceCreator: IResourceCreator = {
toResource: (folderRelativePath: string): URI | null => {
if (typeof folderRelativePath === 'string') {
return resources.joinPath(folderUri, folderRelativePath);
}
return null;
}
};
for (let i = 0, len = lines.length; i < len; i++) {
links.push(...OutputLinkComputer.detectLinks(lines[i], i + 1, folderPatterns, resourceCreator));
}
}
return links;
}
static createPatterns(workspaceFolder: URI): RegExp[] {
const patterns: RegExp[] = [];
const workspaceFolderPath = workspaceFolder.scheme === Schemas.file ? workspaceFolder.fsPath : workspaceFolder.path;
const workspaceFolderVariants = [workspaceFolderPath];
if (isWindows && workspaceFolder.scheme === Schemas.file) {
workspaceFolderVariants.push(extpath.toSlashes(workspaceFolderPath));
}
for (const workspaceFolderVariant of workspaceFolderVariants) {
const validPathCharacterPattern = '[^\\s\\(\\):<>"]';
const validPathCharacterOrSpacePattern = `(?:${validPathCharacterPattern}| ${validPathCharacterPattern})`;
const pathPattern = `${validPathCharacterOrSpacePattern}+\\.${validPathCharacterPattern}+`;
const strictPathPattern = `${validPathCharacterPattern}+`;
// Example: /workspaces/express/server.js on line 8, column 13
patterns.push(new RegExp(strings.escapeRegExpCharacters(workspaceFolderVariant) + `(${pathPattern}) on line ((\\d+)(, column (\\d+))?)`, 'gi'));
// Example: /workspaces/express/server.js:line 8, column 13
patterns.push(new RegExp(strings.escapeRegExpCharacters(workspaceFolderVariant) + `(${pathPattern}):line ((\\d+)(, column (\\d+))?)`, 'gi'));
// Example: /workspaces/mankala/Features.ts(45): error
// Example: /workspaces/mankala/Features.ts (45): error
// Example: /workspaces/mankala/Features.ts(45,18): error
// Example: /workspaces/mankala/Features.ts (45,18): error
// Example: /workspaces/mankala/Features Special.ts (45,18): error
patterns.push(new RegExp(strings.escapeRegExpCharacters(workspaceFolderVariant) + `(${pathPattern})(\\s?\\((\\d+)(,(\\d+))?)\\)`, 'gi'));
// Example: at /workspaces/mankala/Game.ts
// Example: at /workspaces/mankala/Game.ts:336
// Example: at /workspaces/mankala/Game.ts:336:9
patterns.push(new RegExp(strings.escapeRegExpCharacters(workspaceFolderVariant) + `(${strictPathPattern})(:(\\d+))?(:(\\d+))?`, 'gi'));
}
return patterns;
}
/**
* Detect links. Made static to allow for tests.
*/
static detectLinks(line: string, lineIndex: number, patterns: RegExp[], resourceCreator: IResourceCreator): ILink[] {
const links: ILink[] = [];
patterns.forEach(pattern => {
pattern.lastIndex = 0; // the holy grail of software development
let match: RegExpExecArray | null;
let offset = 0;
while ((match = pattern.exec(line)) !== null) {
// Convert the relative path information to a resource that we can use in links
const folderRelativePath = strings.rtrim(match[1], '.').replace(/\\/g, '/'); // remove trailing "." that likely indicate end of sentence
let resourceString: string | undefined;
try {
const resource = resourceCreator.toResource(folderRelativePath);
if (resource) {
resourceString = resource.toString();
}
} catch (error) {
continue; // we might find an invalid URI and then we dont want to loose all other links
}
// Append line/col information to URI if matching
if (match[3]) {
const lineNumber = match[3];
if (match[5]) {
const columnNumber = match[5];
resourceString = strings.format('{0}#{1},{2}', resourceString, lineNumber, columnNumber);
} else {
resourceString = strings.format('{0}#{1}', resourceString, lineNumber);
}
}
const fullMatch = strings.rtrim(match[0], '.'); // remove trailing "." that likely indicate end of sentence
const index = line.indexOf(fullMatch, offset);
offset = index + fullMatch.length;
const linkRange = {
startColumn: index + 1,
startLineNumber: lineIndex,
endColumn: index + 1 + fullMatch.length,
endLineNumber: lineIndex
};
if (links.some(link => Range.areIntersectingOrTouching(link.range, linkRange))) {
return; // Do not detect duplicate links
}
links.push({
range: linkRange,
url: resourceString
});
}
});
return links;
}
}
export function create(ctx: IWorkerContext, createData: ICreateData): OutputLinkComputer {
return new OutputLinkComputer(ctx, createData);
}
| src/vs/workbench/contrib/output/common/outputLinkComputer.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017751834820955992,
0.00017311630654148757,
0.00016697072715032846,
0.00017347183893434703,
0.0000028743506845785305
] |
{
"id": 2,
"code_window": [
"\t\tprivate readonly templateData: CodeCellRenderTemplate,\n",
"\t\tprivate options: { limit: number },\n",
"\t\t@IOpenerService private readonly openerService: IOpenerService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService,\n",
"\t) {\n",
"\t\tsuper();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 446
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { generateUuid } from 'vs/base/common/uuid';
import { ExtensionsListView } from 'vs/workbench/contrib/extensions/browser/extensionsViews';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { IExtensionsWorkbenchService } from 'vs/workbench/contrib/extensions/common/extensions';
import { ExtensionsWorkbenchService } from 'vs/workbench/contrib/extensions/browser/extensionsWorkbenchService';
import {
IExtensionManagementService, IExtensionGalleryService, ILocalExtension, IGalleryExtension, IQueryOptions,
DidUninstallExtensionEvent, InstallExtensionEvent, InstallExtensionResult, getTargetPlatform, IExtensionInfo, UninstallExtensionEvent, SortBy
} from 'vs/platform/extensionManagement/common/extensionManagement';
import { IWorkbenchExtensionEnablementService, EnablementState, IExtensionManagementServerService, IExtensionManagementServer, IProfileAwareExtensionManagementService } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
import { IExtensionRecommendationsService, ExtensionRecommendationReason } from 'vs/workbench/services/extensionRecommendations/common/extensionRecommendations';
import { getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { TestExtensionEnablementService } from 'vs/workbench/services/extensionManagement/test/browser/extensionEnablementService.test';
import { ExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionGalleryService';
import { IURLService } from 'vs/platform/url/common/url';
import { Emitter, Event } from 'vs/base/common/event';
import { IPager } from 'vs/base/common/paging';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { IExtensionService, toExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { TestMenuService } from 'vs/workbench/test/browser/workbenchTestServices';
import { TestSharedProcessService } from 'vs/workbench/test/electron-browser/workbenchTestServices';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILogService, NullLogService } from 'vs/platform/log/common/log';
import { NativeURLService } from 'vs/platform/url/common/urlService';
import { URI } from 'vs/base/common/uri';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { SinonStub } from 'sinon';
import { IExperimentService, ExperimentState, ExperimentActionType, ExperimentService } from 'vs/workbench/contrib/experiments/common/experimentService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { RemoteAgentService } from 'vs/workbench/services/remote/electron-sandbox/remoteAgentService';
import { ExtensionType, IExtension } from 'vs/platform/extensions/common/extensions';
import { ISharedProcessService } from 'vs/platform/ipc/electron-sandbox/services';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { MockContextKeyService } from 'vs/platform/keybinding/test/common/mockKeybindingService';
import { IMenuService } from 'vs/platform/actions/common/actions';
import { TestContextService } from 'vs/workbench/test/common/workbenchTestServices';
import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views';
import { Schemas } from 'vs/base/common/network';
import { platform } from 'vs/base/common/platform';
import { arch } from 'vs/base/common/process';
import { IProductService } from 'vs/platform/product/common/productService';
import { CancellationToken } from 'vs/base/common/cancellation';
suite('ExtensionsViews Tests', () => {
let instantiationService: TestInstantiationService;
let testableView: ExtensionsListView;
let installEvent: Emitter<InstallExtensionEvent>,
didInstallEvent: Emitter<readonly InstallExtensionResult[]>,
uninstallEvent: Emitter<UninstallExtensionEvent>,
didUninstallEvent: Emitter<DidUninstallExtensionEvent>;
const localEnabledTheme = aLocalExtension('first-enabled-extension', { categories: ['Themes', 'random'] }, { installedTimestamp: 123456 });
const localEnabledLanguage = aLocalExtension('second-enabled-extension', { categories: ['Programming languages'], version: '1.0.0' }, { installedTimestamp: Date.now(), updated: false });
const localDisabledTheme = aLocalExtension('first-disabled-extension', { categories: ['themes'] }, { installedTimestamp: 234567 });
const localDisabledLanguage = aLocalExtension('second-disabled-extension', { categories: ['programming languages'] }, { installedTimestamp: Date.now() - 50000, updated: true });
const localRandom = aLocalExtension('random-enabled-extension', { categories: ['random'] }, { installedTimestamp: 345678 });
const builtInTheme = aLocalExtension('my-theme', { contributes: { themes: ['my-theme'] } }, { type: ExtensionType.System, installedTimestamp: 222 });
const builtInBasic = aLocalExtension('my-lang', { contributes: { grammars: [{ language: 'my-language' }] } }, { type: ExtensionType.System, installedTimestamp: 666666 });
const galleryEnabledLanguage = aGalleryExtension(localEnabledLanguage.manifest.name, { ...localEnabledLanguage.manifest, version: '1.0.1', identifier: localDisabledLanguage.identifier });
const workspaceRecommendationA = aGalleryExtension('workspace-recommendation-A');
const workspaceRecommendationB = aGalleryExtension('workspace-recommendation-B');
const configBasedRecommendationA = aGalleryExtension('configbased-recommendation-A');
const configBasedRecommendationB = aGalleryExtension('configbased-recommendation-B');
const fileBasedRecommendationA = aGalleryExtension('filebased-recommendation-A');
const fileBasedRecommendationB = aGalleryExtension('filebased-recommendation-B');
const otherRecommendationA = aGalleryExtension('other-recommendation-A');
suiteSetup(() => {
installEvent = new Emitter<InstallExtensionEvent>();
didInstallEvent = new Emitter<readonly InstallExtensionResult[]>();
uninstallEvent = new Emitter<UninstallExtensionEvent>();
didUninstallEvent = new Emitter<DidUninstallExtensionEvent>();
instantiationService = new TestInstantiationService();
instantiationService.stub(ITelemetryService, NullTelemetryService);
instantiationService.stub(ILogService, NullLogService);
instantiationService.stub(IProductService, {});
instantiationService.stub(IWorkspaceContextService, new TestContextService());
instantiationService.stub(IConfigurationService, new TestConfigurationService());
instantiationService.stub(IExtensionGalleryService, ExtensionGalleryService);
instantiationService.stub(ISharedProcessService, TestSharedProcessService);
instantiationService.stub(IExperimentService, ExperimentService);
instantiationService.stub(IExtensionManagementService, <Partial<IExtensionManagementService>>{
onInstallExtension: installEvent.event,
onDidInstallExtensions: didInstallEvent.event,
onUninstallExtension: uninstallEvent.event,
onDidUninstallExtension: didUninstallEvent.event,
onDidChangeProfile: Event.None,
async getInstalled() { return []; },
async canInstall() { return true; },
async getExtensionsControlManifest() { return { malicious: [], deprecated: {} }; },
async getTargetPlatform() { return getTargetPlatform(platform, arch); },
async updateMetadata(local) { return local; }
});
instantiationService.stub(IRemoteAgentService, RemoteAgentService);
instantiationService.stub(IContextKeyService, new MockContextKeyService());
instantiationService.stub(IMenuService, new TestMenuService());
const localExtensionManagementServer = { extensionManagementService: instantiationService.get(IExtensionManagementService) as IProfileAwareExtensionManagementService, label: 'local', id: 'vscode-local' };
instantiationService.stub(IExtensionManagementServerService, <Partial<IExtensionManagementServerService>>{
get localExtensionManagementServer(): IExtensionManagementServer {
return localExtensionManagementServer;
},
getExtensionManagementServer(extension: IExtension): IExtensionManagementServer | null {
if (extension.location.scheme === Schemas.file) {
return localExtensionManagementServer;
}
throw new Error(`Invalid Extension ${extension.location}`);
}
});
instantiationService.stub(IWorkbenchExtensionEnablementService, new TestExtensionEnablementService(instantiationService));
const reasons: { [key: string]: any } = {};
reasons[workspaceRecommendationA.identifier.id] = { reasonId: ExtensionRecommendationReason.Workspace };
reasons[workspaceRecommendationB.identifier.id] = { reasonId: ExtensionRecommendationReason.Workspace };
reasons[fileBasedRecommendationA.identifier.id] = { reasonId: ExtensionRecommendationReason.File };
reasons[fileBasedRecommendationB.identifier.id] = { reasonId: ExtensionRecommendationReason.File };
reasons[otherRecommendationA.identifier.id] = { reasonId: ExtensionRecommendationReason.Executable };
reasons[configBasedRecommendationA.identifier.id] = { reasonId: ExtensionRecommendationReason.WorkspaceConfig };
instantiationService.stub(IExtensionRecommendationsService, <Partial<IExtensionRecommendationsService>>{
getWorkspaceRecommendations() {
return Promise.resolve([
workspaceRecommendationA.identifier.id,
workspaceRecommendationB.identifier.id]);
},
getConfigBasedRecommendations() {
return Promise.resolve({
important: [configBasedRecommendationA.identifier.id],
others: [configBasedRecommendationB.identifier.id],
});
},
getImportantRecommendations(): Promise<string[]> {
return Promise.resolve([]);
},
getFileBasedRecommendations() {
return [
fileBasedRecommendationA.identifier.id,
fileBasedRecommendationB.identifier.id
];
},
getOtherRecommendations() {
return Promise.resolve([
configBasedRecommendationB.identifier.id,
otherRecommendationA.identifier.id
]);
},
getAllRecommendationsWithReason() {
return reasons;
}
});
instantiationService.stub(IURLService, NativeURLService);
});
setup(async () => {
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [localEnabledTheme, localEnabledLanguage, localRandom, localDisabledTheme, localDisabledLanguage, builtInTheme, builtInBasic]);
instantiationService.stubPromise(IExtensionManagementService, 'getExtensgetExtensionsControlManifestionsReport', {});
instantiationService.stub(IExtensionGalleryService, 'isEnabled', true);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(galleryEnabledLanguage));
instantiationService.stubPromise(IExtensionGalleryService, 'getCompatibleExtension', galleryEnabledLanguage);
instantiationService.stubPromise(IExtensionGalleryService, 'getExtensions', [galleryEnabledLanguage]);
instantiationService.stubPromise(IExperimentService, 'getExperimentsByType', []);
instantiationService.stub(IViewDescriptorService, {
getViewLocationById(): ViewContainerLocation {
return ViewContainerLocation.Sidebar;
},
onDidChangeLocation: Event.None
});
instantiationService.stub(IExtensionService, <Partial<IExtensionService>>{
onDidChangeExtensions: Event.None,
extensions: [
toExtensionDescription(localEnabledTheme),
toExtensionDescription(localEnabledLanguage),
toExtensionDescription(localRandom),
toExtensionDescription(builtInTheme),
toExtensionDescription(builtInBasic)
],
canAddExtension: (extension) => true,
whenInstalledExtensionsRegistered: () => Promise.resolve(true)
});
await (<TestExtensionEnablementService>instantiationService.get(IWorkbenchExtensionEnablementService)).setEnablement([localDisabledTheme], EnablementState.DisabledGlobally);
await (<TestExtensionEnablementService>instantiationService.get(IWorkbenchExtensionEnablementService)).setEnablement([localDisabledLanguage], EnablementState.DisabledGlobally);
instantiationService.set(IExtensionsWorkbenchService, instantiationService.createInstance(ExtensionsWorkbenchService));
testableView = instantiationService.createInstance(ExtensionsListView, {}, { id: '', title: '' });
});
teardown(() => {
(<ExtensionsWorkbenchService>instantiationService.get(IExtensionsWorkbenchService)).dispose();
testableView.dispose();
});
test('Test query types', () => {
assert.strictEqual(ExtensionsListView.isBuiltInExtensionsQuery('@builtin'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@installed'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@enabled'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@disabled'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@outdated'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@updates'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@sort:name'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@sort:updateDate'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@installed searchText'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@enabled searchText'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@disabled searchText'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@outdated searchText'), true);
assert.strictEqual(ExtensionsListView.isLocalExtensionsQuery('@updates searchText'), true);
});
test('Test empty query equates to sort by install count', () => {
const target = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage());
return testableView.show('').then(() => {
assert.ok(target.calledOnce);
const options: IQueryOptions = target.args[0][0];
assert.strictEqual(options.sortBy, SortBy.InstallCount);
});
});
test('Test non empty query without sort doesnt use sortBy', () => {
const target = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage());
return testableView.show('some extension').then(() => {
assert.ok(target.calledOnce);
const options: IQueryOptions = target.args[0][0];
assert.strictEqual(options.sortBy, undefined);
});
});
test('Test query with sort uses sortBy', () => {
const target = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage());
return testableView.show('some extension @sort:rating').then(() => {
assert.ok(target.calledOnce);
const options: IQueryOptions = target.args[0][0];
assert.strictEqual(options.sortBy, SortBy.WeightedRating);
});
});
test('Test default view actions required sorting', async () => {
const workbenchService = instantiationService.get(IExtensionsWorkbenchService);
const extension = (await workbenchService.queryLocal()).find(ex => ex.identifier === localEnabledLanguage.identifier);
await new Promise<void>(c => {
const disposable = workbenchService.onChange(() => {
if (extension?.outdated) {
disposable.dispose();
c();
}
});
instantiationService.get(IExtensionsWorkbenchService).queryGallery(CancellationToken.None);
});
const result = await testableView.show('@installed');
assert.strictEqual(result.length, 5, 'Unexpected number of results for @installed query');
const actual = [result.get(0).name, result.get(1).name, result.get(2).name, result.get(3).name, result.get(4).name];
const expected = [localEnabledLanguage.manifest.name, localEnabledTheme.manifest.name, localRandom.manifest.name, localDisabledTheme.manifest.name, localDisabledLanguage.manifest.name];
for (let i = 0; i < result.length; i++) {
assert.strictEqual(actual[i], expected[i], 'Unexpected extension for @installed query with outadted extension.');
}
});
test('Test installed query results', async () => {
await testableView.show('@installed').then(result => {
assert.strictEqual(result.length, 5, 'Unexpected number of results for @installed query');
const actual = [result.get(0).name, result.get(1).name, result.get(2).name, result.get(3).name, result.get(4).name].sort();
const expected = [localDisabledTheme.manifest.name, localEnabledTheme.manifest.name, localRandom.manifest.name, localDisabledLanguage.manifest.name, localEnabledLanguage.manifest.name];
for (let i = 0; i < result.length; i++) {
assert.strictEqual(actual[i], expected[i], 'Unexpected extension for @installed query.');
}
});
await testableView.show('@installed first').then(result => {
assert.strictEqual(result.length, 2, 'Unexpected number of results for @installed query');
assert.strictEqual(result.get(0).name, localEnabledTheme.manifest.name, 'Unexpected extension for @installed query with search text.');
assert.strictEqual(result.get(1).name, localDisabledTheme.manifest.name, 'Unexpected extension for @installed query with search text.');
});
await testableView.show('@disabled').then(result => {
assert.strictEqual(result.length, 2, 'Unexpected number of results for @disabled query');
assert.strictEqual(result.get(0).name, localDisabledTheme.manifest.name, 'Unexpected extension for @disabled query.');
assert.strictEqual(result.get(1).name, localDisabledLanguage.manifest.name, 'Unexpected extension for @disabled query.');
});
await testableView.show('@enabled').then(result => {
assert.strictEqual(result.length, 3, 'Unexpected number of results for @enabled query');
assert.strictEqual(result.get(0).name, localEnabledTheme.manifest.name, 'Unexpected extension for @enabled query.');
assert.strictEqual(result.get(1).name, localRandom.manifest.name, 'Unexpected extension for @enabled query.');
assert.strictEqual(result.get(2).name, localEnabledLanguage.manifest.name, 'Unexpected extension for @enabled query.');
});
await testableView.show('@builtin:themes').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @builtin:themes query');
assert.strictEqual(result.get(0).name, builtInTheme.manifest.name, 'Unexpected extension for @builtin:themes query.');
});
await testableView.show('@builtin:basics').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @builtin:basics query');
assert.strictEqual(result.get(0).name, builtInBasic.manifest.name, 'Unexpected extension for @builtin:basics query.');
});
await testableView.show('@builtin').then(result => {
assert.strictEqual(result.length, 2, 'Unexpected number of results for @builtin query');
assert.strictEqual(result.get(0).name, builtInBasic.manifest.name, 'Unexpected extension for @builtin query.');
assert.strictEqual(result.get(1).name, builtInTheme.manifest.name, 'Unexpected extension for @builtin query.');
});
await testableView.show('@builtin my-theme').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @builtin query');
assert.strictEqual(result.get(0).name, builtInTheme.manifest.name, 'Unexpected extension for @builtin query.');
});
});
test('Test installed query with category', async () => {
await testableView.show('@installed category:themes').then(result => {
assert.strictEqual(result.length, 2, 'Unexpected number of results for @installed query with category');
assert.strictEqual(result.get(0).name, localEnabledTheme.manifest.name, 'Unexpected extension for @installed query with category.');
assert.strictEqual(result.get(1).name, localDisabledTheme.manifest.name, 'Unexpected extension for @installed query with category.');
});
await testableView.show('@installed category:"themes"').then(result => {
assert.strictEqual(result.length, 2, 'Unexpected number of results for @installed query with quoted category');
assert.strictEqual(result.get(0).name, localEnabledTheme.manifest.name, 'Unexpected extension for @installed query with quoted category.');
assert.strictEqual(result.get(1).name, localDisabledTheme.manifest.name, 'Unexpected extension for @installed query with quoted category.');
});
await testableView.show('@installed category:"programming languages"').then(result => {
assert.strictEqual(result.length, 2, 'Unexpected number of results for @installed query with quoted category including space');
assert.strictEqual(result.get(0).name, localEnabledLanguage.manifest.name, 'Unexpected extension for @installed query with quoted category including space.');
assert.strictEqual(result.get(1).name, localDisabledLanguage.manifest.name, 'Unexpected extension for @installed query with quoted category inlcuding space.');
});
await testableView.show('@installed category:themes category:random').then(result => {
assert.strictEqual(result.length, 3, 'Unexpected number of results for @installed query with multiple category');
assert.strictEqual(result.get(0).name, localEnabledTheme.manifest.name, 'Unexpected extension for @installed query with multiple category.');
assert.strictEqual(result.get(1).name, localRandom.manifest.name, 'Unexpected extension for @installed query with multiple category.');
assert.strictEqual(result.get(2).name, localDisabledTheme.manifest.name, 'Unexpected extension for @installed query with multiple category.');
});
await testableView.show('@enabled category:themes').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @enabled query with category');
assert.strictEqual(result.get(0).name, localEnabledTheme.manifest.name, 'Unexpected extension for @enabled query with category.');
});
await testableView.show('@enabled category:"themes"').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @enabled query with quoted category');
assert.strictEqual(result.get(0).name, localEnabledTheme.manifest.name, 'Unexpected extension for @enabled query with quoted category.');
});
await testableView.show('@enabled category:"programming languages"').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @enabled query with quoted category inlcuding space');
assert.strictEqual(result.get(0).name, localEnabledLanguage.manifest.name, 'Unexpected extension for @enabled query with quoted category including space.');
});
await testableView.show('@disabled category:themes').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @disabled query with category');
assert.strictEqual(result.get(0).name, localDisabledTheme.manifest.name, 'Unexpected extension for @disabled query with category.');
});
await testableView.show('@disabled category:"themes"').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @disabled query with quoted category');
assert.strictEqual(result.get(0).name, localDisabledTheme.manifest.name, 'Unexpected extension for @disabled query with quoted category.');
});
await testableView.show('@disabled category:"programming languages"').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @disabled query with quoted category inlcuding space');
assert.strictEqual(result.get(0).name, localDisabledLanguage.manifest.name, 'Unexpected extension for @disabled query with quoted category including space.');
});
});
test('Test local query with sorting order', async () => {
await testableView.show('@recentlyUpdated').then(result => {
assert.strictEqual(result.length, 1, 'Unexpected number of results for @recentlyUpdated');
assert.strictEqual(result.get(0).name, localDisabledLanguage.manifest.name, 'Unexpected default sort order of extensions for @recentlyUpdate query');
});
await testableView.show('@installed @sort:updateDate').then(result => {
assert.strictEqual(result.length, 5, 'Unexpected number of results for @sort:updateDate. Expected all localy installed Extension which are not builtin');
const actual = [result.get(0).local?.installedTimestamp, result.get(1).local?.installedTimestamp, result.get(2).local?.installedTimestamp, result.get(3).local?.installedTimestamp, result.get(4).local?.installedTimestamp];
const expected = [localEnabledLanguage.installedTimestamp, localDisabledLanguage.installedTimestamp, localRandom.installedTimestamp, localDisabledTheme.installedTimestamp, localEnabledTheme.installedTimestamp];
for (let i = 0; i < result.length; i++) {
assert.strictEqual(actual[i], expected[i], 'Unexpected extension sorting for @sort:updateDate query.');
}
});
});
test('Test @recommended:workspace query', () => {
const workspaceRecommendedExtensions = [
workspaceRecommendationA,
workspaceRecommendationB,
configBasedRecommendationA,
];
const target = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'getExtensions', workspaceRecommendedExtensions);
return testableView.show('@recommended:workspace').then(result => {
const extensionInfos: IExtensionInfo[] = target.args[0][0];
assert.strictEqual(extensionInfos.length, workspaceRecommendedExtensions.length);
assert.strictEqual(result.length, workspaceRecommendedExtensions.length);
for (let i = 0; i < workspaceRecommendedExtensions.length; i++) {
assert.strictEqual(extensionInfos[i].id, workspaceRecommendedExtensions[i].identifier.id);
assert.strictEqual(result.get(i).identifier.id, workspaceRecommendedExtensions[i].identifier.id);
}
});
});
test('Test @recommended query', () => {
const allRecommendedExtensions = [
fileBasedRecommendationA,
fileBasedRecommendationB,
configBasedRecommendationB,
otherRecommendationA
];
const target = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'getExtensions', allRecommendedExtensions);
return testableView.show('@recommended').then(result => {
const extensionInfos: IExtensionInfo[] = target.args[0][0];
assert.strictEqual(extensionInfos.length, allRecommendedExtensions.length);
assert.strictEqual(result.length, allRecommendedExtensions.length);
for (let i = 0; i < allRecommendedExtensions.length; i++) {
assert.strictEqual(extensionInfos[i].id, allRecommendedExtensions[i].identifier.id);
assert.strictEqual(result.get(i).identifier.id, allRecommendedExtensions[i].identifier.id);
}
});
});
test('Test @recommended:all query', () => {
const allRecommendedExtensions = [
workspaceRecommendationA,
workspaceRecommendationB,
configBasedRecommendationA,
fileBasedRecommendationA,
fileBasedRecommendationB,
configBasedRecommendationB,
otherRecommendationA,
];
const target = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'getExtensions', allRecommendedExtensions);
return testableView.show('@recommended:all').then(result => {
const extensionInfos: IExtensionInfo[] = target.args[0][0];
assert.strictEqual(extensionInfos.length, allRecommendedExtensions.length);
assert.strictEqual(result.length, allRecommendedExtensions.length);
for (let i = 0; i < allRecommendedExtensions.length; i++) {
assert.strictEqual(extensionInfos[i].id, allRecommendedExtensions[i].identifier.id);
assert.strictEqual(result.get(i).identifier.id, allRecommendedExtensions[i].identifier.id);
}
});
});
test('Test curated list experiment', () => {
const curatedList = [
workspaceRecommendationA,
fileBasedRecommendationA
];
const experimentTarget = <SinonStub>instantiationService.stubPromise(IExperimentService, 'getCuratedExtensionsList', curatedList.map(e => e.identifier.id));
const queryTarget = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'getExtensions', curatedList);
return testableView.show('curated:mykey').then(result => {
const curatedKey: string = experimentTarget.args[0][0];
const extensionInfos: IExtensionInfo[] = queryTarget.args[0][0];
assert.ok(experimentTarget.calledOnce);
assert.strictEqual(extensionInfos.length, curatedList.length);
assert.strictEqual(result.length, curatedList.length);
for (let i = 0; i < curatedList.length; i++) {
assert.strictEqual(extensionInfos[i].id, curatedList[i].identifier.id);
assert.strictEqual(result.get(i).identifier.id, curatedList[i].identifier.id);
}
assert.strictEqual(curatedKey, 'mykey');
});
});
test('Test search', () => {
const searchText = 'search-me';
const results = [
fileBasedRecommendationA,
workspaceRecommendationA,
otherRecommendationA,
workspaceRecommendationB
];
const queryTarget = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(...results));
return testableView.show('search-me').then(result => {
const options: IQueryOptions = queryTarget.args[0][0];
assert.ok(queryTarget.calledOnce);
assert.strictEqual(options.text, searchText);
assert.strictEqual(result.length, results.length);
for (let i = 0; i < results.length; i++) {
assert.strictEqual(result.get(i).identifier.id, results[i].identifier.id);
}
});
});
test('Test preferred search experiment', () => {
const searchText = 'search-me';
const actual = [
fileBasedRecommendationA,
workspaceRecommendationA,
otherRecommendationA,
workspaceRecommendationB
];
const expected = [
workspaceRecommendationA,
workspaceRecommendationB,
fileBasedRecommendationA,
otherRecommendationA
];
const queryTarget = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(...actual));
const experimentTarget = <SinonStub>instantiationService.stubPromise(IExperimentService, 'getExperimentsByType', [{
id: 'someId',
enabled: true,
state: ExperimentState.Run,
action: {
type: ExperimentActionType.ExtensionSearchResults,
properties: {
searchText: 'search-me',
preferredResults: [
workspaceRecommendationA.identifier.id,
'something-that-wasnt-in-first-page',
workspaceRecommendationB.identifier.id
]
}
}
}]);
testableView.resetSearchExperiments();
testableView.dispose();
testableView = instantiationService.createInstance(ExtensionsListView, {}, { id: '', title: '' });
return testableView.show('search-me').then(result => {
const options: IQueryOptions = queryTarget.args[0][0];
assert.ok(experimentTarget.calledOnce);
assert.ok(queryTarget.calledOnce);
assert.strictEqual(options.text, searchText);
assert.strictEqual(result.length, expected.length);
for (let i = 0; i < expected.length; i++) {
assert.strictEqual(result.get(i).identifier.id, expected[i].identifier.id);
}
});
});
test('Skip preferred search experiment when user defines sort order', () => {
const searchText = 'search-me';
const realResults = [
fileBasedRecommendationA,
workspaceRecommendationA,
otherRecommendationA,
workspaceRecommendationB
];
const queryTarget = <SinonStub>instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage(...realResults));
testableView.dispose();
testableView = instantiationService.createInstance(ExtensionsListView, {}, { id: '', title: '' });
return testableView.show('search-me @sort:installs').then(result => {
const options: IQueryOptions = queryTarget.args[0][0];
assert.ok(queryTarget.calledOnce);
assert.strictEqual(options.text, searchText);
assert.strictEqual(result.length, realResults.length);
for (let i = 0; i < realResults.length; i++) {
assert.strictEqual(result.get(i).identifier.id, realResults[i].identifier.id);
}
});
});
function aLocalExtension(name: string = 'someext', manifest: any = {}, properties: any = {}): ILocalExtension {
manifest = { name, publisher: 'pub', version: '1.0.0', ...manifest };
properties = {
type: ExtensionType.User,
location: URI.file(`pub.${name}`),
identifier: { id: getGalleryExtensionId(manifest.publisher, manifest.name) },
metadata: { id: getGalleryExtensionId(manifest.publisher, manifest.name), publisherId: manifest.publisher, publisherDisplayName: 'somename' },
...properties
};
properties.isBuiltin = properties.type === ExtensionType.System;
return <ILocalExtension>Object.create({ manifest, ...properties });
}
function aGalleryExtension(name: string, properties: any = {}, galleryExtensionProperties: any = {}, assets: any = {}): IGalleryExtension {
const targetPlatform = getTargetPlatform(platform, arch);
const galleryExtension = <IGalleryExtension>Object.create({ name, publisher: 'pub', version: '1.0.0', allTargetPlatforms: [targetPlatform], properties: {}, assets: {}, ...properties });
galleryExtension.properties = { ...galleryExtension.properties, dependencies: [], targetPlatform, ...galleryExtensionProperties };
galleryExtension.assets = { ...galleryExtension.assets, ...assets };
galleryExtension.identifier = { id: getGalleryExtensionId(galleryExtension.publisher, galleryExtension.name), uuid: generateUuid() };
return <IGalleryExtension>galleryExtension;
}
function aPage<T>(...objects: T[]): IPager<T> {
return { firstPage: objects, total: objects.length, pageSize: objects.length, getPage: () => null! };
}
});
| src/vs/workbench/contrib/extensions/test/electron-browser/extensionsViews.test.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.9946159720420837,
0.21267415583133698,
0.00016163577674888074,
0.00017726766236592084,
0.3814016878604889
] |
{
"id": 3,
"code_window": [
"\t) {\n",
"\t\tsuper();\n",
"\n",
"\t\tthis._register(viewCell.onDidChangeOutputs(splice => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t\tthis._register(viewCell.onDidStartExecution(() => {\n",
"\t\t\tviewCell.updateOutputMinHeight(viewCell.layoutInfo.outputTotalHeight);\n",
"\t\t}));\n",
"\n",
"\t\tthis._register(viewCell.onDidStopExecution(() => {\n",
"\t\t\tthis._validateFinalOutputHeight(false);\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 450
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
import { renderMarkdown } from 'vs/base/browser/markdownRenderer';
import { Action, IAction } from 'vs/base/common/actions';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import * as nls from 'vs/nls';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { WorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { IMenuService, MenuId } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSION_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellOutputViewModel, ICellViewModel, IInsetRenderOutput, INotebookEditorDelegate, JUPYTER_EXTENSION_ID, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { mimetypeIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';
import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
interface IRenderResult {
initRenderIsSynchronous: false;
}
// DOM structure
//
// #output
// |
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | | #output-element
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
class CellOutputElement extends Disposable {
private readonly _renderDisposableStore = this._register(new DisposableStore());
innerContainer?: HTMLElement;
renderedOutputContainer!: HTMLElement;
renderResult?: IInsetRenderOutput;
private readonly contextKeyService: IContextKeyService;
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private cellOutputContainer: CellOutputContainer,
private outputContainer: FastDomNode<HTMLElement>,
readonly output: ICellOutputViewModel,
@INotebookService private readonly notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@IContextKeyService parentContextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this.contextKeyService = parentContextKeyService;
this._register(this.output.model.onDidChangeData(() => {
this.rerender();
}));
this._register(this.output.onDidResetRenderer(() => {
this.rerender();
}));
}
detach() {
this.renderedOutputContainer?.parentElement?.removeChild(this.renderedOutputContainer);
let count = 0;
if (this.innerContainer) {
for (let i = 0; i < this.innerContainer.childNodes.length; i++) {
if ((this.innerContainer.childNodes[i] as HTMLElement).className === 'rendered-output') {
count++;
}
if (count > 1) {
break;
}
}
if (count === 0) {
this.innerContainer.parentElement?.removeChild(this.innerContainer);
}
}
this.notebookEditor.removeInset(this.output);
}
updateDOMTop(top: number) {
if (this.innerContainer) {
this.innerContainer.style.top = `${top}px`;
}
}
rerender() {
if (
this.notebookEditor.hasModel() &&
this.innerContainer &&
this.renderResult &&
this.renderResult.type === RenderOutputType.Extension
) {
// Output rendered by extension renderer got an update
const [mimeTypes, pick] = this.output.resolveMimeTypes(this.notebookEditor.textModel, this.notebookEditor.activeKernel?.preloadProvides);
const pickedMimeType = mimeTypes[pick];
if (pickedMimeType.mimeType === this.renderResult.mimeType && pickedMimeType.rendererId === this.renderResult.renderer.id) {
// Same mimetype, same renderer, call the extension renderer to update
const index = this.viewCell.outputsViewModels.indexOf(this.output);
this.notebookEditor.updateOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
return;
}
}
if (!this.innerContainer) {
// init rendering didn't happen
const currOutputIndex = this.cellOutputContainer.renderedOutputEntries.findIndex(entry => entry.element === this);
const previousSibling = currOutputIndex > 0 && !!(this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer?.parentElement)
? this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer
: undefined;
this.render(previousSibling);
} else {
// Another mimetype or renderer is picked, we need to clear the current output and re-render
const nextElement = this.innerContainer.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(this.output);
}
this.render(nextElement as HTMLElement);
}
this._relayoutCell();
}
// insert after previousSibling
private _generateInnerOutputContainer(previousSibling: HTMLElement | undefined, pickedMimeTypeRenderer: IOrderedMimeType) {
this.innerContainer = DOM.$('.output-inner-container');
if (previousSibling && previousSibling.nextElementSibling) {
this.outputContainer.domNode.insertBefore(this.innerContainer, previousSibling.nextElementSibling);
} else {
this.outputContainer.domNode.appendChild(this.innerContainer);
}
this.innerContainer.setAttribute('output-mime-type', pickedMimeTypeRenderer.mimeType);
return this.innerContainer;
}
render(previousSibling: HTMLElement | undefined): IRenderResult | undefined {
const index = this.viewCell.outputsViewModels.indexOf(this.output);
if (this.viewCell.isOutputCollapsed || !this.notebookEditor.hasModel()) {
return undefined;
}
const notebookUri = CellUri.parse(this.viewCell.uri)?.notebook;
if (!notebookUri) {
return undefined;
}
const notebookTextModel = this.notebookEditor.textModel;
const [mimeTypes, pick] = this.output.resolveMimeTypes(notebookTextModel, this.notebookEditor.activeKernel?.preloadProvides);
if (!mimeTypes.find(mimeType => mimeType.isTrusted) || mimeTypes.length === 0) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#noMimeType');
return undefined;
}
const pickedMimeTypeRenderer = mimeTypes[pick];
const innerContainer = this._generateInnerOutputContainer(previousSibling, pickedMimeTypeRenderer);
this._attachToolbar(innerContainer, notebookTextModel, this.notebookEditor.activeKernel, index, mimeTypes);
this.renderedOutputContainer = DOM.append(innerContainer, DOM.$('.rendered-output'));
const renderer = this.notebookService.getRendererInfo(pickedMimeTypeRenderer.rendererId);
this.renderResult = renderer
? { type: RenderOutputType.Extension, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType }
: this._renderMissingRenderer(this.output, pickedMimeTypeRenderer.mimeType);
this.output.pickedMimeType = pickedMimeTypeRenderer;
if (!this.renderResult) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#renderResultUndefined');
return undefined;
}
this.notebookEditor.createOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
innerContainer.classList.add('background');
return { initRenderIsSynchronous: false };
}
private _renderMissingRenderer(viewModel: ICellOutputViewModel, preferredMimeType: string | undefined): IInsetRenderOutput {
if (!viewModel.model.outputs.length) {
return this._renderMessage(viewModel, nls.localize('empty', "Cell has no output"));
}
if (!preferredMimeType) {
const mimeTypes = viewModel.model.outputs.map(op => op.mime);
const mimeTypesMessage = mimeTypes.join(', ');
return this._renderMessage(viewModel, nls.localize('noRenderer.2', "No renderer could be found for output. It has the following mimetypes: {0}", mimeTypesMessage));
}
return this._renderSearchForMimetype(viewModel, preferredMimeType);
}
private _renderSearchForMimetype(viewModel: ICellOutputViewModel, mimeType: string): IInsetRenderOutput {
const query = `@tag:notebookRenderer ${mimeType}`;
const p = DOM.$('p', undefined, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
const a = DOM.$('a', { href: `command:workbench.extensions.search?%22${query}%22`, class: 'monaco-button monaco-text-button', tabindex: 0, role: 'button', style: 'padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;' }, `Search Marketplace`);
return {
type: RenderOutputType.Html,
source: viewModel,
htmlContent: p.outerHTML + a.outerHTML
};
}
private _renderMessage(viewModel: ICellOutputViewModel, message: string): IInsetRenderOutput {
const el = DOM.$('p', undefined, message);
return { type: RenderOutputType.Html, source: viewModel, htmlContent: el.outerHTML };
}
private async _attachToolbar(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, index: number, mimeTypes: readonly IOrderedMimeType[]) {
const hasMultipleMimeTypes = mimeTypes.filter(mimeType => mimeType.isTrusted).length <= 1;
if (index > 0 && hasMultipleMimeTypes) {
return;
}
if (!this.notebookEditor.hasModel()) {
return;
}
const useConsolidatedButton = this.notebookEditor.notebookOptions.getLayoutConfiguration().consolidatedOutputButton;
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.cell-output-toolbar');
outputItemDiv.appendChild(mimeTypePicker);
const toolbar = this._renderDisposableStore.add(this.instantiationService.createInstance(WorkbenchToolBar, mimeTypePicker, {
renderDropdownAsChildElement: false
}));
toolbar.context = <INotebookCellActionContext>{
ui: true,
cell: this.output.cellViewModel as ICellViewModel,
notebookEditor: this.notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
};
// TODO: This could probably be a real registered action, but it has to talk to this output element
const pickAction = new Action('notebook.output.pickMimetype', nls.localize('pickMimeType', "Change Presentation"), ThemeIcon.asClassName(mimetypeIcon), undefined,
async _context => this._pickActiveMimeTypeRenderer(outputItemDiv, notebookTextModel, kernel, this.output));
if (index === 0 && useConsolidatedButton) {
const menu = this._renderDisposableStore.add(this.menuService.createMenu(MenuId.NotebookOutputToolbar, this.contextKeyService));
const updateMenuToolbar = () => {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, result, () => false);
toolbar.setActions([], [pickAction, ...secondary]);
};
updateMenuToolbar();
this._renderDisposableStore.add(menu.onDidChange(updateMenuToolbar));
} else {
toolbar.setActions([pickAction]);
}
}
private async _pickActiveMimeTypeRenderer(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, viewModel: ICellOutputViewModel) {
const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, kernel?.preloadProvides);
const items: IMimeTypeRenderer[] = [];
const unsupportedItems: IMimeTypeRenderer[] = [];
mimeTypes.forEach((mimeType, index) => {
if (mimeType.isTrusted) {
const arr = mimeType.rendererId === RENDERER_NOT_AVAILABLE ?
unsupportedItems :
items;
arr.push({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
detail: this._generateRendererInfo(mimeType.rendererId),
description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined
});
}
});
if (unsupportedItems.some(m => JUPYTER_RENDERER_MIMETYPES.includes(m.id!))) {
unsupportedItems.push({
label: nls.localize('installJupyterPrompt', "Install additional renderers from the marketplace"),
id: 'installRenderers',
index: mimeTypes.length
});
}
const picker = this.quickInputService.createQuickPick();
picker.items = [
...items,
{ type: 'separator' },
...unsupportedItems
];
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = items.length !== mimeTypes.length
? nls.localize('promptChooseMimeTypeInSecure.placeHolder', "Select mimetype to render for current output")
: nls.localize('promptChooseMimeType.placeHolder', "Select mimetype to render for current output");
const pick = await new Promise<IMimeTypeRenderer | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer) : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined || pick.index === currIndex) {
return;
}
if (pick.id === 'installRenderers') {
this._showJupyterExtension();
return;
}
// user chooses another mimetype
const nextElement = outputItemDiv.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(viewModel);
}
viewModel.pickedMimeType = mimeTypes[pick.index];
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
const { mimeType, rendererId } = mimeTypes[pick.index];
this.notebookService.updateMimePreferredRenderer(notebookTextModel.viewType, mimeType, rendererId, mimeTypes.map(m => m.mimeType));
this.render(nextElement as HTMLElement);
this._validateFinalOutputHeight(false);
this._relayoutCell();
}
private async _showJupyterExtension() {
const viewlet = await this.paneCompositeService.openPaneComposite(EXTENSION_VIEWLET_ID, ViewContainerLocation.Sidebar, true);
const view = viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer | undefined;
view?.search(`@id:${JUPYTER_EXTENSION_ID}`);
}
private _generateRendererInfo(renderId: string): string {
const renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
const displayName = renderInfo.displayName !== '' ? renderInfo.displayName : renderInfo.id;
return `${displayName} (${renderInfo.extensionId.value})`;
}
return nls.localize('unavailableRenderInfo', "renderer not available");
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
if (this._outputHeightTimer) {
this.viewCell.unlockOutputHeight();
clearTimeout(this._outputHeightTimer);
}
super.dispose();
}
}
class OutputEntryViewHandler {
constructor(
readonly model: ICellOutputViewModel,
readonly element: CellOutputElement
) {
}
}
export class CellOutputContainer extends CellContentPart {
private _outputEntries: OutputEntryViewHandler[] = [];
get renderedOutputEntries() {
return this._outputEntries;
}
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private readonly templateData: CodeCellRenderTemplate,
private options: { limit: number },
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._register(viewCell.onDidChangeOutputs(splice => {
this._updateOutputs(splice);
}));
this._register(viewCell.onDidChangeLayout(() => {
this.updateInternalLayoutNow(viewCell);
}));
}
override updateInternalLayoutNow(viewCell: CodeCellViewModel) {
this.templateData.outputContainer.setTop(viewCell.layoutInfo.outputContainerOffset);
this.templateData.outputShowMoreContainer.setTop(viewCell.layoutInfo.outputShowMoreContainerOffset);
this._outputEntries.forEach(entry => {
const index = this.viewCell.outputsViewModels.indexOf(entry.model);
if (index >= 0) {
const top = this.viewCell.getOutputOffsetInContainer(index);
entry.element.updateDOMTop(top);
}
});
}
render() {
if (this.viewCell.outputsViewModels.length > 0) {
if (this.viewCell.layoutInfo.outputTotalHeight !== 0) {
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
this._relayoutCell();
}
DOM.show(this.templateData.outputContainer.domNode);
for (let index = 0; index < Math.min(this.options.limit, this.viewCell.outputsViewModels.length); index++) {
const currOutput = this.viewCell.outputsViewModels[index];
const entry = this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, currOutput);
this._outputEntries.push(new OutputEntryViewHandler(currOutput, entry));
entry.render(undefined);
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(46);
}
this._relayoutCell();
this._validateFinalOutputHeight(false);
} else {
// noop
this._relayoutCell();
DOM.hide(this.templateData.outputContainer.domNode);
}
this.templateData.outputShowMoreContainer.domNode.innerText = '';
if (this.viewCell.outputsViewModels.length > this.options.limit) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(0);
}
}
viewUpdateShowOutputs(initRendering: boolean): void {
for (let index = 0; index < this._outputEntries.length; index++) {
const viewHandler = this._outputEntries[index];
const outputEntry = viewHandler.element;
if (outputEntry.renderResult) {
this.notebookEditor.createOutput(this.viewCell, outputEntry.renderResult as IInsetRenderOutput, this.viewCell.getOutputOffset(index));
} else {
outputEntry.render(undefined);
}
}
this._relayoutCell();
}
viewUpdateHideOuputs(): void {
for (let index = 0; index < this._outputEntries.length; index++) {
this.notebookEditor.hideInset(this._outputEntries[index].model);
}
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _updateOutputs(splice: NotebookCellOutputsSplice) {
const previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;
// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.
this.viewCell.updateOutputMinHeight(previousOutputHeight);
if (this.viewCell.outputsViewModels.length) {
DOM.show(this.templateData.outputContainer.domNode);
} else {
DOM.hide(this.templateData.outputContainer.domNode);
}
this.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));
this._renderNow(splice);
}
private _renderNow(splice: NotebookCellOutputsSplice) {
if (splice.start >= this.options.limit) {
// splice items out of limit
return;
}
const firstGroupEntries = this._outputEntries.slice(0, splice.start);
const deletedEntries = this._outputEntries.slice(splice.start, splice.start + splice.deleteCount);
const secondGroupEntries = this._outputEntries.slice(splice.start + splice.deleteCount);
let newlyInserted = this.viewCell.outputsViewModels.slice(splice.start, splice.start + splice.newOutputs.length);
// [...firstGroup, ...deletedEntries, ...secondGroupEntries] [...restInModel]
// [...firstGroup, ...newlyInserted, ...secondGroupEntries, restInModel]
if (firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length > this.options.limit) {
// exceeds limit again
if (firstGroupEntries.length + newlyInserted.length > this.options.limit) {
[...deletedEntries, ...secondGroupEntries].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
newlyInserted = newlyInserted.slice(0, this.options.limit - firstGroupEntries.length);
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries];
// render newly inserted outputs
for (let i = firstGroupEntries.length; i < this._outputEntries.length; i++) {
this._outputEntries[i].element.render(undefined);
}
} else {
// part of secondGroupEntries are pushed out of view
// now we have to be creative as secondGroupEntries might not use dedicated containers
const elementsPushedOutOfView = secondGroupEntries.slice(this.options.limit - firstGroupEntries.length - newlyInserted.length);
[...deletedEntries, ...elementsPushedOutOfView].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
// exclusive
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries.slice(0, this.options.limit - firstGroupEntries.length - newlyInserted.length)];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
}
} else {
// after splice, it doesn't exceed
deletedEntries.forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
let outputsNewlyAvailable: OutputEntryViewHandler[] = [];
if (firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length < this.viewCell.outputsViewModels.length) {
const last = Math.min(this.options.limit, this.viewCell.outputsViewModels.length);
outputsNewlyAvailable = this.viewCell.outputsViewModels.slice(firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length, last).map(output => {
return new OutputEntryViewHandler(output, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, output));
});
}
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries, ...outputsNewlyAvailable];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
for (let i = 0; i < outputsNewlyAvailable.length; i++) {
this._outputEntries[firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length + i].element.render(undefined);
}
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
if (!this.templateData.outputShowMoreContainer.domNode.hasChildNodes()) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
}
this.viewCell.updateOutputShowMoreContainerHeight(46);
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
}
const editorHeight = this.templateData.editor.getContentHeight();
this.viewCell.editorHeight = editorHeight;
this._relayoutCell();
// if it's clearing all outputs, or outputs are all rendered synchronously
// shrink immediately as the final output height will be zero.
this._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);
}
private _generateShowMoreElement(disposables: DisposableStore): HTMLElement {
const md: IMarkdownString = {
value: `There are more than ${this.options.limit} outputs, [show more (open the raw output data in a text editor) ...](command:workbench.action.openLargeOutput)`,
isTrusted: true,
supportThemeIcons: true
};
const rendered = renderMarkdown(md, {
actionHandler: {
callback: (content) => {
if (content === 'command:workbench.action.openLargeOutput') {
this.openerService.open(CellUri.generateCellOutputUri(this.notebookEditor.textModel!.uri));
}
return;
},
disposables
}
});
disposables.add(rendered);
rendered.element.classList.add('output-show-more');
return rendered.element;
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
this.viewCell.updateOutputMinHeight(0);
if (this._outputHeightTimer) {
clearTimeout(this._outputHeightTimer);
}
this._outputEntries.forEach(entry => {
entry.element.dispose();
});
super.dispose();
}
}
const JUPYTER_RENDERER_MIMETYPES = [
'application/geo+json',
'application/vdom.v1+json',
'application/vnd.dataresource+json',
'application/vnd.plotly.v1+json',
'application/vnd.vega.v2+json',
'application/vnd.vega.v3+json',
'application/vnd.vega.v4+json',
'application/vnd.vega.v5+json',
'application/vnd.vegalite.v1+json',
'application/vnd.vegalite.v2+json',
'application/vnd.vegalite.v3+json',
'application/vnd.vegalite.v4+json',
'application/x-nteract-model-debug+json',
'image/svg+xml',
'text/latex',
'text/vnd.plotly.v1+html',
'application/vnd.jupyter.widget-view+json',
'application/vnd.code.notebook.error'
];
| src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.9682831764221191,
0.02708876132965088,
0.00016495231830049306,
0.00019011698896065354,
0.1449815332889557
] |
{
"id": 3,
"code_window": [
"\t) {\n",
"\t\tsuper();\n",
"\n",
"\t\tthis._register(viewCell.onDidChangeOutputs(splice => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t\tthis._register(viewCell.onDidStartExecution(() => {\n",
"\t\t\tviewCell.updateOutputMinHeight(viewCell.layoutInfo.outputTotalHeight);\n",
"\t\t}));\n",
"\n",
"\t\tthis._register(viewCell.onDidStopExecution(() => {\n",
"\t\t\tthis._validateFinalOutputHeight(false);\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 450
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Iterable } from 'vs/base/common/iterator';
import { TestResultState } from 'vs/workbench/contrib/testing/common/testTypes';
import { maxPriority, statePriority } from 'vs/workbench/contrib/testing/common/testingStates';
/**
* Accessor for nodes in get and refresh computed state.
*/
export interface IComputedStateAccessor<T> {
getOwnState(item: T): TestResultState | undefined;
getCurrentComputedState(item: T): TestResultState;
setComputedState(item: T, state: TestResultState): void;
getChildren(item: T): Iterable<T>;
getParents(item: T): Iterable<T>;
}
export interface IComputedStateAndDurationAccessor<T> extends IComputedStateAccessor<T> {
getOwnDuration(item: T): number | undefined;
getCurrentComputedDuration(item: T): number | undefined;
setComputedDuration(item: T, duration: number | undefined): void;
}
const isDurationAccessor = <T>(accessor: IComputedStateAccessor<T>): accessor is IComputedStateAndDurationAccessor<T> => 'getOwnDuration' in accessor;
/**
* Gets the computed state for the node.
* @param force whether to refresh the computed state for this node, even
* if it was previously set.
*/
const getComputedState = <T>(accessor: IComputedStateAccessor<T>, node: T, force = false) => {
let computed = accessor.getCurrentComputedState(node);
if (computed === undefined || force) {
computed = accessor.getOwnState(node) ?? TestResultState.Unset;
for (const child of accessor.getChildren(node)) {
const childComputed = getComputedState(accessor, child);
// If all children are skipped, make the current state skipped too if unset (#131537)
computed = childComputed === TestResultState.Skipped && computed === TestResultState.Unset
? TestResultState.Skipped : maxPriority(computed, childComputed);
}
accessor.setComputedState(node, computed);
}
return computed;
};
const getComputedDuration = <T>(accessor: IComputedStateAndDurationAccessor<T>, node: T, force = false): number | undefined => {
let computed = accessor.getCurrentComputedDuration(node);
if (computed === undefined || force) {
const own = accessor.getOwnDuration(node);
if (own !== undefined) {
computed = own;
} else {
computed = undefined;
for (const child of accessor.getChildren(node)) {
const d = getComputedDuration(accessor, child);
if (d !== undefined) {
computed = (computed || 0) + d;
}
}
}
accessor.setComputedDuration(node, computed);
}
return computed;
};
/**
* Refreshes the computed state for the node and its parents. Any changes
* elements cause `addUpdated` to be called.
*/
export const refreshComputedState = <T>(
accessor: IComputedStateAccessor<T>,
node: T,
explicitNewComputedState?: TestResultState,
refreshDuration = true,
) => {
const oldState = accessor.getCurrentComputedState(node);
const oldPriority = statePriority[oldState];
const newState = explicitNewComputedState ?? getComputedState(accessor, node, true);
const newPriority = statePriority[newState];
const toUpdate = new Set<T>();
if (newPriority !== oldPriority) {
accessor.setComputedState(node, newState);
toUpdate.add(node);
if (newPriority > oldPriority) {
// Update all parents to ensure they're at least this priority.
for (const parent of accessor.getParents(node)) {
const prev = accessor.getCurrentComputedState(parent);
if (prev !== undefined && statePriority[prev] >= newPriority) {
break;
}
accessor.setComputedState(parent, newState);
toUpdate.add(parent);
}
} else if (newPriority < oldPriority) {
// Re-render all parents of this node whose computed priority might have come from this node
for (const parent of accessor.getParents(node)) {
const prev = accessor.getCurrentComputedState(parent);
if (prev === undefined || statePriority[prev] > oldPriority) {
break;
}
accessor.setComputedState(parent, getComputedState(accessor, parent, true));
toUpdate.add(parent);
}
}
}
if (isDurationAccessor(accessor) && refreshDuration) {
for (const parent of Iterable.concat(Iterable.single(node), accessor.getParents(node))) {
const oldDuration = accessor.getCurrentComputedDuration(parent);
const newDuration = getComputedDuration(accessor, parent, true);
if (oldDuration === newDuration) {
break;
}
accessor.setComputedDuration(parent, newDuration);
toUpdate.add(parent);
}
}
return toUpdate;
};
| src/vs/workbench/contrib/testing/common/getComputedState.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00019760643772315234,
0.00017322083294857293,
0.00016638585657346994,
0.00017146668687928468,
0.000007294911483768374
] |
{
"id": 3,
"code_window": [
"\t) {\n",
"\t\tsuper();\n",
"\n",
"\t\tthis._register(viewCell.onDidChangeOutputs(splice => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t\tthis._register(viewCell.onDidStartExecution(() => {\n",
"\t\t\tviewCell.updateOutputMinHeight(viewCell.layoutInfo.outputTotalHeight);\n",
"\t\t}));\n",
"\n",
"\t\tthis._register(viewCell.onDidStopExecution(() => {\n",
"\t\t\tthis._validateFinalOutputHeight(false);\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 450
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const IIntegrityService = createDecorator<IIntegrityService>('integrityService');
export interface ChecksumPair {
uri: URI;
actual: string;
expected: string;
isPure: boolean;
}
export interface IntegrityTestResult {
isPure: boolean;
proof: ChecksumPair[];
}
export interface IIntegrityService {
readonly _serviceBrand: undefined;
isPure(): Promise<IntegrityTestResult>;
}
| src/vs/workbench/services/integrity/common/integrity.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017750666302163154,
0.00017234781989827752,
0.00016917959146667272,
0.00017035721975844353,
0.0000036793942399526713
] |
{
"id": 3,
"code_window": [
"\t) {\n",
"\t\tsuper();\n",
"\n",
"\t\tthis._register(viewCell.onDidChangeOutputs(splice => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t\tthis._register(viewCell.onDidStartExecution(() => {\n",
"\t\t\tviewCell.updateOutputMinHeight(viewCell.layoutInfo.outputTotalHeight);\n",
"\t\t}));\n",
"\n",
"\t\tthis._register(viewCell.onDidStopExecution(() => {\n",
"\t\t\tthis._validateFinalOutputHeight(false);\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "add",
"edit_start_line_idx": 450
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IDisposable } from 'vs/base/common/lifecycle';
import { Disposable } from 'vs/workbench/api/common/extHostTypes';
import type * as vscode from 'vscode';
import { MainContext, ExtHostDocumentContentProvidersShape, MainThreadDocumentContentProvidersShape, IMainContext } from './extHost.protocol';
import { ExtHostDocumentsAndEditors } from './extHostDocumentsAndEditors';
import { Schemas } from 'vs/base/common/network';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationToken } from 'vs/base/common/cancellation';
import { splitLines } from 'vs/base/common/strings';
export class ExtHostDocumentContentProvider implements ExtHostDocumentContentProvidersShape {
private static _handlePool = 0;
private readonly _documentContentProviders = new Map<number, vscode.TextDocumentContentProvider>();
private readonly _proxy: MainThreadDocumentContentProvidersShape;
constructor(
mainContext: IMainContext,
private readonly _documentsAndEditors: ExtHostDocumentsAndEditors,
private readonly _logService: ILogService,
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadDocumentContentProviders);
}
registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider): vscode.Disposable {
// todo@remote
// check with scheme from fs-providers!
if (Object.keys(Schemas).indexOf(scheme) >= 0) {
throw new Error(`scheme '${scheme}' already registered`);
}
const handle = ExtHostDocumentContentProvider._handlePool++;
this._documentContentProviders.set(handle, provider);
this._proxy.$registerTextContentProvider(handle, scheme);
let subscription: IDisposable | undefined;
if (typeof provider.onDidChange === 'function') {
subscription = provider.onDidChange(uri => {
if (uri.scheme !== scheme) {
this._logService.warn(`Provider for scheme '${scheme}' is firing event for schema '${uri.scheme}' which will be IGNORED`);
return;
}
if (this._documentsAndEditors.getDocument(uri)) {
this.$provideTextDocumentContent(handle, uri).then(value => {
if (!value && typeof value !== 'string') {
return;
}
const document = this._documentsAndEditors.getDocument(uri);
if (!document) {
// disposed in the meantime
return;
}
// create lines and compare
const lines = splitLines(value);
// broadcast event when content changed
if (!document.equalLines(lines)) {
return this._proxy.$onVirtualDocumentChange(uri, value);
}
}, onUnexpectedError);
}
});
}
return new Disposable(() => {
if (this._documentContentProviders.delete(handle)) {
this._proxy.$unregisterTextContentProvider(handle);
}
if (subscription) {
subscription.dispose();
subscription = undefined;
}
});
}
$provideTextDocumentContent(handle: number, uri: UriComponents): Promise<string | null | undefined> {
const provider = this._documentContentProviders.get(handle);
if (!provider) {
return Promise.reject(new Error(`unsupported uri-scheme: ${uri.scheme}`));
}
return Promise.resolve(provider.provideTextDocumentContent(URI.revive(uri), CancellationToken.None));
}
}
| src/vs/workbench/api/common/extHostDocumentContentProviders.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017607197514735162,
0.00016814041009638458,
0.00016517250332981348,
0.00016705403686501086,
0.0000030410233193833847
] |
{
"id": 4,
"code_window": [
"\t\tthis._register(viewCell.onDidChangeOutputs(splice => {\n",
"\t\t\tthis._updateOutputs(splice);\n",
"\t\t}));\n",
"\n",
"\t\tthis._register(viewCell.onDidChangeLayout(() => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst executionState = this._notebookExecutionStateService.getCellExecution(viewCell.uri);\n",
"\t\t\tconst context = executionState ? CellOutputUpdateContext.Execution : CellOutputUpdateContext.Other;\n",
"\t\t\tthis._updateOutputs(splice, context);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 451
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
import { renderMarkdown } from 'vs/base/browser/markdownRenderer';
import { Action, IAction } from 'vs/base/common/actions';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import * as nls from 'vs/nls';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { WorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { IMenuService, MenuId } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSION_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellOutputViewModel, ICellViewModel, IInsetRenderOutput, INotebookEditorDelegate, JUPYTER_EXTENSION_ID, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { mimetypeIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { CellContentPart } from 'vs/workbench/contrib/notebook/browser/view/cellPart';
import { CodeCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { CellUri, IOrderedMimeType, NotebookCellOutputsSplice, RENDERER_NOT_AVAILABLE } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookKernel } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
interface IRenderResult {
initRenderIsSynchronous: false;
}
// DOM structure
//
// #output
// |
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | | #output-element
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
// | #output-inner-container
// | | #cell-output-toolbar
// | | #output-element
class CellOutputElement extends Disposable {
private readonly _renderDisposableStore = this._register(new DisposableStore());
innerContainer?: HTMLElement;
renderedOutputContainer!: HTMLElement;
renderResult?: IInsetRenderOutput;
private readonly contextKeyService: IContextKeyService;
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private cellOutputContainer: CellOutputContainer,
private outputContainer: FastDomNode<HTMLElement>,
readonly output: ICellOutputViewModel,
@INotebookService private readonly notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@IContextKeyService parentContextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this.contextKeyService = parentContextKeyService;
this._register(this.output.model.onDidChangeData(() => {
this.rerender();
}));
this._register(this.output.onDidResetRenderer(() => {
this.rerender();
}));
}
detach() {
this.renderedOutputContainer?.parentElement?.removeChild(this.renderedOutputContainer);
let count = 0;
if (this.innerContainer) {
for (let i = 0; i < this.innerContainer.childNodes.length; i++) {
if ((this.innerContainer.childNodes[i] as HTMLElement).className === 'rendered-output') {
count++;
}
if (count > 1) {
break;
}
}
if (count === 0) {
this.innerContainer.parentElement?.removeChild(this.innerContainer);
}
}
this.notebookEditor.removeInset(this.output);
}
updateDOMTop(top: number) {
if (this.innerContainer) {
this.innerContainer.style.top = `${top}px`;
}
}
rerender() {
if (
this.notebookEditor.hasModel() &&
this.innerContainer &&
this.renderResult &&
this.renderResult.type === RenderOutputType.Extension
) {
// Output rendered by extension renderer got an update
const [mimeTypes, pick] = this.output.resolveMimeTypes(this.notebookEditor.textModel, this.notebookEditor.activeKernel?.preloadProvides);
const pickedMimeType = mimeTypes[pick];
if (pickedMimeType.mimeType === this.renderResult.mimeType && pickedMimeType.rendererId === this.renderResult.renderer.id) {
// Same mimetype, same renderer, call the extension renderer to update
const index = this.viewCell.outputsViewModels.indexOf(this.output);
this.notebookEditor.updateOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
return;
}
}
if (!this.innerContainer) {
// init rendering didn't happen
const currOutputIndex = this.cellOutputContainer.renderedOutputEntries.findIndex(entry => entry.element === this);
const previousSibling = currOutputIndex > 0 && !!(this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer?.parentElement)
? this.cellOutputContainer.renderedOutputEntries[currOutputIndex - 1].element.innerContainer
: undefined;
this.render(previousSibling);
} else {
// Another mimetype or renderer is picked, we need to clear the current output and re-render
const nextElement = this.innerContainer.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(this.output);
}
this.render(nextElement as HTMLElement);
}
this._relayoutCell();
}
// insert after previousSibling
private _generateInnerOutputContainer(previousSibling: HTMLElement | undefined, pickedMimeTypeRenderer: IOrderedMimeType) {
this.innerContainer = DOM.$('.output-inner-container');
if (previousSibling && previousSibling.nextElementSibling) {
this.outputContainer.domNode.insertBefore(this.innerContainer, previousSibling.nextElementSibling);
} else {
this.outputContainer.domNode.appendChild(this.innerContainer);
}
this.innerContainer.setAttribute('output-mime-type', pickedMimeTypeRenderer.mimeType);
return this.innerContainer;
}
render(previousSibling: HTMLElement | undefined): IRenderResult | undefined {
const index = this.viewCell.outputsViewModels.indexOf(this.output);
if (this.viewCell.isOutputCollapsed || !this.notebookEditor.hasModel()) {
return undefined;
}
const notebookUri = CellUri.parse(this.viewCell.uri)?.notebook;
if (!notebookUri) {
return undefined;
}
const notebookTextModel = this.notebookEditor.textModel;
const [mimeTypes, pick] = this.output.resolveMimeTypes(notebookTextModel, this.notebookEditor.activeKernel?.preloadProvides);
if (!mimeTypes.find(mimeType => mimeType.isTrusted) || mimeTypes.length === 0) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#noMimeType');
return undefined;
}
const pickedMimeTypeRenderer = mimeTypes[pick];
const innerContainer = this._generateInnerOutputContainer(previousSibling, pickedMimeTypeRenderer);
this._attachToolbar(innerContainer, notebookTextModel, this.notebookEditor.activeKernel, index, mimeTypes);
this.renderedOutputContainer = DOM.append(innerContainer, DOM.$('.rendered-output'));
const renderer = this.notebookService.getRendererInfo(pickedMimeTypeRenderer.rendererId);
this.renderResult = renderer
? { type: RenderOutputType.Extension, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType }
: this._renderMissingRenderer(this.output, pickedMimeTypeRenderer.mimeType);
this.output.pickedMimeType = pickedMimeTypeRenderer;
if (!this.renderResult) {
this.viewCell.updateOutputHeight(index, 0, 'CellOutputElement#renderResultUndefined');
return undefined;
}
this.notebookEditor.createOutput(this.viewCell, this.renderResult, this.viewCell.getOutputOffset(index));
innerContainer.classList.add('background');
return { initRenderIsSynchronous: false };
}
private _renderMissingRenderer(viewModel: ICellOutputViewModel, preferredMimeType: string | undefined): IInsetRenderOutput {
if (!viewModel.model.outputs.length) {
return this._renderMessage(viewModel, nls.localize('empty', "Cell has no output"));
}
if (!preferredMimeType) {
const mimeTypes = viewModel.model.outputs.map(op => op.mime);
const mimeTypesMessage = mimeTypes.join(', ');
return this._renderMessage(viewModel, nls.localize('noRenderer.2', "No renderer could be found for output. It has the following mimetypes: {0}", mimeTypesMessage));
}
return this._renderSearchForMimetype(viewModel, preferredMimeType);
}
private _renderSearchForMimetype(viewModel: ICellOutputViewModel, mimeType: string): IInsetRenderOutput {
const query = `@tag:notebookRenderer ${mimeType}`;
const p = DOM.$('p', undefined, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
const a = DOM.$('a', { href: `command:workbench.extensions.search?%22${query}%22`, class: 'monaco-button monaco-text-button', tabindex: 0, role: 'button', style: 'padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;' }, `Search Marketplace`);
return {
type: RenderOutputType.Html,
source: viewModel,
htmlContent: p.outerHTML + a.outerHTML
};
}
private _renderMessage(viewModel: ICellOutputViewModel, message: string): IInsetRenderOutput {
const el = DOM.$('p', undefined, message);
return { type: RenderOutputType.Html, source: viewModel, htmlContent: el.outerHTML };
}
private async _attachToolbar(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, index: number, mimeTypes: readonly IOrderedMimeType[]) {
const hasMultipleMimeTypes = mimeTypes.filter(mimeType => mimeType.isTrusted).length <= 1;
if (index > 0 && hasMultipleMimeTypes) {
return;
}
if (!this.notebookEditor.hasModel()) {
return;
}
const useConsolidatedButton = this.notebookEditor.notebookOptions.getLayoutConfiguration().consolidatedOutputButton;
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.cell-output-toolbar');
outputItemDiv.appendChild(mimeTypePicker);
const toolbar = this._renderDisposableStore.add(this.instantiationService.createInstance(WorkbenchToolBar, mimeTypePicker, {
renderDropdownAsChildElement: false
}));
toolbar.context = <INotebookCellActionContext>{
ui: true,
cell: this.output.cellViewModel as ICellViewModel,
notebookEditor: this.notebookEditor,
$mid: MarshalledId.NotebookCellActionContext
};
// TODO: This could probably be a real registered action, but it has to talk to this output element
const pickAction = new Action('notebook.output.pickMimetype', nls.localize('pickMimeType', "Change Presentation"), ThemeIcon.asClassName(mimetypeIcon), undefined,
async _context => this._pickActiveMimeTypeRenderer(outputItemDiv, notebookTextModel, kernel, this.output));
if (index === 0 && useConsolidatedButton) {
const menu = this._renderDisposableStore.add(this.menuService.createMenu(MenuId.NotebookOutputToolbar, this.contextKeyService));
const updateMenuToolbar = () => {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, result, () => false);
toolbar.setActions([], [pickAction, ...secondary]);
};
updateMenuToolbar();
this._renderDisposableStore.add(menu.onDidChange(updateMenuToolbar));
} else {
toolbar.setActions([pickAction]);
}
}
private async _pickActiveMimeTypeRenderer(outputItemDiv: HTMLElement, notebookTextModel: NotebookTextModel, kernel: INotebookKernel | undefined, viewModel: ICellOutputViewModel) {
const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, kernel?.preloadProvides);
const items: IMimeTypeRenderer[] = [];
const unsupportedItems: IMimeTypeRenderer[] = [];
mimeTypes.forEach((mimeType, index) => {
if (mimeType.isTrusted) {
const arr = mimeType.rendererId === RENDERER_NOT_AVAILABLE ?
unsupportedItems :
items;
arr.push({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
detail: this._generateRendererInfo(mimeType.rendererId),
description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined
});
}
});
if (unsupportedItems.some(m => JUPYTER_RENDERER_MIMETYPES.includes(m.id!))) {
unsupportedItems.push({
label: nls.localize('installJupyterPrompt', "Install additional renderers from the marketplace"),
id: 'installRenderers',
index: mimeTypes.length
});
}
const picker = this.quickInputService.createQuickPick();
picker.items = [
...items,
{ type: 'separator' },
...unsupportedItems
];
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = items.length !== mimeTypes.length
? nls.localize('promptChooseMimeTypeInSecure.placeHolder', "Select mimetype to render for current output")
: nls.localize('promptChooseMimeType.placeHolder', "Select mimetype to render for current output");
const pick = await new Promise<IMimeTypeRenderer | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer) : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined || pick.index === currIndex) {
return;
}
if (pick.id === 'installRenderers') {
this._showJupyterExtension();
return;
}
// user chooses another mimetype
const nextElement = outputItemDiv.nextElementSibling;
this._renderDisposableStore.clear();
const element = this.innerContainer;
if (element) {
element.parentElement?.removeChild(element);
this.notebookEditor.removeInset(viewModel);
}
viewModel.pickedMimeType = mimeTypes[pick.index];
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
const { mimeType, rendererId } = mimeTypes[pick.index];
this.notebookService.updateMimePreferredRenderer(notebookTextModel.viewType, mimeType, rendererId, mimeTypes.map(m => m.mimeType));
this.render(nextElement as HTMLElement);
this._validateFinalOutputHeight(false);
this._relayoutCell();
}
private async _showJupyterExtension() {
const viewlet = await this.paneCompositeService.openPaneComposite(EXTENSION_VIEWLET_ID, ViewContainerLocation.Sidebar, true);
const view = viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer | undefined;
view?.search(`@id:${JUPYTER_EXTENSION_ID}`);
}
private _generateRendererInfo(renderId: string): string {
const renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
const displayName = renderInfo.displayName !== '' ? renderInfo.displayName : renderInfo.id;
return `${displayName} (${renderInfo.extensionId.value})`;
}
return nls.localize('unavailableRenderInfo', "renderer not available");
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
if (this._outputHeightTimer) {
this.viewCell.unlockOutputHeight();
clearTimeout(this._outputHeightTimer);
}
super.dispose();
}
}
class OutputEntryViewHandler {
constructor(
readonly model: ICellOutputViewModel,
readonly element: CellOutputElement
) {
}
}
export class CellOutputContainer extends CellContentPart {
private _outputEntries: OutputEntryViewHandler[] = [];
get renderedOutputEntries() {
return this._outputEntries;
}
constructor(
private notebookEditor: INotebookEditorDelegate,
private viewCell: CodeCellViewModel,
private readonly templateData: CodeCellRenderTemplate,
private options: { limit: number },
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._register(viewCell.onDidChangeOutputs(splice => {
this._updateOutputs(splice);
}));
this._register(viewCell.onDidChangeLayout(() => {
this.updateInternalLayoutNow(viewCell);
}));
}
override updateInternalLayoutNow(viewCell: CodeCellViewModel) {
this.templateData.outputContainer.setTop(viewCell.layoutInfo.outputContainerOffset);
this.templateData.outputShowMoreContainer.setTop(viewCell.layoutInfo.outputShowMoreContainerOffset);
this._outputEntries.forEach(entry => {
const index = this.viewCell.outputsViewModels.indexOf(entry.model);
if (index >= 0) {
const top = this.viewCell.getOutputOffsetInContainer(index);
entry.element.updateDOMTop(top);
}
});
}
render() {
if (this.viewCell.outputsViewModels.length > 0) {
if (this.viewCell.layoutInfo.outputTotalHeight !== 0) {
this.viewCell.updateOutputMinHeight(this.viewCell.layoutInfo.outputTotalHeight);
this._relayoutCell();
}
DOM.show(this.templateData.outputContainer.domNode);
for (let index = 0; index < Math.min(this.options.limit, this.viewCell.outputsViewModels.length); index++) {
const currOutput = this.viewCell.outputsViewModels[index];
const entry = this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, currOutput);
this._outputEntries.push(new OutputEntryViewHandler(currOutput, entry));
entry.render(undefined);
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(46);
}
this._relayoutCell();
this._validateFinalOutputHeight(false);
} else {
// noop
this._relayoutCell();
DOM.hide(this.templateData.outputContainer.domNode);
}
this.templateData.outputShowMoreContainer.domNode.innerText = '';
if (this.viewCell.outputsViewModels.length > this.options.limit) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
this.viewCell.updateOutputShowMoreContainerHeight(0);
}
}
viewUpdateShowOutputs(initRendering: boolean): void {
for (let index = 0; index < this._outputEntries.length; index++) {
const viewHandler = this._outputEntries[index];
const outputEntry = viewHandler.element;
if (outputEntry.renderResult) {
this.notebookEditor.createOutput(this.viewCell, outputEntry.renderResult as IInsetRenderOutput, this.viewCell.getOutputOffset(index));
} else {
outputEntry.render(undefined);
}
}
this._relayoutCell();
}
viewUpdateHideOuputs(): void {
for (let index = 0; index < this._outputEntries.length; index++) {
this.notebookEditor.hideInset(this._outputEntries[index].model);
}
}
private _outputHeightTimer: any = null;
private _validateFinalOutputHeight(synchronous: boolean) {
if (this._outputHeightTimer !== null) {
clearTimeout(this._outputHeightTimer);
}
if (synchronous) {
this.viewCell.unlockOutputHeight();
} else {
this._outputHeightTimer = setTimeout(() => {
this.viewCell.unlockOutputHeight();
}, 1000);
}
}
private _updateOutputs(splice: NotebookCellOutputsSplice) {
const previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;
// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.
this.viewCell.updateOutputMinHeight(previousOutputHeight);
if (this.viewCell.outputsViewModels.length) {
DOM.show(this.templateData.outputContainer.domNode);
} else {
DOM.hide(this.templateData.outputContainer.domNode);
}
this.viewCell.spliceOutputHeights(splice.start, splice.deleteCount, splice.newOutputs.map(_ => 0));
this._renderNow(splice);
}
private _renderNow(splice: NotebookCellOutputsSplice) {
if (splice.start >= this.options.limit) {
// splice items out of limit
return;
}
const firstGroupEntries = this._outputEntries.slice(0, splice.start);
const deletedEntries = this._outputEntries.slice(splice.start, splice.start + splice.deleteCount);
const secondGroupEntries = this._outputEntries.slice(splice.start + splice.deleteCount);
let newlyInserted = this.viewCell.outputsViewModels.slice(splice.start, splice.start + splice.newOutputs.length);
// [...firstGroup, ...deletedEntries, ...secondGroupEntries] [...restInModel]
// [...firstGroup, ...newlyInserted, ...secondGroupEntries, restInModel]
if (firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length > this.options.limit) {
// exceeds limit again
if (firstGroupEntries.length + newlyInserted.length > this.options.limit) {
[...deletedEntries, ...secondGroupEntries].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
newlyInserted = newlyInserted.slice(0, this.options.limit - firstGroupEntries.length);
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries];
// render newly inserted outputs
for (let i = firstGroupEntries.length; i < this._outputEntries.length; i++) {
this._outputEntries[i].element.render(undefined);
}
} else {
// part of secondGroupEntries are pushed out of view
// now we have to be creative as secondGroupEntries might not use dedicated containers
const elementsPushedOutOfView = secondGroupEntries.slice(this.options.limit - firstGroupEntries.length - newlyInserted.length);
[...deletedEntries, ...elementsPushedOutOfView].forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
// exclusive
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries.slice(0, this.options.limit - firstGroupEntries.length - newlyInserted.length)];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
}
} else {
// after splice, it doesn't exceed
deletedEntries.forEach(entry => {
entry.element.detach();
entry.element.dispose();
});
const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
const newlyInsertedEntries = newlyInserted.map(insert => {
return new OutputEntryViewHandler(insert, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, insert));
});
let outputsNewlyAvailable: OutputEntryViewHandler[] = [];
if (firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length < this.viewCell.outputsViewModels.length) {
const last = Math.min(this.options.limit, this.viewCell.outputsViewModels.length);
outputsNewlyAvailable = this.viewCell.outputsViewModels.slice(firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length, last).map(output => {
return new OutputEntryViewHandler(output, this.instantiationService.createInstance(CellOutputElement, this.notebookEditor, this.viewCell, this, this.templateData.outputContainer, output));
});
}
this._outputEntries = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries, ...outputsNewlyAvailable];
for (let i = firstGroupEntries.length; i < reRenderRightBoundary; i++) {
const previousSibling = i - 1 >= 0 && this._outputEntries[i - 1] && !!(this._outputEntries[i - 1].element.innerContainer?.parentElement) ? this._outputEntries[i - 1].element.innerContainer : undefined;
this._outputEntries[i].element.render(previousSibling);
}
for (let i = 0; i < outputsNewlyAvailable.length; i++) {
this._outputEntries[firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length + i].element.render(undefined);
}
}
if (this.viewCell.outputsViewModels.length > this.options.limit) {
DOM.show(this.templateData.outputShowMoreContainer.domNode);
if (!this.templateData.outputShowMoreContainer.domNode.hasChildNodes()) {
this.templateData.outputShowMoreContainer.domNode.appendChild(this._generateShowMoreElement(this.templateData.templateDisposables));
}
this.viewCell.updateOutputShowMoreContainerHeight(46);
} else {
DOM.hide(this.templateData.outputShowMoreContainer.domNode);
}
const editorHeight = this.templateData.editor.getContentHeight();
this.viewCell.editorHeight = editorHeight;
this._relayoutCell();
// if it's clearing all outputs, or outputs are all rendered synchronously
// shrink immediately as the final output height will be zero.
this._validateFinalOutputHeight(false || this.viewCell.outputsViewModels.length === 0);
}
private _generateShowMoreElement(disposables: DisposableStore): HTMLElement {
const md: IMarkdownString = {
value: `There are more than ${this.options.limit} outputs, [show more (open the raw output data in a text editor) ...](command:workbench.action.openLargeOutput)`,
isTrusted: true,
supportThemeIcons: true
};
const rendered = renderMarkdown(md, {
actionHandler: {
callback: (content) => {
if (content === 'command:workbench.action.openLargeOutput') {
this.openerService.open(CellUri.generateCellOutputUri(this.notebookEditor.textModel!.uri));
}
return;
},
disposables
}
});
disposables.add(rendered);
rendered.element.classList.add('output-show-more');
return rendered.element;
}
private _relayoutCell() {
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight);
}
override dispose() {
this.viewCell.updateOutputMinHeight(0);
if (this._outputHeightTimer) {
clearTimeout(this._outputHeightTimer);
}
this._outputEntries.forEach(entry => {
entry.element.dispose();
});
super.dispose();
}
}
const JUPYTER_RENDERER_MIMETYPES = [
'application/geo+json',
'application/vdom.v1+json',
'application/vnd.dataresource+json',
'application/vnd.plotly.v1+json',
'application/vnd.vega.v2+json',
'application/vnd.vega.v3+json',
'application/vnd.vega.v4+json',
'application/vnd.vega.v5+json',
'application/vnd.vegalite.v1+json',
'application/vnd.vegalite.v2+json',
'application/vnd.vegalite.v3+json',
'application/vnd.vegalite.v4+json',
'application/x-nteract-model-debug+json',
'image/svg+xml',
'text/latex',
'text/vnd.plotly.v1+html',
'application/vnd.jupyter.widget-view+json',
'application/vnd.code.notebook.error'
];
| src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.8373468518257141,
0.015029390342533588,
0.00016426593356300145,
0.00017553239013068378,
0.09659022837877274
] |
{
"id": 4,
"code_window": [
"\t\tthis._register(viewCell.onDidChangeOutputs(splice => {\n",
"\t\t\tthis._updateOutputs(splice);\n",
"\t\t}));\n",
"\n",
"\t\tthis._register(viewCell.onDidChangeLayout(() => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst executionState = this._notebookExecutionStateService.getCellExecution(viewCell.uri);\n",
"\t\t\tconst context = executionState ? CellOutputUpdateContext.Execution : CellOutputUpdateContext.Other;\n",
"\t\t\tthis._updateOutputs(splice, context);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 451
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { isIOS, isLinux, isMacintosh, isMobile, isWeb, isWindows } from 'vs/base/common/platform';
import { localize } from 'vs/nls';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
export const IsMacContext = new RawContextKey<boolean>('isMac', isMacintosh, localize('isMac', "Whether the operating system is macOS"));
export const IsLinuxContext = new RawContextKey<boolean>('isLinux', isLinux, localize('isLinux', "Whether the operating system is Linux"));
export const IsWindowsContext = new RawContextKey<boolean>('isWindows', isWindows, localize('isWindows', "Whether the operating system is Windows"));
export const IsWebContext = new RawContextKey<boolean>('isWeb', isWeb, localize('isWeb', "Whether the platform is a web browser"));
export const IsMacNativeContext = new RawContextKey<boolean>('isMacNative', isMacintosh && !isWeb, localize('isMacNative', "Whether the operating system is macOS on a non-browser platform"));
export const IsIOSContext = new RawContextKey<boolean>('isIOS', isIOS, localize('isIOS', "Whether the operating system is iOS"));
export const IsMobileContext = new RawContextKey<boolean>('isMobile', isMobile, localize('isMobile', "Whether the platform is a mobile web browser"));
export const IsDevelopmentContext = new RawContextKey<boolean>('isDevelopment', false, true);
export const ProductQualityContext = new RawContextKey<string>('productQualityType', '', localize('productQualityType', "Quality type of VS Code"));
export const InputFocusedContextKey = 'inputFocus';
export const InputFocusedContext = new RawContextKey<boolean>(InputFocusedContextKey, false, localize('inputFocus', "Whether keyboard focus is inside an input box"));
| src/vs/platform/contextkey/common/contextkeys.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017597513215150684,
0.00017382689111400396,
0.00016982429951895028,
0.00017568124167155474,
0.0000028328015559964115
] |
{
"id": 4,
"code_window": [
"\t\tthis._register(viewCell.onDidChangeOutputs(splice => {\n",
"\t\t\tthis._updateOutputs(splice);\n",
"\t\t}));\n",
"\n",
"\t\tthis._register(viewCell.onDidChangeLayout(() => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst executionState = this._notebookExecutionStateService.getCellExecution(viewCell.uri);\n",
"\t\t\tconst context = executionState ? CellOutputUpdateContext.Execution : CellOutputUpdateContext.Other;\n",
"\t\t\tthis._updateOutputs(splice, context);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 451
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Range } from 'vs/editor/common/core/range';
import { Selection, SelectionDirection } from 'vs/editor/common/core/selection';
import { ICommand, ICursorStateComputerData, IEditOperationBuilder } from 'vs/editor/common/editorCommon';
import { ITextModel } from 'vs/editor/common/model';
export class ReplaceCommand implements ICommand {
private readonly _range: Range;
private readonly _text: string;
public readonly insertsAutoWhitespace: boolean;
constructor(range: Range, text: string, insertsAutoWhitespace: boolean = false) {
this._range = range;
this._text = text;
this.insertsAutoWhitespace = insertsAutoWhitespace;
}
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
builder.addTrackedEditOperation(this._range, this._text);
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
const inverseEditOperations = helper.getInverseEditOperations();
const srcRange = inverseEditOperations[0].range;
return Selection.fromPositions(srcRange.getEndPosition());
}
}
export class ReplaceCommandThatSelectsText implements ICommand {
private readonly _range: Range;
private readonly _text: string;
constructor(range: Range, text: string) {
this._range = range;
this._text = text;
}
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
builder.addTrackedEditOperation(this._range, this._text);
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
const inverseEditOperations = helper.getInverseEditOperations();
const srcRange = inverseEditOperations[0].range;
return Selection.fromRange(srcRange, SelectionDirection.LTR);
}
}
export class ReplaceCommandWithoutChangingPosition implements ICommand {
private readonly _range: Range;
private readonly _text: string;
public readonly insertsAutoWhitespace: boolean;
constructor(range: Range, text: string, insertsAutoWhitespace: boolean = false) {
this._range = range;
this._text = text;
this.insertsAutoWhitespace = insertsAutoWhitespace;
}
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
builder.addTrackedEditOperation(this._range, this._text);
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
const inverseEditOperations = helper.getInverseEditOperations();
const srcRange = inverseEditOperations[0].range;
return Selection.fromPositions(srcRange.getStartPosition());
}
}
export class ReplaceCommandWithOffsetCursorState implements ICommand {
private readonly _range: Range;
private readonly _text: string;
private readonly _columnDeltaOffset: number;
private readonly _lineNumberDeltaOffset: number;
public readonly insertsAutoWhitespace: boolean;
constructor(range: Range, text: string, lineNumberDeltaOffset: number, columnDeltaOffset: number, insertsAutoWhitespace: boolean = false) {
this._range = range;
this._text = text;
this._columnDeltaOffset = columnDeltaOffset;
this._lineNumberDeltaOffset = lineNumberDeltaOffset;
this.insertsAutoWhitespace = insertsAutoWhitespace;
}
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
builder.addTrackedEditOperation(this._range, this._text);
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
const inverseEditOperations = helper.getInverseEditOperations();
const srcRange = inverseEditOperations[0].range;
return Selection.fromPositions(srcRange.getEndPosition().delta(this._lineNumberDeltaOffset, this._columnDeltaOffset));
}
}
export class ReplaceCommandThatPreservesSelection implements ICommand {
private readonly _range: Range;
private readonly _text: string;
private readonly _initialSelection: Selection;
private readonly _forceMoveMarkers: boolean;
private _selectionId: string | null;
constructor(editRange: Range, text: string, initialSelection: Selection, forceMoveMarkers: boolean = false) {
this._range = editRange;
this._text = text;
this._initialSelection = initialSelection;
this._forceMoveMarkers = forceMoveMarkers;
this._selectionId = null;
}
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers);
this._selectionId = builder.trackSelection(this._initialSelection);
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
return helper.getTrackedSelection(this._selectionId!);
}
}
| src/vs/editor/common/commands/replaceCommand.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.0001766571804182604,
0.0001726567279547453,
0.00016855115245562047,
0.00017277423467021435,
0.0000024007633783185156
] |
{
"id": 4,
"code_window": [
"\t\tthis._register(viewCell.onDidChangeOutputs(splice => {\n",
"\t\t\tthis._updateOutputs(splice);\n",
"\t\t}));\n",
"\n",
"\t\tthis._register(viewCell.onDidChangeLayout(() => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst executionState = this._notebookExecutionStateService.getCellExecution(viewCell.uri);\n",
"\t\t\tconst context = executionState ? CellOutputUpdateContext.Execution : CellOutputUpdateContext.Other;\n",
"\t\t\tthis._updateOutputs(splice, context);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 451
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import Severity from 'vs/base/common/severity';
import { Disposable } from 'vs/base/common/lifecycle';
import { IConfirmation, IConfirmationResult, IDialogOptions, IDialogService, IInput, IInputResult, IShowResult } from 'vs/platform/dialogs/common/dialogs';
import { DialogsModel } from 'vs/workbench/common/dialogs';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { ILogService } from 'vs/platform/log/common/log';
export class DialogService extends Disposable implements IDialogService {
declare readonly _serviceBrand: undefined;
readonly model = this._register(new DialogsModel());
readonly onWillShowDialog = this.model.onWillShowDialog;
readonly onDidShowDialog = this.model.onDidShowDialog;
constructor(
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@ILogService private readonly logService: ILogService
) {
super();
}
private skipDialogs(): boolean {
if (this.environmentService.isExtensionDevelopment && this.environmentService.extensionTestsLocationURI) {
return true; // integration tests
}
return !!this.environmentService.enableSmokeTestDriver; // smoke tests
}
async confirm(confirmation: IConfirmation): Promise<IConfirmationResult> {
if (this.skipDialogs()) {
this.logService.trace('DialogService: refused to show confirmation dialog in tests.');
return { confirmed: true };
}
const handle = this.model.show({ confirmArgs: { confirmation } });
return await handle.result as IConfirmationResult;
}
async show(severity: Severity, message: string, buttons?: string[], options?: IDialogOptions): Promise<IShowResult> {
if (this.skipDialogs()) {
throw new Error('DialogService: refused to show dialog in tests.');
}
const handle = this.model.show({ showArgs: { severity, message, buttons, options } });
return await handle.result as IShowResult;
}
async input(severity: Severity, message: string, buttons: string[], inputs: IInput[], options?: IDialogOptions): Promise<IInputResult> {
if (this.skipDialogs()) {
throw new Error('DialogService: refused to show input dialog in tests.');
}
const handle = this.model.show({ inputArgs: { severity, message, buttons, inputs, options } });
return await handle.result as IInputResult;
}
async about(): Promise<void> {
if (this.skipDialogs()) {
throw new Error('DialogService: refused to show about dialog in tests.');
}
const handle = this.model.show({});
await handle.result;
}
}
registerSingleton(IDialogService, DialogService, InstantiationType.Delayed);
| src/vs/workbench/services/dialogs/common/dialogService.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017573166405782104,
0.00017208144709002227,
0.00016681286797393113,
0.0001721505104796961,
0.0000032623543120280374
] |
{
"id": 5,
"code_window": [
"\t\t\t}, 1000);\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate _updateOutputs(splice: NotebookCellOutputsSplice) {\n",
"\t\tconst previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;\n",
"\n",
"\t\t// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _updateOutputs(splice: NotebookCellOutputsSplice, context: CellOutputUpdateContext = CellOutputUpdateContext.Other) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 545
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event';
import { dispose } from 'vs/base/common/lifecycle';
import * as UUID from 'vs/base/common/uuid';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { PrefixSumComputer } from 'vs/editor/common/model/prefixSumComputer';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { CellEditState, CellFindMatch, CodeCellLayoutChangeEvent, CodeCellLayoutInfo, CellLayoutState, ICellOutputViewModel, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CellOutputViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/cellOutputViewModel';
import { ViewContext } from 'vs/workbench/contrib/notebook/browser/viewModel/viewContext';
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { CellKind, INotebookSearchOptions, NotebookCellOutputsSplice } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptionsChangeEvent } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { BaseCellViewModel } from './baseCellViewModel';
import { NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
export class CodeCellViewModel extends BaseCellViewModel implements ICellViewModel {
readonly cellKind = CellKind.Code;
protected readonly _onLayoutInfoRead = this._register(new Emitter<void>());
readonly onLayoutInfoRead = this._onLayoutInfoRead.event;
protected readonly _onDidChangeOutputs = this._register(new Emitter<NotebookCellOutputsSplice>());
readonly onDidChangeOutputs = this._onDidChangeOutputs.event;
private readonly _onDidRemoveOutputs = this._register(new Emitter<readonly ICellOutputViewModel[]>());
readonly onDidRemoveOutputs = this._onDidRemoveOutputs.event;
private _outputCollection: number[] = [];
private _outputsTop: PrefixSumComputer | null = null;
protected _pauseableEmitter = this._register(new PauseableEmitter<CodeCellLayoutChangeEvent>());
readonly onDidChangeLayout = this._pauseableEmitter.event;
private _editorHeight = 0;
set editorHeight(height: number) {
this._editorHeight = height;
this.layoutChange({ editorHeight: true }, 'CodeCellViewModel#editorHeight');
}
get editorHeight() {
throw new Error('editorHeight is write-only');
}
private _commentHeight = 0;
set commentHeight(height: number) {
if (this._commentHeight === height) {
return;
}
this._commentHeight = height;
this.layoutChange({ commentHeight: true }, 'CodeCellViewModel#commentHeight');
}
private _hoveringOutput: boolean = false;
public get outputIsHovered(): boolean {
return this._hoveringOutput;
}
public set outputIsHovered(v: boolean) {
this._hoveringOutput = v;
this._onDidChangeState.fire({ outputIsHoveredChanged: true });
}
private _focusOnOutput: boolean = false;
public get outputIsFocused(): boolean {
return this._focusOnOutput;
}
public set outputIsFocused(v: boolean) {
this._focusOnOutput = v;
this._onDidChangeState.fire({ outputIsFocusedChanged: true });
}
private _outputMinHeight: number = 0;
private get outputMinHeight() {
return this._outputMinHeight;
}
/**
* The minimum height of the output region. It's only set to non-zero temporarily when replacing an output with a new one.
* It's reset to 0 when the new output is rendered, or in one second.
*/
private set outputMinHeight(newMin: number) {
this._outputMinHeight = newMin;
}
private _layoutInfo: CodeCellLayoutInfo;
get layoutInfo() {
return this._layoutInfo;
}
private _outputViewModels: ICellOutputViewModel[];
get outputsViewModels() {
return this._outputViewModels;
}
constructor(
viewType: string,
model: NotebookCellTextModel,
initialNotebookLayoutInfo: NotebookLayoutInfo | null,
readonly viewContext: ViewContext,
@IConfigurationService configurationService: IConfigurationService,
@INotebookService private readonly _notebookService: INotebookService,
@ITextModelService modelService: ITextModelService,
@IUndoRedoService undoRedoService: IUndoRedoService,
@ICodeEditorService codeEditorService: ICodeEditorService
) {
super(viewType, model, UUID.generateUuid(), viewContext, configurationService, modelService, undoRedoService, codeEditorService);
this._outputViewModels = this.model.outputs.map(output => new CellOutputViewModel(this, output, this._notebookService));
this._register(this.model.onDidChangeOutputs((splice) => {
const removedOutputs: ICellOutputViewModel[] = [];
let outputLayoutChange = false;
for (let i = splice.start; i < splice.start + splice.deleteCount; i++) {
if (this._outputCollection[i] !== undefined && this._outputCollection[i] !== 0) {
outputLayoutChange = true;
}
}
this._outputCollection.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(() => 0));
removedOutputs.push(...this._outputViewModels.splice(splice.start, splice.deleteCount, ...splice.newOutputs.map(output => new CellOutputViewModel(this, output, this._notebookService))));
this._outputsTop = null;
this._onDidChangeOutputs.fire(splice);
this._onDidRemoveOutputs.fire(removedOutputs);
if (outputLayoutChange) {
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#model.onDidChangeOutputs');
}
dispose(removedOutputs);
}));
this._outputCollection = new Array(this.model.outputs.length);
this._layoutInfo = {
fontInfo: initialNotebookLayoutInfo?.fontInfo || null,
editorHeight: 0,
editorWidth: initialNotebookLayoutInfo
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(initialNotebookLayoutInfo.width)
: 0,
statusBarHeight: 0,
commentHeight: 0,
outputContainerOffset: 0,
outputTotalHeight: 0,
outputShowMoreContainerHeight: 0,
outputShowMoreContainerOffset: 0,
totalHeight: this.computeTotalHeight(17, 0, 0),
codeIndicatorHeight: 0,
outputIndicatorHeight: 0,
bottomToolbarOffset: 0,
layoutState: CellLayoutState.Uninitialized,
estimatedHasHorizontalScrolling: false
};
}
updateOptions(e: NotebookOptionsChangeEvent) {
if (e.cellStatusBarVisibility || e.insertToolbarPosition || e.cellToolbarLocation) {
this.layoutChange({});
}
}
pauseLayout() {
this._pauseableEmitter.pause();
}
resumeLayout() {
this._pauseableEmitter.resume();
}
layoutChange(state: CodeCellLayoutChangeEvent, source?: string) {
// recompute
this._ensureOutputsTop();
const notebookLayoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const bottomToolbarDimensions = this.viewContext.notebookOptions.computeBottomToolbarDimensions();
const outputShowMoreContainerHeight = state.outputShowMoreContainerHeight ? state.outputShowMoreContainerHeight : this._layoutInfo.outputShowMoreContainerHeight;
const outputTotalHeight = Math.max(this._outputMinHeight, this.isOutputCollapsed ? notebookLayoutConfiguration.collapsedIndicatorHeight : this._outputsTop!.getTotalSum());
const commentHeight = state.commentHeight ? this._commentHeight : this._layoutInfo.commentHeight;
const originalLayout = this.layoutInfo;
if (!this.isInputCollapsed) {
let newState: CellLayoutState;
let editorHeight: number;
let totalHeight: number;
let hasHorizontalScrolling = false;
if (!state.editorHeight && this._layoutInfo.layoutState === CellLayoutState.FromCache && !state.outputHeight) {
// No new editorHeight info - keep cached totalHeight and estimate editorHeight
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this._layoutInfo.totalHeight;
newState = CellLayoutState.FromCache;
} else if (state.editorHeight || this._layoutInfo.layoutState === CellLayoutState.Measured) {
// Editor has been measured
editorHeight = this._editorHeight;
totalHeight = this.computeTotalHeight(this._editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Measured;
hasHorizontalScrolling = this._layoutInfo.estimatedHasHorizontalScrolling;
} else {
const estimate = this.estimateEditorHeight(state.font?.lineHeight ?? this._layoutInfo.fontInfo?.lineHeight);
editorHeight = estimate.editorHeight;
hasHorizontalScrolling = estimate.hasHorizontalScrolling;
totalHeight = this.computeTotalHeight(editorHeight, outputTotalHeight, outputShowMoreContainerHeight);
newState = CellLayoutState.Estimated;
}
const statusBarHeight = this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri);
const codeIndicatorHeight = editorHeight + statusBarHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.editorToolbarHeight
+ notebookLayoutConfiguration.cellTopMargin // CELL_TOP_MARGIN
+ editorHeight
+ statusBarHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight,
editorWidth,
statusBarHeight,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: newState,
estimatedHasHorizontalScrolling: hasHorizontalScrolling
};
} else {
const codeIndicatorHeight = notebookLayoutConfiguration.collapsedIndicatorHeight;
const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
const outputContainerOffset = notebookLayoutConfiguration.cellTopMargin + notebookLayoutConfiguration.collapsedIndicatorHeight;
const totalHeight =
notebookLayoutConfiguration.cellTopMargin
+ notebookLayoutConfiguration.collapsedIndicatorHeight
+ notebookLayoutConfiguration.cellBottomMargin //CELL_BOTTOM_MARGIN
+ bottomToolbarDimensions.bottomToolbarGap //BOTTOM_CELL_TOOLBAR_GAP
+ commentHeight
+ outputTotalHeight + outputShowMoreContainerHeight;
const outputShowMoreContainerOffset = totalHeight
- bottomToolbarDimensions.bottomToolbarGap
- bottomToolbarDimensions.bottomToolbarHeight / 2
- outputShowMoreContainerHeight;
const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
const editorWidth = state.outerWidth !== undefined
? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth)
: this._layoutInfo?.editorWidth;
this._layoutInfo = {
fontInfo: state.font ?? this._layoutInfo.fontInfo ?? null,
editorHeight: this._layoutInfo.editorHeight,
editorWidth,
statusBarHeight: 0,
commentHeight,
outputContainerOffset,
outputTotalHeight,
outputShowMoreContainerHeight,
outputShowMoreContainerOffset,
totalHeight,
codeIndicatorHeight,
outputIndicatorHeight,
bottomToolbarOffset,
layoutState: this._layoutInfo.layoutState,
estimatedHasHorizontalScrolling: false
};
}
this._fireOnDidChangeLayout({
...state,
totalHeight: this.layoutInfo.totalHeight !== originalLayout.totalHeight,
source,
});
}
private _fireOnDidChangeLayout(state: CodeCellLayoutChangeEvent) {
this._pauseableEmitter.fire(state);
}
override restoreEditorViewState(editorViewStates: editorCommon.ICodeEditorViewState | null, totalHeight?: number) {
super.restoreEditorViewState(editorViewStates);
if (totalHeight !== undefined && this._layoutInfo.layoutState !== CellLayoutState.Measured) {
this._layoutInfo = {
fontInfo: this._layoutInfo.fontInfo,
editorHeight: this._layoutInfo.editorHeight,
editorWidth: this._layoutInfo.editorWidth,
statusBarHeight: this.layoutInfo.statusBarHeight,
commentHeight: this.layoutInfo.commentHeight,
outputContainerOffset: this._layoutInfo.outputContainerOffset,
outputTotalHeight: this._layoutInfo.outputTotalHeight,
outputShowMoreContainerHeight: this._layoutInfo.outputShowMoreContainerHeight,
outputShowMoreContainerOffset: this._layoutInfo.outputShowMoreContainerOffset,
totalHeight: totalHeight,
codeIndicatorHeight: this._layoutInfo.codeIndicatorHeight,
outputIndicatorHeight: this._layoutInfo.outputIndicatorHeight,
bottomToolbarOffset: this._layoutInfo.bottomToolbarOffset,
layoutState: CellLayoutState.FromCache,
estimatedHasHorizontalScrolling: this._layoutInfo.estimatedHasHorizontalScrolling
};
}
}
hasDynamicHeight() {
// CodeCellVM always measures itself and controls its cell's height
return false;
}
getDynamicHeight() {
this._onLayoutInfoRead.fire();
return this._layoutInfo.totalHeight;
}
getHeight(lineHeight: number) {
if (this._layoutInfo.layoutState === CellLayoutState.Uninitialized) {
const estimate = this.estimateEditorHeight(lineHeight);
return this.computeTotalHeight(estimate.editorHeight, 0, 0);
} else {
return this._layoutInfo.totalHeight;
}
}
private estimateEditorHeight(lineHeight: number | undefined = 20): { editorHeight: number; hasHorizontalScrolling: boolean } {
let hasHorizontalScrolling = false;
const cellEditorOptions = this.viewContext.getBaseCellEditorOptions(this.language);
if (this.layoutInfo.fontInfo && cellEditorOptions.value.wordWrap === 'off') {
for (let i = 0; i < this.lineCount; i++) {
const max = this.textBuffer.getLineLastNonWhitespaceColumn(i + 1);
const estimatedWidth = max * (this.layoutInfo.fontInfo.typicalHalfwidthCharacterWidth + this.layoutInfo.fontInfo.letterSpacing);
if (estimatedWidth > this.layoutInfo.editorWidth) {
hasHorizontalScrolling = true;
break;
}
}
}
const verticalScrollbarHeight = hasHorizontalScrolling ? 12 : 0; // take zoom level into account
const editorPadding = this.viewContext.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
const editorHeight = this.lineCount * lineHeight
+ editorPadding.top
+ editorPadding.bottom // EDITOR_BOTTOM_PADDING
+ verticalScrollbarHeight;
return {
editorHeight,
hasHorizontalScrolling
};
}
private computeTotalHeight(editorHeight: number, outputsTotalHeight: number, outputShowMoreContainerHeight: number): number {
const layoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
const { bottomToolbarGap } = this.viewContext.notebookOptions.computeBottomToolbarDimensions(this.viewType);
return layoutConfiguration.editorToolbarHeight
+ layoutConfiguration.cellTopMargin
+ editorHeight
+ this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri)
+ this._commentHeight
+ outputsTotalHeight
+ outputShowMoreContainerHeight
+ bottomToolbarGap
+ layoutConfiguration.cellBottomMargin;
}
protected onDidChangeTextModelContent(): void {
if (this.getEditState() !== CellEditState.Editing) {
this.updateEditState(CellEditState.Editing, 'onDidChangeTextModelContent');
this._onDidChangeState.fire({ contentChanged: true });
}
}
onDeselect() {
this.updateEditState(CellEditState.Preview, 'onDeselect');
}
updateOutputShowMoreContainerHeight(height: number) {
this.layoutChange({ outputShowMoreContainerHeight: height }, 'CodeCellViewModel#updateOutputShowMoreContainerHeight');
}
updateOutputMinHeight(height: number) {
this.outputMinHeight = height;
}
unlockOutputHeight() {
this.outputMinHeight = 0;
this.layoutChange({ outputHeight: true });
}
updateOutputHeight(index: number, height: number, source?: string) {
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
this._ensureOutputsTop();
if (height < 28 && this._outputViewModels[index].hasMultiMimeType()) {
height = 28;
}
this._outputCollection[index] = height;
if (this._outputsTop!.setValue(index, height)) {
this.layoutChange({ outputHeight: true }, source);
}
}
getOutputOffsetInContainer(index: number) {
this._ensureOutputsTop();
if (index >= this._outputCollection.length) {
throw new Error('Output index out of range!');
}
return this._outputsTop!.getPrefixSum(index - 1);
}
getOutputOffset(index: number): number {
return this.layoutInfo.outputContainerOffset + this.getOutputOffsetInContainer(index);
}
spliceOutputHeights(start: number, deleteCnt: number, heights: number[]) {
this._ensureOutputsTop();
this._outputsTop!.removeValues(start, deleteCnt);
if (heights.length) {
const values = new Uint32Array(heights.length);
for (let i = 0; i < heights.length; i++) {
values[i] = heights[i];
}
this._outputsTop!.insertValues(start, values);
}
this.layoutChange({ outputHeight: true }, 'CodeCellViewModel#spliceOutputs');
}
private _ensureOutputsTop(): void {
if (!this._outputsTop) {
const values = new Uint32Array(this._outputCollection.length);
for (let i = 0; i < this._outputCollection.length; i++) {
values[i] = this._outputCollection[i];
}
this._outputsTop = new PrefixSumComputer(values);
}
}
private readonly _hasFindResult = this._register(new Emitter<boolean>());
public readonly hasFindResult: Event<boolean> = this._hasFindResult.event;
startFind(value: string, options: INotebookSearchOptions): CellFindMatch | null {
const matches = super.cellStartFind(value, options);
if (matches === null) {
return null;
}
return {
cell: this,
contentMatches: matches
};
}
override dispose() {
super.dispose();
this._outputCollection = [];
this._outputsTop = null;
dispose(this._outputViewModels);
}
}
| src/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.ts | 1 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.03662377595901489,
0.005180292297154665,
0.00016876198060344905,
0.001491377828642726,
0.008165575563907623
] |
{
"id": 5,
"code_window": [
"\t\t\t}, 1000);\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate _updateOutputs(splice: NotebookCellOutputsSplice) {\n",
"\t\tconst previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight;\n",
"\n",
"\t\t// for cell output update, we make sure the cell does not shrink before the new outputs are rendered.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _updateOutputs(splice: NotebookCellOutputsSplice, context: CellOutputUpdateContext = CellOutputUpdateContext.Other) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.ts",
"type": "replace",
"edit_start_line_idx": 545
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { WebviewThemeDataProvider } from 'vs/workbench/contrib/webview/browser/themeing';
import { IOverlayWebview, IWebview, IWebviewElement, IWebviewService, WebviewInitInfo } from 'vs/workbench/contrib/webview/browser/webview';
import { WebviewElement } from 'vs/workbench/contrib/webview/browser/webviewElement';
import { OverlayWebview } from './overlayWebview';
export class WebviewService extends Disposable implements IWebviewService {
declare readonly _serviceBrand: undefined;
protected readonly _webviewThemeDataProvider: WebviewThemeDataProvider;
constructor(
@IInstantiationService protected readonly _instantiationService: IInstantiationService,
) {
super();
this._webviewThemeDataProvider = this._instantiationService.createInstance(WebviewThemeDataProvider);
}
private _activeWebview?: IWebview;
public get activeWebview() { return this._activeWebview; }
private _updateActiveWebview(value: IWebview | undefined) {
if (value !== this._activeWebview) {
this._activeWebview = value;
this._onDidChangeActiveWebview.fire(value);
}
}
private _webviews = new Set<IWebview>();
public get webviews(): Iterable<IWebview> {
return this._webviews.values();
}
private readonly _onDidChangeActiveWebview = this._register(new Emitter<IWebview | undefined>());
public readonly onDidChangeActiveWebview = this._onDidChangeActiveWebview.event;
createWebviewElement(initInfo: WebviewInitInfo): IWebviewElement {
const webview = this._instantiationService.createInstance(WebviewElement, initInfo, this._webviewThemeDataProvider);
this.registerNewWebview(webview);
return webview;
}
createWebviewOverlay(initInfo: WebviewInitInfo): IOverlayWebview {
const webview = this._instantiationService.createInstance(OverlayWebview, initInfo);
this.registerNewWebview(webview);
return webview;
}
protected registerNewWebview(webview: IWebview) {
this._webviews.add(webview);
webview.onDidFocus(() => {
this._updateActiveWebview(webview);
});
const onBlur = () => {
if (this._activeWebview === webview) {
this._updateActiveWebview(undefined);
}
};
webview.onDidBlur(onBlur);
webview.onDidDispose(() => {
onBlur();
this._webviews.delete(webview);
});
}
}
| src/vs/workbench/contrib/webview/browser/webviewService.ts | 0 | https://github.com/microsoft/vscode/commit/a40ce8aa30c52ef0561ca2d136f8c7d975f73f0d | [
0.00017515820218250155,
0.0001716179249342531,
0.000165611068950966,
0.00017312390264123678,
0.000003636997007561149
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.