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": 2, "code_window": [ "\n", " const config: StorybookConfig = {\n", " addons: [\n", " 'foo',\n", " { name: 'bar', options: {} },\n", " ]\n", " }\n", " export default config;\n", " `;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ],\n", " \"otherField\": [\n", " \"foo\",\n", " { \"name\": 'bar', options: {} },\n", " ],\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.test.ts", "type": "replace", "edit_start_line_idx": 814 }
```js // .storybook/main.js export function webpackFinal(config, { presets }) { const version = await presets.apply('webpackVersion'); const instance = (await presets.apply('webpackInstance'))?.default; logger.info(`=> Running in webpack ${version}: ${instance}`); return config; } ```
docs/snippets/common/storybook-main-versioned-webpack.js.mdx
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.0017370929708704352, 0.0009557367884553969, 0.00017438064969610423, 0.0009557367884553969, 0.0007813561242073774 ]
{ "id": 2, "code_window": [ "\n", " const config: StorybookConfig = {\n", " addons: [\n", " 'foo',\n", " { name: 'bar', options: {} },\n", " ]\n", " }\n", " export default config;\n", " `;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ],\n", " \"otherField\": [\n", " \"foo\",\n", " { \"name\": 'bar', options: {} },\n", " ],\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.test.ts", "type": "replace", "edit_start_line_idx": 814 }
# Storybook CLI This is a wrapper for <https://www.npmjs.com/package/@storybook/cli>
code/lib/cli-storybook/README.md
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.0011212581302970648, 0.0011212581302970648, 0.0011212581302970648, 0.0011212581302970648, 0 ]
{ "id": 3, "code_window": [ " export default config;\n", " `;\n", " const config = loadConfig(source).parse();\n", " expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']);\n", " });\n", " });\n", "\n", " it(`returns undefined when accessing a field that does not exist`, () => {\n", " const source = dedent`\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(config.getNamesFromPath(['otherField'])).toEqual(['foo', 'bar']);\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.test.ts", "type": "add", "edit_start_line_idx": 820 }
/// <reference types="@types/jest" />; import { dedent } from 'ts-dedent'; import { formatConfig, loadConfig } from './ConfigFile'; expect.addSnapshotSerializer({ print: (val: any) => val, test: (val) => true, }); const getField = (path: string[], source: string) => { const config = loadConfig(source).parse(); return config.getFieldValue(path); }; const setField = (path: string[], value: any, source: string) => { const config = loadConfig(source).parse(); config.setFieldValue(path, value); return formatConfig(config); }; const removeField = (path: string[], source: string) => { const config = loadConfig(source).parse(); config.removeField(path); return formatConfig(config); }; describe('ConfigFile', () => { describe('getField', () => { describe('named exports', () => { it('missing export', () => { expect( getField( ['core', 'builder'], dedent` export const foo = { builder: 'webpack5' } ` ) ).toBeUndefined(); }); it('missing field', () => { expect( getField( ['core', 'builder'], dedent` export const core = { foo: 'webpack5' } ` ) ).toBeUndefined(); }); it('found scalar', () => { expect( getField( ['core', 'builder'], dedent` export const core = { builder: 'webpack5' } ` ) ).toEqual('webpack5'); }); it('found object', () => { expect( getField( ['core', 'builder'], dedent` export const core = { builder: { name: 'webpack5' } } ` ) ).toEqual({ name: 'webpack5' }); }); it('variable ref export', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; export const core = coreVar; ` ) ).toEqual('webpack5'); }); it('variable export', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; export const core = coreVar; ` ) ).toEqual('webpack5'); }); }); describe('module exports', () => { it('missing export', () => { expect( getField( ['core', 'builder'], dedent` module.exports = { foo: { builder: 'webpack5' } } ` ) ).toBeUndefined(); }); it('found scalar', () => { expect( getField( ['core', 'builder'], dedent` module.exports = { core: { builder: 'webpack5' } } ` ) ).toEqual('webpack5'); }); it('variable ref export', () => { expect( getField( ['core', 'builder'], dedent` const core = { builder: 'webpack5' }; module.exports = { core }; ` ) ).toEqual('webpack5'); }); it('variable rename', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; module.exports = { core: coreVar }; ` ) ).toEqual('webpack5'); }); it('variable exports', () => { expect( getField( ['stories'], dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { stories: [{ directory: '../src', titlePrefix: 'Demo' }], } module.exports = config; ` ) ).toEqual([{ directory: '../src', titlePrefix: 'Demo' }]); }); }); describe('default export', () => { it('missing export', () => { expect( getField( ['core', 'builder'], dedent` export default { foo: { builder: 'webpack5' } } ` ) ).toBeUndefined(); }); it('found scalar', () => { expect( getField( ['core', 'builder'], dedent` export default { core: { builder: 'webpack5' } } ` ) ).toEqual('webpack5'); }); it('variable ref export', () => { expect( getField( ['core', 'builder'], dedent` const core = { builder: 'webpack5' }; export default { core }; ` ) ).toEqual('webpack5'); }); it('variable rename', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; export default { core: coreVar }; ` ) ).toEqual('webpack5'); }); it('variable exports', () => { expect( getField( ['stories'], dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { stories: [{ directory: '../src', titlePrefix: 'Demo' }], } export default config; ` ) ).toEqual([{ directory: '../src', titlePrefix: 'Demo' }]); }); }); }); describe('setField', () => { describe('named exports', () => { it('missing export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export const addons = []; ` ) ).toMatchInlineSnapshot(` export const addons = []; export const core = { builder: "webpack5" }; `); }); it('missing field', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export const core = { foo: 'bar' }; ` ) ).toMatchInlineSnapshot(` export const core = { foo: 'bar', builder: 'webpack5' }; `); }); it('found scalar', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export const core = { builder: 'webpack4' }; ` ) ).toMatchInlineSnapshot(` export const core = { builder: 'webpack5' }; `); }); it('found object', () => { expect( setField( ['core', 'builder'], { name: 'webpack5' }, dedent` export const core = { builder: { name: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export const core = { builder: { name: 'webpack5' } }; `); }); it('variable export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` const coreVar = { builder: 'webpack4' }; export const core = coreVar; ` ) ).toMatchInlineSnapshot(` const coreVar = { builder: 'webpack5' }; export const core = coreVar; `); }); }); describe('module exports', () => { it('missing export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` module.exports = { addons: [] }; ` ) ).toMatchInlineSnapshot(` module.exports = { addons: [], core: { builder: "webpack5" } }; `); }); it('missing field', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` module.exports = { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { foo: 'bar', builder: 'webpack5' } }; `); }); it('found scalar', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` module.exports = { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { builder: 'webpack5' } }; `); }); }); describe('default export', () => { it('missing export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export default { addons: [] }; ` ) ).toMatchInlineSnapshot(` export default { addons: [], core: { builder: "webpack5" } }; `); }); it('missing field', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export default { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` export default { core: { foo: 'bar', builder: 'webpack5' } }; `); }); it('found scalar', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export default { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export default { core: { builder: 'webpack5' } }; `); }); }); describe('quotes', () => { it('no quotes', () => { expect(setField(['foo', 'bar'], 'baz', '')).toMatchInlineSnapshot(` export const foo = { bar: "baz" }; `); }); it('more single quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', 'b', "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', 'b', "c"]; export const foo = { bar: 'baz' }; `); }); it('more double quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', "b", "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', "b", "c"]; export const foo = { bar: "baz" }; `); }); }); }); describe('removeField', () => { describe('named exports', () => { it('missing export', () => { expect( removeField( ['core', 'builder'], dedent` export const addons = []; ` ) ).toMatchInlineSnapshot(`export const addons = [];`); }); it('missing field', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { foo: 'bar' }; ` ) ).toMatchInlineSnapshot(` export const core = { foo: 'bar' }; `); }); it('found scalar', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { builder: 'webpack4' }; ` ) ).toMatchInlineSnapshot(`export const core = {};`); }); it('found object', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { builder: { name: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(`export const core = {};`); }); it('nested object', () => { expect( removeField( ['core', 'builder', 'name'], dedent` export const core = { builder: { name: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export const core = { builder: {} }; `); }); it('string literal key', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { 'builder': 'webpack4' }; ` ) ).toMatchInlineSnapshot(`export const core = {};`); }); it('variable export', () => { expect( removeField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack4' }; export const core = coreVar; ` ) ).toMatchInlineSnapshot(` const coreVar = {}; export const core = coreVar; `); }); it('root export variable', () => { expect( removeField( ['core'], dedent` export const core = { builder: { name: 'webpack4' } }; export const addons = []; ` ) ).toMatchInlineSnapshot(`export const addons = [];`); }); }); describe('module exports', () => { it('missing export', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { addons: [] }; ` ) ).toMatchInlineSnapshot(` module.exports = { addons: [] }; `); }); it('missing field', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { foo: 'bar' } }; `); }); it('found scalar', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` module.exports = { core: {} }; `); }); it('nested scalar', () => { expect( removeField( ['core', 'builder', 'name'], dedent` module.exports = { core: { builder: { name: 'webpack4' } } }; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { builder: {} } }; `); }); it('string literal key', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { 'core': { 'builder': 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` module.exports = { 'core': {} }; `); }); it('root property', () => { expect( removeField( ['core'], dedent` module.exports = { core: { builder: { name: 'webpack4' } }, addons: [] }; ` ) ).toMatchInlineSnapshot(` module.exports = { addons: [] }; `); }); }); describe('default export', () => { it('missing export', () => { expect( removeField( ['core', 'builder'], dedent` export default { addons: [] }; ` ) ).toMatchInlineSnapshot(` export default { addons: [] }; `); }); it('missing field', () => { expect( removeField( ['core', 'builder'], dedent` export default { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` export default { core: { foo: 'bar' } }; `); }); it('found scalar', () => { expect( removeField( ['core', 'builder'], dedent` export default { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export default { core: {} }; `); }); it('nested scalar', () => { expect( removeField( ['core', 'builder', 'name'], dedent` export default { core: { builder: { name: 'webpack4' } } }; ` ) ).toMatchInlineSnapshot(` export default { core: { builder: {} } }; `); }); it('string literal key', () => { expect( removeField( ['core', 'builder'], dedent` export default { 'core': { 'builder': 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export default { 'core': {} }; `); }); it('root property', () => { expect( removeField( ['core'], dedent` export default { core: { builder: { name: 'webpack4' } }, addons: [] }; ` ) ).toMatchInlineSnapshot(` export default { addons: [] }; `); }); }); describe('quotes', () => { it('no quotes', () => { expect(setField(['foo', 'bar'], 'baz', '')).toMatchInlineSnapshot(` export const foo = { bar: "baz" }; `); }); it('more single quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', 'b', "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', 'b', "c"]; export const foo = { bar: 'baz' }; `); }); it('more double quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', "b", "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', "b", "c"]; export const foo = { bar: "baz" }; `); }); }); }); describe('config helpers', () => { describe('getNameFromPath', () => { it(`supports string literal node`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { framework: 'foo', } export default config; `; const config = loadConfig(source).parse(); expect(config.getNameFromPath(['framework'])).toEqual('foo'); }); it(`supports object expression node with name property`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { framework: { name: 'foo', options: { bar: require('baz') } }, } export default config; `; const config = loadConfig(source).parse(); expect(config.getNameFromPath(['framework'])).toEqual('foo'); }); it(`returns undefined when accessing a field that does not exist`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { } export default config; `; const config = loadConfig(source).parse(); expect(config.getNameFromPath(['framework'])).toBeUndefined(); }); it(`throws an error when node is of unexpected type`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { framework: makesNoSense(), } export default config; `; const config = loadConfig(source).parse(); expect(() => config.getNameFromPath(['framework'])).toThrowError( `The given node must be a string literal or an object expression with a "name" property that is a string literal.` ); }); }); describe('getNamesFromPath', () => { it(`supports an array with string literal and object expression with name property`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { addons: [ 'foo', { name: 'bar', options: {} }, ] } export default config; `; const config = loadConfig(source).parse(); expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']); }); }); it(`returns undefined when accessing a field that does not exist`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { } export default config; `; const config = loadConfig(source).parse(); expect(config.getNamesFromPath(['addons'])).toBeUndefined(); }); }); });
code/lib/csf-tools/src/ConfigFile.test.ts
1
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.9980664849281311, 0.08180402219295502, 0.00016368071374017745, 0.000529178767465055, 0.25587016344070435 ]
{ "id": 3, "code_window": [ " export default config;\n", " `;\n", " const config = loadConfig(source).parse();\n", " expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']);\n", " });\n", " });\n", "\n", " it(`returns undefined when accessing a field that does not exist`, () => {\n", " const source = dedent`\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(config.getNamesFromPath(['otherField'])).toEqual(['foo', 'bar']);\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.test.ts", "type": "add", "edit_start_line_idx": 820 }
import React from 'react'; export default function DynamicComponent() { return <div>I am a dynamically loaded component</div>; }
code/frameworks/nextjs/template/stories/dynamic-component.js
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.00016630291065666825, 0.00016630291065666825, 0.00016630291065666825, 0.00016630291065666825, 0 ]
{ "id": 3, "code_window": [ " export default config;\n", " `;\n", " const config = loadConfig(source).parse();\n", " expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']);\n", " });\n", " });\n", "\n", " it(`returns undefined when accessing a field that does not exist`, () => {\n", " const source = dedent`\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(config.getNamesFromPath(['otherField'])).toEqual(['foo', 'bar']);\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.test.ts", "type": "add", "edit_start_line_idx": 820 }
```ts // MyComponent.stories.ts import { html } from 'lit-html'; import type { Meta, StoryObj } from '@storybook/web-components'; const meta: Meta = { title: 'Path/To/MyComponent', component: 'my-component', }; export default meta; type Story = StoryObj; export const Basic: Story = {}; export const WithProp: Story = { render: () => html`<my-component prop="value" />`, }; ```
docs/snippets/web-components/my-component-story-basic-and-props.ts.mdx
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.00017883021791931242, 0.00017440442752558738, 0.00017149663472082466, 0.00017288645904045552, 0.000003180519343004562 ]
{ "id": 3, "code_window": [ " export default config;\n", " `;\n", " const config = loadConfig(source).parse();\n", " expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']);\n", " });\n", " });\n", "\n", " it(`returns undefined when accessing a field that does not exist`, () => {\n", " const source = dedent`\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(config.getNamesFromPath(['otherField'])).toEqual(['foo', 'bar']);\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.test.ts", "type": "add", "edit_start_line_idx": 820 }
import { basename, join } from 'path'; import type { DocsOptions, Options } from '@storybook/types'; import { getRefs } from '@storybook/core-common'; import { readTemplate } from './template'; // eslint-disable-next-line import/no-cycle import { executor, getConfig } from '../index'; import { safeResolve } from './safeResolve'; export const getData = async (options: Options) => { const refs = getRefs(options); const favicon = options.presets.apply<string>('favicon').then((p) => basename(p)); const features = options.presets.apply<Record<string, string | boolean>>('features'); const logLevel = options.presets.apply<string>('logLevel'); const title = options.presets.apply<string>('title'); const docsOptions = options.presets.apply<DocsOptions>('docs', {}); const template = readTemplate('template.ejs'); const customHead = safeResolve(join(options.configDir, 'manager-head.html')); // we await these, because crucially if these fail, we want to bail out asap const [instance, config] = await Promise.all([ // executor.get(), getConfig(options), ]); return { refs, features, title, docsOptions, template, customHead, instance, config, logLevel, favicon, }; };
code/lib/builder-manager/src/utils/data.ts
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.0015261481748893857, 0.0004897360922768712, 0.000170395418535918, 0.0001725463807815686, 0.0005261843907646835 ]
{ "id": 4, "code_window": [ " if (t.isStringLiteral(node)) {\n", " value = node.value;\n", " } else if (t.isObjectExpression(node)) {\n", " node.properties.forEach((prop) => {\n", " if (\n", " t.isObjectProperty(prop) &&\n", " t.isIdentifier(prop.key) &&\n", " prop.key.name === fallbackProperty\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // { framework: { name: 'value' } }\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.ts", "type": "add", "edit_start_line_idx": 317 }
/// <reference types="@types/jest" />; import { dedent } from 'ts-dedent'; import { formatConfig, loadConfig } from './ConfigFile'; expect.addSnapshotSerializer({ print: (val: any) => val, test: (val) => true, }); const getField = (path: string[], source: string) => { const config = loadConfig(source).parse(); return config.getFieldValue(path); }; const setField = (path: string[], value: any, source: string) => { const config = loadConfig(source).parse(); config.setFieldValue(path, value); return formatConfig(config); }; const removeField = (path: string[], source: string) => { const config = loadConfig(source).parse(); config.removeField(path); return formatConfig(config); }; describe('ConfigFile', () => { describe('getField', () => { describe('named exports', () => { it('missing export', () => { expect( getField( ['core', 'builder'], dedent` export const foo = { builder: 'webpack5' } ` ) ).toBeUndefined(); }); it('missing field', () => { expect( getField( ['core', 'builder'], dedent` export const core = { foo: 'webpack5' } ` ) ).toBeUndefined(); }); it('found scalar', () => { expect( getField( ['core', 'builder'], dedent` export const core = { builder: 'webpack5' } ` ) ).toEqual('webpack5'); }); it('found object', () => { expect( getField( ['core', 'builder'], dedent` export const core = { builder: { name: 'webpack5' } } ` ) ).toEqual({ name: 'webpack5' }); }); it('variable ref export', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; export const core = coreVar; ` ) ).toEqual('webpack5'); }); it('variable export', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; export const core = coreVar; ` ) ).toEqual('webpack5'); }); }); describe('module exports', () => { it('missing export', () => { expect( getField( ['core', 'builder'], dedent` module.exports = { foo: { builder: 'webpack5' } } ` ) ).toBeUndefined(); }); it('found scalar', () => { expect( getField( ['core', 'builder'], dedent` module.exports = { core: { builder: 'webpack5' } } ` ) ).toEqual('webpack5'); }); it('variable ref export', () => { expect( getField( ['core', 'builder'], dedent` const core = { builder: 'webpack5' }; module.exports = { core }; ` ) ).toEqual('webpack5'); }); it('variable rename', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; module.exports = { core: coreVar }; ` ) ).toEqual('webpack5'); }); it('variable exports', () => { expect( getField( ['stories'], dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { stories: [{ directory: '../src', titlePrefix: 'Demo' }], } module.exports = config; ` ) ).toEqual([{ directory: '../src', titlePrefix: 'Demo' }]); }); }); describe('default export', () => { it('missing export', () => { expect( getField( ['core', 'builder'], dedent` export default { foo: { builder: 'webpack5' } } ` ) ).toBeUndefined(); }); it('found scalar', () => { expect( getField( ['core', 'builder'], dedent` export default { core: { builder: 'webpack5' } } ` ) ).toEqual('webpack5'); }); it('variable ref export', () => { expect( getField( ['core', 'builder'], dedent` const core = { builder: 'webpack5' }; export default { core }; ` ) ).toEqual('webpack5'); }); it('variable rename', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; export default { core: coreVar }; ` ) ).toEqual('webpack5'); }); it('variable exports', () => { expect( getField( ['stories'], dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { stories: [{ directory: '../src', titlePrefix: 'Demo' }], } export default config; ` ) ).toEqual([{ directory: '../src', titlePrefix: 'Demo' }]); }); }); }); describe('setField', () => { describe('named exports', () => { it('missing export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export const addons = []; ` ) ).toMatchInlineSnapshot(` export const addons = []; export const core = { builder: "webpack5" }; `); }); it('missing field', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export const core = { foo: 'bar' }; ` ) ).toMatchInlineSnapshot(` export const core = { foo: 'bar', builder: 'webpack5' }; `); }); it('found scalar', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export const core = { builder: 'webpack4' }; ` ) ).toMatchInlineSnapshot(` export const core = { builder: 'webpack5' }; `); }); it('found object', () => { expect( setField( ['core', 'builder'], { name: 'webpack5' }, dedent` export const core = { builder: { name: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export const core = { builder: { name: 'webpack5' } }; `); }); it('variable export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` const coreVar = { builder: 'webpack4' }; export const core = coreVar; ` ) ).toMatchInlineSnapshot(` const coreVar = { builder: 'webpack5' }; export const core = coreVar; `); }); }); describe('module exports', () => { it('missing export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` module.exports = { addons: [] }; ` ) ).toMatchInlineSnapshot(` module.exports = { addons: [], core: { builder: "webpack5" } }; `); }); it('missing field', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` module.exports = { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { foo: 'bar', builder: 'webpack5' } }; `); }); it('found scalar', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` module.exports = { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { builder: 'webpack5' } }; `); }); }); describe('default export', () => { it('missing export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export default { addons: [] }; ` ) ).toMatchInlineSnapshot(` export default { addons: [], core: { builder: "webpack5" } }; `); }); it('missing field', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export default { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` export default { core: { foo: 'bar', builder: 'webpack5' } }; `); }); it('found scalar', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export default { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export default { core: { builder: 'webpack5' } }; `); }); }); describe('quotes', () => { it('no quotes', () => { expect(setField(['foo', 'bar'], 'baz', '')).toMatchInlineSnapshot(` export const foo = { bar: "baz" }; `); }); it('more single quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', 'b', "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', 'b', "c"]; export const foo = { bar: 'baz' }; `); }); it('more double quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', "b", "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', "b", "c"]; export const foo = { bar: "baz" }; `); }); }); }); describe('removeField', () => { describe('named exports', () => { it('missing export', () => { expect( removeField( ['core', 'builder'], dedent` export const addons = []; ` ) ).toMatchInlineSnapshot(`export const addons = [];`); }); it('missing field', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { foo: 'bar' }; ` ) ).toMatchInlineSnapshot(` export const core = { foo: 'bar' }; `); }); it('found scalar', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { builder: 'webpack4' }; ` ) ).toMatchInlineSnapshot(`export const core = {};`); }); it('found object', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { builder: { name: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(`export const core = {};`); }); it('nested object', () => { expect( removeField( ['core', 'builder', 'name'], dedent` export const core = { builder: { name: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export const core = { builder: {} }; `); }); it('string literal key', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { 'builder': 'webpack4' }; ` ) ).toMatchInlineSnapshot(`export const core = {};`); }); it('variable export', () => { expect( removeField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack4' }; export const core = coreVar; ` ) ).toMatchInlineSnapshot(` const coreVar = {}; export const core = coreVar; `); }); it('root export variable', () => { expect( removeField( ['core'], dedent` export const core = { builder: { name: 'webpack4' } }; export const addons = []; ` ) ).toMatchInlineSnapshot(`export const addons = [];`); }); }); describe('module exports', () => { it('missing export', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { addons: [] }; ` ) ).toMatchInlineSnapshot(` module.exports = { addons: [] }; `); }); it('missing field', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { foo: 'bar' } }; `); }); it('found scalar', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` module.exports = { core: {} }; `); }); it('nested scalar', () => { expect( removeField( ['core', 'builder', 'name'], dedent` module.exports = { core: { builder: { name: 'webpack4' } } }; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { builder: {} } }; `); }); it('string literal key', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { 'core': { 'builder': 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` module.exports = { 'core': {} }; `); }); it('root property', () => { expect( removeField( ['core'], dedent` module.exports = { core: { builder: { name: 'webpack4' } }, addons: [] }; ` ) ).toMatchInlineSnapshot(` module.exports = { addons: [] }; `); }); }); describe('default export', () => { it('missing export', () => { expect( removeField( ['core', 'builder'], dedent` export default { addons: [] }; ` ) ).toMatchInlineSnapshot(` export default { addons: [] }; `); }); it('missing field', () => { expect( removeField( ['core', 'builder'], dedent` export default { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` export default { core: { foo: 'bar' } }; `); }); it('found scalar', () => { expect( removeField( ['core', 'builder'], dedent` export default { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export default { core: {} }; `); }); it('nested scalar', () => { expect( removeField( ['core', 'builder', 'name'], dedent` export default { core: { builder: { name: 'webpack4' } } }; ` ) ).toMatchInlineSnapshot(` export default { core: { builder: {} } }; `); }); it('string literal key', () => { expect( removeField( ['core', 'builder'], dedent` export default { 'core': { 'builder': 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export default { 'core': {} }; `); }); it('root property', () => { expect( removeField( ['core'], dedent` export default { core: { builder: { name: 'webpack4' } }, addons: [] }; ` ) ).toMatchInlineSnapshot(` export default { addons: [] }; `); }); }); describe('quotes', () => { it('no quotes', () => { expect(setField(['foo', 'bar'], 'baz', '')).toMatchInlineSnapshot(` export const foo = { bar: "baz" }; `); }); it('more single quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', 'b', "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', 'b', "c"]; export const foo = { bar: 'baz' }; `); }); it('more double quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', "b", "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', "b", "c"]; export const foo = { bar: "baz" }; `); }); }); }); describe('config helpers', () => { describe('getNameFromPath', () => { it(`supports string literal node`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { framework: 'foo', } export default config; `; const config = loadConfig(source).parse(); expect(config.getNameFromPath(['framework'])).toEqual('foo'); }); it(`supports object expression node with name property`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { framework: { name: 'foo', options: { bar: require('baz') } }, } export default config; `; const config = loadConfig(source).parse(); expect(config.getNameFromPath(['framework'])).toEqual('foo'); }); it(`returns undefined when accessing a field that does not exist`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { } export default config; `; const config = loadConfig(source).parse(); expect(config.getNameFromPath(['framework'])).toBeUndefined(); }); it(`throws an error when node is of unexpected type`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { framework: makesNoSense(), } export default config; `; const config = loadConfig(source).parse(); expect(() => config.getNameFromPath(['framework'])).toThrowError( `The given node must be a string literal or an object expression with a "name" property that is a string literal.` ); }); }); describe('getNamesFromPath', () => { it(`supports an array with string literal and object expression with name property`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { addons: [ 'foo', { name: 'bar', options: {} }, ] } export default config; `; const config = loadConfig(source).parse(); expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']); }); }); it(`returns undefined when accessing a field that does not exist`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { } export default config; `; const config = loadConfig(source).parse(); expect(config.getNamesFromPath(['addons'])).toBeUndefined(); }); }); });
code/lib/csf-tools/src/ConfigFile.test.ts
1
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.0010995488846674562, 0.00018902309238910675, 0.00016435164434369653, 0.00017352774739265442, 0.00010877691966015846 ]
{ "id": 4, "code_window": [ " if (t.isStringLiteral(node)) {\n", " value = node.value;\n", " } else if (t.isObjectExpression(node)) {\n", " node.properties.forEach((prop) => {\n", " if (\n", " t.isObjectProperty(prop) &&\n", " t.isIdentifier(prop.key) &&\n", " prop.key.name === fallbackProperty\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // { framework: { name: 'value' } }\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.ts", "type": "add", "edit_start_line_idx": 317 }
```shell yarn storybook ```
docs/snippets/common/storybook-run-dev.yarn.js.mdx
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.00017092459893319756, 0.00017092459893319756, 0.00017092459893319756, 0.00017092459893319756, 0 ]
{ "id": 4, "code_window": [ " if (t.isStringLiteral(node)) {\n", " value = node.value;\n", " } else if (t.isObjectExpression(node)) {\n", " node.properties.forEach((prop) => {\n", " if (\n", " t.isObjectProperty(prop) &&\n", " t.isIdentifier(prop.key) &&\n", " prop.key.name === fallbackProperty\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // { framework: { name: 'value' } }\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.ts", "type": "add", "edit_start_line_idx": 317 }
<h1>Storybook Docs Recipes</h1> [Storybook Docs](../README.md) consists of two basic mechanisms, [DocsPage](docspage.md) and [MDX](mdx.md). But how should you use them in your project? - [Component Story Format (CSF) with DocsPage](#component-story-format-csf-with-docspage) - [Pure MDX Stories](#pure-mdx-stories) - [CSF Stories with MDX Docs](#csf-stories-with-mdx-docs) - [CSF Stories with arbitrary MDX](#csf-stories-with-arbitrary-mdx) - [Mixing storiesOf with CSF/MDX](#mixing-storiesof-with-csfmdx) - [Migrating from notes/info addons](#migrating-from-notesinfo-addons) - [Exporting documentation](#exporting-documentation) - [Disabling docs stories](#disabling-docs-stories) - [DocsPage](#docspage) - [MDX Stories](#mdx-stories) - [Controlling a story's view mode](#controlling-a-storys-view-mode) - [Reordering Docs tab first](#reordering-docs-tab-first) - [Customizing source snippets](#customizing-source-snippets) - [Overwriting docs container](#overwriting-docs-container) - [Add description to individual stories](#add-description-to-individual-stories) - [More resources](#more-resources) ## Component Story Format (CSF) with DocsPage Storybook's [Component Story Format (CSF)](https://medium.com/storybookjs/component-story-format-66f4c32366df) is a convenient, portable way to write stories. [DocsPage](docspage.md) is a convenient, zero-config way to get rich docs for CSF stories. Using these together is a primary use case for Storybook Docs. If you want to intersperse longform documentation in your Storybook, for example to include an introductory page at the beginning of your storybook with an explanation of your design system and installation instructions, [Documentation-only MDX](mdx.md#documentation-only-mdx) is a good way to achieve this. ## Pure MDX Stories [MDX](mdx.md) is an alternative syntax to CSF that allows you to co-locate your stories and your documentation. Everything you can do in CSF, you can do in MDX. And if you're consuming it in [Webpack](https://webpack.js.org/), it exposes an _identical_ interface, so the two files are interchangeable. Some teams will choose to write all of their Storybook in MDX and never look back. ## CSF Stories with MDX Docs Perhaps you want to write your stories in CSF, but document them in MDX? Here's how to do that: **Button.stories.js** ```js import React from 'react'; import { Button } from './Button'; // NOTE: no default export since `Button.stories.mdx` is the story file for `Button` now // // export default { // title: 'Demo/Button', // component: Button, // }; export const basic = () => <Button>Basic</Button>; basic.parameters = { foo: 'bar', }; ``` **Button.stories.mdx** ```md import { Meta, Story } from '@storybook/addon-docs'; import \* as stories from './Button.stories.js'; import { Button } from './Button'; import { SomeComponent } from 'path/to/SomeComponent'; <Meta title="Demo/Button" component={Button} /> # Button I can define a story with the function imported from CSF: <Story story={stories.basic} /> And I can also embed arbitrary markdown & JSX in this file. <SomeComponent prop1="val1" /> ``` What's happening here: - Your stories are defined in CSF, but because of `includeStories: []`, they are not actually added to Storybook. - The named story exports are annotated with story-level decorators, parameters, args, and the `<Story story={}>` construct respects this. - All component-level decorators, parameters, etc. from `Button.stories` default export must be manually copied over into `<Meta>` if desired. ## CSF Stories with arbitrary MDX We recommend [MDX Docs](#csf-stories-with-mdx-docs) as the most ergonomic way to annotate CSF stories with MDX. There's also a second option if you want to annotate your CSF with arbitrary markdown: **Button.mdx** ```md import { Story } from '@storybook/addon-docs'; import { SomeComponent } from 'somewhere'; # Button I can embed a story (but not define one, since this file should not contain a `Meta`): <Story id="some--id" /> And I can also embed arbitrary markdown & JSX in this file. <SomeComponent prop1="val1" /> ``` **Button.stories.js** ```js import React from 'react'; import { Button } from './Button'; import mdx from './Button.mdx'; export default { title: 'Demo/Button', parameters: { docs: { page: mdx, }, }, component: Button, }; export const basic = () => <Button>Basic</Button>; ``` Note that in contrast to other examples, the MDX file suffix is `.mdx` rather than `.stories.mdx`. This key difference means that the file will be loaded with the default MDX loader rather than Storybook's CSF loader, which has several implications: 1. You shouldn't provide a `Meta` declaration. 2. You can refer to existing stories (i.e. `<Story id="...">`) but cannot define new stories (i.e. `<Story name="...">`). 3. The documentation gets exported as the default export (MDX default) rather than as a parameter hanging off the default export (CSF). ## Mixing storiesOf with CSF/MDX You might have a collection of stories using the `storiesOf` API and want to add CSF/MDX piecemeal. Or you might have certain stories that are only possible with the `storiesOf` API (e.g. dynamically generated ones) So how do you mix these two types? The first argument to `configure` can be a `require.context "req"`, an array of `req's`, or a `loader function`. The loader function should either return null or an array of module exports that include the default export. The default export is used by `configure` to load CSF/MDX files. So here's a naive implementation of a loader function that assumes that none of your `storiesOf` files contains a default export, and filters out those exports: ```js const loadFn = () => { const req = require.context('../src', true, /\.stories\.js$/); return req .keys() .map((fname) => req(fname)) .filter((exp) => !!exp.default); }; configure(loadFn, module); ``` We could have baked this heuristic into Storybook, but we can't assume that your `storiesOf` files don't have default exports. If they do, you can filter them some other way (e.g. by file name). If you don't filter out those files, you'll see the following error: > "Loader function passed to 'configure' should return void or an array of module exports that all contain a 'default' export" We made this error explicit to make sure you know what you're doing when you mix `storiesOf` and CSF/MDX. ## Migrating from notes/info addons If you're currently using the notes/info addons, you can upgrade to DocsPage by providing a custom `docs.extractComponentDescription` parameter. There are different ways to use each addon, so you can adapt this recipe according to your use case. Suppose you've added a `notes` parameter to each component in your library, containing markdown text, and you want that to show up at the top of the page in the `Description` slot. You could do that by adding the following snippet to `.storybook/preview.js`: ```js import { addParameters } from '@storybook/preview-api'; addParameters({ docs: { extractComponentDescription: (component, { notes }) => { if (notes) { return typeof notes === 'string' ? notes : notes.markdown || notes.text; } return null; }, }, }); ``` The default `extractComponentDescription` provided by the docs preset extracts JSDoc code comments from the component source, and ignores the second argument, which is the story parameters of the currently-selected story. In contrast, the code snippet above ignores the comment and uses the notes parameter for that story. ## Exporting documentation > ⚠️ The `--docs` flag is an experimental feature in Storybook 5.2. The behavior may change in 5.3 outside of the normal semver rules. Be forewarned! The Storybook UI is a workshop for developing components in isolation. Storybook Docs is a showcase for documenting your components. During component/docs development, it’s useful to see both of these modes side by side. But when you export your static storybook, you might want to export the docs to reduce clutter. To address this, we’ve added a CLI flag to only export the docs. This flag is also available in dev mode: ```sh yarn build-storybook --docs ``` ## Disabling docs stories There are two cases where a user might wish to exclude stories from their documentation pages: ### DocsPage User defines stories in CSF and renders docs using DocsPage, but wishes to exclude some fo the stories from the DocsPage to reduce noise on the page. ```js export const foo = () => <Button>foo</Button>; foo.parameters = { docs: { disable: true } }; ``` ### MDX Stories User writes documentation & stories side-by-side in a single MDX file, and wants those stories to show up in the canvas but not in the docs themselves. They want something similar to the recipe "CSF stories with MDX docs" but want to do everything in MDX: ```js <Story name="foo" parameters={{ docs: { disable: true } }}> <Button>foo</Button> </Story> ``` ## Controlling a story's view mode Storybook's default story navigation behavior is to preserve the existing view mode. In other words, if a user is viewing a story in "docs" mode, and clicks on another story, they will navigate to the other story in "docs" mode. If they are viewing a story in "story" mode (i.e. "canvas" in the UI) they will navigate to another story in "story" mode (with the exception of "docs-only" pages, which are always shown in "docs" mode). Based on user feedback, it's also possible to control the view mode for an individual story using the `viewMode` story parameter. In the following example, the nav link will always set the view mode to story: ```js export const Foo = () => <Component />; Foo.parameters = { // reset the view mode to "story" whenever the user navigates to this story viewMode: 'story', }; ``` This can also be applied globally in `.storybook/preview.js`: ```js // always reset the view mode to "docs" whenever the user navigates export const parameters = { viewMode: 'docs', }; ``` ## Reordering Docs tab first You can configure Storybook's preview tabs with the `previewTabs` story parameter. Here's how to show the `Docs` tab first for a story (or globally in `.storybook/preview.js`): ```js export const Foo = () => <Component />; Foo.parameters = { previewTabs: { 'storybook/docs/panel': { index: -1 } }, }; ``` ## Customizing source snippets As of SB 6.0, there are two ways to customize how Docs renders source code, via story parameter or via a formatting function. If you override the `docs.source.code` parameter, the `Source` block will render whatever string is added: ```js const Example = () => <Button />; Example.parameters = { docs: { source: { code: 'some arbitrary string' } }, }; ``` Alternatively, you can provide a function in the `docs.transformSource` parameter. For example, the following snippet in `.storybook/preview.js` globally removes the arrow at the beginning of a function that returns a string: ```js const SOURCE_REGEX = /^\(\) => `(.*)`$/; export const parameters = { docs: { transformSource: (src, storyContext) => { const match = SOURCE_REGEX.exec(src); return match ? match[1] : src; }, }, }; ``` These two methods are complementary. The former is useful for story-specific, and the latter is useful for global formatting. ## Overwriting docs container What happens if you want to add some wrapper for your MDX page, or add some other kind of React context? When you're writing stories you can do this by adding a [decorator](https://storybook.js.org/docs/react/writing-stories/decorators), but when you're adding arbitrary JSX to your MDX documentation outside of a `<Story>` block, decorators no longer apply, and you need to use the `docs.container` parameter. The closest Docs equivalent of a decorator is the `container`, a wrapper element that is rendered around the page that is being rendered. Here's an example of adding a solid red border around the page. It uses Storybook's default page container (that sets up various contexts and other magic) and then inserts its own logic between that container and the contents of the page: ```js import { Meta, DocsContainer } from '@storybook/addon-docs'; <Meta title="Addons/Docs/container-override" parameters={{ docs: { container: ({ children, context }) => ( <DocsContainer context={context}> <div style={{ border: '5px solid red' }}>{children}</div> </DocsContainer> ), }, }} /> # Title Rest of your file... ``` This is especially useful if you are using `styled-components` and need to wrap your JSX with a `ThemeProvider` to have access to your theme: ```js import { Meta, DocsContainer } from '@storybook/addon-docs'; import { ThemeProvider } from 'styled-components' import { theme } from '../path/to/theme' <Meta title="Addons/Docs/container-override" parameters={{ docs: { container: ({ children, context }) => ( <DocsContainer context={context}> <ThemeProvider theme={theme}> {children} </ThemeProvider> </DocsContainer> ), }, }} /> # Title Rest of your file... ``` ## Add description to individual stories Add `story` to `docs.description` parameter ```js const Example = () => <Button />; Example.parameters = { docs: { description: { story: 'Individual story description, may contain `markdown` markup', }, }, }; ``` There is also an webpack loader package that extracts descriptions from jsdoc comments [story-description-loader](https://www.npmjs.com/package/story-description-loader) ## More resources - References: [README](../README.md) / [DocsPage](docspage.md) / [MDX](mdx.md) / [FAQ](faq.md) / [Recipes](recipes.md) / [Theming](theming.md) / [Props](props-tables.md) - Framework-specific docs: [React](../react/README.md) / [Vue](../vue/README.md) / [Angular](../angular/README.md) / [Web components](../web-components/README.md) / [Ember](../ember/README.md) - Announcements: [Vision](https://medium.com/storybookjs/storybook-docs-sneak-peak-5be78445094a) / [DocsPage](https://medium.com/storybookjs/storybook-docspage-e185bc3622bf) / [MDX](https://medium.com/storybookjs/rich-docs-with-storybook-mdx-61bc145ae7bc) / [Framework support](https://medium.com/storybookjs/storybook-docs-for-new-frameworks-b1f6090ee0ea) - Example: [Storybook Design System](https://github.com/storybookjs/design-system)
code/addons/docs/docs/recipes.md
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.00022497338068205863, 0.00017214837134815753, 0.00016130029689520597, 0.00017198528803419322, 0.000009601578312867787 ]
{ "id": 4, "code_window": [ " if (t.isStringLiteral(node)) {\n", " value = node.value;\n", " } else if (t.isObjectExpression(node)) {\n", " node.properties.forEach((prop) => {\n", " if (\n", " t.isObjectProperty(prop) &&\n", " t.isIdentifier(prop.key) &&\n", " prop.key.name === fallbackProperty\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // { framework: { name: 'value' } }\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.ts", "type": "add", "edit_start_line_idx": 317 }
{ "name": "@storybook/addon-jest", "version": "7.0.0-beta.33", "description": "React storybook addon that show component jest report", "keywords": [ "addon", "jest", "react", "report", "results", "storybook", "unit-testing", "test" ], "homepage": "https://github.com/storybookjs/storybook/tree/main/addons/jest", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "https://github.com/storybookjs/storybook.git", "directory": "addons/jest" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/storybook" }, "license": "MIT", "author": "Renaud Tertrais <[email protected]> (https://github.com/renaudtertrais)", "exports": { ".": { "node": "./dist/index.js", "require": "./dist/index.js", "import": "./dist/index.mjs", "types": "./dist/index.d.ts" }, "./manager": { "require": "./dist/manager.js", "import": "./dist/manager.mjs", "types": "./dist/manager.d.ts" }, "./register": { "require": "./dist/manager.js", "import": "./dist/manager.mjs", "types": "./dist/manager.d.ts" }, "./package.json": "./package.json" }, "main": "dist/index.js", "module": "dist/index.mjs", "types": "dist/index.d.ts", "typesVersions": { "*": { "*": [ "dist/index.d.ts" ], "manager": [ "dist/manager.d.ts" ] } }, "files": [ "dist/**/*", "README.md", "*.js", "*.d.ts" ], "scripts": { "check": "../../../scripts/node_modules/.bin/tsc --noEmit", "prep": "../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "7.0.0-beta.33", "@storybook/components": "7.0.0-beta.33", "@storybook/core-events": "7.0.0-beta.33", "@storybook/global": "^5.0.0", "@storybook/manager-api": "7.0.0-beta.33", "@storybook/preview-api": "7.0.0-beta.33", "@storybook/theming": "7.0.0-beta.33", "react-resize-detector": "^7.1.2", "upath": "^1.2.0" }, "devDependencies": { "typescript": "~4.9.3" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" }, "peerDependenciesMeta": { "react": { "optional": true }, "react-dom": { "optional": true } }, "publishConfig": { "access": "public" }, "bundler": { "entries": [ "./src/index.ts", "./src/manager.tsx" ], "platform": "browser" }, "gitHead": "7b662c444875d3890ee935878fb1b2b45fbfdfb7", "storybook": { "displayName": "Jest", "icon": "https://pbs.twimg.com/profile_images/821713465245102080/mMtKIMax_400x400.jpg", "unsupportedFrameworks": [ "react-native" ] } }
code/addons/jest/package.json
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.00017560871492605656, 0.00017313736316282302, 0.00017085240688174963, 0.00017312289855908602, 0.0000015481524542337866 ]
{ "id": 5, "code_window": [ " if (t.isStringLiteral(prop.value)) {\n", " value = prop.value.value;\n", " }\n", " }\n", " });\n", " }\n", "\n", " if (!value) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " // { \"framework\": { \"name\": \"value\" } }\n", " if (\n", " t.isObjectProperty(prop) &&\n", " t.isStringLiteral(prop.key) &&\n", " prop.key.value === 'name' &&\n", " t.isStringLiteral(prop.value)\n", " ) {\n", " value = prop.value.value;\n", " }\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.ts", "type": "add", "edit_start_line_idx": 326 }
/// <reference types="@types/jest" />; import { dedent } from 'ts-dedent'; import { formatConfig, loadConfig } from './ConfigFile'; expect.addSnapshotSerializer({ print: (val: any) => val, test: (val) => true, }); const getField = (path: string[], source: string) => { const config = loadConfig(source).parse(); return config.getFieldValue(path); }; const setField = (path: string[], value: any, source: string) => { const config = loadConfig(source).parse(); config.setFieldValue(path, value); return formatConfig(config); }; const removeField = (path: string[], source: string) => { const config = loadConfig(source).parse(); config.removeField(path); return formatConfig(config); }; describe('ConfigFile', () => { describe('getField', () => { describe('named exports', () => { it('missing export', () => { expect( getField( ['core', 'builder'], dedent` export const foo = { builder: 'webpack5' } ` ) ).toBeUndefined(); }); it('missing field', () => { expect( getField( ['core', 'builder'], dedent` export const core = { foo: 'webpack5' } ` ) ).toBeUndefined(); }); it('found scalar', () => { expect( getField( ['core', 'builder'], dedent` export const core = { builder: 'webpack5' } ` ) ).toEqual('webpack5'); }); it('found object', () => { expect( getField( ['core', 'builder'], dedent` export const core = { builder: { name: 'webpack5' } } ` ) ).toEqual({ name: 'webpack5' }); }); it('variable ref export', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; export const core = coreVar; ` ) ).toEqual('webpack5'); }); it('variable export', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; export const core = coreVar; ` ) ).toEqual('webpack5'); }); }); describe('module exports', () => { it('missing export', () => { expect( getField( ['core', 'builder'], dedent` module.exports = { foo: { builder: 'webpack5' } } ` ) ).toBeUndefined(); }); it('found scalar', () => { expect( getField( ['core', 'builder'], dedent` module.exports = { core: { builder: 'webpack5' } } ` ) ).toEqual('webpack5'); }); it('variable ref export', () => { expect( getField( ['core', 'builder'], dedent` const core = { builder: 'webpack5' }; module.exports = { core }; ` ) ).toEqual('webpack5'); }); it('variable rename', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; module.exports = { core: coreVar }; ` ) ).toEqual('webpack5'); }); it('variable exports', () => { expect( getField( ['stories'], dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { stories: [{ directory: '../src', titlePrefix: 'Demo' }], } module.exports = config; ` ) ).toEqual([{ directory: '../src', titlePrefix: 'Demo' }]); }); }); describe('default export', () => { it('missing export', () => { expect( getField( ['core', 'builder'], dedent` export default { foo: { builder: 'webpack5' } } ` ) ).toBeUndefined(); }); it('found scalar', () => { expect( getField( ['core', 'builder'], dedent` export default { core: { builder: 'webpack5' } } ` ) ).toEqual('webpack5'); }); it('variable ref export', () => { expect( getField( ['core', 'builder'], dedent` const core = { builder: 'webpack5' }; export default { core }; ` ) ).toEqual('webpack5'); }); it('variable rename', () => { expect( getField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack5' }; export default { core: coreVar }; ` ) ).toEqual('webpack5'); }); it('variable exports', () => { expect( getField( ['stories'], dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { stories: [{ directory: '../src', titlePrefix: 'Demo' }], } export default config; ` ) ).toEqual([{ directory: '../src', titlePrefix: 'Demo' }]); }); }); }); describe('setField', () => { describe('named exports', () => { it('missing export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export const addons = []; ` ) ).toMatchInlineSnapshot(` export const addons = []; export const core = { builder: "webpack5" }; `); }); it('missing field', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export const core = { foo: 'bar' }; ` ) ).toMatchInlineSnapshot(` export const core = { foo: 'bar', builder: 'webpack5' }; `); }); it('found scalar', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export const core = { builder: 'webpack4' }; ` ) ).toMatchInlineSnapshot(` export const core = { builder: 'webpack5' }; `); }); it('found object', () => { expect( setField( ['core', 'builder'], { name: 'webpack5' }, dedent` export const core = { builder: { name: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export const core = { builder: { name: 'webpack5' } }; `); }); it('variable export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` const coreVar = { builder: 'webpack4' }; export const core = coreVar; ` ) ).toMatchInlineSnapshot(` const coreVar = { builder: 'webpack5' }; export const core = coreVar; `); }); }); describe('module exports', () => { it('missing export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` module.exports = { addons: [] }; ` ) ).toMatchInlineSnapshot(` module.exports = { addons: [], core: { builder: "webpack5" } }; `); }); it('missing field', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` module.exports = { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { foo: 'bar', builder: 'webpack5' } }; `); }); it('found scalar', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` module.exports = { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { builder: 'webpack5' } }; `); }); }); describe('default export', () => { it('missing export', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export default { addons: [] }; ` ) ).toMatchInlineSnapshot(` export default { addons: [], core: { builder: "webpack5" } }; `); }); it('missing field', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export default { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` export default { core: { foo: 'bar', builder: 'webpack5' } }; `); }); it('found scalar', () => { expect( setField( ['core', 'builder'], 'webpack5', dedent` export default { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export default { core: { builder: 'webpack5' } }; `); }); }); describe('quotes', () => { it('no quotes', () => { expect(setField(['foo', 'bar'], 'baz', '')).toMatchInlineSnapshot(` export const foo = { bar: "baz" }; `); }); it('more single quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', 'b', "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', 'b', "c"]; export const foo = { bar: 'baz' }; `); }); it('more double quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', "b", "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', "b", "c"]; export const foo = { bar: "baz" }; `); }); }); }); describe('removeField', () => { describe('named exports', () => { it('missing export', () => { expect( removeField( ['core', 'builder'], dedent` export const addons = []; ` ) ).toMatchInlineSnapshot(`export const addons = [];`); }); it('missing field', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { foo: 'bar' }; ` ) ).toMatchInlineSnapshot(` export const core = { foo: 'bar' }; `); }); it('found scalar', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { builder: 'webpack4' }; ` ) ).toMatchInlineSnapshot(`export const core = {};`); }); it('found object', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { builder: { name: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(`export const core = {};`); }); it('nested object', () => { expect( removeField( ['core', 'builder', 'name'], dedent` export const core = { builder: { name: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export const core = { builder: {} }; `); }); it('string literal key', () => { expect( removeField( ['core', 'builder'], dedent` export const core = { 'builder': 'webpack4' }; ` ) ).toMatchInlineSnapshot(`export const core = {};`); }); it('variable export', () => { expect( removeField( ['core', 'builder'], dedent` const coreVar = { builder: 'webpack4' }; export const core = coreVar; ` ) ).toMatchInlineSnapshot(` const coreVar = {}; export const core = coreVar; `); }); it('root export variable', () => { expect( removeField( ['core'], dedent` export const core = { builder: { name: 'webpack4' } }; export const addons = []; ` ) ).toMatchInlineSnapshot(`export const addons = [];`); }); }); describe('module exports', () => { it('missing export', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { addons: [] }; ` ) ).toMatchInlineSnapshot(` module.exports = { addons: [] }; `); }); it('missing field', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { foo: 'bar' } }; `); }); it('found scalar', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` module.exports = { core: {} }; `); }); it('nested scalar', () => { expect( removeField( ['core', 'builder', 'name'], dedent` module.exports = { core: { builder: { name: 'webpack4' } } }; ` ) ).toMatchInlineSnapshot(` module.exports = { core: { builder: {} } }; `); }); it('string literal key', () => { expect( removeField( ['core', 'builder'], dedent` module.exports = { 'core': { 'builder': 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` module.exports = { 'core': {} }; `); }); it('root property', () => { expect( removeField( ['core'], dedent` module.exports = { core: { builder: { name: 'webpack4' } }, addons: [] }; ` ) ).toMatchInlineSnapshot(` module.exports = { addons: [] }; `); }); }); describe('default export', () => { it('missing export', () => { expect( removeField( ['core', 'builder'], dedent` export default { addons: [] }; ` ) ).toMatchInlineSnapshot(` export default { addons: [] }; `); }); it('missing field', () => { expect( removeField( ['core', 'builder'], dedent` export default { core: { foo: 'bar' }}; ` ) ).toMatchInlineSnapshot(` export default { core: { foo: 'bar' } }; `); }); it('found scalar', () => { expect( removeField( ['core', 'builder'], dedent` export default { core: { builder: 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export default { core: {} }; `); }); it('nested scalar', () => { expect( removeField( ['core', 'builder', 'name'], dedent` export default { core: { builder: { name: 'webpack4' } } }; ` ) ).toMatchInlineSnapshot(` export default { core: { builder: {} } }; `); }); it('string literal key', () => { expect( removeField( ['core', 'builder'], dedent` export default { 'core': { 'builder': 'webpack4' } }; ` ) ).toMatchInlineSnapshot(` export default { 'core': {} }; `); }); it('root property', () => { expect( removeField( ['core'], dedent` export default { core: { builder: { name: 'webpack4' } }, addons: [] }; ` ) ).toMatchInlineSnapshot(` export default { addons: [] }; `); }); }); describe('quotes', () => { it('no quotes', () => { expect(setField(['foo', 'bar'], 'baz', '')).toMatchInlineSnapshot(` export const foo = { bar: "baz" }; `); }); it('more single quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', 'b', "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', 'b', "c"]; export const foo = { bar: 'baz' }; `); }); it('more double quotes', () => { expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', "b", "c"]`)) .toMatchInlineSnapshot(` export const stories = ['a', "b", "c"]; export const foo = { bar: "baz" }; `); }); }); }); describe('config helpers', () => { describe('getNameFromPath', () => { it(`supports string literal node`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { framework: 'foo', } export default config; `; const config = loadConfig(source).parse(); expect(config.getNameFromPath(['framework'])).toEqual('foo'); }); it(`supports object expression node with name property`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { framework: { name: 'foo', options: { bar: require('baz') } }, } export default config; `; const config = loadConfig(source).parse(); expect(config.getNameFromPath(['framework'])).toEqual('foo'); }); it(`returns undefined when accessing a field that does not exist`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { } export default config; `; const config = loadConfig(source).parse(); expect(config.getNameFromPath(['framework'])).toBeUndefined(); }); it(`throws an error when node is of unexpected type`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { framework: makesNoSense(), } export default config; `; const config = loadConfig(source).parse(); expect(() => config.getNameFromPath(['framework'])).toThrowError( `The given node must be a string literal or an object expression with a "name" property that is a string literal.` ); }); }); describe('getNamesFromPath', () => { it(`supports an array with string literal and object expression with name property`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { addons: [ 'foo', { name: 'bar', options: {} }, ] } export default config; `; const config = loadConfig(source).parse(); expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']); }); }); it(`returns undefined when accessing a field that does not exist`, () => { const source = dedent` import type { StorybookConfig } from '@storybook/react-webpack5'; const config: StorybookConfig = { } export default config; `; const config = loadConfig(source).parse(); expect(config.getNamesFromPath(['addons'])).toBeUndefined(); }); }); });
code/lib/csf-tools/src/ConfigFile.test.ts
1
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.0001795368589228019, 0.00017065877909772098, 0.00016461183258797973, 0.0001705484464764595, 0.0000028628683139686473 ]
{ "id": 5, "code_window": [ " if (t.isStringLiteral(prop.value)) {\n", " value = prop.value.value;\n", " }\n", " }\n", " });\n", " }\n", "\n", " if (!value) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " // { \"framework\": { \"name\": \"value\" } }\n", " if (\n", " t.isObjectProperty(prop) &&\n", " t.isStringLiteral(prop.key) &&\n", " prop.key.value === 'name' &&\n", " t.isStringLiteral(prop.value)\n", " ) {\n", " value = prop.value.value;\n", " }\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.ts", "type": "add", "edit_start_line_idx": 326 }
declare class AnsiToHtml { constructor(options: { escapeHtml: boolean }); toHtml: (ansi: string) => string; }
code/lib/core-client/typings.d.ts
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.00036023580469191074, 0.00036023580469191074, 0.00036023580469191074, 0.00036023580469191074, 0 ]
{ "id": 5, "code_window": [ " if (t.isStringLiteral(prop.value)) {\n", " value = prop.value.value;\n", " }\n", " }\n", " });\n", " }\n", "\n", " if (!value) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " // { \"framework\": { \"name\": \"value\" } }\n", " if (\n", " t.isObjectProperty(prop) &&\n", " t.isStringLiteral(prop.key) &&\n", " prop.key.value === 'name' &&\n", " t.isStringLiteral(prop.value)\n", " ) {\n", " value = prop.value.value;\n", " }\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.ts", "type": "add", "edit_start_line_idx": 326 }
import path from 'path'; import initStoryshots, { shallowSnapshot } from '../src'; initStoryshots({ framework: 'react', configPath: path.join(__dirname, 'exported_metadata'), test: (data) => shallowSnapshot({ ...data, }), });
code/addons/storyshots-core/stories/storyshot.shallowWithOptions.test.js
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.00017459878290537745, 0.00017381345969624817, 0.00017302812193520367, 0.00017381345969624817, 7.853304850868881e-7 ]
{ "id": 5, "code_window": [ " if (t.isStringLiteral(prop.value)) {\n", " value = prop.value.value;\n", " }\n", " }\n", " });\n", " }\n", "\n", " if (!value) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " // { \"framework\": { \"name\": \"value\" } }\n", " if (\n", " t.isObjectProperty(prop) &&\n", " t.isStringLiteral(prop.key) &&\n", " prop.key.value === 'name' &&\n", " t.isStringLiteral(prop.value)\n", " ) {\n", " value = prop.value.value;\n", " }\n" ], "file_path": "code/lib/csf-tools/src/ConfigFile.ts", "type": "add", "edit_start_line_idx": 326 }
import type * as BabelCoreNamespace from '@babel/core'; import { getVariableMetasBySpecifier, isDefined, removeTransformedVariableDeclarations, replaceImportWithParamterImport, } from './helpers'; type Babel = typeof BabelCoreNamespace; /** * Transforms "@next/font" imports and usages to a webpack loader friendly format with parameters * @example * // src/example.js * // Turns this code: * import { Inter, Roboto } from '@next/font/google' * import localFont from '@next/font/local' * * const myFont = localFont({ src: './my-font.woff2' }) * const roboto = Roboto({ * weight: '400', * }) * * const inter = Inter({ * subsets: ['latin'], * }); * * // Into this code: * import inter from 'storybook-nextjs-font-loader?{filename: "src/example.js", source: "@next/font/google", fontFamily: "Inter", props: {"subsets":["latin"]}}!@next/font/google' * import roboto from 'storybook-nextjs-font-loader?{filename: "src/example.js", source: "@next/font/google", fontFamily: "Roboto", props: {"weight": "400"}}!@next/font/google' * import myFont from 'storybook-nextjs-font-loader?{filename: "src/example.js", source: "@next/font/local", props: {"src": "./my-font.woff2"}}!@next/font/local' * * This Plugin tries to adopt the functionality which is provided by the nextjs swc plugin * https://github.com/vercel/next.js/pull/40221 */ export default function TransformFontImports({ types }: Babel): BabelCoreNamespace.PluginObj { return { name: 'storybook-nextjs-font-imports', visitor: { ImportDeclaration(path, state) { const { node } = path; const { source } = node; const { filename = '' } = state; if (source.value === '@next/font/local') { const { specifiers } = node; // @next/font/local only provides a default export const specifier = specifiers[0]; if (!path.parentPath.isProgram()) { return; } const program = path.parentPath; const variableMetas = getVariableMetasBySpecifier(program, types, specifier); removeTransformedVariableDeclarations(path, types, variableMetas); replaceImportWithParamterImport(path, types, source, variableMetas, filename); } if (source.value === '@next/font/google') { const { specifiers } = node; const variableMetas = specifiers .flatMap((specifier) => { if (!path.parentPath.isProgram()) { return []; } const program = path.parentPath; return getVariableMetasBySpecifier(program, types, specifier); }) .filter(isDefined); removeTransformedVariableDeclarations(path, types, variableMetas); replaceImportWithParamterImport(path, types, source, variableMetas, filename); } }, }, }; }
code/frameworks/nextjs/src/font/babel/index.ts
0
https://github.com/storybookjs/storybook/commit/4691ac0f76a0e3fce09bf338ef699e063f5a3fa5
[ 0.00017563384608365595, 0.00017073954222723842, 0.00016581268573645502, 0.00017080274119507521, 0.000002790267672025948 ]
{ "id": 0, "code_window": [ "};\n", "\n", "export class FastifyAdapter<\n", " TServer extends RawServerBase = RawServerDefault,\n", " TRawRequest extends RawRequestDefaultExpression<\n", " TServer\n", " > = RawRequestDefaultExpression<TServer>,\n", " TRawResponse extends RawReplyDefaultExpression<\n", " TServer\n", " > = RawReplyDefaultExpression<TServer>\n", "> extends AbstractHttpAdapter<\n", " TServer,\n", " FastifyRequest<RequestGenericInterface, TServer, TRawRequest>,\n", " FastifyReply<TServer, TRawRequest, TRawResponse>\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " TRawRequest extends RawRequestDefaultExpression<TServer> = RawRequestDefaultExpression<TServer>,\n", " TRawResponse extends RawReplyDefaultExpression<TServer> = RawReplyDefaultExpression<TServer>\n" ], "file_path": "packages/platform-fastify/adapters/fastify-adapter.ts", "type": "replace", "edit_start_line_idx": 61 }
/* eslint-disable @typescript-eslint/no-var-requires */ import { HttpStatus, Logger, RequestMethod } from '@nestjs/common'; import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface'; import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { AbstractHttpAdapter } from '@nestjs/core/adapters/http-adapter'; import { fastify, FastifyInstance, FastifyLoggerInstance, FastifyPluginAsync, FastifyPluginCallback, FastifyPluginOptions, FastifyRegisterOptions, FastifyReply, FastifyRequest, FastifyServerOptions, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerBase, RawServerDefault, RequestGenericInterface, } from 'fastify'; import * as Reply from 'fastify/lib/reply'; import * as http2 from 'http2'; import * as https from 'https'; import { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, } from 'light-my-request'; import * as pathToRegexp from 'path-to-regexp'; import { FastifyStaticOptions, PointOfViewOptions, } from '../interfaces/external'; type FastifyHttp2SecureOptions< Server extends http2.Http2SecureServer, Logger extends FastifyLoggerInstance = FastifyLoggerInstance > = FastifyServerOptions<Server, Logger> & { http2: true; https: http2.SecureServerOptions; }; type FastifyHttp2Options< Server extends http2.Http2Server, Logger extends FastifyLoggerInstance = FastifyLoggerInstance > = FastifyServerOptions<Server, Logger> & { http2: true; http2SessionTimeout?: number; }; type FastifyHttpsOptions< Server extends https.Server, Logger extends FastifyLoggerInstance = FastifyLoggerInstance > = FastifyServerOptions<Server, Logger> & { https: https.ServerOptions; }; export class FastifyAdapter< TServer extends RawServerBase = RawServerDefault, TRawRequest extends RawRequestDefaultExpression< TServer > = RawRequestDefaultExpression<TServer>, TRawResponse extends RawReplyDefaultExpression< TServer > = RawReplyDefaultExpression<TServer> > extends AbstractHttpAdapter< TServer, FastifyRequest<RequestGenericInterface, TServer, TRawRequest>, FastifyReply<TServer, TRawRequest, TRawResponse> > { protected readonly instance: FastifyInstance< TServer, TRawRequest, TRawResponse >; private _isParserRegistered: boolean; private isMiddieRegistered: boolean; get isParserRegistered(): boolean { return !!this._isParserRegistered; } constructor( instanceOrOptions: | FastifyInstance<TServer> | FastifyHttp2Options<TServer> | FastifyHttp2SecureOptions<any> | FastifyHttpsOptions<any> | FastifyServerOptions<TServer> = fastify() as any, ) { const instance = instanceOrOptions && (instanceOrOptions as FastifyInstance<TServer>).server ? instanceOrOptions : fastify(instanceOrOptions as FastifyServerOptions); super(instance); } public async init() { if (this.isMiddieRegistered) { return; } await this.registerMiddie(); } public listen(port: string | number, callback?: () => void): void; public listen( port: string | number, hostname: string, callback?: () => void, ): void; public listen(port: string | number, ...args: any[]): Promise<string> { if (typeof port === 'string') { port = parseInt(port); } return this.instance.listen(port, ...args); } public reply( response: TRawResponse | FastifyReply, body: any, statusCode?: number, ) { const fastifyReply: FastifyReply = this.isNativeResponse(response) ? new Reply( response, { context: { preSerialization: null, preValidation: [], preHandler: [], onSend: [], onError: [], }, }, {}, ) : response; if (statusCode) { fastifyReply.status(statusCode); } return fastifyReply.send(body); } public status(response: TRawResponse | FastifyReply, statusCode: number) { if (this.isNativeResponse(response)) { response.statusCode = statusCode; return response; } return response.code(statusCode); } public render( response: FastifyReply & { view: Function }, view: string, options: any, ) { return response && response.view(view, options); } public redirect(response: FastifyReply, statusCode: number, url: string) { const code = statusCode ?? HttpStatus.FOUND; return response.status(code).redirect(url); } public setErrorHandler( handler: Parameters< FastifyInstance<TServer, TRawRequest, TRawResponse>['setErrorHandler'] >[0], ) { return this.instance.setErrorHandler(handler); } public setNotFoundHandler( handler: Parameters< FastifyInstance<TServer, TRawRequest, TRawResponse>['setNotFoundHandler'] >[0], ) { return this.instance.setNotFoundHandler(handler); } public getHttpServer<T = TServer>(): T { return (this.instance.server as unknown) as T; } public getInstance< T = FastifyInstance<TServer, TRawRequest, TRawResponse> >(): T { return (this.instance as unknown) as T; } public register<Options extends FastifyPluginOptions = any>( plugin: | FastifyPluginCallback<Options> | FastifyPluginAsync<Options> | Promise<{ default: FastifyPluginCallback<Options> }> | Promise<{ default: FastifyPluginAsync<Options> }>, opts?: FastifyRegisterOptions<Options>, ) { return this.instance.register(plugin, opts); } public inject(): LightMyRequestChain; public inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>; public inject( opts?: InjectOptions | string, ): LightMyRequestChain | Promise<LightMyRequestResponse> { return this.instance.inject(opts); } public async close() { try { return await this.instance.close(); } catch (err) { // Check if server is still running if (err.code !== 'ERR_SERVER_NOT_RUNNING') { throw err; } return; } } public initHttpServer() { this.httpServer = this.instance.server; } public useStaticAssets(options: FastifyStaticOptions) { return this.register( loadPackage('fastify-static', 'FastifyAdapter.useStaticAssets()'), options, ); } public setViewEngine(options: PointOfViewOptions | string) { if (typeof options === 'string') { new Logger('FastifyAdapter').error( "setViewEngine() doesn't support a string argument.", ); process.exit(1); } return this.register( loadPackage('point-of-view', 'FastifyAdapter.setViewEngine()'), options, ); } public setHeader(response: FastifyReply, name: string, value: string) { return response.header(name, value); } public getRequestHostname(request: FastifyRequest): string { return request.hostname; } public getRequestMethod(request: FastifyRequest): string { return request.raw ? request.raw.method : request.method; } public getRequestUrl(request: FastifyRequest): string { return request.raw ? request.raw.url : request.url; } public enableCors(options: CorsOptions) { this.register(require('fastify-cors'), options); } public registerParserMiddleware() { if (this._isParserRegistered) { return; } this.register(require('fastify-formbody')); this._isParserRegistered = true; } public async createMiddlewareFactory( requestMethod: RequestMethod, ): Promise<(path: string, callback: Function) => any> { if (!this.isMiddieRegistered) { await this.registerMiddie(); } return (path: string, callback: Function) => { const re = pathToRegexp(path); const normalizedPath = path === '/*' ? '' : path; // The following type assertion is valid as we enforce "middie" plugin registration // which enhances the FastifyInstance with the "use()" method. // ref https://github.com/fastify/middie/pull/55 const instanceWithUseFn = (this .instance as unknown) as FastifyInstance & { use: Function }; instanceWithUseFn.use( normalizedPath, (req: any, res: any, next: Function) => { const queryParamsIndex = req.originalUrl.indexOf('?'); const pathname = queryParamsIndex >= 0 ? req.originalUrl.slice(0, queryParamsIndex) : req.originalUrl; if (!re.exec(pathname + '/') && normalizedPath) { return next(); } if ( requestMethod === RequestMethod.ALL || req.method === RequestMethod[requestMethod] ) { return callback(req, res, next); } next(); }, ); }; } public getType(): string { return 'fastify'; } protected registerWithPrefix( factory: | FastifyPluginCallback<any> | FastifyPluginAsync<any> | Promise<{ default: FastifyPluginCallback<any> }> | Promise<{ default: FastifyPluginAsync<any> }>, prefix = '/', ) { return this.instance.register(factory, { prefix }); } private isNativeResponse( response: TRawResponse | FastifyReply, ): response is TRawResponse { return !('status' in response); } private async registerMiddie() { this.isMiddieRegistered = true; await this.register(require('middie')); } }
packages/platform-fastify/adapters/fastify-adapter.ts
1
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.9982894062995911, 0.17346759140491486, 0.00016393751138821244, 0.00018612761050462723, 0.37430936098098755 ]
{ "id": 0, "code_window": [ "};\n", "\n", "export class FastifyAdapter<\n", " TServer extends RawServerBase = RawServerDefault,\n", " TRawRequest extends RawRequestDefaultExpression<\n", " TServer\n", " > = RawRequestDefaultExpression<TServer>,\n", " TRawResponse extends RawReplyDefaultExpression<\n", " TServer\n", " > = RawReplyDefaultExpression<TServer>\n", "> extends AbstractHttpAdapter<\n", " TServer,\n", " FastifyRequest<RequestGenericInterface, TServer, TRawRequest>,\n", " FastifyReply<TServer, TRawRequest, TRawResponse>\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " TRawRequest extends RawRequestDefaultExpression<TServer> = RawRequestDefaultExpression<TServer>,\n", " TRawResponse extends RawReplyDefaultExpression<TServer> = RawReplyDefaultExpression<TServer>\n" ], "file_path": "packages/platform-fastify/adapters/fastify-adapter.ts", "type": "replace", "edit_start_line_idx": 61 }
export type ContextType = 'http' | 'ws' | 'rpc'; /** * Methods to obtain request and response objects. * * @publicApi */ export interface HttpArgumentsHost { /** * Returns the in-flight `request` object. */ getRequest<T = any>(): T; /** * Returns the in-flight `response` object. */ getResponse<T = any>(): T; getNext<T = any>(): T; } /** * Methods to obtain WebSocket data and client objects. * * @publicApi */ export interface WsArgumentsHost { /** * Returns the data object. */ getData<T = any>(): T; /** * Returns the client object. */ getClient<T = any>(): T; } /** * Methods to obtain RPC data object. * * @publicApi */ export interface RpcArgumentsHost { /** * Returns the data object. */ getData<T = any>(): T; /** * Returns the context object. */ getContext<T = any>(): T; } /** * Provides methods for retrieving the arguments being passed to a handler. * Allows choosing the appropriate execution context (e.g., Http, RPC, or * WebSockets) to retrieve the arguments from. * * @publicApi */ export interface ArgumentsHost { /** * Returns the array of arguments being passed to the handler. */ getArgs<T extends Array<any> = any[]>(): T; /** * Returns a particular argument by index. * @param index index of argument to retrieve */ getArgByIndex<T = any>(index: number): T; /** * Switch context to RPC. * @returns interface with methods to retrieve RPC arguments */ switchToRpc(): RpcArgumentsHost; /** * Switch context to HTTP. * @returns interface with methods to retrieve HTTP arguments */ switchToHttp(): HttpArgumentsHost; /** * Switch context to WebSockets. * @returns interface with methods to retrieve WebSockets arguments */ switchToWs(): WsArgumentsHost; /** * Returns the current execution context type (string) */ getType<TContext extends string = ContextType>(): TContext; }
packages/common/interfaces/features/arguments-host.interface.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00019921996863558888, 0.00017390301218256354, 0.00016670188051648438, 0.0001700743450783193, 0.000009308153494202998 ]
{ "id": 0, "code_window": [ "};\n", "\n", "export class FastifyAdapter<\n", " TServer extends RawServerBase = RawServerDefault,\n", " TRawRequest extends RawRequestDefaultExpression<\n", " TServer\n", " > = RawRequestDefaultExpression<TServer>,\n", " TRawResponse extends RawReplyDefaultExpression<\n", " TServer\n", " > = RawReplyDefaultExpression<TServer>\n", "> extends AbstractHttpAdapter<\n", " TServer,\n", " FastifyRequest<RequestGenericInterface, TServer, TRawRequest>,\n", " FastifyReply<TServer, TRawRequest, TRawResponse>\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " TRawRequest extends RawRequestDefaultExpression<TServer> = RawRequestDefaultExpression<TServer>,\n", " TRawResponse extends RawReplyDefaultExpression<TServer> = RawReplyDefaultExpression<TServer>\n" ], "file_path": "packages/platform-fastify/adapters/fastify-adapter.ts", "type": "replace", "edit_start_line_idx": 61 }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>App</title> </head> <body> {{ message }} </body> </html>
sample/15-mvc/views/index.hbs
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00017452103202231228, 0.00017240640590898693, 0.00017029177979566157, 0.00017240640590898693, 0.0000021146261133253574 ]
{ "id": 0, "code_window": [ "};\n", "\n", "export class FastifyAdapter<\n", " TServer extends RawServerBase = RawServerDefault,\n", " TRawRequest extends RawRequestDefaultExpression<\n", " TServer\n", " > = RawRequestDefaultExpression<TServer>,\n", " TRawResponse extends RawReplyDefaultExpression<\n", " TServer\n", " > = RawReplyDefaultExpression<TServer>\n", "> extends AbstractHttpAdapter<\n", " TServer,\n", " FastifyRequest<RequestGenericInterface, TServer, TRawRequest>,\n", " FastifyReply<TServer, TRawRequest, TRawResponse>\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " TRawRequest extends RawRequestDefaultExpression<TServer> = RawRequestDefaultExpression<TServer>,\n", " TRawResponse extends RawReplyDefaultExpression<TServer> = RawReplyDefaultExpression<TServer>\n" ], "file_path": "packages/platform-fastify/adapters/fastify-adapter.ts", "type": "replace", "edit_start_line_idx": 61 }
import { NestFactory } from '@nestjs/core'; import { ApplicationModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(ApplicationModule); await app.listen(3000); } bootstrap();
integration/graphql-schema-first/src/main.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00017400013166479766, 0.00017400013166479766, 0.00017400013166479766, 0.00017400013166479766, 0 ]
{ "id": 1, "code_window": [ " hostname: string,\n", " callback?: () => void,\n", " ): void;\n", " public listen(port: string | number, ...args: any[]): Promise<string> {\n", " if (typeof port === 'string') {\n", " port = parseInt(port);\n", " }\n", " return this.instance.listen(port, ...args);\n", " }\n", "\n", " public reply(\n", " response: TRawResponse | FastifyReply,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/platform-fastify/adapters/fastify-adapter.ts", "type": "replace", "edit_start_line_idx": 115 }
import { INestApplication } from '@nestjs/common'; import { FastifyInstance, FastifyPluginAsync, FastifyPluginCallback, FastifyPluginOptions, FastifyRegisterOptions, } from 'fastify'; import { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, } from 'light-my-request'; import { FastifyStaticOptions, PointOfViewOptions } from './external'; export interface NestFastifyApplication extends INestApplication { /** * A wrapper function around native `fastify.register()` method. * Example `app.register(require('fastify-formbody')) * @returns {Promise<FastifyInstance>} */ register<Options extends FastifyPluginOptions = any>( plugin: | FastifyPluginCallback<Options> | FastifyPluginAsync<Options> | Promise<{ default: FastifyPluginCallback<Options> }> | Promise<{ default: FastifyPluginAsync<Options> }>, opts?: FastifyRegisterOptions<Options>, ): Promise<FastifyInstance>; /** * Sets a base directory for public assets. * Example `app.useStaticAssets({ root: 'public' })` * @returns {this} */ useStaticAssets(options: FastifyStaticOptions): this; /** * Sets a view engine for templates (views), for example: `pug`, `handlebars`, or `ejs`. * * Don't pass in a string. The string type in the argument is for compatibilility reason and will cause an exception. * @returns {this} */ setViewEngine(options: PointOfViewOptions | string): this; /** * A wrapper function around native `fastify.inject()` method. * @returns {void} */ inject(): LightMyRequestChain; inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>; /** * Starts the application. * @returns A Promise that, when resolved, is a reference to the underlying HttpServer. */ listen( port: number, callback?: (err: Error, address: string) => void, ): Promise<any>; listen( port: number, address: string, callback?: (err: Error, address: string) => void, ): Promise<any>; listen( port: number, address: string, backlog: number, callback?: (err: Error, address: string) => void, ): Promise<any>; }
packages/platform-fastify/interfaces/nest-fastify-application.interface.ts
1
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.9750598073005676, 0.12230025976896286, 0.00016620129463262856, 0.00018758894293569028, 0.3223135471343994 ]
{ "id": 1, "code_window": [ " hostname: string,\n", " callback?: () => void,\n", " ): void;\n", " public listen(port: string | number, ...args: any[]): Promise<string> {\n", " if (typeof port === 'string') {\n", " port = parseInt(port);\n", " }\n", " return this.instance.listen(port, ...args);\n", " }\n", "\n", " public reply(\n", " response: TRawResponse | FastifyReply,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/platform-fastify/adapters/fastify-adapter.ts", "type": "replace", "edit_start_line_idx": 115 }
import { expect } from 'chai'; import { PARAM_ARGS_METADATA } from '../../constants'; import { ConnectedSocket } from '../../decorators'; import { WsParamtype } from '../../enums/ws-paramtype.enum'; class ConnectedSocketTest { public test(@ConnectedSocket() socket: any) {} } describe('@ConnectedSocket', () => { it('should enhance class with expected request metadata', () => { const argsMetadata = Reflect.getMetadata( PARAM_ARGS_METADATA, ConnectedSocketTest, 'test', ); const expectedMetadata = { [`${WsParamtype.SOCKET}:0`]: { data: undefined, index: 0, pipes: [], }, }; expect(argsMetadata).to.be.eql(expectedMetadata); }); });
packages/websockets/test/decorators/connected-socket.decorator.spec.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00017494973144493997, 0.0001703311427263543, 0.00016580558440182358, 0.00017023805412463844, 0.0000037336624245654093 ]
{ "id": 1, "code_window": [ " hostname: string,\n", " callback?: () => void,\n", " ): void;\n", " public listen(port: string | number, ...args: any[]): Promise<string> {\n", " if (typeof port === 'string') {\n", " port = parseInt(port);\n", " }\n", " return this.instance.listen(port, ...args);\n", " }\n", "\n", " public reply(\n", " response: TRawResponse | FastifyReply,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/platform-fastify/adapters/fastify-adapter.ts", "type": "replace", "edit_start_line_idx": 115 }
export enum RpcParamtype { PAYLOAD = 3, CONTEXT = 6, GRPC_CALL = 9, }
packages/microservices/enums/rpc-paramtype.enum.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.0003644552198238671, 0.0003644552198238671, 0.0003644552198238671, 0.0003644552198238671, 0 ]
{ "id": 1, "code_window": [ " hostname: string,\n", " callback?: () => void,\n", " ): void;\n", " public listen(port: string | number, ...args: any[]): Promise<string> {\n", " if (typeof port === 'string') {\n", " port = parseInt(port);\n", " }\n", " return this.instance.listen(port, ...args);\n", " }\n", "\n", " public reply(\n", " response: TRawResponse | FastifyReply,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/platform-fastify/adapters/fastify-adapter.ts", "type": "replace", "edit_start_line_idx": 115 }
import { NotFoundException, UseGuards, UseInterceptors } from '@nestjs/common'; import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql'; import { PubSub } from 'apollo-server-express'; import { AuthGuard } from '../common/guards/auth.guard'; import { DataInterceptor } from '../common/interceptors/data.interceptor'; import { NewRecipeInput } from './dto/new-recipe.input'; import { RecipesArgs } from './dto/recipes.args'; import { Recipe } from './models/recipe'; import { RecipesService } from './recipes.service'; const pubSub = new PubSub(); @UseInterceptors(DataInterceptor) @Resolver(of => Recipe) export class RecipesResolver { constructor(private readonly recipesService: RecipesService) {} @UseGuards(AuthGuard) @Query(returns => Recipe) async recipe(@Args('id') id: string): Promise<Recipe> { const recipe = await this.recipesService.findOneById(id); if (!recipe) { throw new NotFoundException(id); } return recipe; } @Query(returns => [Recipe]) recipes(@Args() recipesArgs: RecipesArgs): Promise<Recipe[]> { return this.recipesService.findAll(recipesArgs); } @Mutation(returns => Recipe) async addRecipe( @Args('newRecipeData') newRecipeData: NewRecipeInput, ): Promise<Recipe> { const recipe = await this.recipesService.create(newRecipeData); pubSub.publish('recipeAdded', { recipeAdded: recipe }); return recipe; } @Mutation(returns => Boolean) async removeRecipe(@Args('id') id: string) { return this.recipesService.remove(id); } @Subscription(returns => Recipe) recipeAdded() { return pubSub.asyncIterator('recipeAdded'); } }
integration/graphql-code-first/src/recipes/recipes.resolver.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00017438712529838085, 0.00017030932940542698, 0.00016568388673476875, 0.0001699893327895552, 0.000003233734332752647 ]
{ "id": 2, "code_window": [ " * @returns A Promise that, when resolved, is a reference to the underlying HttpServer.\n", " */\n", " listen(\n", " port: number,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 57 }
import { INestApplication } from '@nestjs/common'; import { FastifyInstance, FastifyPluginAsync, FastifyPluginCallback, FastifyPluginOptions, FastifyRegisterOptions, } from 'fastify'; import { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, } from 'light-my-request'; import { FastifyStaticOptions, PointOfViewOptions } from './external'; export interface NestFastifyApplication extends INestApplication { /** * A wrapper function around native `fastify.register()` method. * Example `app.register(require('fastify-formbody')) * @returns {Promise<FastifyInstance>} */ register<Options extends FastifyPluginOptions = any>( plugin: | FastifyPluginCallback<Options> | FastifyPluginAsync<Options> | Promise<{ default: FastifyPluginCallback<Options> }> | Promise<{ default: FastifyPluginAsync<Options> }>, opts?: FastifyRegisterOptions<Options>, ): Promise<FastifyInstance>; /** * Sets a base directory for public assets. * Example `app.useStaticAssets({ root: 'public' })` * @returns {this} */ useStaticAssets(options: FastifyStaticOptions): this; /** * Sets a view engine for templates (views), for example: `pug`, `handlebars`, or `ejs`. * * Don't pass in a string. The string type in the argument is for compatibilility reason and will cause an exception. * @returns {this} */ setViewEngine(options: PointOfViewOptions | string): this; /** * A wrapper function around native `fastify.inject()` method. * @returns {void} */ inject(): LightMyRequestChain; inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>; /** * Starts the application. * @returns A Promise that, when resolved, is a reference to the underlying HttpServer. */ listen( port: number, callback?: (err: Error, address: string) => void, ): Promise<any>; listen( port: number, address: string, callback?: (err: Error, address: string) => void, ): Promise<any>; listen( port: number, address: string, backlog: number, callback?: (err: Error, address: string) => void, ): Promise<any>; }
packages/platform-fastify/interfaces/nest-fastify-application.interface.ts
1
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.995555579662323, 0.12489182502031326, 0.0001677408436080441, 0.00019310561765450984, 0.3290807902812958 ]
{ "id": 2, "code_window": [ " * @returns A Promise that, when resolved, is a reference to the underlying HttpServer.\n", " */\n", " listen(\n", " port: number,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 57 }
import { HttpStatus } from '../enums/http-status.enum'; import { HttpException } from './http.exception'; /** * Defines an HTTP exception for *Gone* type errors. * * @see [Base Exceptions](https://docs.nestjs.com/exception-filters#base-exceptions) * * @publicApi */ export class GoneException extends HttpException { /** * Instantiate a `GoneException` Exception. * * @example * `throw new GoneException()` * * @usageNotes * The HTTP response status code will be 410. * - The `objectOrError` argument defines the JSON response body or the message string. * - The `description` argument contains a short description of the HTTP error. * * By default, the JSON response body contains two properties: * - `statusCode`: this will be the value 410. * - `message`: the string `'Gone'` by default; override this by supplying * a string in the `objectOrError` parameter. * * If the parameter `objectOrError` is a string, the response body will contain an * additional property, `error`, with a short description of the HTTP error. To override the * entire JSON response body, pass an object instead. Nest will serialize the object * and return it as the JSON response body. * * @param objectOrError string or object describing the error condition. * @param description a short description of the HTTP error. */ constructor(objectOrError?: string | object | any, description = 'Gone') { super( HttpException.createBody(objectOrError, description, HttpStatus.GONE), HttpStatus.GONE, ); } }
packages/common/exceptions/gone.exception.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00017947833111975342, 0.00017055956413969398, 0.0001638432586332783, 0.0001704498426988721, 0.000005073909960628953 ]
{ "id": 2, "code_window": [ " * @returns A Promise that, when resolved, is a reference to the underlying HttpServer.\n", " */\n", " listen(\n", " port: number,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 57 }
export * from './global.decorator'; export * from './module.decorator';
packages/common/decorators/modules/index.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00017705094069242477, 0.00017705094069242477, 0.00017705094069242477, 0.00017705094069242477, 0 ]
{ "id": 2, "code_window": [ " * @returns A Promise that, when resolved, is a reference to the underlying HttpServer.\n", " */\n", " listen(\n", " port: number,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 57 }
module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'prettier', 'prettier/@typescript-eslint', ], root: true, env: { node: true, jest: true, }, rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/no-explicit-any': 'off', }, };
sample/15-mvc/.eslintrc.js
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00017753205611370504, 0.0001755377306835726, 0.00017342569481115788, 0.00017565545567777008, 0.0000016784803165137419 ]
{ "id": 3, "code_window": [ " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n", " port: number,\n", " address: string,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 61 }
/* eslint-disable @typescript-eslint/no-var-requires */ import { HttpStatus, Logger, RequestMethod } from '@nestjs/common'; import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface'; import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { AbstractHttpAdapter } from '@nestjs/core/adapters/http-adapter'; import { fastify, FastifyInstance, FastifyLoggerInstance, FastifyPluginAsync, FastifyPluginCallback, FastifyPluginOptions, FastifyRegisterOptions, FastifyReply, FastifyRequest, FastifyServerOptions, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerBase, RawServerDefault, RequestGenericInterface, } from 'fastify'; import * as Reply from 'fastify/lib/reply'; import * as http2 from 'http2'; import * as https from 'https'; import { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, } from 'light-my-request'; import * as pathToRegexp from 'path-to-regexp'; import { FastifyStaticOptions, PointOfViewOptions, } from '../interfaces/external'; type FastifyHttp2SecureOptions< Server extends http2.Http2SecureServer, Logger extends FastifyLoggerInstance = FastifyLoggerInstance > = FastifyServerOptions<Server, Logger> & { http2: true; https: http2.SecureServerOptions; }; type FastifyHttp2Options< Server extends http2.Http2Server, Logger extends FastifyLoggerInstance = FastifyLoggerInstance > = FastifyServerOptions<Server, Logger> & { http2: true; http2SessionTimeout?: number; }; type FastifyHttpsOptions< Server extends https.Server, Logger extends FastifyLoggerInstance = FastifyLoggerInstance > = FastifyServerOptions<Server, Logger> & { https: https.ServerOptions; }; export class FastifyAdapter< TServer extends RawServerBase = RawServerDefault, TRawRequest extends RawRequestDefaultExpression< TServer > = RawRequestDefaultExpression<TServer>, TRawResponse extends RawReplyDefaultExpression< TServer > = RawReplyDefaultExpression<TServer> > extends AbstractHttpAdapter< TServer, FastifyRequest<RequestGenericInterface, TServer, TRawRequest>, FastifyReply<TServer, TRawRequest, TRawResponse> > { protected readonly instance: FastifyInstance< TServer, TRawRequest, TRawResponse >; private _isParserRegistered: boolean; private isMiddieRegistered: boolean; get isParserRegistered(): boolean { return !!this._isParserRegistered; } constructor( instanceOrOptions: | FastifyInstance<TServer> | FastifyHttp2Options<TServer> | FastifyHttp2SecureOptions<any> | FastifyHttpsOptions<any> | FastifyServerOptions<TServer> = fastify() as any, ) { const instance = instanceOrOptions && (instanceOrOptions as FastifyInstance<TServer>).server ? instanceOrOptions : fastify(instanceOrOptions as FastifyServerOptions); super(instance); } public async init() { if (this.isMiddieRegistered) { return; } await this.registerMiddie(); } public listen(port: string | number, callback?: () => void): void; public listen( port: string | number, hostname: string, callback?: () => void, ): void; public listen(port: string | number, ...args: any[]): Promise<string> { if (typeof port === 'string') { port = parseInt(port); } return this.instance.listen(port, ...args); } public reply( response: TRawResponse | FastifyReply, body: any, statusCode?: number, ) { const fastifyReply: FastifyReply = this.isNativeResponse(response) ? new Reply( response, { context: { preSerialization: null, preValidation: [], preHandler: [], onSend: [], onError: [], }, }, {}, ) : response; if (statusCode) { fastifyReply.status(statusCode); } return fastifyReply.send(body); } public status(response: TRawResponse | FastifyReply, statusCode: number) { if (this.isNativeResponse(response)) { response.statusCode = statusCode; return response; } return response.code(statusCode); } public render( response: FastifyReply & { view: Function }, view: string, options: any, ) { return response && response.view(view, options); } public redirect(response: FastifyReply, statusCode: number, url: string) { const code = statusCode ?? HttpStatus.FOUND; return response.status(code).redirect(url); } public setErrorHandler( handler: Parameters< FastifyInstance<TServer, TRawRequest, TRawResponse>['setErrorHandler'] >[0], ) { return this.instance.setErrorHandler(handler); } public setNotFoundHandler( handler: Parameters< FastifyInstance<TServer, TRawRequest, TRawResponse>['setNotFoundHandler'] >[0], ) { return this.instance.setNotFoundHandler(handler); } public getHttpServer<T = TServer>(): T { return (this.instance.server as unknown) as T; } public getInstance< T = FastifyInstance<TServer, TRawRequest, TRawResponse> >(): T { return (this.instance as unknown) as T; } public register<Options extends FastifyPluginOptions = any>( plugin: | FastifyPluginCallback<Options> | FastifyPluginAsync<Options> | Promise<{ default: FastifyPluginCallback<Options> }> | Promise<{ default: FastifyPluginAsync<Options> }>, opts?: FastifyRegisterOptions<Options>, ) { return this.instance.register(plugin, opts); } public inject(): LightMyRequestChain; public inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>; public inject( opts?: InjectOptions | string, ): LightMyRequestChain | Promise<LightMyRequestResponse> { return this.instance.inject(opts); } public async close() { try { return await this.instance.close(); } catch (err) { // Check if server is still running if (err.code !== 'ERR_SERVER_NOT_RUNNING') { throw err; } return; } } public initHttpServer() { this.httpServer = this.instance.server; } public useStaticAssets(options: FastifyStaticOptions) { return this.register( loadPackage('fastify-static', 'FastifyAdapter.useStaticAssets()'), options, ); } public setViewEngine(options: PointOfViewOptions | string) { if (typeof options === 'string') { new Logger('FastifyAdapter').error( "setViewEngine() doesn't support a string argument.", ); process.exit(1); } return this.register( loadPackage('point-of-view', 'FastifyAdapter.setViewEngine()'), options, ); } public setHeader(response: FastifyReply, name: string, value: string) { return response.header(name, value); } public getRequestHostname(request: FastifyRequest): string { return request.hostname; } public getRequestMethod(request: FastifyRequest): string { return request.raw ? request.raw.method : request.method; } public getRequestUrl(request: FastifyRequest): string { return request.raw ? request.raw.url : request.url; } public enableCors(options: CorsOptions) { this.register(require('fastify-cors'), options); } public registerParserMiddleware() { if (this._isParserRegistered) { return; } this.register(require('fastify-formbody')); this._isParserRegistered = true; } public async createMiddlewareFactory( requestMethod: RequestMethod, ): Promise<(path: string, callback: Function) => any> { if (!this.isMiddieRegistered) { await this.registerMiddie(); } return (path: string, callback: Function) => { const re = pathToRegexp(path); const normalizedPath = path === '/*' ? '' : path; // The following type assertion is valid as we enforce "middie" plugin registration // which enhances the FastifyInstance with the "use()" method. // ref https://github.com/fastify/middie/pull/55 const instanceWithUseFn = (this .instance as unknown) as FastifyInstance & { use: Function }; instanceWithUseFn.use( normalizedPath, (req: any, res: any, next: Function) => { const queryParamsIndex = req.originalUrl.indexOf('?'); const pathname = queryParamsIndex >= 0 ? req.originalUrl.slice(0, queryParamsIndex) : req.originalUrl; if (!re.exec(pathname + '/') && normalizedPath) { return next(); } if ( requestMethod === RequestMethod.ALL || req.method === RequestMethod[requestMethod] ) { return callback(req, res, next); } next(); }, ); }; } public getType(): string { return 'fastify'; } protected registerWithPrefix( factory: | FastifyPluginCallback<any> | FastifyPluginAsync<any> | Promise<{ default: FastifyPluginCallback<any> }> | Promise<{ default: FastifyPluginAsync<any> }>, prefix = '/', ) { return this.instance.register(factory, { prefix }); } private isNativeResponse( response: TRawResponse | FastifyReply, ): response is TRawResponse { return !('status' in response); } private async registerMiddie() { this.isMiddieRegistered = true; await this.register(require('middie')); } }
packages/platform-fastify/adapters/fastify-adapter.ts
1
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.004479942377656698, 0.00037668642471544445, 0.00016284832963719964, 0.0001707615447230637, 0.0008494226494804025 ]
{ "id": 3, "code_window": [ " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n", " port: number,\n", " address: string,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 61 }
import { Inject, Injectable, Scope } from '@nestjs/common'; @Injectable({ scope: Scope.REQUEST }) export class HelloService { static COUNTER = 0; constructor(@Inject('META') private readonly meta) { HelloService.COUNTER++; } greeting(): string { return 'Hello world!'; } }
integration/scopes/src/circular-transient/hello.service.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.0001724730245769024, 0.00017217249842360616, 0.00017187198682222515, 0.00017217249842360616, 3.0051887733861804e-7 ]
{ "id": 3, "code_window": [ " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n", " port: number,\n", " address: string,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 61 }
import { Injectable } from '@nestjs/common'; @Injectable() export class AppService { getHello() { return 'Hello world!'; } }
sample/08-webpack/src/app.service.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00017433293396607041, 0.00017433293396607041, 0.00017433293396607041, 0.00017433293396607041, 0 ]
{ "id": 3, "code_window": [ " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n", " port: number,\n", " address: string,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 61 }
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { AppService } from './app.service'; async function bootstrap() { const app = await NestFactory.createApplicationContext(AppModule); const appService = app.get(AppService); console.log(appService.getHello()); } bootstrap();
sample/18-context/src/main.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.0001731444790493697, 0.00017227436183020473, 0.00017140425916295499, 0.00017227436183020473, 8.701099432073534e-7 ]
{ "id": 4, "code_window": [ " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n", " port: number,\n", " address: string,\n", " backlog: number,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 66 }
import { INestApplication } from '@nestjs/common'; import { FastifyInstance, FastifyPluginAsync, FastifyPluginCallback, FastifyPluginOptions, FastifyRegisterOptions, } from 'fastify'; import { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, } from 'light-my-request'; import { FastifyStaticOptions, PointOfViewOptions } from './external'; export interface NestFastifyApplication extends INestApplication { /** * A wrapper function around native `fastify.register()` method. * Example `app.register(require('fastify-formbody')) * @returns {Promise<FastifyInstance>} */ register<Options extends FastifyPluginOptions = any>( plugin: | FastifyPluginCallback<Options> | FastifyPluginAsync<Options> | Promise<{ default: FastifyPluginCallback<Options> }> | Promise<{ default: FastifyPluginAsync<Options> }>, opts?: FastifyRegisterOptions<Options>, ): Promise<FastifyInstance>; /** * Sets a base directory for public assets. * Example `app.useStaticAssets({ root: 'public' })` * @returns {this} */ useStaticAssets(options: FastifyStaticOptions): this; /** * Sets a view engine for templates (views), for example: `pug`, `handlebars`, or `ejs`. * * Don't pass in a string. The string type in the argument is for compatibilility reason and will cause an exception. * @returns {this} */ setViewEngine(options: PointOfViewOptions | string): this; /** * A wrapper function around native `fastify.inject()` method. * @returns {void} */ inject(): LightMyRequestChain; inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>; /** * Starts the application. * @returns A Promise that, when resolved, is a reference to the underlying HttpServer. */ listen( port: number, callback?: (err: Error, address: string) => void, ): Promise<any>; listen( port: number, address: string, callback?: (err: Error, address: string) => void, ): Promise<any>; listen( port: number, address: string, backlog: number, callback?: (err: Error, address: string) => void, ): Promise<any>; }
packages/platform-fastify/interfaces/nest-fastify-application.interface.ts
1
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.9979318380355835, 0.20819564163684845, 0.0001661721325945109, 0.00021996967552695423, 0.36966031789779663 ]
{ "id": 4, "code_window": [ " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n", " port: number,\n", " address: string,\n", " backlog: number,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 66 }
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; export interface Response<T> { data: T; } @Injectable() export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> { intercept( context: ExecutionContext, next: CallHandler<T>, ): Observable<Response<T>> { return next.handle().pipe(map(data => ({ data }))); } }
sample/10-fastify/src/core/interceptors/transform.interceptor.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.00017422738892491907, 0.00017241737805306911, 0.00016928109107539058, 0.0001737436541588977, 0.0000022264653125603218 ]
{ "id": 4, "code_window": [ " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n", " port: number,\n", " address: string,\n", " backlog: number,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 66 }
import { INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import * as request from 'supertest'; import { ApplicationModule } from '../src/app.module'; describe('GraphQL', () => { let app: INestApplication; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [ApplicationModule], }).compile(); app = module.createNestApplication(); await app.init(); }); it(`should return query result`, () => { return request(app.getHttpServer()) .post('/graphql') .send({ operationName: null, variables: {}, query: '{\n getCats {\n id\n }\n}\n', }) .expect(200, { data: { getCats: [ { id: 1, }, ], }, }); }); afterEach(async () => { await app.close(); }); });
integration/graphql-schema-first/e2e/graphql.spec.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.0001753441902110353, 0.0001734899851726368, 0.00017011082672979683, 0.00017421312804799527, 0.0000017877511027108994 ]
{ "id": 4, "code_window": [ " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", " listen(\n", " port: number,\n", " address: string,\n", " backlog: number,\n", " callback?: (err: Error, address: string) => void,\n", " ): Promise<any>;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " port: number | string,\n" ], "file_path": "packages/platform-fastify/interfaces/nest-fastify-application.interface.ts", "type": "replace", "edit_start_line_idx": 66 }
import { isFunction, isNil } from '@nestjs/common/utils/shared.utils'; import { AbstractWsAdapter, MessageMappingProperties, } from '@nestjs/websockets'; import { DISCONNECT_EVENT } from '@nestjs/websockets/constants'; import { fromEvent, Observable } from 'rxjs'; import { filter, first, map, mergeMap, share, takeUntil } from 'rxjs/operators'; import * as io from 'socket.io'; export class IoAdapter extends AbstractWsAdapter { public create( port: number, options?: any & { namespace?: string; server?: any }, ): any { if (!options) { return this.createIOServer(port); } const { namespace, server, ...opt } = options; return server && isFunction(server.of) ? server.of(namespace) : namespace ? this.createIOServer(port, opt).of(namespace) : this.createIOServer(port, opt); } public createIOServer(port: number, options?: any): any { if (this.httpServer && port === 0) { return io(this.httpServer, options); } return io(port, options); } public bindMessageHandlers( client: any, handlers: MessageMappingProperties[], transform: (data: any) => Observable<any>, ) { const disconnect$ = fromEvent(client, DISCONNECT_EVENT).pipe( share(), first(), ); handlers.forEach(({ message, callback }) => { const source$ = fromEvent(client, message).pipe( mergeMap((payload: any) => { const { data, ack } = this.mapPayload(payload); return transform(callback(data, ack)).pipe( filter((response: any) => !isNil(response)), map((response: any) => [response, ack]), ); }), takeUntil(disconnect$), ); source$.subscribe(([response, ack]) => { if (response.event) { return client.emit(response.event, response.data); } isFunction(ack) && ack(response); }); }); } public mapPayload(payload: any): { data: any; ack?: Function } { if (!Array.isArray(payload)) { if (isFunction(payload)) { return { data: undefined, ack: payload }; } return { data: payload }; } const lastElement = payload[payload.length - 1]; const isAck = isFunction(lastElement); if (isAck) { const size = payload.length - 1; return { data: size === 1 ? payload[0] : payload.slice(0, size), ack: lastElement, }; } return { data: payload }; } }
packages/platform-socket.io/adapters/io-adapter.ts
0
https://github.com/nestjs/nest/commit/4fd7e164441e0285f9ad84fa0e085e9b9e56cc9f
[ 0.0006372726056724787, 0.00025162470410577953, 0.00016856432193890214, 0.0001747578353388235, 0.00014574571105185896 ]
{ "id": 0, "code_window": [ " v-if=\"vGroup.root\"\n", " v-model:pagination-data=\"vGroup.paginationData\"\n", " align-count-on-right\n", " custom-label=\"groups\"\n", " :change-page=\"(p: number) => groupWrapperChangePage(p, vGroup)\"\n", " :style=\"`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}`\"\n", " ></LazySmartsheetPagination>\n", " <LazySmartsheetPagination\n", " v-else\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " show-api-timing\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/GroupBy.vue", "type": "add", "edit_start_line_idx": 299 }
<script lang="ts" setup> import tinycolor from 'tinycolor2' import Table from './Table.vue' import GroupBy from './GroupBy.vue' import GroupByTable from './GroupByTable.vue' import { GROUP_BY_VARS, computed, ref } from '#imports' import type { Group, Row } from '#imports' const props = defineProps<{ group: Group loadGroups: (params?: any, group?: Group) => Promise<void> loadGroupData: (group: Group, force?: boolean) => Promise<void> loadGroupPage: (group: Group, p: number) => Promise<void> groupWrapperChangePage: (page: number, groupWrapper?: Group) => Promise<void> redistributeRows?: (group?: Group) => void viewWidth?: number scrollLeft?: number fullPage?: boolean depth?: number maxDepth?: number rowHeight?: number expandForm?: (row: Row, state?: Record<string, any>, fromToolbar?: boolean) => void }>() const emits = defineEmits(['update:paginationData']) const vGroup = useVModel(props, 'group', emits) const { isViewDataLoading, isPaginationLoading } = storeToRefs(useViewsStore()) const reloadViewDataHook = inject(ReloadViewDataHookInj, createEventHook()) const _depth = props.depth ?? 0 const wrapper = ref<HTMLElement | undefined>() const scrollable = ref<HTMLElement | undefined>() const tableHeader = ref<HTMLElement | undefined>() const fullPage = computed<boolean>(() => { return props.fullPage ?? (tableHeader.value?.offsetWidth ?? 0) > (props.viewWidth ?? 0) }) const _activeGroupKeys = ref<string[] | string>() const activeGroups = computed<string[]>(() => { if (!_activeGroupKeys.value) return [] if (Array.isArray(_activeGroupKeys.value)) { return _activeGroupKeys.value.map((k) => k.replace('group-panel-', '')) } else { return [_activeGroupKeys.value.replace('group-panel-', '')] } }) const oldActiveGroups = ref<string[]>([]) const findAndLoadSubGroup = (key: any) => { key = Array.isArray(key) ? key : [key] if (key.length > 0 && vGroup.value.children) { if (!oldActiveGroups.value.includes(key[key.length - 1])) { const k = key[key.length - 1].replace('group-panel-', '') const grp = vGroup.value.children[k] if (grp) { if (grp.nested) { if (!grp.children?.length) props.loadGroups({}, grp) } else { if (!grp.rows?.length) props.loadGroupData(grp) } } } } oldActiveGroups.value = key } const reloadViewDataHandler = () => { if (vGroup.value.nested) { props.loadGroups({}, vGroup.value) } else { props.loadGroupData(vGroup.value, true) } } onBeforeUnmount(async () => { reloadViewDataHook?.off(reloadViewDataHandler) }) reloadViewDataHook?.on(reloadViewDataHandler) watch( [() => vGroup.value.key], async (n, o) => { if (n !== o) { isViewDataLoading.value = true isPaginationLoading.value = true if (vGroup.value.nested) { await props.loadGroups({}, vGroup.value) } else { await props.loadGroupData(vGroup.value, true) } isViewDataLoading.value = false isPaginationLoading.value = false } }, { immediate: true }, ) if (vGroup.value.root === true) provide(ScrollParentInj, wrapper) const _scrollLeft = ref<number>() const scrollBump = computed<number>(() => { if (vGroup.value.root === true) { return _scrollLeft.value ?? 0 } else { if (props.scrollLeft && props.viewWidth && scrollable.value) { const scrollWidth = scrollable.value.scrollWidth + 12 + 12 if (props.scrollLeft + props.viewWidth > scrollWidth) { return scrollWidth - props.viewWidth } return Math.max(Math.min(scrollWidth - props.viewWidth, (props.scrollLeft ?? 0) - 12), 0) } return 0 } }) const onScroll = (e: Event) => { if (!vGroup.value.root) return _scrollLeft.value = (e.target as HTMLElement).scrollLeft } </script> <template> <div class="flex flex-col h-full w-full"> <div ref="wrapper" class="flex flex-col h-full w-full scrollbar-thin-dull overflow-auto" :style="`${!vGroup.root && vGroup.nested ? 'padding-left: 12px; padding-right: 12px;' : ''}`" @scroll="onScroll" > <div ref="scrollable" class="flex flex-col h-full" :class="{ 'my-2': vGroup.root !== true }" :style="`${vGroup.root === true ? 'width: fit-content' : 'width: 100%'}`" > <div v-if="vGroup.root === true" class="flex sticky top-0 z-5"> <div class="bumper mb-2" style="background-color: #f9f9fa; border-color: #e7e7e9; border-bottom-width: 1px" :style="{ 'padding-left': `${(maxDepth || 1) * 13}px` }" ></div> <Table ref="tableHeader" class="mb-2" :data="[]" :header-only="true" /> </div> <div :class="{ 'px-[12px]': vGroup.root === true }"> <a-collapse v-model:activeKey="_activeGroupKeys" class="!bg-transparent w-full nc-group-wrapper" :bordered="false" destroy-inactive-panel @change="findAndLoadSubGroup" > <a-collapse-panel v-for="[i, grp] of Object.entries(vGroup?.children ?? [])" :key="`group-panel-${i}`" class="!border-1 nc-group rounded-[12px]" :class="{ 'mb-4': vGroup.children && +i !== vGroup.children.length - 1 }" :style="`background: rgb(${245 - _depth * 10}, ${245 - _depth * 10}, ${245 - _depth * 10})`" :show-arrow="false" > <template #header> <div class="flex !sticky left-[15px]"> <div class="flex items-center"> <span role="img" aria-label="right" class="anticon anticon-right ant-collapse-arrow"> <svg focusable="false" data-icon="right" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896" :style="`${activeGroups.includes(i) ? 'transform: rotate(90deg)' : ''}`" > <path d="M765.7 486.8L314.9 134.7A7.97 7.97 0 00302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 000-50.4z" ></path> </svg> </span> </div> <div class="flex items-center"> <div class="flex flex-col"> <div class="flex gap-2"> <div class="text-xs nc-group-column-title">{{ grp.column.title }}</div> <div class="text-xs text-gray-400 nc-group-row-count">({{ $t('datatype.Count') }}: {{ grp.count }})</div> </div> <div class="flex mt-1"> <template v-if="grp.column.uidt === 'MultiSelect'"> <a-tag v-for="[tagIndex, tag] of Object.entries(grp.key.split(','))" :key="`panel-tag-${grp.column.id}-${tag}`" class="!py-0 !px-[12px] !rounded-[12px]" :color="grp.color.split(',')[+tagIndex]" > <span class="nc-group-value" :style="{ 'color': tinycolor.isReadable(grp.color.split(',')[+tagIndex] || '#ccc', '#fff', { level: 'AA', size: 'large', }) ? '#fff' : tinycolor .mostReadable(grp.color.split(',')[+tagIndex] || '#ccc', ['#0b1d05', '#fff']) .toHex8String(), 'font-size': '14px', 'font-weight': 500, }" > {{ tag in GROUP_BY_VARS.VAR_TITLES ? GROUP_BY_VARS.VAR_TITLES[tag] : tag }} </span> </a-tag> </template> <a-tag v-else :key="`panel-tag-${grp.column.id}-${grp.key}`" class="!py-0 !px-[12px]" :class="`${grp.column.uidt === 'SingleSelect' ? '!rounded-[12px]' : '!rounded-[6px]'}`" :color="grp.color" > <span class="nc-group-value" :style="{ 'color': tinycolor.isReadable(grp.color || '#ccc', '#fff', { level: 'AA', size: 'large', }) ? '#fff' : tinycolor.mostReadable(grp.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '14px', 'font-weight': 500, }" > {{ grp.key in GROUP_BY_VARS.VAR_TITLES ? GROUP_BY_VARS.VAR_TITLES[grp.key] : grp.key }} </span> </a-tag> </div> </div> </div> </div> </template> <GroupByTable v-if="!grp.nested && grp.rows" :group="grp" :load-groups="loadGroups" :load-group-data="loadGroupData" :load-group-page="loadGroupPage" :group-wrapper-change-page="groupWrapperChangePage" :row-height="rowHeight" :redistribute-rows="redistributeRows" :expand-form="expandForm" :pagination-fixed-size="fullPage ? props.viewWidth : undefined" :pagination-hide-sidebars="true" :scroll-left="props.scrollLeft || _scrollLeft" :view-width="viewWidth" :scrollable="scrollable" :full-page="fullPage" /> <GroupBy v-else :group="grp" :load-groups="loadGroups" :load-group-data="loadGroupData" :load-group-page="loadGroupPage" :group-wrapper-change-page="groupWrapperChangePage" :row-height="rowHeight" :redistribute-rows="redistributeRows" :expand-form="expandForm" :view-width="viewWidth" :depth="_depth + 1" :scroll-left="scrollBump" :full-page="fullPage" /> </a-collapse-panel> </a-collapse> </div> </div> </div> <LazySmartsheetPagination v-if="vGroup.root" v-model:pagination-data="vGroup.paginationData" align-count-on-right custom-label="groups" :change-page="(p: number) => groupWrapperChangePage(p, vGroup)" :style="`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}`" ></LazySmartsheetPagination> <LazySmartsheetPagination v-else v-model:pagination-data="vGroup.paginationData" align-count-on-right custom-label="groups" :change-page="(p: number) => groupWrapperChangePage(p, vGroup)" :hide-sidebars="true" :style="`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}margin-left: ${scrollBump}px;`" :fixed-size="fullPage ? props.viewWidth : undefined" ></LazySmartsheetPagination> </div> </template> <style scoped lang="scss"> :deep(.ant-collapse-content > .ant-collapse-content-box) { padding: 0px !important; border-radius: 0 0 12px 12px !important; } :deep(.ant-collapse-item > .ant-collapse-header) { border-radius: 12px !important; background: white; } :deep(.ant-collapse-item-active > .ant-collapse-header) { border-radius: 12px 12px 0 0 !important; background: white; border-bottom: solid 1px lightgray; } :deep(.ant-collapse-borderless > .ant-collapse-item:last-child) { border-radius: 12px !important; } :deep(.ant-collapse > .ant-collapse-item:last-child) { border-radius: 12px !important; } </style>
packages/nc-gui/components/smartsheet/grid/GroupBy.vue
1
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.9948034882545471, 0.056747421622276306, 0.0001644075964577496, 0.00046747952001169324, 0.22572314739227295 ]
{ "id": 0, "code_window": [ " v-if=\"vGroup.root\"\n", " v-model:pagination-data=\"vGroup.paginationData\"\n", " align-count-on-right\n", " custom-label=\"groups\"\n", " :change-page=\"(p: number) => groupWrapperChangePage(p, vGroup)\"\n", " :style=\"`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}`\"\n", " ></LazySmartsheetPagination>\n", " <LazySmartsheetPagination\n", " v-else\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " show-api-timing\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/GroupBy.vue", "type": "add", "edit_start_line_idx": 299 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none"> <path d="M12.6667 2H3.33333C2.59695 2 2 2.59695 2 3.33333V12.6667C2 13.403 2.59695 14 3.33333 14H12.6667C13.403 14 14 13.403 14 12.6667V3.33333C14 2.59695 13.403 2 12.6667 2Z" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M6 14V6" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M2 6H14" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> </svg>
packages/nc-gui/assets/nc-icons/layout.svg
0
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.0001729072246234864, 0.0001729072246234864, 0.0001729072246234864, 0.0001729072246234864, 0 ]
{ "id": 0, "code_window": [ " v-if=\"vGroup.root\"\n", " v-model:pagination-data=\"vGroup.paginationData\"\n", " align-count-on-right\n", " custom-label=\"groups\"\n", " :change-page=\"(p: number) => groupWrapperChangePage(p, vGroup)\"\n", " :style=\"`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}`\"\n", " ></LazySmartsheetPagination>\n", " <LazySmartsheetPagination\n", " v-else\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " show-api-timing\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/GroupBy.vue", "type": "add", "edit_start_line_idx": 299 }
import { XcStoragePlugin } from 'nc-plugin'; import ScalewayObjectStorage from './ScalewayObjectStorage'; import type { IStorageAdapterV2 } from 'nc-plugin'; class ScalewayObjectStoragePlugin extends XcStoragePlugin { private static storageAdapter: ScalewayObjectStorage; public async init(config: any): Promise<any> { ScalewayObjectStoragePlugin.storageAdapter = new ScalewayObjectStorage( config, ); await ScalewayObjectStoragePlugin.storageAdapter.init(); } public getAdapter(): IStorageAdapterV2 { return ScalewayObjectStoragePlugin.storageAdapter; } } export default ScalewayObjectStoragePlugin;
packages/nocodb/src/plugins/scaleway/ScalewayObjectStoragePlugin.ts
0
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.00017503232811577618, 0.0001741078740451485, 0.00017318343452643603, 0.0001741078740451485, 9.244467946700752e-7 ]
{ "id": 0, "code_window": [ " v-if=\"vGroup.root\"\n", " v-model:pagination-data=\"vGroup.paginationData\"\n", " align-count-on-right\n", " custom-label=\"groups\"\n", " :change-page=\"(p: number) => groupWrapperChangePage(p, vGroup)\"\n", " :style=\"`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}`\"\n", " ></LazySmartsheetPagination>\n", " <LazySmartsheetPagination\n", " v-else\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " show-api-timing\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/GroupBy.vue", "type": "add", "edit_start_line_idx": 299 }
import { Injectable } from '@nestjs/common'; import { extractRolesObj, OrgUserRoles } from 'nocodb-sdk'; import type { UserType } from 'nocodb-sdk'; import { PagedResponseImpl } from '~/helpers/PagedResponse'; import { ApiToken } from '~/models'; @Injectable() export class OrgTokensEeService { async apiTokenListEE(param: { user: UserType; query: any }) { let fk_user_id = param.user.id; // if super admin get all tokens if (extractRolesObj(param.user.roles)[OrgUserRoles.SUPER_ADMIN]) { fk_user_id = undefined; } return new PagedResponseImpl( await ApiToken.listWithCreatedBy({ ...param.query, fk_user_id }), { ...(param.query || {}), count: await ApiToken.count({}), }, ); } }
packages/nocodb/src/services/org-tokens-ee.service.ts
0
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.00017620666767470539, 0.0001719903521006927, 0.0001685175666352734, 0.0001712467783363536, 0.0000031827901239012135 ]
{ "id": 1, "code_window": [ " <LazySmartsheetPagination\n", " v-else\n", " v-model:pagination-data=\"vGroup.paginationData\"\n", " align-count-on-right\n", " custom-label=\"groups\"\n", " :change-page=\"(p: number) => groupWrapperChangePage(p, vGroup)\"\n", " :hide-sidebars=\"true\"\n", " :style=\"`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}margin-left: ${scrollBump}px;`\"\n", " :fixed-size=\"fullPage ? props.viewWidth : undefined\"\n", " ></LazySmartsheetPagination>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " show-api-timing\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/GroupBy.vue", "type": "add", "edit_start_line_idx": 307 }
<script lang="ts" setup> import tinycolor from 'tinycolor2' import Table from './Table.vue' import GroupBy from './GroupBy.vue' import GroupByTable from './GroupByTable.vue' import { GROUP_BY_VARS, computed, ref } from '#imports' import type { Group, Row } from '#imports' const props = defineProps<{ group: Group loadGroups: (params?: any, group?: Group) => Promise<void> loadGroupData: (group: Group, force?: boolean) => Promise<void> loadGroupPage: (group: Group, p: number) => Promise<void> groupWrapperChangePage: (page: number, groupWrapper?: Group) => Promise<void> redistributeRows?: (group?: Group) => void viewWidth?: number scrollLeft?: number fullPage?: boolean depth?: number maxDepth?: number rowHeight?: number expandForm?: (row: Row, state?: Record<string, any>, fromToolbar?: boolean) => void }>() const emits = defineEmits(['update:paginationData']) const vGroup = useVModel(props, 'group', emits) const { isViewDataLoading, isPaginationLoading } = storeToRefs(useViewsStore()) const reloadViewDataHook = inject(ReloadViewDataHookInj, createEventHook()) const _depth = props.depth ?? 0 const wrapper = ref<HTMLElement | undefined>() const scrollable = ref<HTMLElement | undefined>() const tableHeader = ref<HTMLElement | undefined>() const fullPage = computed<boolean>(() => { return props.fullPage ?? (tableHeader.value?.offsetWidth ?? 0) > (props.viewWidth ?? 0) }) const _activeGroupKeys = ref<string[] | string>() const activeGroups = computed<string[]>(() => { if (!_activeGroupKeys.value) return [] if (Array.isArray(_activeGroupKeys.value)) { return _activeGroupKeys.value.map((k) => k.replace('group-panel-', '')) } else { return [_activeGroupKeys.value.replace('group-panel-', '')] } }) const oldActiveGroups = ref<string[]>([]) const findAndLoadSubGroup = (key: any) => { key = Array.isArray(key) ? key : [key] if (key.length > 0 && vGroup.value.children) { if (!oldActiveGroups.value.includes(key[key.length - 1])) { const k = key[key.length - 1].replace('group-panel-', '') const grp = vGroup.value.children[k] if (grp) { if (grp.nested) { if (!grp.children?.length) props.loadGroups({}, grp) } else { if (!grp.rows?.length) props.loadGroupData(grp) } } } } oldActiveGroups.value = key } const reloadViewDataHandler = () => { if (vGroup.value.nested) { props.loadGroups({}, vGroup.value) } else { props.loadGroupData(vGroup.value, true) } } onBeforeUnmount(async () => { reloadViewDataHook?.off(reloadViewDataHandler) }) reloadViewDataHook?.on(reloadViewDataHandler) watch( [() => vGroup.value.key], async (n, o) => { if (n !== o) { isViewDataLoading.value = true isPaginationLoading.value = true if (vGroup.value.nested) { await props.loadGroups({}, vGroup.value) } else { await props.loadGroupData(vGroup.value, true) } isViewDataLoading.value = false isPaginationLoading.value = false } }, { immediate: true }, ) if (vGroup.value.root === true) provide(ScrollParentInj, wrapper) const _scrollLeft = ref<number>() const scrollBump = computed<number>(() => { if (vGroup.value.root === true) { return _scrollLeft.value ?? 0 } else { if (props.scrollLeft && props.viewWidth && scrollable.value) { const scrollWidth = scrollable.value.scrollWidth + 12 + 12 if (props.scrollLeft + props.viewWidth > scrollWidth) { return scrollWidth - props.viewWidth } return Math.max(Math.min(scrollWidth - props.viewWidth, (props.scrollLeft ?? 0) - 12), 0) } return 0 } }) const onScroll = (e: Event) => { if (!vGroup.value.root) return _scrollLeft.value = (e.target as HTMLElement).scrollLeft } </script> <template> <div class="flex flex-col h-full w-full"> <div ref="wrapper" class="flex flex-col h-full w-full scrollbar-thin-dull overflow-auto" :style="`${!vGroup.root && vGroup.nested ? 'padding-left: 12px; padding-right: 12px;' : ''}`" @scroll="onScroll" > <div ref="scrollable" class="flex flex-col h-full" :class="{ 'my-2': vGroup.root !== true }" :style="`${vGroup.root === true ? 'width: fit-content' : 'width: 100%'}`" > <div v-if="vGroup.root === true" class="flex sticky top-0 z-5"> <div class="bumper mb-2" style="background-color: #f9f9fa; border-color: #e7e7e9; border-bottom-width: 1px" :style="{ 'padding-left': `${(maxDepth || 1) * 13}px` }" ></div> <Table ref="tableHeader" class="mb-2" :data="[]" :header-only="true" /> </div> <div :class="{ 'px-[12px]': vGroup.root === true }"> <a-collapse v-model:activeKey="_activeGroupKeys" class="!bg-transparent w-full nc-group-wrapper" :bordered="false" destroy-inactive-panel @change="findAndLoadSubGroup" > <a-collapse-panel v-for="[i, grp] of Object.entries(vGroup?.children ?? [])" :key="`group-panel-${i}`" class="!border-1 nc-group rounded-[12px]" :class="{ 'mb-4': vGroup.children && +i !== vGroup.children.length - 1 }" :style="`background: rgb(${245 - _depth * 10}, ${245 - _depth * 10}, ${245 - _depth * 10})`" :show-arrow="false" > <template #header> <div class="flex !sticky left-[15px]"> <div class="flex items-center"> <span role="img" aria-label="right" class="anticon anticon-right ant-collapse-arrow"> <svg focusable="false" data-icon="right" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896" :style="`${activeGroups.includes(i) ? 'transform: rotate(90deg)' : ''}`" > <path d="M765.7 486.8L314.9 134.7A7.97 7.97 0 00302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 000-50.4z" ></path> </svg> </span> </div> <div class="flex items-center"> <div class="flex flex-col"> <div class="flex gap-2"> <div class="text-xs nc-group-column-title">{{ grp.column.title }}</div> <div class="text-xs text-gray-400 nc-group-row-count">({{ $t('datatype.Count') }}: {{ grp.count }})</div> </div> <div class="flex mt-1"> <template v-if="grp.column.uidt === 'MultiSelect'"> <a-tag v-for="[tagIndex, tag] of Object.entries(grp.key.split(','))" :key="`panel-tag-${grp.column.id}-${tag}`" class="!py-0 !px-[12px] !rounded-[12px]" :color="grp.color.split(',')[+tagIndex]" > <span class="nc-group-value" :style="{ 'color': tinycolor.isReadable(grp.color.split(',')[+tagIndex] || '#ccc', '#fff', { level: 'AA', size: 'large', }) ? '#fff' : tinycolor .mostReadable(grp.color.split(',')[+tagIndex] || '#ccc', ['#0b1d05', '#fff']) .toHex8String(), 'font-size': '14px', 'font-weight': 500, }" > {{ tag in GROUP_BY_VARS.VAR_TITLES ? GROUP_BY_VARS.VAR_TITLES[tag] : tag }} </span> </a-tag> </template> <a-tag v-else :key="`panel-tag-${grp.column.id}-${grp.key}`" class="!py-0 !px-[12px]" :class="`${grp.column.uidt === 'SingleSelect' ? '!rounded-[12px]' : '!rounded-[6px]'}`" :color="grp.color" > <span class="nc-group-value" :style="{ 'color': tinycolor.isReadable(grp.color || '#ccc', '#fff', { level: 'AA', size: 'large', }) ? '#fff' : tinycolor.mostReadable(grp.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '14px', 'font-weight': 500, }" > {{ grp.key in GROUP_BY_VARS.VAR_TITLES ? GROUP_BY_VARS.VAR_TITLES[grp.key] : grp.key }} </span> </a-tag> </div> </div> </div> </div> </template> <GroupByTable v-if="!grp.nested && grp.rows" :group="grp" :load-groups="loadGroups" :load-group-data="loadGroupData" :load-group-page="loadGroupPage" :group-wrapper-change-page="groupWrapperChangePage" :row-height="rowHeight" :redistribute-rows="redistributeRows" :expand-form="expandForm" :pagination-fixed-size="fullPage ? props.viewWidth : undefined" :pagination-hide-sidebars="true" :scroll-left="props.scrollLeft || _scrollLeft" :view-width="viewWidth" :scrollable="scrollable" :full-page="fullPage" /> <GroupBy v-else :group="grp" :load-groups="loadGroups" :load-group-data="loadGroupData" :load-group-page="loadGroupPage" :group-wrapper-change-page="groupWrapperChangePage" :row-height="rowHeight" :redistribute-rows="redistributeRows" :expand-form="expandForm" :view-width="viewWidth" :depth="_depth + 1" :scroll-left="scrollBump" :full-page="fullPage" /> </a-collapse-panel> </a-collapse> </div> </div> </div> <LazySmartsheetPagination v-if="vGroup.root" v-model:pagination-data="vGroup.paginationData" align-count-on-right custom-label="groups" :change-page="(p: number) => groupWrapperChangePage(p, vGroup)" :style="`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}`" ></LazySmartsheetPagination> <LazySmartsheetPagination v-else v-model:pagination-data="vGroup.paginationData" align-count-on-right custom-label="groups" :change-page="(p: number) => groupWrapperChangePage(p, vGroup)" :hide-sidebars="true" :style="`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}margin-left: ${scrollBump}px;`" :fixed-size="fullPage ? props.viewWidth : undefined" ></LazySmartsheetPagination> </div> </template> <style scoped lang="scss"> :deep(.ant-collapse-content > .ant-collapse-content-box) { padding: 0px !important; border-radius: 0 0 12px 12px !important; } :deep(.ant-collapse-item > .ant-collapse-header) { border-radius: 12px !important; background: white; } :deep(.ant-collapse-item-active > .ant-collapse-header) { border-radius: 12px 12px 0 0 !important; background: white; border-bottom: solid 1px lightgray; } :deep(.ant-collapse-borderless > .ant-collapse-item:last-child) { border-radius: 12px !important; } :deep(.ant-collapse > .ant-collapse-item:last-child) { border-radius: 12px !important; } </style>
packages/nc-gui/components/smartsheet/grid/GroupBy.vue
1
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.9967325925827026, 0.03383840247988701, 0.00016277830582112074, 0.0005211293464526534, 0.16577105224132538 ]
{ "id": 1, "code_window": [ " <LazySmartsheetPagination\n", " v-else\n", " v-model:pagination-data=\"vGroup.paginationData\"\n", " align-count-on-right\n", " custom-label=\"groups\"\n", " :change-page=\"(p: number) => groupWrapperChangePage(p, vGroup)\"\n", " :hide-sidebars=\"true\"\n", " :style=\"`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}margin-left: ${scrollBump}px;`\"\n", " :fixed-size=\"fullPage ? props.viewWidth : undefined\"\n", " ></LazySmartsheetPagination>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " show-api-timing\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/GroupBy.vue", "type": "add", "edit_start_line_idx": 307 }
import { XcWebhookNotificationPlugin } from 'nc-plugin'; import TwilioWhatsapp from './TwilioWhatsapp'; import type { IWebhookNotificationAdapter } from 'nc-plugin'; class TwilioWhatsappPlugin extends XcWebhookNotificationPlugin { private static notificationAdapter: TwilioWhatsapp; public getAdapter(): IWebhookNotificationAdapter { return TwilioWhatsappPlugin.notificationAdapter; } public async init(config: any): Promise<any> { TwilioWhatsappPlugin.notificationAdapter = new TwilioWhatsapp(config); await TwilioWhatsappPlugin.notificationAdapter.init(); } } export default TwilioWhatsappPlugin;
packages/nocodb/src/plugins/twilioWhatsapp/TwilioWhatsappPlugin.ts
0
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.00017612571537028998, 0.00017510059115011245, 0.00017407546692993492, 0.00017510059115011245, 0.0000010251242201775312 ]
{ "id": 1, "code_window": [ " <LazySmartsheetPagination\n", " v-else\n", " v-model:pagination-data=\"vGroup.paginationData\"\n", " align-count-on-right\n", " custom-label=\"groups\"\n", " :change-page=\"(p: number) => groupWrapperChangePage(p, vGroup)\"\n", " :hide-sidebars=\"true\"\n", " :style=\"`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}margin-left: ${scrollBump}px;`\"\n", " :fixed-size=\"fullPage ? props.viewWidth : undefined\"\n", " ></LazySmartsheetPagination>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " show-api-timing\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/GroupBy.vue", "type": "add", "edit_start_line_idx": 307 }
<template> <span /> </template>
packages/nc-gui/pages/index/[typeOrId]/[baseId]/index/index/sql.vue
0
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.00017097609816119075, 0.00017097609816119075, 0.00017097609816119075, 0.00017097609816119075, 0 ]
{ "id": 1, "code_window": [ " <LazySmartsheetPagination\n", " v-else\n", " v-model:pagination-data=\"vGroup.paginationData\"\n", " align-count-on-right\n", " custom-label=\"groups\"\n", " :change-page=\"(p: number) => groupWrapperChangePage(p, vGroup)\"\n", " :hide-sidebars=\"true\"\n", " :style=\"`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}margin-left: ${scrollBump}px;`\"\n", " :fixed-size=\"fullPage ? props.viewWidth : undefined\"\n", " ></LazySmartsheetPagination>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " show-api-timing\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/GroupBy.vue", "type": "add", "edit_start_line_idx": 307 }
import { message } from 'ant-design-vue' import type { WatchStopHandle } from 'vue' import type { TableType } from 'nocodb-sdk' import { extractSdkResponseErrorMsg, storeToRefs, useBase, useNuxtApp, useState, watch } from '#imports' export function useMetas() { const { $api } = useNuxtApp() const { tables: _tables } = storeToRefs(useBase()) const { baseTables } = storeToRefs(useTablesStore()) const metas = useState<{ [idOrTitle: string]: TableType | any }>('metas', () => ({})) const metasWithIdAsKey = computed<Record<string, TableType>>(() => { const idEntries = Object.entries(metas.value).filter(([k, v]) => k === v.id) return Object.fromEntries(idEntries) }) const loadingState = useState<Record<string, boolean>>('metas-loading-state', () => ({})) const setMeta = async (model: any) => { metas.value = { ...metas.value, [model.id!]: model, [model.title]: model, } } // todo: this needs a proper refactor, arbitrary waiting times are usually not a good idea const getMeta = async ( tableIdOrTitle: string, force = false, skipIfCacheMiss = false, baseId?: string, ): Promise<TableType | null> => { if (!tableIdOrTitle) return null const tables = (baseId ? baseTables.value.get(baseId) : _tables.value) ?? [] /** wait until loading is finished if requesting same meta * use while to recheck loading state since it can be changed by other requests * */ // eslint-disable-next-line no-unmodified-loop-condition while (!force && loadingState.value[tableIdOrTitle]) { await new Promise((resolve) => { let unwatch: WatchStopHandle // set maximum 10sec timeout to wait loading meta const timeout = setTimeout(() => { unwatch?.() clearTimeout(timeout) resolve(null) }, 10000) // watch for loading state change unwatch = watch( () => !!loadingState.value[tableIdOrTitle], (isLoading) => { if (!isLoading) { clearTimeout(timeout) unwatch?.() resolve(null) } }, { immediate: true }, ) }) if (metas.value[tableIdOrTitle]) { return metas.value[tableIdOrTitle] } } // return null if cache miss if (skipIfCacheMiss) return null loadingState.value[tableIdOrTitle] = true try { if (!force && metas.value[tableIdOrTitle]) { return metas.value[tableIdOrTitle] } const modelId = (tables.find((t) => t.id === tableIdOrTitle) || tables.find((t) => t.title === tableIdOrTitle))?.id if (!modelId) { console.warn(`Table '${tableIdOrTitle}' is not found in the table list`) return null } const model = await $api.dbTable.read(modelId) metas.value = { ...metas.value, [model.id!]: model, [model.title]: model, } return model } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { delete loadingState.value[tableIdOrTitle] } return null } const clearAllMeta = () => { metas.value = {} } const removeMeta = (idOrTitle: string) => { const meta = metas.value[idOrTitle] if (meta) { delete metas.value[meta.id] delete metas.value[meta.title] } } return { getMeta, clearAllMeta, metas, metasWithIdAsKey, removeMeta, setMeta } }
packages/nc-gui/composables/useMetas.ts
0
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.0001766706700436771, 0.00017256707360502332, 0.00016996540944091976, 0.00017160116112791002, 0.0000019690194221766433 ]
{ "id": 2, "code_window": [ "\n", " <LazySmartsheetPagination\n", " v-if=\"headerOnly !== true\"\n", " :key=\"isMobileMode\"\n", " v-model:pagination-data=\"paginationDataRef\"\n", " show-api-timing\n", " align-count-on-right\n", " :change-page=\"changePage\"\n", " :hide-sidebars=\"paginationStyleRef?.hideSidebars === true\"\n", " :fixed-size=\"paginationStyleRef?.fixedSize\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-api-timing=\"!isGroupBy\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/Table.vue", "type": "replace", "edit_start_line_idx": 1000 }
<script lang="ts" setup> import tinycolor from 'tinycolor2' import Table from './Table.vue' import GroupBy from './GroupBy.vue' import GroupByTable from './GroupByTable.vue' import { GROUP_BY_VARS, computed, ref } from '#imports' import type { Group, Row } from '#imports' const props = defineProps<{ group: Group loadGroups: (params?: any, group?: Group) => Promise<void> loadGroupData: (group: Group, force?: boolean) => Promise<void> loadGroupPage: (group: Group, p: number) => Promise<void> groupWrapperChangePage: (page: number, groupWrapper?: Group) => Promise<void> redistributeRows?: (group?: Group) => void viewWidth?: number scrollLeft?: number fullPage?: boolean depth?: number maxDepth?: number rowHeight?: number expandForm?: (row: Row, state?: Record<string, any>, fromToolbar?: boolean) => void }>() const emits = defineEmits(['update:paginationData']) const vGroup = useVModel(props, 'group', emits) const { isViewDataLoading, isPaginationLoading } = storeToRefs(useViewsStore()) const reloadViewDataHook = inject(ReloadViewDataHookInj, createEventHook()) const _depth = props.depth ?? 0 const wrapper = ref<HTMLElement | undefined>() const scrollable = ref<HTMLElement | undefined>() const tableHeader = ref<HTMLElement | undefined>() const fullPage = computed<boolean>(() => { return props.fullPage ?? (tableHeader.value?.offsetWidth ?? 0) > (props.viewWidth ?? 0) }) const _activeGroupKeys = ref<string[] | string>() const activeGroups = computed<string[]>(() => { if (!_activeGroupKeys.value) return [] if (Array.isArray(_activeGroupKeys.value)) { return _activeGroupKeys.value.map((k) => k.replace('group-panel-', '')) } else { return [_activeGroupKeys.value.replace('group-panel-', '')] } }) const oldActiveGroups = ref<string[]>([]) const findAndLoadSubGroup = (key: any) => { key = Array.isArray(key) ? key : [key] if (key.length > 0 && vGroup.value.children) { if (!oldActiveGroups.value.includes(key[key.length - 1])) { const k = key[key.length - 1].replace('group-panel-', '') const grp = vGroup.value.children[k] if (grp) { if (grp.nested) { if (!grp.children?.length) props.loadGroups({}, grp) } else { if (!grp.rows?.length) props.loadGroupData(grp) } } } } oldActiveGroups.value = key } const reloadViewDataHandler = () => { if (vGroup.value.nested) { props.loadGroups({}, vGroup.value) } else { props.loadGroupData(vGroup.value, true) } } onBeforeUnmount(async () => { reloadViewDataHook?.off(reloadViewDataHandler) }) reloadViewDataHook?.on(reloadViewDataHandler) watch( [() => vGroup.value.key], async (n, o) => { if (n !== o) { isViewDataLoading.value = true isPaginationLoading.value = true if (vGroup.value.nested) { await props.loadGroups({}, vGroup.value) } else { await props.loadGroupData(vGroup.value, true) } isViewDataLoading.value = false isPaginationLoading.value = false } }, { immediate: true }, ) if (vGroup.value.root === true) provide(ScrollParentInj, wrapper) const _scrollLeft = ref<number>() const scrollBump = computed<number>(() => { if (vGroup.value.root === true) { return _scrollLeft.value ?? 0 } else { if (props.scrollLeft && props.viewWidth && scrollable.value) { const scrollWidth = scrollable.value.scrollWidth + 12 + 12 if (props.scrollLeft + props.viewWidth > scrollWidth) { return scrollWidth - props.viewWidth } return Math.max(Math.min(scrollWidth - props.viewWidth, (props.scrollLeft ?? 0) - 12), 0) } return 0 } }) const onScroll = (e: Event) => { if (!vGroup.value.root) return _scrollLeft.value = (e.target as HTMLElement).scrollLeft } </script> <template> <div class="flex flex-col h-full w-full"> <div ref="wrapper" class="flex flex-col h-full w-full scrollbar-thin-dull overflow-auto" :style="`${!vGroup.root && vGroup.nested ? 'padding-left: 12px; padding-right: 12px;' : ''}`" @scroll="onScroll" > <div ref="scrollable" class="flex flex-col h-full" :class="{ 'my-2': vGroup.root !== true }" :style="`${vGroup.root === true ? 'width: fit-content' : 'width: 100%'}`" > <div v-if="vGroup.root === true" class="flex sticky top-0 z-5"> <div class="bumper mb-2" style="background-color: #f9f9fa; border-color: #e7e7e9; border-bottom-width: 1px" :style="{ 'padding-left': `${(maxDepth || 1) * 13}px` }" ></div> <Table ref="tableHeader" class="mb-2" :data="[]" :header-only="true" /> </div> <div :class="{ 'px-[12px]': vGroup.root === true }"> <a-collapse v-model:activeKey="_activeGroupKeys" class="!bg-transparent w-full nc-group-wrapper" :bordered="false" destroy-inactive-panel @change="findAndLoadSubGroup" > <a-collapse-panel v-for="[i, grp] of Object.entries(vGroup?.children ?? [])" :key="`group-panel-${i}`" class="!border-1 nc-group rounded-[12px]" :class="{ 'mb-4': vGroup.children && +i !== vGroup.children.length - 1 }" :style="`background: rgb(${245 - _depth * 10}, ${245 - _depth * 10}, ${245 - _depth * 10})`" :show-arrow="false" > <template #header> <div class="flex !sticky left-[15px]"> <div class="flex items-center"> <span role="img" aria-label="right" class="anticon anticon-right ant-collapse-arrow"> <svg focusable="false" data-icon="right" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896" :style="`${activeGroups.includes(i) ? 'transform: rotate(90deg)' : ''}`" > <path d="M765.7 486.8L314.9 134.7A7.97 7.97 0 00302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 000-50.4z" ></path> </svg> </span> </div> <div class="flex items-center"> <div class="flex flex-col"> <div class="flex gap-2"> <div class="text-xs nc-group-column-title">{{ grp.column.title }}</div> <div class="text-xs text-gray-400 nc-group-row-count">({{ $t('datatype.Count') }}: {{ grp.count }})</div> </div> <div class="flex mt-1"> <template v-if="grp.column.uidt === 'MultiSelect'"> <a-tag v-for="[tagIndex, tag] of Object.entries(grp.key.split(','))" :key="`panel-tag-${grp.column.id}-${tag}`" class="!py-0 !px-[12px] !rounded-[12px]" :color="grp.color.split(',')[+tagIndex]" > <span class="nc-group-value" :style="{ 'color': tinycolor.isReadable(grp.color.split(',')[+tagIndex] || '#ccc', '#fff', { level: 'AA', size: 'large', }) ? '#fff' : tinycolor .mostReadable(grp.color.split(',')[+tagIndex] || '#ccc', ['#0b1d05', '#fff']) .toHex8String(), 'font-size': '14px', 'font-weight': 500, }" > {{ tag in GROUP_BY_VARS.VAR_TITLES ? GROUP_BY_VARS.VAR_TITLES[tag] : tag }} </span> </a-tag> </template> <a-tag v-else :key="`panel-tag-${grp.column.id}-${grp.key}`" class="!py-0 !px-[12px]" :class="`${grp.column.uidt === 'SingleSelect' ? '!rounded-[12px]' : '!rounded-[6px]'}`" :color="grp.color" > <span class="nc-group-value" :style="{ 'color': tinycolor.isReadable(grp.color || '#ccc', '#fff', { level: 'AA', size: 'large', }) ? '#fff' : tinycolor.mostReadable(grp.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '14px', 'font-weight': 500, }" > {{ grp.key in GROUP_BY_VARS.VAR_TITLES ? GROUP_BY_VARS.VAR_TITLES[grp.key] : grp.key }} </span> </a-tag> </div> </div> </div> </div> </template> <GroupByTable v-if="!grp.nested && grp.rows" :group="grp" :load-groups="loadGroups" :load-group-data="loadGroupData" :load-group-page="loadGroupPage" :group-wrapper-change-page="groupWrapperChangePage" :row-height="rowHeight" :redistribute-rows="redistributeRows" :expand-form="expandForm" :pagination-fixed-size="fullPage ? props.viewWidth : undefined" :pagination-hide-sidebars="true" :scroll-left="props.scrollLeft || _scrollLeft" :view-width="viewWidth" :scrollable="scrollable" :full-page="fullPage" /> <GroupBy v-else :group="grp" :load-groups="loadGroups" :load-group-data="loadGroupData" :load-group-page="loadGroupPage" :group-wrapper-change-page="groupWrapperChangePage" :row-height="rowHeight" :redistribute-rows="redistributeRows" :expand-form="expandForm" :view-width="viewWidth" :depth="_depth + 1" :scroll-left="scrollBump" :full-page="fullPage" /> </a-collapse-panel> </a-collapse> </div> </div> </div> <LazySmartsheetPagination v-if="vGroup.root" v-model:pagination-data="vGroup.paginationData" align-count-on-right custom-label="groups" :change-page="(p: number) => groupWrapperChangePage(p, vGroup)" :style="`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}`" ></LazySmartsheetPagination> <LazySmartsheetPagination v-else v-model:pagination-data="vGroup.paginationData" align-count-on-right custom-label="groups" :change-page="(p: number) => groupWrapperChangePage(p, vGroup)" :hide-sidebars="true" :style="`${props.depth && props.depth > 0 ? 'border-radius: 0 0 12px 12px !important;' : ''}margin-left: ${scrollBump}px;`" :fixed-size="fullPage ? props.viewWidth : undefined" ></LazySmartsheetPagination> </div> </template> <style scoped lang="scss"> :deep(.ant-collapse-content > .ant-collapse-content-box) { padding: 0px !important; border-radius: 0 0 12px 12px !important; } :deep(.ant-collapse-item > .ant-collapse-header) { border-radius: 12px !important; background: white; } :deep(.ant-collapse-item-active > .ant-collapse-header) { border-radius: 12px 12px 0 0 !important; background: white; border-bottom: solid 1px lightgray; } :deep(.ant-collapse-borderless > .ant-collapse-item:last-child) { border-radius: 12px !important; } :deep(.ant-collapse > .ant-collapse-item:last-child) { border-radius: 12px !important; } </style>
packages/nc-gui/components/smartsheet/grid/GroupBy.vue
1
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.005320725496858358, 0.0006506359786726534, 0.00016404913912992924, 0.0001697776751825586, 0.001340935006737709 ]
{ "id": 2, "code_window": [ "\n", " <LazySmartsheetPagination\n", " v-if=\"headerOnly !== true\"\n", " :key=\"isMobileMode\"\n", " v-model:pagination-data=\"paginationDataRef\"\n", " show-api-timing\n", " align-count-on-right\n", " :change-page=\"changePage\"\n", " :hide-sidebars=\"paginationStyleRef?.hideSidebars === true\"\n", " :fixed-size=\"paginationStyleRef?.fixedSize\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-api-timing=\"!isGroupBy\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/Table.vue", "type": "replace", "edit_start_line_idx": 1000 }
import { Body, Controller, Get, HttpCode, Param, Patch, Post, Req, UseGuards, } from '@nestjs/common'; import { ViewCreateReqType } from 'nocodb-sdk'; import { GlobalGuard } from '~/guards/global/global.guard'; import { KanbansService } from '~/services/kanbans.service'; import { Acl } from '~/middlewares/extract-ids/extract-ids.middleware'; import { MetaApiLimiterGuard } from '~/guards/meta-api-limiter.guard'; @Controller() @UseGuards(MetaApiLimiterGuard, GlobalGuard) export class KanbansController { constructor(private readonly kanbansService: KanbansService) {} @Get([ '/api/v1/db/meta/kanbans/:kanbanViewId', '/api/v1/meta/kanbans/:kanbanViewId', ]) @Acl('kanbanViewGet') async kanbanViewGet(@Param('kanbanViewId') kanbanViewId: string) { return await this.kanbansService.kanbanViewGet({ kanbanViewId, }); } @Post([ '/api/v1/db/meta/tables/:tableId/kanbans', '/api/v1/meta/tables/:tableId/kanbans', ]) @HttpCode(200) @Acl('kanbanViewCreate') async kanbanViewCreate( @Param('tableId') tableId: string, @Body() body: ViewCreateReqType, @Req() req: any, ) { return await this.kanbansService.kanbanViewCreate({ tableId, kanban: body, user: req.user, }); } @Patch([ '/api/v1/db/meta/kanbans/:kanbanViewId', '/api/v1/meta/kanbans/:kanbanViewId', ]) @Acl('kanbanViewUpdate') async kanbanViewUpdate( @Param('kanbanViewId') kanbanViewId: string, @Body() body, ) { return await this.kanbansService.kanbanViewUpdate({ kanbanViewId, kanban: body, }); } }
packages/nocodb/src/controllers/kanbans.controller.ts
0
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.00017567018221598119, 0.00017230641969945282, 0.00016672715719323605, 0.0001730954390950501, 0.0000027721903279598337 ]
{ "id": 2, "code_window": [ "\n", " <LazySmartsheetPagination\n", " v-if=\"headerOnly !== true\"\n", " :key=\"isMobileMode\"\n", " v-model:pagination-data=\"paginationDataRef\"\n", " show-api-timing\n", " align-count-on-right\n", " :change-page=\"changePage\"\n", " :hide-sidebars=\"paginationStyleRef?.hideSidebars === true\"\n", " :fixed-size=\"paginationStyleRef?.fixedSize\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-api-timing=\"!isGroupBy\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/Table.vue", "type": "replace", "edit_start_line_idx": 1000 }
import { Injectable } from '@nestjs/common'; import Redis from 'ioredis'; @Injectable() export class JobsRedisService { private redisClient: Redis; private redisSubscriber: Redis; private unsubscribeCallbacks: { [key: string]: () => void } = {}; constructor() { this.redisClient = new Redis(process.env.NC_REDIS_JOB_URL); this.redisSubscriber = new Redis(process.env.NC_REDIS_JOB_URL); } publish(channel: string, message: string | any) { if (typeof message === 'string') { this.redisClient.publish(channel, message); } else { try { this.redisClient.publish(channel, JSON.stringify(message)); } catch (e) { console.error(e); } } } subscribe(channel: string, callback: (message: any) => void) { this.redisSubscriber.subscribe(channel); const onMessage = (_channel, message) => { try { message = JSON.parse(message); } catch (e) {} callback(message); }; this.redisSubscriber.on('message', onMessage); this.unsubscribeCallbacks[channel] = () => { this.redisSubscriber.unsubscribe(channel); this.redisSubscriber.off('message', onMessage); }; } unsubscribe(channel: string) { if (this.unsubscribeCallbacks[channel]) { this.unsubscribeCallbacks[channel](); delete this.unsubscribeCallbacks[channel]; } } }
packages/nocodb/src/modules/jobs/redis/jobs-redis.service.ts
0
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.0001741609739838168, 0.00016801051970105618, 0.00015743776748422533, 0.0001698324631433934, 0.000005345268164091976 ]
{ "id": 2, "code_window": [ "\n", " <LazySmartsheetPagination\n", " v-if=\"headerOnly !== true\"\n", " :key=\"isMobileMode\"\n", " v-model:pagination-data=\"paginationDataRef\"\n", " show-api-timing\n", " align-count-on-right\n", " :change-page=\"changePage\"\n", " :hide-sidebars=\"paginationStyleRef?.hideSidebars === true\"\n", " :fixed-size=\"paginationStyleRef?.fixedSize\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-api-timing=\"!isGroupBy\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/grid/Table.vue", "type": "replace", "edit_start_line_idx": 1000 }
<script lang="ts" setup> const props = defineProps<{ visible: boolean baseId: string }>() const emits = defineEmits(['update:visible']) const visible = useVModel(props, 'visible', emits) const { closeTab } = useTabs() const basesStore = useBases() const { deleteProject, navigateToFirstProjectOrHome } = basesStore const { bases } = storeToRefs(basesStore) const { removeFromRecentViews } = useViewsStore() const { refreshCommandPalette } = useCommandPalette() const base = computed(() => bases.value.get(props.baseId)) const isLoading = ref(false) const onDelete = async () => { if (!base.value) return const toBeDeletedProject = JSON.parse(JSON.stringify(base.value)) isLoading.value = true try { await deleteProject(toBeDeletedProject.id!) await closeTab(toBeDeletedProject.id as any) refreshCommandPalette() visible.value = false if (toBeDeletedProject.id === basesStore.activeProjectId) { await navigateToFirstProjectOrHome() } } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isLoading.value = false removeFromRecentViews({ baseId: toBeDeletedProject.id! }) } } </script> <template> <GeneralDeleteModal v-model:visible="visible" :entity-name="$t('objects.project')" :on-delete="onDelete"> <template #entity-preview> <div v-if="base" class="flex flex-row items-center py-2 px-2.25 bg-gray-50 rounded-lg text-gray-700 mb-4"> <GeneralProjectIcon :type="base.type" class="nc-view-icon px-1.5 w-10" /> <div class="capitalize text-ellipsis overflow-hidden select-none w-full pl-1.75" :style="{ wordBreak: 'keep-all', whiteSpace: 'nowrap', display: 'inline' }" > {{ base.title }} </div> </div> </template> </GeneralDeleteModal> </template>
packages/nc-gui/components/dlg/ProjectDelete.vue
0
https://github.com/nocodb/nocodb/commit/24efc38c7aa8bcf68944b321ef64d829f3c2f815
[ 0.0001731725496938452, 0.00017047424626071006, 0.00016528641572222114, 0.00017185152682941407, 0.0000028815684345318004 ]
{ "id": 0, "code_window": [ "\n", "var nodeEnv = prodOrDev === 'production' ? 'http://www.freecodecamp.com' : 'http://localhost:3001';\n", "function updatePreview() {\n", " editorValueForIFrame = editor.getValue();\n", " goodTests = 0;\n", " var previewFrame = document.getElementById('preview');\n", " var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var failedCommentTest = false;\n", " if(editorValueForIFrame.match(/\\<\\!\\-\\-/gi) && editorValueForIFrame.match(/\\-\\-\\>/gi) == null){\n", " failedCommentTest = true;\n", " }\n", " else if(editorValueForIFrame.match(/\\<\\!\\-\\-/gi) && editorValueForIFrame.match(/\\<\\!\\-\\-/gi).length > editorValueForIFrame.match(/\\-\\-\\>/gi).length){\n", " failedCommentTest = true;\n", " }\n", " if(failedCommentTest){\n", " editor.setValue(editor.getValue()+ \"-->\");\n", " editorValueForIFrame = editorValueForIFrame + \"-->\";\n", " }\n" ], "file_path": "public/js/lib/coursewares/coursewaresHCJQFramework_0.1.9.js", "type": "add", "edit_start_line_idx": 73 }
/** * Created by nathanleniz on 2/2/15. */ var widgets = []; var editor = CodeMirror.fromTextArea(document.getElementById("codeEditor"), { lineNumbers: true, mode: "text/html", theme: 'monokai', runnable: true, matchBrackets: true, autoCloseBrackets: true, scrollbarStyle: 'null', lineWrapping: true, gutters: ["CodeMirror-lint-markers"], onKeyEvent: doLinting }); var defaultKeymap = { 'Cmd-E': 'emmet.expand_abbreviation', 'Tab': 'emmet.expand_abbreviation_with_tab', 'Enter': 'emmet.insert_formatted_line_break_only' }; emmetCodeMirror(editor, defaultKeymap); // Hijack tab key to insert two spaces instead editor.setOption("extraKeys", { Tab: function(cm) { if (cm.somethingSelected()){ cm.indentSelection("add"); } else { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces); } }, "Shift-Tab": function(cm) { if (cm.somethingSelected()){ cm.indentSelection("subtract"); } else { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces); } } }); editor.setSize("100%", "auto"); var libraryIncludes = "<script src='//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>" + "<script src='/js/lib/chai/chai.js'></script>" + "<script src='/js/lib/chai/chai-jquery.js'></script>" + "<script src='//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js'></script>" + "<link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.min.css'/>" + "<link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css'/>" + "<link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css'/>" + "<style>body { padding: 0px 3px 0px 3px; }</style>" + "<script>var expect = chai.expect; var should = chai.should(); var assert = chai.assert;</script>"; var editorValueForIFrame; var iFrameScript = "<script src='/js/lib/coursewares/iFrameScripts_0.0.4.js'></script>"; var delay; // Initialize CodeMirror editor with a nice html5 canvas demo. editor.on("keyup", function () { clearTimeout(delay); delay = setTimeout(updatePreview, 300); }); var nodeEnv = prodOrDev === 'production' ? 'http://www.freecodecamp.com' : 'http://localhost:3001'; function updatePreview() { editorValueForIFrame = editor.getValue(); goodTests = 0; var previewFrame = document.getElementById('preview'); var preview = previewFrame.contentDocument || previewFrame.contentWindow.document; preview.open(); $('#testSuite').empty(); preview.write(libraryIncludes + editor.getValue() + iFrameScript); codeStorage.updateStorage(); preview.close(); } setTimeout(updatePreview, 300); /** * "post" methods */ var testResults = []; var postSuccess = function(data) { var testDoc = document.createElement("div"); $(testDoc) .html("<div class='row'><div class='col-xs-2 text-center'><i class='ion-checkmark-circled big-success-icon'></i></div><div class='col-xs-10 test-output test-vertical-center wrappable'>" + JSON.parse(data) + "</div>"); $('#testSuite').append(testDoc); testSuccess(); }; var postError = function(data) { var testDoc = document.createElement("div"); $(testDoc) .html("<div class='row'><div class='col-xs-2 text-center'><i class='ion-close-circled big-error-icon'></i></div><div class='col-xs-10 test-vertical-center test-output wrappable'>" + JSON.parse(data) + "</div>"); $('#testSuite').append(testDoc); }; var goodTests = 0; var testSuccess = function() { goodTests++; if (goodTests === tests.length) { showCompletion(); } }; function doLinting () { editor.operation(function () { for (var i = 0; i < widgets.length; ++i) editor.removeLineWidget(widgets[i]); widgets.length = 0; JSHINT(editor.getValue()); for (var i = 0; i < JSHINT.errors.length; ++i) { var err = JSHINT.errors[i]; if (!err) continue; var msg = document.createElement("div"); var icon = msg.appendChild(document.createElement("span")); icon.innerHTML = "!!"; icon.className = "lint-error-icon"; msg.appendChild(document.createTextNode(err.reason)); msg.className = "lint-error"; widgets.push(editor.addLineWidget(err.line - 1, msg, { coverGutter: false, noHScroll: true })); } }); }; //$('#testSuite').empty(); function showCompletion() { var time = Math.floor(Date.now()) - started; ga('send', 'event', 'Challenge', 'solved', challenge_Name + ', Time: ' + time); $('#next-courseware-button').removeAttr('disabled'); $('#next-courseware-button').addClass('animated tada'); if (!userLoggedIn) { $('#complete-courseware-dialog').modal('show'); } $('body').keydown(function(e) { if (e.ctrlKey && e.keyCode == 13) { $('#next-courseware-button').click(); $('#next-courseware-button').unbind('click'); } }); } /* Local Storage Update System By Andrew Cay(Resto) codeStorage: singleton object that contains properties and methods related to dealing with the localStorage system. The keys work off of the variable challenge_name to make unique identifiers per bonfire Two extra functionalities: Added anonymous version checking system incase of future updates to the system Added keyup listener to editor(myCodeMirror) so the last update has been saved to storage */ var codeStorage = { version: 0.01, keyVersion:"saveVersion", keyValue: null,//where the value of the editor is saved updateWait: 2000,// 2 seconds updateTimeoutId: null, eventArray: []//for firing saves }; // Returns true if the editor code was saved since last key press (use this if you want to make a "saved" notification somewhere") codeStorage.hasSaved = function(){ return ( updateTimeoutId === null ); }; codeStorage.onSave = function(func){ codeStorage.eventArray.push(func); }; codeStorage.setSaveKey = function(key){ codeStorage.keyValue = key + 'Val'; }; codeStorage.getEditorValue = function(){ return ('' + localStorage.getItem(codeStorage.keyValue)); }; codeStorage.isAlive = function() { var val = this.getEditorValue() return val !== 'null' && val !== 'undefined' && (val && val.length > 0); } codeStorage.updateStorage = function(){ if(typeof(Storage) !== undefined) { var value = editor.getValue(); localStorage.setItem(codeStorage.keyValue, value); } else { var debugging = false; if( debugging ){ console.log('no web storage'); } } codeStorage.updateTimeoutId = null; codeStorage.eventArray.forEach(function(func){ func(); }); }; //Update Version (function(){ var savedVersion = localStorage.getItem('saveVersion'); if( savedVersion === null ){ localStorage.setItem(codeStorage.keyVersion, codeStorage.version);//just write current version }else{ if( savedVersion !== codeStorage.version ){ //Update version } } })(); ///Set everything up one page /// Update local save when editor has changed codeStorage.setSaveKey(challenge_Name); editor.on('keyup', function(){ window.clearTimeout(codeStorage.updateTimeoutId); codeStorage.updateTimeoutId = window.setTimeout(codeStorage.updateStorage, codeStorage.updateWait); }); var editorValue; var challengeSeed = challengeSeed || null; var tests = tests || []; var allSeeds = ''; (function() { challengeSeed.forEach(function(elem) { allSeeds += elem + '\n'; }); })(); editorValue = (codeStorage.isAlive())? codeStorage.getEditorValue() : allSeeds; editor.setValue(editorValue); var resetEditor = function resetEditor() { editor.setValue(allSeeds); updatePreview(); codeStorage.updateStorage(); }; var challengeSeed = challengeSeed || null; var allSeeds = ''; (function() { challengeSeed.forEach(function(elem) { allSeeds += elem.replace(/fccss/g, '<script>').replace(/fcces/g,'</script>') + '\n'; }); editor.setValue(allSeeds); (function() { setTimeout(function() { editor.refresh(); }, 200); })(); })();
public/js/lib/coursewares/coursewaresHCJQFramework_0.1.9.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.9985750913619995, 0.11943884938955307, 0.0001651236816542223, 0.0001738429127726704, 0.313351035118103 ]
{ "id": 0, "code_window": [ "\n", "var nodeEnv = prodOrDev === 'production' ? 'http://www.freecodecamp.com' : 'http://localhost:3001';\n", "function updatePreview() {\n", " editorValueForIFrame = editor.getValue();\n", " goodTests = 0;\n", " var previewFrame = document.getElementById('preview');\n", " var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var failedCommentTest = false;\n", " if(editorValueForIFrame.match(/\\<\\!\\-\\-/gi) && editorValueForIFrame.match(/\\-\\-\\>/gi) == null){\n", " failedCommentTest = true;\n", " }\n", " else if(editorValueForIFrame.match(/\\<\\!\\-\\-/gi) && editorValueForIFrame.match(/\\<\\!\\-\\-/gi).length > editorValueForIFrame.match(/\\-\\-\\>/gi).length){\n", " failedCommentTest = true;\n", " }\n", " if(failedCommentTest){\n", " editor.setValue(editor.getValue()+ \"-->\");\n", " editorValueForIFrame = editorValueForIFrame + \"-->\";\n", " }\n" ], "file_path": "public/js/lib/coursewares/coursewaresHCJQFramework_0.1.9.js", "type": "add", "edit_start_line_idx": 73 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE /** * Tag-closer extension for CodeMirror. * * This extension adds an "autoCloseTags" option that can be set to * either true to get the default behavior, or an object to further * configure its behavior. * * These are supported options: * * `whenClosing` (default true) * Whether to autoclose when the '/' of a closing tag is typed. * `whenOpening` (default true) * Whether to autoclose the tag when the final '>' of an opening * tag is typed. * `dontCloseTags` (default is empty tags for HTML, none for XML) * An array of tag names that should not be autoclosed. * `indentTags` (default is block tags for HTML, none for XML) * An array of tag names that should, when opened, cause a * blank line to be added inside the tag, and the blank line and * closing line to be indented. * * See demos/closetag.html for a usage example. */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../fold/xml-fold")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../fold/xml-fold"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) { if (old != CodeMirror.Init && old) cm.removeKeyMap("autoCloseTags"); if (!val) return; var map = {name: "autoCloseTags"}; if (typeof val != "object" || val.whenClosing) map["'/'"] = function(cm) { return autoCloseSlash(cm); }; if (typeof val != "object" || val.whenOpening) map["'>'"] = function(cm) { return autoCloseGT(cm); }; cm.addKeyMap(map); }); var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]; var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"]; function autoCloseGT(cm) { if (cm.getOption("disableInput")) return CodeMirror.Pass; var ranges = cm.listSelections(), replacements = []; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var pos = ranges[i].head, tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass; var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html"; var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose); var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent); var tagName = state.tagName; if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch); var lowerTagName = tagName.toLowerCase(); // Don't process the '>' at the end of an end-tag or self-closing tag if (!tagName || tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) || tok.type == "tag" && state.type == "closeTag" || tok.string.indexOf("/") == (tok.string.length - 1) || // match something like <someTagName /> dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 || closingTagExists(cm, tagName, pos, state, true)) return CodeMirror.Pass; var indent = indentTags && indexOf(indentTags, lowerTagName) > -1; replacements[i] = {indent: indent, text: ">" + (indent ? "\n\n" : "") + "</" + tagName + ">", newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)}; } for (var i = ranges.length - 1; i >= 0; i--) { var info = replacements[i]; cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert"); var sel = cm.listSelections().slice(0); sel[i] = {head: info.newPos, anchor: info.newPos}; cm.setSelections(sel); if (info.indent) { cm.indentLine(info.newPos.line, null, true); cm.indentLine(info.newPos.line + 1, null, true); } } } function autoCloseSlash(cm) { if (cm.getOption("disableInput")) return CodeMirror.Pass; var ranges = cm.listSelections(), replacements = []; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) return CodeMirror.Pass; var pos = ranges[i].head, tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (tok.type == "string" || tok.string.charAt(0) != "<" || tok.start != pos.ch - 1) return CodeMirror.Pass; // Kludge to get around the fact that we are not in XML mode // when completing in JS/CSS snippet in htmlmixed mode. Does not // work for other XML embedded languages (there is no general // way to go from a mixed mode to its current XML state). if (inner.mode.name != "xml") { if (cm.getMode().name == "htmlmixed" && inner.mode.name == "javascript") replacements[i] = "/script>"; else if (cm.getMode().name == "htmlmixed" && inner.mode.name == "css") replacements[i] = "/style>"; else return CodeMirror.Pass; } else { if (!state.context || !state.context.tagName || closingTagExists(cm, state.context.tagName, pos, state)) return CodeMirror.Pass; replacements[i] = "/" + state.context.tagName + ">"; } } cm.replaceSelections(replacements); ranges = cm.listSelections(); for (var i = 0; i < ranges.length; i++) if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line) cm.indentLine(ranges[i].head.line); } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } // If xml-fold is loaded, we use its functionality to try and verify // whether a given tag is actually unclosed. function closingTagExists(cm, tagName, pos, state, newTag) { if (!CodeMirror.scanForClosingTag) return false; var end = Math.min(cm.lastLine() + 1, pos.line + 500); var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end); if (!nextClose || nextClose.tag != tagName) return false; var cx = state.context; // If the immediate wrapping context contains onCx instances of // the same tag, a closing tag only exists if there are at least // that many closing tags of that type following. for (var onCx = newTag ? 1 : 0; cx && cx.tagName == tagName; cx = cx.prev) ++onCx; pos = nextClose.to; for (var i = 1; i < onCx; i++) { var next = CodeMirror.scanForClosingTag(cm, pos, null, end); if (!next || next.tag != tagName) return false; pos = next.to; } return true; } });
public/js/lib/codemirror/addon/edit/closetag.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.00017682199541013688, 0.00017354992451146245, 0.00016608786245342344, 0.00017439175280742347, 0.0000028013566861773143 ]
{ "id": 0, "code_window": [ "\n", "var nodeEnv = prodOrDev === 'production' ? 'http://www.freecodecamp.com' : 'http://localhost:3001';\n", "function updatePreview() {\n", " editorValueForIFrame = editor.getValue();\n", " goodTests = 0;\n", " var previewFrame = document.getElementById('preview');\n", " var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var failedCommentTest = false;\n", " if(editorValueForIFrame.match(/\\<\\!\\-\\-/gi) && editorValueForIFrame.match(/\\-\\-\\>/gi) == null){\n", " failedCommentTest = true;\n", " }\n", " else if(editorValueForIFrame.match(/\\<\\!\\-\\-/gi) && editorValueForIFrame.match(/\\<\\!\\-\\-/gi).length > editorValueForIFrame.match(/\\-\\-\\>/gi).length){\n", " failedCommentTest = true;\n", " }\n", " if(failedCommentTest){\n", " editor.setValue(editor.getValue()+ \"-->\");\n", " editorValueForIFrame = editorValueForIFrame + \"-->\";\n", " }\n" ], "file_path": "public/js/lib/coursewares/coursewaresHCJQFramework_0.1.9.js", "type": "add", "edit_start_line_idx": 73 }
{ "ecmaFeatures": { "jsx": true }, "env": { "browser": true, "mocha": true, "node": true }, "parser": "babel-eslint", "plugins": [ "react" ], "globals": { "window": true, "$": true, "ga": true, "jQuery": true, "router": true }, "rules": { "comma-dangle": 2, "no-cond-assign": 2, "no-console": 0, "no-constant-condition": 2, "no-control-regex": 2, "no-debugger": 2, "no-dupe-keys": 2, "no-empty": 2, "no-empty-character-class": 2, "no-ex-assign": 2, "no-extra-boolean-cast": 2, "no-extra-parens": 0, "no-extra-semi": 2, "no-func-assign": 2, "no-inner-declarations": 2, "no-invalid-regexp": 2, "no-irregular-whitespace": 2, "no-negated-in-lhs": 2, "no-obj-calls": 2, "no-regex-spaces": 2, "no-reserved-keys": 0, "no-sparse-arrays": 2, "no-unreachable": 2, "use-isnan": 2, "valid-jsdoc": 2, "valid-typeof": 2, "block-scoped-var": 0, "complexity": 0, "consistent-return": 2, "curly": 2, "default-case": 1, "dot-notation": 0, "eqeqeq": 1, "guard-for-in": 1, "no-alert": 1, "no-caller": 2, "no-div-regex": 2, "no-else-return": 0, "no-empty-label": 2, "no-eq-null": 1, "no-eval": 2, "no-extend-native": 2, "no-extra-bind": 2, "no-fallthrough": 2, "no-floating-decimal": 2, "no-implied-eval": 2, "no-iterator": 2, "no-labels": 2, "no-lone-blocks": 2, "no-loop-func": 1, "no-multi-spaces": 1, "no-multi-str": 2, "no-native-reassign": 2, "no-new": 2, "no-new-func": 2, "no-new-wrappers": 2, "no-octal": 2, "no-octal-escape": 2, "no-process-env": 0, "no-proto": 2, "no-redeclare": 1, "no-return-assign": 2, "no-script-url": 2, "no-self-compare": 2, "no-sequences": 2, "no-unused-expressions": 2, "no-void": 1, "no-warning-comments": [ 1, { "terms": [ "fixme" ], "location": "start" } ], "no-with": 2, "radix": 2, "vars-on-top": 0, "wrap-iife": [2, "any"], "yoda": 0, "strict": 0, "no-catch-shadow": 2, "no-delete-var": 2, "no-label-var": 2, "no-shadow": 0, "no-shadow-restricted-names": 2, "no-undef": 2, "no-undef-init": 2, "no-undefined": 1, "no-unused-vars": 2, "no-use-before-define": 0, "handle-callback-err": 2, "no-mixed-requires": 0, "no-new-require": 2, "no-path-concat": 2, "no-process-exit": 2, "no-restricted-modules": 0, "no-sync": 0, "brace-style": [ 2, "1tbs", { "allowSingleLine": true } ], "camelcase": 1, "comma-spacing": [ 2, { "before": false, "after": true } ], "comma-style": [ 2, "last" ], "consistent-this": 0, "eol-last": 2, "func-names": 0, "func-style": 0, "key-spacing": [ 2, { "beforeColon": false, "afterColon": true } ], "max-nested-callbacks": 0, "new-cap": 0, "new-parens": 2, "no-array-constructor": 2, "no-inline-comments": 1, "no-lonely-if": 1, "no-mixed-spaces-and-tabs": 2, "no-multiple-empty-lines": [ 1, { "max": 2 } ], "no-nested-ternary": 2, "no-new-object": 2, "semi-spacing": [2, { "before": false, "after": true }], "no-spaced-func": 2, "no-ternary": 0, "no-trailing-spaces": 1, "no-underscore-dangle": 0, "one-var": 0, "operator-assignment": 0, "padded-blocks": 0, "quote-props": 0, "quotes": [ 2, "single", "avoid-escape" ], "semi": [ 2, "always" ], "sort-vars": 0, "space-after-keywords": [ 2, "always" ], "space-before-function-paren": [ 2, "never" ], "space-before-blocks": [ 2, "always" ], "space-in-brackets": 0, "space-in-parens": 0, "space-infix-ops": 2, "space-return-throw-case": 2, "space-unary-ops": [ 1, { "words": true, "nonwords": false } ], "spaced-comment": [ 2, "always", { "exceptions": ["-"] } ], "wrap-regex": 1, "max-depth": 0, "max-len": [ 1, 80, 2 ], "max-params": 0, "max-statements": 0, "no-bitwise": 1, "no-plusplus": 0, "react/display-name": 1, "react/jsx-boolean-value": 1, "react/jsx-quotes": [1, "single", "avoid-escape"], "react/jsx-no-undef": 1, "react/jsx-sort-props": 1, "react/jsx-uses-react": 1, "react/jsx-uses-vars": 1, "react/no-did-mount-set-state": 2, "react/no-did-update-set-state": 2, "react/no-multi-comp": 2, "react/prop-types": 2, "react/react-in-jsx-scope": 1, "react/self-closing-comp": 1, "react/wrap-multilines": 1 } }
.eslintrc
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.00017641883459873497, 0.00017442878743167967, 0.00017286353977397084, 0.00017446628771722317, 7.872287710597448e-7 ]
{ "id": 0, "code_window": [ "\n", "var nodeEnv = prodOrDev === 'production' ? 'http://www.freecodecamp.com' : 'http://localhost:3001';\n", "function updatePreview() {\n", " editorValueForIFrame = editor.getValue();\n", " goodTests = 0;\n", " var previewFrame = document.getElementById('preview');\n", " var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var failedCommentTest = false;\n", " if(editorValueForIFrame.match(/\\<\\!\\-\\-/gi) && editorValueForIFrame.match(/\\-\\-\\>/gi) == null){\n", " failedCommentTest = true;\n", " }\n", " else if(editorValueForIFrame.match(/\\<\\!\\-\\-/gi) && editorValueForIFrame.match(/\\<\\!\\-\\-/gi).length > editorValueForIFrame.match(/\\-\\-\\>/gi).length){\n", " failedCommentTest = true;\n", " }\n", " if(failedCommentTest){\n", " editor.setValue(editor.getValue()+ \"-->\");\n", " editorValueForIFrame = editorValueForIFrame + \"-->\";\n", " }\n" ], "file_path": "public/js/lib/coursewares/coursewaresHCJQFramework_0.1.9.js", "type": "add", "edit_start_line_idx": 73 }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // Depends on coffeelint.js from http://www.coffeelint.org/js/coffeelint.js // declare global: coffeelint (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.registerHelper("lint", "coffeescript", function(text) { var found = []; var parseError = function(err) { var loc = err.lineNumber; found.push({from: CodeMirror.Pos(loc-1, 0), to: CodeMirror.Pos(loc, 0), severity: err.level, message: err.message}); }; try { var res = coffeelint.lint(text); for(var i = 0; i < res.length; i++) { parseError(res[i]); } } catch(e) { found.push({from: CodeMirror.Pos(e.location.first_line, 0), to: CodeMirror.Pos(e.location.last_line, e.location.last_column), severity: 'error', message: e.message}); } return found; }); });
public/js/lib/codemirror/addon/lint/coffeescript-lint.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.0001778636360540986, 0.0001754324184730649, 0.00017072752234525979, 0.00017659553850535303, 0.0000025504959921818227 ]
{ "id": 1, "code_window": [ " userTests = null;\n", " $('#codeOutput').empty();\n", " var userJavaScript = myCodeMirror.getValue();\n", " userJavaScript = removeComments(userJavaScript);\n", " userJavaScript = scrapeTests(userJavaScript);\n", " // simple fix in case the user forgets to invoke their function\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var failedCommentTest = false;\n", " if(userJavaScript.match(/\\/\\*/gi) && userJavaScript.match(/\\*\\//gi) == null){\n", " failedCommentTest = true;\n", " }\n", " else if(!failedCommentTest && userJavaScript.match(/\\/\\*/gi) && userJavaScript.match(/\\/\\*/gi).length > userJavaScript.match(/\\*\\//gi).length){\n", " failedCommentTest = true;\n", " }\n" ], "file_path": "public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js", "type": "add", "edit_start_line_idx": 102 }
var widgets = []; var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("codeEditor"), { lineNumbers: true, mode: "javascript", theme: 'monokai', runnable: true, lint: true, matchBrackets: true, autoCloseBrackets: true, scrollbarStyle: 'null', lineWrapping: true, gutters: ["CodeMirror-lint-markers"], onKeyEvent: doLinting }); var editor = myCodeMirror; editor.setSize("100%", "auto"); // Hijack tab key to enter two spaces intead editor.setOption("extraKeys", { Tab: function(cm) { if (cm.somethingSelected()) { cm.indentSelection("add"); } else { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces); } }, "Shift-Tab": function(cm) { if (cm.somethingSelected()) { cm.indentSelection("subtract"); } else { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces); } }, "Ctrl-Enter": function() { bonfireExecute(); return false; } }); var attempts = 0; if (attempts) { attempts = 0; } var codeOutput = CodeMirror.fromTextArea(document.getElementById("codeOutput"), { lineNumbers: false, mode: "text", theme: 'monokai', readOnly: 'nocursor', lineWrapping: true }); codeOutput.setValue('/**\n' + ' * Your output will go here.\n' + ' * Console.log() -type statements\n' + ' * will appear in your browser\'s\n' + ' * DevTools JavaScript console.\n' + ' */'); codeOutput.setSize("100%", "100%"); var info = editor.getScrollInfo(); var after = editor.charCoords({ line: editor.getCursor().line + 1, ch: 0 }, "local").top; if (info.top + info.clientHeight < after) editor.scrollTo(null, after - info.clientHeight + 3); function doLinting() { editor.operation(function() { for (var i = 0; i < widgets.length; ++i) editor.removeLineWidget(widgets[i]); widgets.length = 0; JSHINT(editor.getValue()); for (var i = 0; i < JSHINT.errors.length; ++i) { var err = JSHINT.errors[i]; if (!err) continue; var msg = document.createElement("div"); var icon = msg.appendChild(document.createElement("span")); icon.innerHTML = "!!"; icon.className = "lint-error-icon"; msg.appendChild(document.createTextNode(err.reason)); msg.className = "lint-error"; widgets.push(editor.addLineWidget(err.line - 1, msg, { coverGutter: false, noHScroll: true })); } }); } $('#submitButton').on('click', function() { bonfireExecute(); }); function bonfireExecute() { attempts++; ga('send', 'event', 'Challenge', 'ran-code', challenge_Name); userTests = null; $('#codeOutput').empty(); var userJavaScript = myCodeMirror.getValue(); userJavaScript = removeComments(userJavaScript); userJavaScript = scrapeTests(userJavaScript); // simple fix in case the user forgets to invoke their function submit(userJavaScript, function(cls, message) { if (cls) { codeOutput.setValue(message.error); runTests('Error', null); } else { codeOutput.setValue(message.output); codeOutput.setValue(codeOutput.getValue().replace(/\\\"/gi,'')); message.input = removeLogs(message.input); runTests(null, message); } }); } var userTests; var testSalt = Math.random(); var scrapeTests = function(userJavaScript) { // insert tests from mongo for (var i = 0; i < tests.length; i++) { userJavaScript += '\n' + tests[i]; } var counter = 0; var regex = new RegExp( /(expect(\s+)?\(.*\;)|(assert(\s+)?\(.*\;)|(assert\.\w.*\;)|(.*\.should\..*\;)/ ); var match = regex.exec(userJavaScript); while (match != null) { var replacement = '//' + counter + testSalt; userJavaScript = userJavaScript.substring(0, match.index) + replacement + userJavaScript.substring(match.index + match[0].length); if (!userTests) { userTests = []; } userTests.push({ "text": match[0], "line": counter, "err": null }); counter++; match = regex.exec(userJavaScript); } return userJavaScript; }; function removeComments(userJavaScript) { var regex = new RegExp(/(\/\*[^(\*\/)]*\*\/)|\/\/[^\n]*/g); return userJavaScript.replace(regex, ''); } function removeLogs(userJavaScript) { return userJavaScript.replace(/(console\.[\w]+\s*\(.*\;)/g, ''); } var pushed = false; var createTestDisplay = function() { if (pushed) { userTests.pop(); } for (var i = 0; i < userTests.length; i++) { var test = userTests[i]; var testDoc = document.createElement("div"); if (test.err != null) { console.log('Should be displaying bad tests'); $(testDoc) .html( "<div class='row'><div class='col-xs-2 text-center'><i class='ion-close-circled big-error-icon'></i></div><div class='col-xs-10 test-output wrappable test-vertical-center grayed-out-test-output'>" + test.text + "</div><div class='col-xs-10 test-output wrappable'>" + test.err + "</div></div><div class='ten-pixel-break'/>") .appendTo($('#testSuite')); } else { $(testDoc) .html( "<div class='row'><div class='col-xs-2 text-center'><i class='ion-checkmark-circled big-success-icon'></i></div><div class='col-xs-10 test-output test-vertical-center wrappable grayed-out-test-output'>" + test.text + "</div></div><div class='ten-pixel-break'/>") .appendTo($('#testSuite')); } }; }; var expect = chai.expect; var assert = chai.assert; var should = chai.should(); var reassembleTest = function(test, data) { var lineNum = test.line; var regexp = new RegExp("\/\/" + lineNum + testSalt); return data.input.replace(regexp, test.text); }; var runTests = function(err, data) { var allTestsPassed = true; pushed = false; $('#testSuite').children().remove(); if (err && userTests.length > 0) { userTests = [{ text: "Program Execution Failure", err: "No user tests were run." }]; createTestDisplay(); } //Add blocks to test exploits here! else if(editorValue.match(/if\s\(null\)\sconsole\.log\(1\);/gi)){ allTestsPassed = false; userTests = [{ text: "Program Execution Failure", err: "Invalid if (null) console.log(1); detected" }]; createTestDisplay(); } else if (userTests) { userTests.push(false); pushed = true; userTests.forEach(function(chaiTestFromJSON, indexOfTestArray, __testArray) { try { if (chaiTestFromJSON) { var output = eval(reassembleTest(chaiTestFromJSON, data)); } } catch (error) { allTestsPassed = false; __testArray[indexOfTestArray].err = error.message; } finally { if (!chaiTestFromJSON) { createTestDisplay(); } } }); if (allTestsPassed) { allTestsPassed = false; showCompletion(); } } }; function showCompletion() { var time = Math.floor(Date.now()) - started; ga('send', 'event', 'Challenge', 'solved', challenge_Name + ', Time: ' + time + ', Attempts: ' + attempts); var bonfireSolution = myCodeMirror.getValue(); var didCompleteWith = $('#completed-with').val() || null; $.post( '/completed-bonfire/', { challengeInfo: { challengeId: challenge_Id, challengeName: challenge_Name, completedWith: didCompleteWith, challengeType: challengeType, solution: bonfireSolution } }, function(res) { if (res) { $('#complete-courseware-dialog').modal('show'); $('#complete-courseware-dialog').keydown(function(e) { if (e.ctrlKey && e.keyCode == 13) { $('#next-courseware-button').click(); } }); } } ); } /* Local Storage Update System By Andrew Cay(Resto) codeStorage: singleton object that contains properties and methods related to dealing with the localStorage system. The keys work off of the variable challenge_name to make unique identifiers per bonfire Two extra functionalities: Added anonymous version checking system incase of future updates to the system Added keyup listener to editor(myCodeMirror) so the last update has been saved to storage */ var codeStorage = { version: 0.01, keyVersion:"saveVersion", keyValue: null,//where the value of the editor is saved updateWait: 2000,// 2 seconds updateTimeoutId: null, eventArray: []//for firing saves }; // Returns true if the editor code was saved since last key press (use this if you want to make a "saved" notification somewhere") codeStorage.hasSaved = function(){ return ( updateTimeoutId === null ); }; codeStorage.onSave = function(func){ codeStorage.eventArray.push(func); }; codeStorage.setSaveKey = function(key){ codeStorage.keyValue = key + 'Val'; }; codeStorage.getEditorValue = function(){ return ('' + localStorage.getItem(codeStorage.keyValue)); }; codeStorage.isAlive = function() { var val = this.getEditorValue() return val !== 'null' && val !== 'undefined' && (val && val.length > 0); } codeStorage.updateStorage = function(){ if(typeof(Storage) !== undefined) { var value = editor.getValue(); localStorage.setItem(codeStorage.keyValue, value); } else { var debugging = false; if( debugging ){ console.log('no web storage'); } } codeStorage.updateTimeoutId = null; codeStorage.eventArray.forEach(function(func){ func(); }); }; //Update Version (function(){ var savedVersion = localStorage.getItem('saveVersion'); if( savedVersion === null ){ localStorage.setItem(codeStorage.keyVersion, codeStorage.version);//just write current version }else{ if( savedVersion !== codeStorage.version ){ //Update version } } })(); ///Set everything up one page /// Update local save when editor has changed codeStorage.setSaveKey(challenge_Name); editor.on('keyup', function(){ window.clearTimeout(codeStorage.updateTimeoutId); codeStorage.updateTimeoutId = window.setTimeout(codeStorage.updateStorage, codeStorage.updateWait); }); var editorValue; var challengeSeed = challengeSeed || null; var tests = tests || []; var allSeeds = ''; (function() { challengeSeed.forEach(function(elem) { allSeeds += elem + '\n'; }); })(); editorValue = (codeStorage.isAlive())? codeStorage.getEditorValue() : allSeeds; myCodeMirror.setValue(editorValue); var resetEditor = function resetEditor() { editor.setValue(allSeeds); codeStorage.updateStorage(); };
public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.9981932044029236, 0.21099266409873962, 0.00016397018043790013, 0.00017635620315559208, 0.40067529678344727 ]
{ "id": 1, "code_window": [ " userTests = null;\n", " $('#codeOutput').empty();\n", " var userJavaScript = myCodeMirror.getValue();\n", " userJavaScript = removeComments(userJavaScript);\n", " userJavaScript = scrapeTests(userJavaScript);\n", " // simple fix in case the user forgets to invoke their function\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var failedCommentTest = false;\n", " if(userJavaScript.match(/\\/\\*/gi) && userJavaScript.match(/\\*\\//gi) == null){\n", " failedCommentTest = true;\n", " }\n", " else if(!failedCommentTest && userJavaScript.match(/\\/\\*/gi) && userJavaScript.match(/\\/\\*/gi).length > userJavaScript.match(/\\*\\//gi).length){\n", " failedCommentTest = true;\n", " }\n" ], "file_path": "public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js", "type": "add", "edit_start_line_idx": 102 }
// Tables .table-row-variant(@state; @background) { // Exact selectors below required to override `.table-striped` and prevent // inheritance to nested tables. .table > thead > tr, .table > tbody > tr, .table > tfoot > tr { > td.@{state}, > th.@{state}, &.@{state} > td, &.@{state} > th { background-color: @background; } } // Hover states for `.table-hover` // Note: this is not available for cells or rows within `thead` or `tfoot`. .table-hover > tbody > tr { > td.@{state}:hover, > th.@{state}:hover, &.@{state}:hover > td, &:hover > .@{state}, &.@{state}:hover > th { background-color: darken(@background, 5%); } } }
public/css/lib/bootstrap/mixins/table-row.less
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.00018190812261309475, 0.0001793608971638605, 0.00017754509462974966, 0.00017862945969682187, 0.0000018547683566794149 ]
{ "id": 1, "code_window": [ " userTests = null;\n", " $('#codeOutput').empty();\n", " var userJavaScript = myCodeMirror.getValue();\n", " userJavaScript = removeComments(userJavaScript);\n", " userJavaScript = scrapeTests(userJavaScript);\n", " // simple fix in case the user forgets to invoke their function\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var failedCommentTest = false;\n", " if(userJavaScript.match(/\\/\\*/gi) && userJavaScript.match(/\\*\\//gi) == null){\n", " failedCommentTest = true;\n", " }\n", " else if(!failedCommentTest && userJavaScript.match(/\\/\\*/gi) && userJavaScript.match(/\\/\\*/gi).length > userJavaScript.match(/\\*\\//gi).length){\n", " failedCommentTest = true;\n", " }\n" ], "file_path": "public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js", "type": "add", "edit_start_line_idx": 102 }
import Rx from 'rx'; import React from 'react'; import Fetchr from 'fetchr'; import debugFactory from 'debug'; import { Router } from 'react-router'; import { history } from 'react-router/lib/BrowserHistory'; import { hydrate } from 'thundercats'; import { Render } from 'thundercats-react'; import { app$ } from '../common/app'; const debug = debugFactory('fcc:client'); const DOMContianer = document.getElementById('fcc'); const catState = window.__fcc__.data || {}; const services = new Fetchr({ xhrPath: '/services' }); Rx.config.longStackSupport = !!debug.enabled; // returns an observable app$(history) .flatMap( ({ AppCat }) => { const appCat = AppCat(null, services); return hydrate(appCat, catState) .map(() => appCat); }, ({ initialState }, appCat) => ({ initialState, appCat }) ) .flatMap(({ initialState, appCat }) => { return Render( appCat, React.createElement(Router, initialState), DOMContianer ); }) .subscribe( () => { debug('react rendered'); }, err => { debug('an error has occured', err.stack); }, () => { debug('react closed subscription'); } );
client/index.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.00018026333418674767, 0.0001765216438798234, 0.00017267015937250108, 0.00017645971092861146, 0.0000026815334877028363 ]
{ "id": 1, "code_window": [ " userTests = null;\n", " $('#codeOutput').empty();\n", " var userJavaScript = myCodeMirror.getValue();\n", " userJavaScript = removeComments(userJavaScript);\n", " userJavaScript = scrapeTests(userJavaScript);\n", " // simple fix in case the user forgets to invoke their function\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var failedCommentTest = false;\n", " if(userJavaScript.match(/\\/\\*/gi) && userJavaScript.match(/\\*\\//gi) == null){\n", " failedCommentTest = true;\n", " }\n", " else if(!failedCommentTest && userJavaScript.match(/\\/\\*/gi) && userJavaScript.match(/\\/\\*/gi).length > userJavaScript.match(/\\*\\//gi).length){\n", " failedCommentTest = true;\n", " }\n" ], "file_path": "public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js", "type": "add", "edit_start_line_idx": 102 }
(function() { // A minilanguage for instantiating linked CodeMirror instances and Docs function instantiateSpec(spec, place, opts) { var names = {}, pos = 0, l = spec.length, editors = []; while (spec) { var m = spec.match(/^(\w+)(\*?)(?:='([^\']*)'|<(~?)(\w+)(?:\/(\d+)-(\d+))?)\s*/); var name = m[1], isDoc = m[2], cur; if (m[3]) { cur = isDoc ? CodeMirror.Doc(m[3]) : CodeMirror(place, clone(opts, {value: m[3]})); } else { var other = m[5]; if (!names.hasOwnProperty(other)) { names[other] = editors.length; editors.push(CodeMirror(place, opts)); } var doc = editors[names[other]].linkedDoc({ sharedHist: !m[4], from: m[6] ? Number(m[6]) : null, to: m[7] ? Number(m[7]) : null }); cur = isDoc ? doc : CodeMirror(place, clone(opts, {value: doc})); } names[name] = editors.length; editors.push(cur); spec = spec.slice(m[0].length); } return editors; } function clone(obj, props) { if (!obj) return; clone.prototype = obj; var inst = new clone(); if (props) for (var n in props) if (props.hasOwnProperty(n)) inst[n] = props[n]; return inst; } function eqAll(val) { var end = arguments.length, msg = null; if (typeof arguments[end-1] == "string") msg = arguments[--end]; if (i == end) throw new Error("No editors provided to eqAll"); for (var i = 1; i < end; ++i) eq(arguments[i].getValue(), val, msg) } function testDoc(name, spec, run, opts, expectFail) { if (!opts) opts = {}; return test("doc_" + name, function() { var place = document.getElementById("testground"); var editors = instantiateSpec(spec, place, opts); var successful = false; try { run.apply(null, editors); successful = true; } finally { if (!successful || verbose) { place.style.visibility = "visible"; } else { for (var i = 0; i < editors.length; ++i) if (editors[i] instanceof CodeMirror) place.removeChild(editors[i].getWrapperElement()); } } }, expectFail); } var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); function testBasic(a, b) { eqAll("x", a, b); a.setValue("hey"); eqAll("hey", a, b); b.setValue("wow"); eqAll("wow", a, b); a.replaceRange("u\nv\nw", Pos(0, 3)); b.replaceRange("i", Pos(0, 4)); b.replaceRange("j", Pos(2, 1)); eqAll("wowui\nv\nwj", a, b); } testDoc("basic", "A='x' B<A", testBasic); testDoc("basicSeparate", "A='x' B<~A", testBasic); testDoc("sharedHist", "A='ab\ncd\nef' B<A", function(a, b) { a.replaceRange("x", Pos(0)); b.replaceRange("y", Pos(1)); a.replaceRange("z", Pos(2)); eqAll("abx\ncdy\nefz", a, b); a.undo(); a.undo(); eqAll("abx\ncd\nef", a, b); a.redo(); eqAll("abx\ncdy\nef", a, b); b.redo(); eqAll("abx\ncdy\nefz", a, b); a.undo(); b.undo(); a.undo(); a.undo(); eqAll("ab\ncd\nef", a, b); }, null, ie_lt8); testDoc("undoIntact", "A='ab\ncd\nef' B<~A", function(a, b) { a.replaceRange("x", Pos(0)); b.replaceRange("y", Pos(1)); a.replaceRange("z", Pos(2)); a.replaceRange("q", Pos(0)); eqAll("abxq\ncdy\nefz", a, b); a.undo(); a.undo(); eqAll("abx\ncdy\nef", a, b); b.undo(); eqAll("abx\ncd\nef", a, b); a.redo(); eqAll("abx\ncd\nefz", a, b); a.redo(); eqAll("abxq\ncd\nefz", a, b); a.undo(); a.undo(); a.undo(); a.undo(); eqAll("ab\ncd\nef", a, b); b.redo(); eqAll("ab\ncdy\nef", a, b); }); testDoc("undoConflict", "A='ab\ncd\nef' B<~A", function(a, b) { a.replaceRange("x", Pos(0)); a.replaceRange("z", Pos(2)); // This should clear the first undo event in a, but not the second b.replaceRange("y", Pos(0)); a.undo(); a.undo(); eqAll("abxy\ncd\nef", a, b); a.replaceRange("u", Pos(2)); a.replaceRange("v", Pos(0)); // This should clear both events in a b.replaceRange("w", Pos(0)); a.undo(); a.undo(); eqAll("abxyvw\ncd\nefu", a, b); }); testDoc("doubleRebase", "A='ab\ncd\nef\ng' B<~A C<B", function(a, b, c) { c.replaceRange("u", Pos(3)); a.replaceRange("", Pos(0, 0), Pos(1, 0)); c.undo(); eqAll("cd\nef\ng", a, b, c); }); testDoc("undoUpdate", "A='ab\ncd\nef' B<~A", function(a, b) { a.replaceRange("x", Pos(2)); b.replaceRange("u\nv\nw\n", Pos(0, 0)); a.undo(); eqAll("u\nv\nw\nab\ncd\nef", a, b); a.redo(); eqAll("u\nv\nw\nab\ncd\nefx", a, b); a.undo(); eqAll("u\nv\nw\nab\ncd\nef", a, b); b.undo(); a.redo(); eqAll("ab\ncd\nefx", a, b); a.undo(); eqAll("ab\ncd\nef", a, b); }); testDoc("undoKeepRanges", "A='abcdefg' B<A", function(a, b) { var m = a.markText(Pos(0, 1), Pos(0, 3), {className: "foo"}); b.replaceRange("x", Pos(0, 0)); eqPos(m.find().from, Pos(0, 2)); b.replaceRange("yzzy", Pos(0, 1), Pos(0)); eq(m.find(), null); b.undo(); eqPos(m.find().from, Pos(0, 2)); b.undo(); eqPos(m.find().from, Pos(0, 1)); }); testDoc("longChain", "A='uv' B<A C<B D<C", function(a, b, c, d) { a.replaceSelection("X"); eqAll("Xuv", a, b, c, d); d.replaceRange("Y", Pos(0)); eqAll("XuvY", a, b, c, d); }); testDoc("broadCast", "B<A C<A D<A E<A", function(a, b, c, d, e) { b.setValue("uu"); eqAll("uu", a, b, c, d, e); a.replaceRange("v", Pos(0, 1)); eqAll("uvu", a, b, c, d, e); }); // A and B share a history, C and D share a separate one testDoc("islands", "A='x\ny\nz' B<A C<~A D<C", function(a, b, c, d) { a.replaceRange("u", Pos(0)); d.replaceRange("v", Pos(2)); b.undo(); eqAll("x\ny\nzv", a, b, c, d); c.undo(); eqAll("x\ny\nz", a, b, c, d); a.redo(); eqAll("xu\ny\nz", a, b, c, d); d.redo(); eqAll("xu\ny\nzv", a, b, c, d); }); testDoc("unlink", "B<A C<A D<B", function(a, b, c, d) { a.setValue("hi"); b.unlinkDoc(a); d.setValue("aye"); eqAll("hi", a, c); eqAll("aye", b, d); a.setValue("oo"); eqAll("oo", a, c); eqAll("aye", b, d); }); testDoc("bareDoc", "A*='foo' B*<A C<B", function(a, b, c) { is(a instanceof CodeMirror.Doc); is(b instanceof CodeMirror.Doc); is(c instanceof CodeMirror); eqAll("foo", a, b, c); a.replaceRange("hey", Pos(0, 0), Pos(0)); c.replaceRange("!", Pos(0)); eqAll("hey!", a, b, c); b.unlinkDoc(a); b.setValue("x"); eqAll("x", b, c); eqAll("hey!", a); }); testDoc("swapDoc", "A='a' B*='b' C<A", function(a, b, c) { var d = a.swapDoc(b); d.setValue("x"); eqAll("x", c, d); eqAll("b", a, b); }); testDoc("docKeepsScroll", "A='x' B*='y'", function(a, b) { addDoc(a, 200, 200); a.scrollIntoView(Pos(199, 200)); var c = a.swapDoc(b); a.swapDoc(c); var pos = a.getScrollInfo(); is(pos.left > 0, "not at left"); is(pos.top > 0, "not at top"); }); testDoc("copyDoc", "A='u'", function(a) { var copy = a.getDoc().copy(true); a.setValue("foo"); copy.setValue("bar"); var old = a.swapDoc(copy); eq(a.getValue(), "bar"); a.undo(); eq(a.getValue(), "u"); a.swapDoc(old); eq(a.getValue(), "foo"); eq(old.historySize().undo, 1); eq(old.copy(false).historySize().undo, 0); }); testDoc("docKeepsMode", "A='1+1'", function(a) { var other = CodeMirror.Doc("hi", "text/x-markdown"); a.setOption("mode", "text/javascript"); var old = a.swapDoc(other); eq(a.getOption("mode"), "text/x-markdown"); eq(a.getMode().name, "markdown"); a.swapDoc(old); eq(a.getOption("mode"), "text/javascript"); eq(a.getMode().name, "javascript"); }); testDoc("subview", "A='1\n2\n3\n4\n5' B<~A/1-3", function(a, b) { eq(b.getValue(), "2\n3"); eq(b.firstLine(), 1); b.setCursor(Pos(4)); eqPos(b.getCursor(), Pos(2, 1)); a.replaceRange("-1\n0\n", Pos(0, 0)); eq(b.firstLine(), 3); eqPos(b.getCursor(), Pos(4, 1)); a.undo(); eqPos(b.getCursor(), Pos(2, 1)); b.replaceRange("oyoy\n", Pos(2, 0)); eq(a.getValue(), "1\n2\noyoy\n3\n4\n5"); b.undo(); eq(a.getValue(), "1\n2\n3\n4\n5"); }); testDoc("subviewEditOnBoundary", "A='11\n22\n33\n44\n55' B<~A/1-4", function(a, b) { a.replaceRange("x\nyy\nz", Pos(0, 1), Pos(2, 1)); eq(b.firstLine(), 2); eq(b.lineCount(), 2); eq(b.getValue(), "z3\n44"); a.replaceRange("q\nrr\ns", Pos(3, 1), Pos(4, 1)); eq(b.firstLine(), 2); eq(b.getValue(), "z3\n4q"); eq(a.getValue(), "1x\nyy\nz3\n4q\nrr\ns5"); a.execCommand("selectAll"); a.replaceSelection("!"); eqAll("!", a, b); }); testDoc("sharedMarker", "A='ab\ncd\nef\ngh' B<A C<~A/1-2", function(a, b, c) { var mark = b.markText(Pos(0, 1), Pos(3, 1), {className: "cm-searching", shared: true}); var found = a.findMarksAt(Pos(0, 2)); eq(found.length, 1); eq(found[0], mark); eq(c.findMarksAt(Pos(1, 1)).length, 1); eqPos(mark.find().from, Pos(0, 1)); eqPos(mark.find().to, Pos(3, 1)); b.replaceRange("x\ny\n", Pos(0, 0)); eqPos(mark.find().from, Pos(2, 1)); eqPos(mark.find().to, Pos(5, 1)); var cleared = 0; CodeMirror.on(mark, "clear", function() {++cleared;}); b.operation(function(){mark.clear();}); eq(a.findMarksAt(Pos(3, 1)).length, 0); eq(b.findMarksAt(Pos(3, 1)).length, 0); eq(c.findMarksAt(Pos(3, 1)).length, 0); eq(mark.find(), null); eq(cleared, 1); }); testDoc("sharedMarkerCopy", "A='abcde'", function(a) { var shared = a.markText(Pos(0, 1), Pos(0, 3), {shared: true}); var b = a.linkedDoc(); var found = b.findMarksAt(Pos(0, 2)); eq(found.length, 1); eq(found[0], shared); shared.clear(); eq(b.findMarksAt(Pos(0, 2)), 0); }); testDoc("sharedMarkerDetach", "A='abcde' B<A C<B", function(a, b, c) { var shared = a.markText(Pos(0, 1), Pos(0, 3), {shared: true}); a.unlinkDoc(b); var inB = b.findMarksAt(Pos(0, 2)); eq(inB.length, 1); is(inB[0] != shared); var inC = c.findMarksAt(Pos(0, 2)); eq(inC.length, 1); is(inC[0] != shared); inC[0].clear(); is(shared.find()); }); testDoc("sharedBookmark", "A='ab\ncd\nef\ngh' B<A C<~A/1-2", function(a, b, c) { var mark = b.setBookmark(Pos(1, 1), {shared: true}); var found = a.findMarksAt(Pos(1, 1)); eq(found.length, 1); eq(found[0], mark); eq(c.findMarksAt(Pos(1, 1)).length, 1); eqPos(mark.find(), Pos(1, 1)); b.replaceRange("x\ny\n", Pos(0, 0)); eqPos(mark.find(), Pos(3, 1)); var cleared = 0; CodeMirror.on(mark, "clear", function() {++cleared;}); b.operation(function() {mark.clear();}); eq(a.findMarks(Pos(0, 0), Pos(5)).length, 0); eq(b.findMarks(Pos(0, 0), Pos(5)).length, 0); eq(c.findMarks(Pos(0, 0), Pos(5)).length, 0); eq(mark.find(), null); eq(cleared, 1); }); testDoc("undoInSubview", "A='line 0\nline 1\nline 2\nline 3\nline 4' B<A/1-4", function(a, b) { b.replaceRange("x", Pos(2, 0)); a.undo(); eq(a.getValue(), "line 0\nline 1\nline 2\nline 3\nline 4"); eq(b.getValue(), "line 1\nline 2\nline 3"); }); })();
public/js/lib/codemirror/test/doc_test.js
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.00018139751045964658, 0.00017611632938496768, 0.00016327590856235474, 0.00017623783787712455, 0.0000032935554372670595 ]
{ "id": 2, "code_window": [ " userJavaScript = scrapeTests(userJavaScript);\n", " // simple fix in case the user forgets to invoke their function\n", "\n", " submit(userJavaScript, function(cls, message) {\n", " if (cls) {\n", " codeOutput.setValue(message.error);\n", " runTests('Error', null);\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if(failedCommentTest){\n", " myCodeMirror.setValue(myCodeMirror.getValue() + \"*/\");\n", " console.log('Caught Unfinished Comment');\n", " codeOutput.setValue(\"Unfinished mulit-line comment\");\n", " failedCommentTest = false;\n", " }\n", " else if (cls) {\n" ], "file_path": "public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js", "type": "replace", "edit_start_line_idx": 107 }
var widgets = []; var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("codeEditor"), { lineNumbers: true, mode: "javascript", theme: 'monokai', runnable: true, lint: true, matchBrackets: true, autoCloseBrackets: true, scrollbarStyle: 'null', lineWrapping: true, gutters: ["CodeMirror-lint-markers"], onKeyEvent: doLinting }); var editor = myCodeMirror; editor.setSize("100%", "auto"); // Hijack tab key to enter two spaces intead editor.setOption("extraKeys", { Tab: function(cm) { if (cm.somethingSelected()) { cm.indentSelection("add"); } else { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces); } }, "Shift-Tab": function(cm) { if (cm.somethingSelected()) { cm.indentSelection("subtract"); } else { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces); } }, "Ctrl-Enter": function() { bonfireExecute(); return false; } }); var attempts = 0; if (attempts) { attempts = 0; } var codeOutput = CodeMirror.fromTextArea(document.getElementById("codeOutput"), { lineNumbers: false, mode: "text", theme: 'monokai', readOnly: 'nocursor', lineWrapping: true }); codeOutput.setValue('/**\n' + ' * Your output will go here.\n' + ' * Console.log() -type statements\n' + ' * will appear in your browser\'s\n' + ' * DevTools JavaScript console.\n' + ' */'); codeOutput.setSize("100%", "100%"); var info = editor.getScrollInfo(); var after = editor.charCoords({ line: editor.getCursor().line + 1, ch: 0 }, "local").top; if (info.top + info.clientHeight < after) editor.scrollTo(null, after - info.clientHeight + 3); function doLinting() { editor.operation(function() { for (var i = 0; i < widgets.length; ++i) editor.removeLineWidget(widgets[i]); widgets.length = 0; JSHINT(editor.getValue()); for (var i = 0; i < JSHINT.errors.length; ++i) { var err = JSHINT.errors[i]; if (!err) continue; var msg = document.createElement("div"); var icon = msg.appendChild(document.createElement("span")); icon.innerHTML = "!!"; icon.className = "lint-error-icon"; msg.appendChild(document.createTextNode(err.reason)); msg.className = "lint-error"; widgets.push(editor.addLineWidget(err.line - 1, msg, { coverGutter: false, noHScroll: true })); } }); } $('#submitButton').on('click', function() { bonfireExecute(); }); function bonfireExecute() { attempts++; ga('send', 'event', 'Challenge', 'ran-code', challenge_Name); userTests = null; $('#codeOutput').empty(); var userJavaScript = myCodeMirror.getValue(); userJavaScript = removeComments(userJavaScript); userJavaScript = scrapeTests(userJavaScript); // simple fix in case the user forgets to invoke their function submit(userJavaScript, function(cls, message) { if (cls) { codeOutput.setValue(message.error); runTests('Error', null); } else { codeOutput.setValue(message.output); codeOutput.setValue(codeOutput.getValue().replace(/\\\"/gi,'')); message.input = removeLogs(message.input); runTests(null, message); } }); } var userTests; var testSalt = Math.random(); var scrapeTests = function(userJavaScript) { // insert tests from mongo for (var i = 0; i < tests.length; i++) { userJavaScript += '\n' + tests[i]; } var counter = 0; var regex = new RegExp( /(expect(\s+)?\(.*\;)|(assert(\s+)?\(.*\;)|(assert\.\w.*\;)|(.*\.should\..*\;)/ ); var match = regex.exec(userJavaScript); while (match != null) { var replacement = '//' + counter + testSalt; userJavaScript = userJavaScript.substring(0, match.index) + replacement + userJavaScript.substring(match.index + match[0].length); if (!userTests) { userTests = []; } userTests.push({ "text": match[0], "line": counter, "err": null }); counter++; match = regex.exec(userJavaScript); } return userJavaScript; }; function removeComments(userJavaScript) { var regex = new RegExp(/(\/\*[^(\*\/)]*\*\/)|\/\/[^\n]*/g); return userJavaScript.replace(regex, ''); } function removeLogs(userJavaScript) { return userJavaScript.replace(/(console\.[\w]+\s*\(.*\;)/g, ''); } var pushed = false; var createTestDisplay = function() { if (pushed) { userTests.pop(); } for (var i = 0; i < userTests.length; i++) { var test = userTests[i]; var testDoc = document.createElement("div"); if (test.err != null) { console.log('Should be displaying bad tests'); $(testDoc) .html( "<div class='row'><div class='col-xs-2 text-center'><i class='ion-close-circled big-error-icon'></i></div><div class='col-xs-10 test-output wrappable test-vertical-center grayed-out-test-output'>" + test.text + "</div><div class='col-xs-10 test-output wrappable'>" + test.err + "</div></div><div class='ten-pixel-break'/>") .appendTo($('#testSuite')); } else { $(testDoc) .html( "<div class='row'><div class='col-xs-2 text-center'><i class='ion-checkmark-circled big-success-icon'></i></div><div class='col-xs-10 test-output test-vertical-center wrappable grayed-out-test-output'>" + test.text + "</div></div><div class='ten-pixel-break'/>") .appendTo($('#testSuite')); } }; }; var expect = chai.expect; var assert = chai.assert; var should = chai.should(); var reassembleTest = function(test, data) { var lineNum = test.line; var regexp = new RegExp("\/\/" + lineNum + testSalt); return data.input.replace(regexp, test.text); }; var runTests = function(err, data) { var allTestsPassed = true; pushed = false; $('#testSuite').children().remove(); if (err && userTests.length > 0) { userTests = [{ text: "Program Execution Failure", err: "No user tests were run." }]; createTestDisplay(); } //Add blocks to test exploits here! else if(editorValue.match(/if\s\(null\)\sconsole\.log\(1\);/gi)){ allTestsPassed = false; userTests = [{ text: "Program Execution Failure", err: "Invalid if (null) console.log(1); detected" }]; createTestDisplay(); } else if (userTests) { userTests.push(false); pushed = true; userTests.forEach(function(chaiTestFromJSON, indexOfTestArray, __testArray) { try { if (chaiTestFromJSON) { var output = eval(reassembleTest(chaiTestFromJSON, data)); } } catch (error) { allTestsPassed = false; __testArray[indexOfTestArray].err = error.message; } finally { if (!chaiTestFromJSON) { createTestDisplay(); } } }); if (allTestsPassed) { allTestsPassed = false; showCompletion(); } } }; function showCompletion() { var time = Math.floor(Date.now()) - started; ga('send', 'event', 'Challenge', 'solved', challenge_Name + ', Time: ' + time + ', Attempts: ' + attempts); var bonfireSolution = myCodeMirror.getValue(); var didCompleteWith = $('#completed-with').val() || null; $.post( '/completed-bonfire/', { challengeInfo: { challengeId: challenge_Id, challengeName: challenge_Name, completedWith: didCompleteWith, challengeType: challengeType, solution: bonfireSolution } }, function(res) { if (res) { $('#complete-courseware-dialog').modal('show'); $('#complete-courseware-dialog').keydown(function(e) { if (e.ctrlKey && e.keyCode == 13) { $('#next-courseware-button').click(); } }); } } ); } /* Local Storage Update System By Andrew Cay(Resto) codeStorage: singleton object that contains properties and methods related to dealing with the localStorage system. The keys work off of the variable challenge_name to make unique identifiers per bonfire Two extra functionalities: Added anonymous version checking system incase of future updates to the system Added keyup listener to editor(myCodeMirror) so the last update has been saved to storage */ var codeStorage = { version: 0.01, keyVersion:"saveVersion", keyValue: null,//where the value of the editor is saved updateWait: 2000,// 2 seconds updateTimeoutId: null, eventArray: []//for firing saves }; // Returns true if the editor code was saved since last key press (use this if you want to make a "saved" notification somewhere") codeStorage.hasSaved = function(){ return ( updateTimeoutId === null ); }; codeStorage.onSave = function(func){ codeStorage.eventArray.push(func); }; codeStorage.setSaveKey = function(key){ codeStorage.keyValue = key + 'Val'; }; codeStorage.getEditorValue = function(){ return ('' + localStorage.getItem(codeStorage.keyValue)); }; codeStorage.isAlive = function() { var val = this.getEditorValue() return val !== 'null' && val !== 'undefined' && (val && val.length > 0); } codeStorage.updateStorage = function(){ if(typeof(Storage) !== undefined) { var value = editor.getValue(); localStorage.setItem(codeStorage.keyValue, value); } else { var debugging = false; if( debugging ){ console.log('no web storage'); } } codeStorage.updateTimeoutId = null; codeStorage.eventArray.forEach(function(func){ func(); }); }; //Update Version (function(){ var savedVersion = localStorage.getItem('saveVersion'); if( savedVersion === null ){ localStorage.setItem(codeStorage.keyVersion, codeStorage.version);//just write current version }else{ if( savedVersion !== codeStorage.version ){ //Update version } } })(); ///Set everything up one page /// Update local save when editor has changed codeStorage.setSaveKey(challenge_Name); editor.on('keyup', function(){ window.clearTimeout(codeStorage.updateTimeoutId); codeStorage.updateTimeoutId = window.setTimeout(codeStorage.updateStorage, codeStorage.updateWait); }); var editorValue; var challengeSeed = challengeSeed || null; var tests = tests || []; var allSeeds = ''; (function() { challengeSeed.forEach(function(elem) { allSeeds += elem + '\n'; }); })(); editorValue = (codeStorage.isAlive())? codeStorage.getEditorValue() : allSeeds; myCodeMirror.setValue(editorValue); var resetEditor = function resetEditor() { editor.setValue(allSeeds); codeStorage.updateStorage(); };
public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.9975693821907043, 0.02756001427769661, 0.00016528468404430896, 0.000174014363437891, 0.15950332581996918 ]
{ "id": 2, "code_window": [ " userJavaScript = scrapeTests(userJavaScript);\n", " // simple fix in case the user forgets to invoke their function\n", "\n", " submit(userJavaScript, function(cls, message) {\n", " if (cls) {\n", " codeOutput.setValue(message.error);\n", " runTests('Error', null);\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if(failedCommentTest){\n", " myCodeMirror.setValue(myCodeMirror.getValue() + \"*/\");\n", " console.log('Caught Unfinished Comment');\n", " codeOutput.setValue(\"Unfinished mulit-line comment\");\n", " failedCommentTest = false;\n", " }\n", " else if (cls) {\n" ], "file_path": "public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js", "type": "replace", "edit_start_line_idx": 107 }
<!doctype html> <title>CodeMirror: SCSS mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="css.js"></script> <style>.CodeMirror {background: #f8f8f8;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">SCSS</a> </ul> </div> <article> <h2>SCSS mode</h2> <form><textarea id="code" name="code"> /* Some example SCSS */ @import "compass/css3"; $variable: #333; $blue: #3bbfce; $margin: 16px; .content-navigation { #nested { background-color: black; } border-color: $blue; color: darken($blue, 9%); } .border { padding: $margin / 2; margin: $margin / 2; border-color: $blue; } @mixin table-base { th { text-align: center; font-weight: bold; } td, th {padding: 2px} } table.hl { margin: 2em 0; td.ln { text-align: right; } } li { font: { family: serif; weight: bold; size: 1.2em; } } @mixin left($dist) { float: left; margin-left: $dist; } #data { @include left(10px); @include table-base; } .source { @include flow-into(target); border: 10px solid green; margin: 20px; width: 200px; } .new-container { @include flow-from(target); border: 10px solid red; margin: 20px; width: 200px; } body { margin: 0; padding: 3em 6em; font-family: tahoma, arial, sans-serif; color: #000; } @mixin yellow() { background: yellow; } .big { font-size: 14px; } .nested { @include border-radius(3px); @extend .big; p { background: whitesmoke; a { color: red; } } } #navigation a { font-weight: bold; text-decoration: none !important; } h1 { font-size: 2.5em; } h2 { font-size: 1.7em; } h1:before, h2:before { content: "::"; } code { font-family: courier, monospace; font-size: 80%; color: #418A8A; } </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-scss" }); </script> <p>The SCSS mode is a sub-mode of the <a href="index.html">CSS mode</a> (defined in <code>css.js</code>.</p> <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#scss_*">normal</a>, <a href="../../test/index.html#verbose,scss_*">verbose</a>.</p> </article>
public/js/lib/codemirror/mode/css/scss.html
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.00017878726066555828, 0.00017495604697614908, 0.000169108941918239, 0.00017478413064964116, 0.0000026559303023532266 ]
{ "id": 2, "code_window": [ " userJavaScript = scrapeTests(userJavaScript);\n", " // simple fix in case the user forgets to invoke their function\n", "\n", " submit(userJavaScript, function(cls, message) {\n", " if (cls) {\n", " codeOutput.setValue(message.error);\n", " runTests('Error', null);\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if(failedCommentTest){\n", " myCodeMirror.setValue(myCodeMirror.getValue() + \"*/\");\n", " console.log('Caught Unfinished Comment');\n", " codeOutput.setValue(\"Unfinished mulit-line comment\");\n", " failedCommentTest = false;\n", " }\n", " else if (cls) {\n" ], "file_path": "public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js", "type": "replace", "edit_start_line_idx": 107 }
// // Input groups // -------------------------------------------------- // Base styles // ------------------------- .input-group { position: relative; // For dropdowns display: table; border-collapse: separate; // prevent input groups from inheriting border styles from table cells when placed within a table // Undo padding and float of grid classes &[class*="col-"] { float: none; padding-left: 0; padding-right: 0; } .form-control { // Ensure that the input is always above the *appended* addon button for // proper border colors. position: relative; z-index: 2; // IE9 fubars the placeholder attribute in text inputs and the arrows on // select elements in input groups. To fix it, we float the input. Details: // https://github.com/twbs/bootstrap/issues/11561#issuecomment-28936855 float: left; width: 100%; margin-bottom: 0; } } // Sizing options // // Remix the default form control sizing classes into new ones for easier // manipulation. .input-group-lg > .form-control, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .btn { .input-lg(); } .input-group-sm > .form-control, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .btn { .input-sm(); } // Display as table-cell // ------------------------- .input-group-addon, .input-group-btn, .input-group .form-control { display: table-cell; &:not(:first-child):not(:last-child) { border-radius: 0; } } // Addon and addon wrapper for buttons .input-group-addon, .input-group-btn { width: 1%; white-space: nowrap; vertical-align: middle; // Match the inputs } // Text input groups // ------------------------- .input-group-addon { padding: @padding-base-vertical @padding-base-horizontal; font-size: @font-size-base; font-weight: normal; line-height: 1; color: @input-color; text-align: center; background-color: @input-group-addon-bg; border: 1px solid @input-group-addon-border-color; border-radius: @border-radius-base; // Sizing &.input-sm { padding: @padding-small-vertical @padding-small-horizontal; font-size: @font-size-small; border-radius: @border-radius-small; } &.input-lg { padding: @padding-large-vertical @padding-large-horizontal; font-size: @font-size-large; border-radius: @border-radius-large; } // Nuke default margins from checkboxes and radios to vertically center within. input[type="radio"], input[type="checkbox"] { margin-top: 0; } } // Reset rounded corners .input-group .form-control:first-child, .input-group-addon:first-child, .input-group-btn:first-child > .btn, .input-group-btn:first-child > .btn-group > .btn, .input-group-btn:first-child > .dropdown-toggle, .input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle), .input-group-btn:last-child > .btn-group:not(:last-child) > .btn { .border-right-radius(0); } .input-group-addon:first-child { border-right: 0; } .input-group .form-control:last-child, .input-group-addon:last-child, .input-group-btn:last-child > .btn, .input-group-btn:last-child > .btn-group > .btn, .input-group-btn:last-child > .dropdown-toggle, .input-group-btn:first-child > .btn:not(:first-child), .input-group-btn:first-child > .btn-group:not(:first-child) > .btn { .border-left-radius(0); } .input-group-addon:last-child { border-left: 0; } // Button input groups // ------------------------- .input-group-btn { position: relative; // Jankily prevent input button groups from wrapping with `white-space` and // `font-size` in combination with `inline-block` on buttons. font-size: 0; white-space: nowrap; // Negative margin for spacing, position for bringing hovered/focused/actived // element above the siblings. > .btn { position: relative; + .btn { margin-left: -1px; } // Bring the "active" button to the front &:hover, &:focus, &:active { z-index: 2; } } // Negative margin to only have a 1px border between the two &:first-child { > .btn, > .btn-group { margin-right: -1px; } } &:last-child { > .btn, > .btn-group { margin-left: -1px; } } }
public/css/lib/bootstrap/input-groups.less
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.00017689097148831934, 0.00017328726244159043, 0.0001678794069448486, 0.00017359726189170033, 0.0000022205026652954984 ]
{ "id": 2, "code_window": [ " userJavaScript = scrapeTests(userJavaScript);\n", " // simple fix in case the user forgets to invoke their function\n", "\n", " submit(userJavaScript, function(cls, message) {\n", " if (cls) {\n", " codeOutput.setValue(message.error);\n", " runTests('Error', null);\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if(failedCommentTest){\n", " myCodeMirror.setValue(myCodeMirror.getValue() + \"*/\");\n", " console.log('Caught Unfinished Comment');\n", " codeOutput.setValue(\"Unfinished mulit-line comment\");\n", " failedCommentTest = false;\n", " }\n", " else if (cls) {\n" ], "file_path": "public/js/lib/coursewares/coursewaresJSFramework_0.0.6.js", "type": "replace", "edit_start_line_idx": 107 }
// Text overflow // Requires inline-block or block for proper styling .text-overflow() { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
public/css/lib/bootstrap/mixins/text-overflow.less
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/1bdb40bcafaffc666c43bc7b685b7c1fb4daed68
[ 0.00016693842189852148, 0.00016693842189852148, 0.00016693842189852148, 0.00016693842189852148, 0 ]
{ "id": 0, "code_window": [ " \"test\": \"exit 0\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"react\": \"^17.0.2\"\n", " },\n", " \"peerDependenciesMeta\": {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-docs/package.json", "type": "replace", "edit_start_line_idx": 36 }
{ "name": "@mui/lab", "version": "5.0.0-alpha.50", "private": false, "author": "MUI Team", "description": "Laboratory for new MUI modules.", "main": "./src/index.js", "keywords": [ "react", "react-component", "material-ui", "material design", "lab" ], "repository": { "type": "git", "url": "https://github.com/mui-org/material-ui.git", "directory": "packages/mui-lab" }, "license": "MIT", "bugs": { "url": "https://github.com/mui-org/material-ui/issues" }, "homepage": "https://mui.com/components/about-the-lab/", "scripts": { "build": "yarn build:legacy && yarn build:modern && yarn build:node && yarn build:stable && yarn build:types && yarn build:copy-files ", "build:legacy": "node ../../scripts/build legacy", "build:modern": "node ../../scripts/build modern", "build:node": "node ../../scripts/build node", "build:stable": "node ../../scripts/build stable", "build:copy-files": "node ../../scripts/copy-files.js", "build:types": "node ../../scripts/buildTypes", "prebuild": "rimraf build tsconfig.build.tsbuildinfo", "release": "yarn build && npm publish build", "test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-lab/**/*.test.{js,ts,tsx}'", "typescript": "tslint -p tsconfig.json \"{src,test}/**/*.{spec,d}.{ts,tsx}\" && tsc -p tsconfig.json" }, "peerDependencies": { "@mui/material": "^5.0.0-rc.0", "@types/react": "^16.8.6 || ^17.0.0", "date-fns": "^2.25.0", "dayjs": "^1.10.7", "luxon": "^1.28.0", "moment": "^2.29.1", "react": "^17.0.2", "react-dom": "^17.0.2" }, "peerDependenciesMeta": { "@types/react": { "optional": true }, "date-fns": { "optional": true }, "dayjs": { "optional": true }, "luxon": { "optional": true }, "moment": { "optional": true } }, "dependencies": { "@babel/runtime": "^7.15.4", "@date-io/date-fns": "^2.11.0", "@date-io/dayjs": "^2.11.0", "@date-io/luxon": "^2.11.1", "@date-io/moment": "^2.11.0", "@mui/core": "5.0.0-alpha.50", "@mui/system": "^5.0.3", "@mui/utils": "^5.0.1", "clsx": "^1.1.1", "prop-types": "^15.7.2", "react-is": "^17.0.2", "react-transition-group": "^4.4.2", "rifm": "^0.12.0" }, "devDependencies": { "@mui/types": "^7.0.0", "@types/luxon": "^1.27.1", "date-fns": "^2.25.0", "dayjs": "^1.10.7", "luxon": "^1.28.0", "moment": "^2.29.1" }, "sideEffects": false, "publishConfig": { "access": "public" }, "engines": { "node": ">=12.0.0" } }
packages/mui-lab/package.json
1
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.017893455922603607, 0.0030672363936901093, 0.00016566239355597645, 0.00016755421529524028, 0.005966451950371265 ]
{ "id": 0, "code_window": [ " \"test\": \"exit 0\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"react\": \"^17.0.2\"\n", " },\n", " \"peerDependenciesMeta\": {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-docs/package.json", "type": "replace", "edit_start_line_idx": 36 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M15 17h2v-3h1v-2l-1-5H2l-1 5v2h1v6h9v-6h4v3zm-6 1H4v-4h5v4zM2 4h15v2H2z" }, "0"), /*#__PURE__*/_jsx("path", { d: "M20 18v-3h-2v3h-3v2h3v3h2v-3h3v-2z" }, "1")], 'AddBusiness');
packages/mui-icons-material/lib/esm/AddBusiness.js
0
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.0001707840128801763, 0.0001707840128801763, 0.0001707840128801763, 0.0001707840128801763, 0 ]
{ "id": 0, "code_window": [ " \"test\": \"exit 0\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"react\": \"^17.0.2\"\n", " },\n", " \"peerDependenciesMeta\": {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-docs/package.json", "type": "replace", "edit_start_line_idx": 36 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM15 5h-2c-1.1 0-2 .89-2 2v2c0 1.11.9 2 2 2h2v2h-4v2h4c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2zm0 4h-2V7h2v2z"/></svg>
packages/mui-icons-material/material-icons/filter_9_outlined_24px.svg
0
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.00016700130072422326, 0.00016700130072422326, 0.00016700130072422326, 0.00016700130072422326, 0 ]
{ "id": 0, "code_window": [ " \"test\": \"exit 0\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"react\": \"^17.0.2\"\n", " },\n", " \"peerDependenciesMeta\": {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-docs/package.json", "type": "replace", "edit_start_line_idx": 36 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M18.36 9l.6 3H5.04l.6-3h12.72M20 4H4v2h16V4zm0 3H4l-1 5v2h1v6h10v-6h4v6h2v-6h1v-2l-1-5zM6 18v-4h6v4H6z"/></svg>
packages/mui-icons-material/material-icons/store_mall_directory_outlined_24px.svg
0
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.0001682165457168594, 0.0001682165457168594, 0.0001682165457168594, 0.0001682165457168594, 0 ]
{ "id": 1, "code_window": [ " \"test\": \"cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-icons-material/**/*.test.{js,ts,tsx}'\",\n", " \"test:built-typings\": \"tslint -p test/generated-types/tsconfig.json \\\"test/generated-types/*.{ts,tsx}\\\"\",\n", " \"typescript\": \"tslint -p tsconfig.json \\\"src/**/*.{ts,tsx}\\\"\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"react\": \"^17.0.2\"\n", " },\n", " \"peerDependenciesMeta\": {\n", " \"@types/react\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-icons-material/package.json", "type": "replace", "edit_start_line_idx": 43 }
{ "name": "@mui/icons-material", "version": "5.0.3", "private": false, "author": "MUI Team", "description": "Material Design icons distributed as SVG React components.", "main": "./src/index.js", "keywords": [ "react", "react-component", "material-ui", "material design", "icons" ], "repository": { "type": "git", "url": "https://github.com/mui-org/material-ui.git", "directory": "packages/mui-icons-material" }, "license": "MIT", "bugs": { "url": "https://github.com/mui-org/material-ui/issues" }, "homepage": "https://mui.com/components/material-icons/", "scripts": { "build": "shx cp -r lib/ build/ && yarn build:typings && yarn build:copy-files", "build:lib": "yarn build:node && yarn build:stable", "build:lib:clean": "rimraf lib/ && yarn build:lib", "build:legacy": "echo 'Skip legacy build'", "build:modern": "echo 'Skip modern build'", "build:node": "node ../../scripts/build node --largeFiles --outDir lib", "build:stable": "node ../../scripts/build stable --largeFiles --outDir lib", "build:copy-files": "node ../../scripts/copy-files.js", "build:typings": "babel-node --config-file ../../babel.config.js ./scripts/create-typings.js", "prebuild": "rimraf build", "release": "yarn build && npm publish build", "src:download": "cd ../../ && babel-node --config-file ./babel.config.js packages/mui-icons-material/scripts/download.js", "src:icons": "cd ../../ && UV_THREADPOOL_SIZE=64 babel-node --config-file ./babel.config.js packages/mui-icons-material/builder.js --output-dir packages/mui-icons-material/src --svg-dir packages/mui-icons-material/material-icons --renameFilter ./renameFilters/material-design-icons.js && cd packages/mui-icons-material && yarn build:lib:clean", "test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-icons-material/**/*.test.{js,ts,tsx}'", "test:built-typings": "tslint -p test/generated-types/tsconfig.json \"test/generated-types/*.{ts,tsx}\"", "typescript": "tslint -p tsconfig.json \"src/**/*.{ts,tsx}\"" }, "peerDependencies": { "@mui/material": "^5.0.0-rc.0", "@types/react": "^16.8.6 || ^17.0.0", "react": "^17.0.2" }, "peerDependenciesMeta": { "@types/react": { "optional": true } }, "dependencies": { "@babel/runtime": "^7.15.4" }, "devDependencies": { "fs-extra": "^10.0.0", "mustache": "^4.2.0", "shx": "^0.3.3", "svgo": "^2.4.0", "yargs": "^17.2.1" }, "sideEffects": false, "publishConfig": { "access": "public" }, "engines": { "node": ">=12.0.0" } }
packages/mui-icons-material/package.json
1
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.9786362648010254, 0.1224796399474144, 0.00016386389324907213, 0.00017103322898037732, 0.3235968053340912 ]
{ "id": 1, "code_window": [ " \"test\": \"cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-icons-material/**/*.test.{js,ts,tsx}'\",\n", " \"test:built-typings\": \"tslint -p test/generated-types/tsconfig.json \\\"test/generated-types/*.{ts,tsx}\\\"\",\n", " \"typescript\": \"tslint -p tsconfig.json \\\"src/**/*.{ts,tsx}\\\"\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"react\": \"^17.0.2\"\n", " },\n", " \"peerDependenciesMeta\": {\n", " \"@types/react\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-icons-material/package.json", "type": "replace", "edit_start_line_idx": 43 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><path d="M0,0h24v24H0V0z" fill="none"/></g><g><g><path d="M18,11c0.34,0,0.67,0.03,1,0.08V2H3v20h9.26C11.47,20.87,11,19.49,11,18C11,14.13,14.13,11,18,11z M7,11V4h5v7L9.5,9.5 L7,11z"/><path d="M18,13c-2.76,0-5,2.24-5,5s2.24,5,5,5s5-2.24,5-5S20.76,13,18,13z M16.75,20.5v-5l4,2.5L16.75,20.5z"/></g></g></svg>
packages/mui-icons-material/material-icons/play_lesson_sharp_24px.svg
0
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.00017242088506463915, 0.00017242088506463915, 0.00017242088506463915, 0.00017242088506463915, 0 ]
{ "id": 1, "code_window": [ " \"test\": \"cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-icons-material/**/*.test.{js,ts,tsx}'\",\n", " \"test:built-typings\": \"tslint -p test/generated-types/tsconfig.json \\\"test/generated-types/*.{ts,tsx}\\\"\",\n", " \"typescript\": \"tslint -p tsconfig.json \\\"src/**/*.{ts,tsx}\\\"\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"react\": \"^17.0.2\"\n", " },\n", " \"peerDependenciesMeta\": {\n", " \"@types/react\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-icons-material/package.json", "type": "replace", "edit_start_line_idx": 43 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><g><rect enable-background="new" height="1.5" opacity=".3" width="1.5" x="8" y="12.5"/><path d="M5,19h14V5H5V19z M13,9h1.5v2.25L16.25,9H18l-2.25,3L18,15h-1.75l-1.75-2.25 V15H13V9z M6.5,10c0-0.55,0.45-1,1-1H11v1.5H8v1h2c0.55,0,1,0.45,1,1V14c0,0.55-0.45,1-1,1H7.5c-0.55,0-1-0.45-1-1V10z" enable-background="new" opacity=".3"/><path d="M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h14c1.1,0,2-0.9,2-2V5C21,3.9,20.1,3,19,3z M19,19H5V5h14V19z"/><polygon points="14.5,12.75 16.25,15 18,15 15.75,12 18,9 16.25,9 14.5,11.25 14.5,9 13,9 13,15 14.5,15"/><path d="M7.5,15H10c0.55,0,1-0.45,1-1v-1.5c0-0.55-0.45-1-1-1H8v-1h3V9H7.5c-0.55,0-1,0.45-1,1v4C6.5,14.55,6.95,15,7.5,15z M8,12.5h1.5V14H8V12.5z"/></g></g></svg>
packages/mui-icons-material/material-icons/6k_two_tone_24px.svg
0
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.00016625360876787454, 0.00016625360876787454, 0.00016625360876787454, 0.00016625360876787454, 0 ]
{ "id": 1, "code_window": [ " \"test\": \"cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-icons-material/**/*.test.{js,ts,tsx}'\",\n", " \"test:built-typings\": \"tslint -p test/generated-types/tsconfig.json \\\"test/generated-types/*.{ts,tsx}\\\"\",\n", " \"typescript\": \"tslint -p tsconfig.json \\\"src/**/*.{ts,tsx}\\\"\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"react\": \"^17.0.2\"\n", " },\n", " \"peerDependenciesMeta\": {\n", " \"@types/react\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-icons-material/package.json", "type": "replace", "edit_start_line_idx": 43 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsxs(React.Fragment, { children: [/*#__PURE__*/_jsx("path", { fillOpacity: ".3", d: "M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z" }), /*#__PURE__*/_jsx("path", { d: "M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z" })] }), 'Battery90Outlined');
packages/mui-icons-material/lib/esm/Battery90Outlined.js
0
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.00017419485084246844, 0.00017275544814765453, 0.0001713160309009254, 0.00017275544814765453, 0.000001439410084458359 ]
{ "id": 2, "code_window": [ " \"test\": \"cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-lab/**/*.test.{js,ts,tsx}'\",\n", " \"typescript\": \"tslint -p tsconfig.json \\\"{src,test}/**/*.{spec,d}.{ts,tsx}\\\" && tsc -p tsconfig.json\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"date-fns\": \"^2.25.0\",\n", " \"dayjs\": \"^1.10.7\",\n", " \"luxon\": \"^1.28.0\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-lab/package.json", "type": "replace", "edit_start_line_idx": 38 }
{ "name": "@mui/docs", "version": "5.0.1", "private": false, "author": "MUI Team", "description": "MUI Docs - Documentation building blocks.", "main": "./src/index.js", "keywords": [ "react", "react-component", "material-ui", "material design", "docs" ], "repository": { "type": "git", "url": "https://github.com/mui-org/material-ui.git", "directory": "packages/mui-docs" }, "license": "MIT", "bugs": { "url": "https://github.com/mui-org/material-ui/issues" }, "homepage": "https://github.com/mui-org/material-ui/tree/master/packages/mui-docs", "scripts": { "build": "yarn build:legacy && yarn build:modern && yarn build:node && yarn build:stable && yarn build:copy-files", "build:legacy": "node ../../scripts/build legacy", "build:modern": "echo 'Skip modern build'", "build:node": "node ../../scripts/build node", "build:stable": "node ../../scripts/build stable", "build:copy-files": "node ../../scripts/copy-files.js", "prebuild": "rimraf build", "release": "yarn build && npm publish build", "test": "exit 0" }, "peerDependencies": { "@mui/material": "^5.0.0-rc.0", "@types/react": "^16.8.6 || ^17.0.0", "react": "^17.0.2" }, "peerDependenciesMeta": { "@types/react": { "optional": true } }, "dependencies": { "@babel/runtime": "^7.15.4", "@mui/utils": "^5.0.1", "nprogress": "^0.2.0" }, "publishConfig": { "access": "public" }, "engines": { "node": ">=12.0.0" } }
packages/mui-docs/package.json
1
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.0003804597072303295, 0.0002222750918008387, 0.00016310116916429251, 0.0001673937658779323, 0.00008428718865616247 ]
{ "id": 2, "code_window": [ " \"test\": \"cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-lab/**/*.test.{js,ts,tsx}'\",\n", " \"typescript\": \"tslint -p tsconfig.json \\\"{src,test}/**/*.{spec,d}.{ts,tsx}\\\" && tsc -p tsconfig.json\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"date-fns\": \"^2.25.0\",\n", " \"dayjs\": \"^1.10.7\",\n", " \"luxon\": \"^1.28.0\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-lab/package.json", "type": "replace", "edit_start_line_idx": 38 }
{ "props": { "onChange": { "type": { "name": "func" }, "required": true }, "renderInput": { "type": { "name": "func" }, "required": true }, "acceptRegex": { "type": { "name": "instanceOf", "description": "RegExp" }, "default": "/\\dap/gi" }, "ampm": { "type": { "name": "bool" } }, "ampmInClock": { "type": { "name": "bool" } }, "cancelText": { "type": { "name": "node" }, "default": "'Cancel'" }, "className": { "type": { "name": "string" } }, "clearable": { "type": { "name": "bool" } }, "clearText": { "type": { "name": "node" }, "default": "'Clear'" }, "components": { "type": { "name": "shape", "description": "{ OpenPickerIcon?: elementType }" } }, "DialogProps": { "type": { "name": "object" } }, "disableCloseOnSelect": { "type": { "name": "bool" }, "default": "`true` for Desktop, `false` for Mobile (based on the chosen wrapper and `desktopModeMediaQuery` prop)." }, "disabled": { "type": { "name": "bool" } }, "disableIgnoringDatePartForTimeValidation": { "type": { "name": "bool" } }, "disableMaskedInput": { "type": { "name": "bool" } }, "disableOpenPicker": { "type": { "name": "bool" } }, "getClockLabelText": { "type": { "name": "func" }, "default": "<TDate extends any>(\n view: ClockView,\n time: TDate | null,\n adapter: MuiPickersAdapter<TDate>,\n) =>\n `Select ${view}. ${\n time === null ? 'No time selected' : `Selected time is ${adapter.format(time, 'fullTime')}`\n }`" }, "getOpenDialogAriaText": { "type": { "name": "func" }, "default": "(value, utils) => `Choose date, selected date is ${utils.format(utils.date(value), 'fullDate')}`" }, "InputAdornmentProps": { "type": { "name": "object" } }, "inputFormat": { "type": { "name": "string" } }, "inputRef": { "type": { "name": "union", "description": "func<br>&#124;&nbsp;{ current?: object }" } }, "mask": { "type": { "name": "string" } }, "maxTime": { "type": { "name": "any" } }, "minTime": { "type": { "name": "any" } }, "minutesStep": { "type": { "name": "number" }, "default": "1" }, "okText": { "type": { "name": "node" }, "default": "'OK'" }, "onAccept": { "type": { "name": "func" } }, "onClose": { "type": { "name": "func" } }, "onError": { "type": { "name": "func" } }, "onOpen": { "type": { "name": "func" } }, "onViewChange": { "type": { "name": "func" } }, "open": { "type": { "name": "bool" } }, "OpenPickerButtonProps": { "type": { "name": "object" } }, "openTo": { "type": { "name": "enum", "description": "'hours'<br>&#124;&nbsp;'minutes'<br>&#124;&nbsp;'seconds'" } }, "orientation": { "type": { "name": "enum", "description": "'landscape'<br>&#124;&nbsp;'portrait'" } }, "readOnly": { "type": { "name": "bool" } }, "rifmFormatter": { "type": { "name": "func" } }, "shouldDisableTime": { "type": { "name": "func" } }, "showTodayButton": { "type": { "name": "bool" } }, "showToolbar": { "type": { "name": "bool" } }, "todayText": { "type": { "name": "node" }, "default": "'Today'" }, "ToolbarComponent": { "type": { "name": "elementType" }, "default": "TimePickerToolbar" }, "toolbarFormat": { "type": { "name": "string" } }, "toolbarPlaceholder": { "type": { "name": "node" }, "default": "'–'" }, "toolbarTitle": { "type": { "name": "node" }, "default": "'Select time'" }, "value": { "type": { "name": "union", "description": "any<br>&#124;&nbsp;Date<br>&#124;&nbsp;number<br>&#124;&nbsp;string" } }, "views": { "type": { "name": "arrayOf", "description": "Array&lt;'hours'<br>&#124;&nbsp;'minutes'<br>&#124;&nbsp;'seconds'&gt;" } } }, "name": "MobileTimePicker", "styles": { "classes": [], "globalClasses": {}, "name": null }, "spread": false, "forwardsRefTo": "HTMLDivElement", "filename": "/packages/mui-lab/src/MobileTimePicker/MobileTimePicker.tsx", "inheritance": null, "demos": "<ul><li><a href=\"/components/time-picker/\">Time Picker</a></li></ul>", "cssComponent": false }
docs/pages/api-docs/mobile-time-picker.json
0
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.00017766973178368062, 0.00017330711125396192, 0.0001630661718081683, 0.00017355120508000255, 0.000003941214799851878 ]
{ "id": 2, "code_window": [ " \"test\": \"cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-lab/**/*.test.{js,ts,tsx}'\",\n", " \"typescript\": \"tslint -p tsconfig.json \\\"{src,test}/**/*.{spec,d}.{ts,tsx}\\\" && tsc -p tsconfig.json\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"date-fns\": \"^2.25.0\",\n", " \"dayjs\": \"^1.10.7\",\n", " \"luxon\": \"^1.28.0\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-lab/package.json", "type": "replace", "edit_start_line_idx": 38 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" }), 'CheckBoxOutlineBlankOutlined'); exports.default = _default;
packages/mui-icons-material/lib/CheckBoxOutlineBlankOutlined.js
0
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.00017177205882035196, 0.0001694358215900138, 0.00016709958435967565, 0.0001694358215900138, 0.0000023362372303381562 ]
{ "id": 2, "code_window": [ " \"test\": \"cd ../../ && cross-env NODE_ENV=test mocha 'packages/mui-lab/**/*.test.{js,ts,tsx}'\",\n", " \"typescript\": \"tslint -p tsconfig.json \\\"{src,test}/**/*.{spec,d}.{ts,tsx}\\\" && tsc -p tsconfig.json\"\n", " },\n", " \"peerDependencies\": {\n", " \"@mui/material\": \"^5.0.0-rc.0\",\n", " \"@types/react\": \"^16.8.6 || ^17.0.0\",\n", " \"date-fns\": \"^2.25.0\",\n", " \"dayjs\": \"^1.10.7\",\n", " \"luxon\": \"^1.28.0\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"@mui/material\": \"^5.0.0\",\n" ], "file_path": "packages/mui-lab/package.json", "type": "replace", "edit_start_line_idx": 38 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M15.61 7.41 14.2 6l-6 6 6 6 1.41-1.41L11.03 12l4.58-4.59z" }), 'NavigateBeforeSharp');
packages/mui-icons-material/lib/esm/NavigateBeforeSharp.js
0
https://github.com/mui/material-ui/commit/e4b856fdd1686b09357d36c7cefdf0daddfb8bfc
[ 0.00017681306053418666, 0.00017681306053418666, 0.00017681306053418666, 0.00017681306053418666, 0 ]
{ "id": 0, "code_window": [ " }\n", "}\n", "\n", "// props handlers are special in the sense that it should not unwrap top-level\n", "// refs (in order to allow refs to be explicitly passed down), but should\n", "// retain the reactivity of the normal readonly object.\n", "export const shallowReadonlyHandlers: ProxyHandler<object> = {\n", " ...readonlyHandlers,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Props handlers are special in the sense that it should not unwrap top-level\n" ], "file_path": "packages/reactivity/src/baseHandlers.ts", "type": "replace", "edit_start_line_idx": 167 }
import { isObject, toRawType, EMPTY_OBJ } from '@vue/shared' import { mutableHandlers, readonlyHandlers, shallowReadonlyHandlers } from './baseHandlers' import { mutableCollectionHandlers, readonlyCollectionHandlers } from './collectionHandlers' import { UnwrapRef, Ref } from './ref' import { makeMap } from '@vue/shared' // WeakMaps that store {raw <-> observed} pairs. const rawToReactive = new WeakMap<any, any>() const reactiveToRaw = new WeakMap<any, any>() const rawToReadonly = new WeakMap<any, any>() const readonlyToRaw = new WeakMap<any, any>() // WeakSets for values that are marked readonly or non-reactive during // observable creation. const readonlyValues = new WeakSet<any>() const nonReactiveValues = new WeakSet<any>() const collectionTypes = new Set<Function>([Set, Map, WeakMap, WeakSet]) const isObservableType = /*#__PURE__*/ makeMap( 'Object,Array,Map,Set,WeakMap,WeakSet' ) const canObserve = (value: any): boolean => { return ( !value._isVue && !value._isVNode && isObservableType(toRawType(value)) && !nonReactiveValues.has(value) ) } // only unwrap nested ref type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRef<T> export function reactive<T extends object>(target: T): UnwrapNestedRefs<T> export function reactive(target: object) { // if trying to observe a readonly proxy, return the readonly version. if (readonlyToRaw.has(target)) { return target } // target is explicitly marked as readonly by user if (readonlyValues.has(target)) { return readonly(target) } return createReactiveObject( target, rawToReactive, reactiveToRaw, mutableHandlers, mutableCollectionHandlers ) } export function readonly<T extends object>( target: T ): Readonly<UnwrapNestedRefs<T>> { // value is a mutable observable, retrieve its original and return // a readonly version. if (reactiveToRaw.has(target)) { target = reactiveToRaw.get(target) } return createReactiveObject( target, rawToReadonly, readonlyToRaw, readonlyHandlers, readonlyCollectionHandlers ) } // @internal // Return a reactive-copy of the original object, where only the root level // properties are readonly, and does not recursively convert returned properties. // This is used for creating the props proxy object for stateful components. export function shallowReadonly<T extends object>( target: T ): Readonly<{ [K in keyof T]: UnwrapNestedRefs<T[K]> }> { return createReactiveObject( target, rawToReadonly, readonlyToRaw, shallowReadonlyHandlers, readonlyCollectionHandlers ) } function createReactiveObject( target: unknown, toProxy: WeakMap<any, any>, toRaw: WeakMap<any, any>, baseHandlers: ProxyHandler<any>, collectionHandlers: ProxyHandler<any> ) { if (!isObject(target)) { if (__DEV__) { console.warn(`value cannot be made reactive: ${String(target)}`) } return target } // target already has corresponding Proxy let observed = toProxy.get(target) if (observed !== void 0) { return observed } // target is already a Proxy if (toRaw.has(target)) { return target } // only a whitelist of value types can be observed. if (!canObserve(target)) { return target } const handlers = __SSR__ ? // disable reactivity in SSR. // NOTE: a potential caveat here is isReactive check may return different // values on nested values on client/server. This should be very rare but // we should keep an eye on this. EMPTY_OBJ : collectionTypes.has(target.constructor) ? collectionHandlers : baseHandlers observed = new Proxy(target, handlers) toProxy.set(target, observed) toRaw.set(observed, target) return observed } export function isReactive(value: unknown): boolean { return reactiveToRaw.has(value) || readonlyToRaw.has(value) } export function isReadonly(value: unknown): boolean { return readonlyToRaw.has(value) } export function toRaw<T>(observed: T): T { return reactiveToRaw.get(observed) || readonlyToRaw.get(observed) || observed } export function markReadonly<T>(value: T): T { readonlyValues.add(value) return value } export function markNonReactive<T>(value: T): T { nonReactiveValues.add(value) return value }
packages/reactivity/src/reactive.ts
1
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.9989125728607178, 0.1293461173772812, 0.0001678749395068735, 0.0006766230799257755, 0.3284139335155487 ]
{ "id": 0, "code_window": [ " }\n", "}\n", "\n", "// props handlers are special in the sense that it should not unwrap top-level\n", "// refs (in order to allow refs to be explicitly passed down), but should\n", "// retain the reactivity of the normal readonly object.\n", "export const shallowReadonlyHandlers: ProxyHandler<object> = {\n", " ...readonlyHandlers,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Props handlers are special in the sense that it should not unwrap top-level\n" ], "file_path": "packages/reactivity/src/baseHandlers.ts", "type": "replace", "edit_start_line_idx": 167 }
import { CompilerOptions, baseParse as parse, transform, generate, ElementNode, NodeTypes, ErrorCodes, ForNode, CallExpression, ComponentNode } from '../../src' import { transformElement } from '../../src/transforms/transformElement' import { transformOn } from '../../src/transforms/vOn' import { transformBind } from '../../src/transforms/vBind' import { transformExpression } from '../../src/transforms/transformExpression' import { trackSlotScopes, trackVForSlotScopes } from '../../src/transforms/vSlot' import { CREATE_SLOTS, RENDER_LIST } from '../../src/runtimeHelpers' import { createObjectMatcher, genFlagText } from '../testUtils' import { PatchFlags } from '@vue/shared' import { transformFor } from '../../src/transforms/vFor' import { transformIf } from '../../src/transforms/vIf' function parseWithSlots(template: string, options: CompilerOptions = {}) { const ast = parse(template) transform(ast, { nodeTransforms: [ transformIf, transformFor, ...(options.prefixIdentifiers ? [trackVForSlotScopes, transformExpression] : []), transformElement, trackSlotScopes ], directiveTransforms: { on: transformOn, bind: transformBind }, ...options }) return { root: ast, slots: ast.children[0].type === NodeTypes.ELEMENT ? (ast.children[0].codegenNode as CallExpression).arguments[2] : null } } function createSlotMatcher(obj: Record<string, any>) { return { type: NodeTypes.JS_OBJECT_EXPRESSION, properties: Object.keys(obj) .map(key => { return { type: NodeTypes.JS_PROPERTY, key: { type: NodeTypes.SIMPLE_EXPRESSION, isStatic: !/^\[/.test(key), content: key.replace(/^\[|\]$/g, '') }, value: obj[key] } as any }) .concat({ key: { content: `_compiled` }, value: { content: `true` } }) } } describe('compiler: transform component slots', () => { test('implicit default slot', () => { const { root, slots } = parseWithSlots(`<Comp><div/></Comp>`, { prefixIdentifiers: true }) expect(slots).toMatchObject( createSlotMatcher({ default: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: undefined, returns: [ { type: NodeTypes.ELEMENT, tag: `div` } ] } }) ) expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot() }) test('on-component default slot', () => { const { root, slots } = parseWithSlots( `<Comp v-slot="{ foo }">{{ foo }}{{ bar }}</Comp>`, { prefixIdentifiers: true } ) expect(slots).toMatchObject( createSlotMatcher({ default: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: { type: NodeTypes.COMPOUND_EXPRESSION, children: [`{ `, { content: `foo` }, ` }`] }, returns: [ { type: NodeTypes.INTERPOLATION, content: { content: `foo` } }, { type: NodeTypes.INTERPOLATION, content: { content: `_ctx.bar` } } ] } }) ) expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot() }) test('named slots', () => { const { root, slots } = parseWithSlots( `<Comp> <template v-slot:one="{ foo }"> {{ foo }}{{ bar }} </template> <template #two="{ bar }"> {{ foo }}{{ bar }} </template> </Comp>`, { prefixIdentifiers: true } ) expect(slots).toMatchObject( createSlotMatcher({ one: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: { type: NodeTypes.COMPOUND_EXPRESSION, children: [`{ `, { content: `foo` }, ` }`] }, returns: [ { type: NodeTypes.INTERPOLATION, content: { content: `foo` } }, { type: NodeTypes.INTERPOLATION, content: { content: `_ctx.bar` } } ] }, two: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: { type: NodeTypes.COMPOUND_EXPRESSION, children: [`{ `, { content: `bar` }, ` }`] }, returns: [ { type: NodeTypes.INTERPOLATION, content: { content: `_ctx.foo` } }, { type: NodeTypes.INTERPOLATION, content: { content: `bar` } } ] } }) ) expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot() }) test('named slots w/ implicit default slot', () => { const { root, slots } = parseWithSlots( `<Comp> <template #one>foo</template>bar<span/> </Comp>` ) expect(slots).toMatchObject( createSlotMatcher({ one: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: undefined, returns: [ { type: NodeTypes.TEXT, content: `foo` } ] }, default: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: undefined, returns: [ { type: NodeTypes.TEXT, content: `bar` }, { type: NodeTypes.ELEMENT, tag: `span` } ] } }) ) expect(generate(root).code).toMatchSnapshot() }) test('dynamically named slots', () => { const { root, slots } = parseWithSlots( `<Comp> <template v-slot:[one]="{ foo }"> {{ foo }}{{ bar }} </template> <template #[two]="{ bar }"> {{ foo }}{{ bar }} </template> </Comp>`, { prefixIdentifiers: true } ) expect(slots).toMatchObject( createSlotMatcher({ '[_ctx.one]': { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: { type: NodeTypes.COMPOUND_EXPRESSION, children: [`{ `, { content: `foo` }, ` }`] }, returns: [ { type: NodeTypes.INTERPOLATION, content: { content: `foo` } }, { type: NodeTypes.INTERPOLATION, content: { content: `_ctx.bar` } } ] }, '[_ctx.two]': { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: { type: NodeTypes.COMPOUND_EXPRESSION, children: [`{ `, { content: `bar` }, ` }`] }, returns: [ { type: NodeTypes.INTERPOLATION, content: { content: `_ctx.foo` } }, { type: NodeTypes.INTERPOLATION, content: { content: `bar` } } ] } }) ) expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot() }) test('nested slots scoping', () => { const { root, slots } = parseWithSlots( `<Comp> <template #default="{ foo }"> <Inner v-slot="{ bar }"> {{ foo }}{{ bar }}{{ baz }} </Inner> {{ foo }}{{ bar }}{{ baz }} </template> </Comp>`, { prefixIdentifiers: true } ) expect(slots).toMatchObject( createSlotMatcher({ default: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: { type: NodeTypes.COMPOUND_EXPRESSION, children: [`{ `, { content: `foo` }, ` }`] }, returns: [ { type: NodeTypes.ELEMENT, codegenNode: { type: NodeTypes.JS_CALL_EXPRESSION, arguments: [ `_component_Inner`, `null`, createSlotMatcher({ default: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: { type: NodeTypes.COMPOUND_EXPRESSION, children: [`{ `, { content: `bar` }, ` }`] }, returns: [ { type: NodeTypes.INTERPOLATION, content: { content: `foo` } }, { type: NodeTypes.INTERPOLATION, content: { content: `bar` } }, { type: NodeTypes.INTERPOLATION, content: { content: `_ctx.baz` } } ] } }), // nested slot should be forced dynamic, since scope variables // are not tracked as dependencies of the slot. genFlagText(PatchFlags.DYNAMIC_SLOTS) ] } }, // test scope { type: NodeTypes.TEXT, content: ` ` }, { type: NodeTypes.INTERPOLATION, content: { content: `foo` } }, { type: NodeTypes.INTERPOLATION, content: { content: `_ctx.bar` } }, { type: NodeTypes.INTERPOLATION, content: { content: `_ctx.baz` } } ] } }) ) expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot() }) test('should force dynamic when inside v-for', () => { const { root } = parseWithSlots( `<div v-for="i in list"> <Comp v-slot="bar">foo</Comp> </div>` ) const div = ((root.children[0] as ForNode).children[0] as ElementNode) .codegenNode as any const comp = div.arguments[2][0] expect(comp.codegenNode.arguments[3]).toBe( genFlagText(PatchFlags.DYNAMIC_SLOTS) ) }) test('should only force dynamic slots when actually using scope vars w/ prefixIdentifiers: true', () => { function assertDynamicSlots(template: string, shouldForce: boolean) { const { root } = parseWithSlots(template, { prefixIdentifiers: true }) let flag: any if (root.children[0].type === NodeTypes.FOR) { const div = (root.children[0].children[0] as ElementNode) .codegenNode as any const comp = div.arguments[2][0] flag = comp.codegenNode.arguments[3] } else { const innerComp = (root.children[0] as ComponentNode) .children[0] as ComponentNode flag = (innerComp.codegenNode as CallExpression).arguments[3] } if (shouldForce) { expect(flag).toBe(genFlagText(PatchFlags.DYNAMIC_SLOTS)) } else { expect(flag).toBeUndefined() } } assertDynamicSlots( `<div v-for="i in list"> <Comp v-slot="bar">foo</Comp> </div>`, false ) assertDynamicSlots( `<div v-for="i in list"> <Comp v-slot="bar">{{ i }}</Comp> </div>`, true ) // reference the component's own slot variable should not force dynamic slots assertDynamicSlots( `<Comp v-slot="foo"> <Comp v-slot="bar">{{ bar }}</Comp> </Comp>`, false ) assertDynamicSlots( `<Comp v-slot="foo"> <Comp v-slot="bar">{{ foo }}</Comp> </Comp>`, true ) }) test('named slot with v-if', () => { const { root, slots } = parseWithSlots( `<Comp> <template #one v-if="ok">hello</template> </Comp>` ) expect(slots).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_SLOTS, arguments: [ createObjectMatcher({ _compiled: `[true]` }), { type: NodeTypes.JS_ARRAY_EXPRESSION, elements: [ { type: NodeTypes.JS_CONDITIONAL_EXPRESSION, test: { content: `ok` }, consequent: createObjectMatcher({ name: `one`, fn: { type: NodeTypes.JS_FUNCTION_EXPRESSION, returns: [{ type: NodeTypes.TEXT, content: `hello` }] } }), alternate: { content: `undefined`, isStatic: false } } ] } ] }) expect((root as any).children[0].codegenNode.arguments[3]).toMatch( PatchFlags.DYNAMIC_SLOTS + '' ) expect(generate(root).code).toMatchSnapshot() }) test('named slot with v-if + prefixIdentifiers: true', () => { const { root, slots } = parseWithSlots( `<Comp> <template #one="props" v-if="ok">{{ props }}</template> </Comp>`, { prefixIdentifiers: true } ) expect(slots).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_SLOTS, arguments: [ createObjectMatcher({ _compiled: `[true]` }), { type: NodeTypes.JS_ARRAY_EXPRESSION, elements: [ { type: NodeTypes.JS_CONDITIONAL_EXPRESSION, test: { content: `_ctx.ok` }, consequent: createObjectMatcher({ name: `one`, fn: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: { content: `props` }, returns: [ { type: NodeTypes.INTERPOLATION, content: { content: `props` } } ] } }), alternate: { content: `undefined`, isStatic: false } } ] } ] }) expect((root as any).children[0].codegenNode.arguments[3]).toMatch( PatchFlags.DYNAMIC_SLOTS + '' ) expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot() }) test('named slot with v-if + v-else-if + v-else', () => { const { root, slots } = parseWithSlots( `<Comp> <template #one v-if="ok">foo</template> <template #two="props" v-else-if="orNot">bar</template> <template #one v-else>baz</template> </Comp>` ) expect(slots).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_SLOTS, arguments: [ createObjectMatcher({ _compiled: `[true]` }), { type: NodeTypes.JS_ARRAY_EXPRESSION, elements: [ { type: NodeTypes.JS_CONDITIONAL_EXPRESSION, test: { content: `ok` }, consequent: createObjectMatcher({ name: `one`, fn: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: undefined, returns: [{ type: NodeTypes.TEXT, content: `foo` }] } }), alternate: { type: NodeTypes.JS_CONDITIONAL_EXPRESSION, test: { content: `orNot` }, consequent: createObjectMatcher({ name: `two`, fn: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: { content: `props` }, returns: [{ type: NodeTypes.TEXT, content: `bar` }] } }), alternate: createObjectMatcher({ name: `one`, fn: { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: undefined, returns: [{ type: NodeTypes.TEXT, content: `baz` }] } }) } } ] } ] }) expect((root as any).children[0].codegenNode.arguments[3]).toMatch( PatchFlags.DYNAMIC_SLOTS + '' ) expect(generate(root).code).toMatchSnapshot() }) test('named slot with v-for w/ prefixIdentifiers: true', () => { const { root, slots } = parseWithSlots( `<Comp> <template v-for="name in list" #[name]>{{ name }}</template> </Comp>`, { prefixIdentifiers: true } ) expect(slots).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_SLOTS, arguments: [ createObjectMatcher({ _compiled: `[true]` }), { type: NodeTypes.JS_ARRAY_EXPRESSION, elements: [ { type: NodeTypes.JS_CALL_EXPRESSION, callee: RENDER_LIST, arguments: [ { content: `_ctx.list` }, { type: NodeTypes.JS_FUNCTION_EXPRESSION, params: [{ content: `name` }], returns: createObjectMatcher({ name: `[name]`, fn: { type: NodeTypes.JS_FUNCTION_EXPRESSION, returns: [ { type: NodeTypes.INTERPOLATION, content: { content: `name`, isStatic: false } } ] } }) } ] } ] } ] }) expect((root as any).children[0].codegenNode.arguments[3]).toMatch( PatchFlags.DYNAMIC_SLOTS + '' ) expect(generate(root, { prefixIdentifiers: true }).code).toMatchSnapshot() }) describe('errors', () => { test('error on extraneous children w/ named default slot', () => { const onError = jest.fn() const source = `<Comp><template #default>foo</template>bar</Comp>` parseWithSlots(source, { onError }) const index = source.indexOf('bar') expect(onError.mock.calls[0][0]).toMatchObject({ code: ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN, loc: { source: `bar`, start: { offset: index, line: 1, column: index + 1 }, end: { offset: index + 3, line: 1, column: index + 4 } } }) }) test('error on duplicated slot names', () => { const onError = jest.fn() const source = `<Comp><template #foo></template><template #foo></template></Comp>` parseWithSlots(source, { onError }) const index = source.lastIndexOf('#foo') expect(onError.mock.calls[0][0]).toMatchObject({ code: ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES, loc: { source: `#foo`, start: { offset: index, line: 1, column: index + 1 }, end: { offset: index + 4, line: 1, column: index + 5 } } }) }) test('error on invalid mixed slot usage', () => { const onError = jest.fn() const source = `<Comp v-slot="foo"><template #foo></template></Comp>` parseWithSlots(source, { onError }) const index = source.lastIndexOf('#foo') expect(onError.mock.calls[0][0]).toMatchObject({ code: ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE, loc: { source: `#foo`, start: { offset: index, line: 1, column: index + 1 }, end: { offset: index + 4, line: 1, column: index + 5 } } }) }) test('error on v-slot usage on plain elements', () => { const onError = jest.fn() const source = `<div v-slot/>` parseWithSlots(source, { onError }) const index = source.indexOf('v-slot') expect(onError.mock.calls[0][0]).toMatchObject({ code: ErrorCodes.X_V_SLOT_MISPLACED, loc: { source: `v-slot`, start: { offset: index, line: 1, column: index + 1 }, end: { offset: index + 6, line: 1, column: index + 7 } } }) }) test('error on named slot on component', () => { const onError = jest.fn() const source = `<Comp v-slot:foo>foo</Comp>` parseWithSlots(source, { onError }) const index = source.indexOf('v-slot') expect(onError.mock.calls[0][0]).toMatchObject({ code: ErrorCodes.X_V_SLOT_NAMED_SLOT_ON_COMPONENT, loc: { source: `v-slot:foo`, start: { offset: index, line: 1, column: index + 1 }, end: { offset: index + 10, line: 1, column: index + 11 } } }) }) }) })
packages/compiler-core/__tests__/transforms/vSlot.spec.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00017605804896447808, 0.00017138407565653324, 0.00016532157314941287, 0.00017094300710596144, 0.0000024607338673376944 ]
{ "id": 0, "code_window": [ " }\n", "}\n", "\n", "// props handlers are special in the sense that it should not unwrap top-level\n", "// refs (in order to allow refs to be explicitly passed down), but should\n", "// retain the reactivity of the normal readonly object.\n", "export const shallowReadonlyHandlers: ProxyHandler<object> = {\n", " ...readonlyHandlers,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Props handlers are special in the sense that it should not unwrap top-level\n" ], "file_path": "packages/reactivity/src/baseHandlers.ts", "type": "replace", "edit_start_line_idx": 167 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`compiler: transform v-model compound expression (with prefixIdentifiers) 1`] = ` "import { createVNode, createBlock, openBlock } from \\"vue\\" export function render() { const _ctx = this return (openBlock(), createBlock(\\"input\\", { modelValue: _ctx.model[_ctx.index], \\"onUpdate:modelValue\\": $event => (_ctx.model[_ctx.index] = $event) }, null, 8 /* PROPS */, [\\"modelValue\\", \\"onUpdate:modelValue\\"])) }" `; exports[`compiler: transform v-model compound expression 1`] = ` "const _Vue = Vue return function render() { with (this) { const { createVNode: _createVNode, createBlock: _createBlock, openBlock: _openBlock } = _Vue return (_openBlock(), _createBlock(\\"input\\", { modelValue: model[index], \\"onUpdate:modelValue\\": $event => (model[index] = $event) }, null, 8 /* PROPS */, [\\"modelValue\\", \\"onUpdate:modelValue\\"])) } }" `; exports[`compiler: transform v-model simple exprssion (with prefixIdentifiers) 1`] = ` "import { createVNode, createBlock, openBlock } from \\"vue\\" export function render() { const _ctx = this return (openBlock(), createBlock(\\"input\\", { modelValue: _ctx.model, \\"onUpdate:modelValue\\": $event => (_ctx.model = $event) }, null, 8 /* PROPS */, [\\"modelValue\\", \\"onUpdate:modelValue\\"])) }" `; exports[`compiler: transform v-model simple exprssion 1`] = ` "const _Vue = Vue return function render() { with (this) { const { createVNode: _createVNode, createBlock: _createBlock, openBlock: _openBlock } = _Vue return (_openBlock(), _createBlock(\\"input\\", { modelValue: model, \\"onUpdate:modelValue\\": $event => (model = $event) }, null, 8 /* PROPS */, [\\"modelValue\\", \\"onUpdate:modelValue\\"])) } }" `; exports[`compiler: transform v-model with argument 1`] = ` "const _Vue = Vue return function render() { with (this) { const { createVNode: _createVNode, createBlock: _createBlock, openBlock: _openBlock } = _Vue return (_openBlock(), _createBlock(\\"input\\", { value: model, \\"onUpdate:value\\": $event => (model = $event) }, null, 8 /* PROPS */, [\\"value\\", \\"onUpdate:value\\"])) } }" `; exports[`compiler: transform v-model with dynamic argument (with prefixIdentifiers) 1`] = ` "import { createVNode, createBlock, openBlock } from \\"vue\\" export function render() { const _ctx = this return (openBlock(), createBlock(\\"input\\", { [_ctx.value]: _ctx.model, [\\"onUpdate:\\" + _ctx.value]: $event => (_ctx.model = $event) }, null, 16 /* FULL_PROPS */)) }" `; exports[`compiler: transform v-model with dynamic argument 1`] = ` "const _Vue = Vue return function render() { with (this) { const { createVNode: _createVNode, createBlock: _createBlock, openBlock: _openBlock } = _Vue return (_openBlock(), _createBlock(\\"input\\", { [value]: model, [\\"onUpdate:\\" + value]: $event => (model = $event) }, null, 16 /* FULL_PROPS */)) } }" `;
packages/compiler-core/__tests__/transforms/__snapshots__/vModel.spec.ts.snap
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00017772565479390323, 0.0001686484320089221, 0.00016336886619683355, 0.00016854776185937226, 0.00000414537589676911 ]
{ "id": 0, "code_window": [ " }\n", "}\n", "\n", "// props handlers are special in the sense that it should not unwrap top-level\n", "// refs (in order to allow refs to be explicitly passed down), but should\n", "// retain the reactivity of the normal readonly object.\n", "export const shallowReadonlyHandlers: ProxyHandler<object> = {\n", " ...readonlyHandlers,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "// Props handlers are special in the sense that it should not unwrap top-level\n" ], "file_path": "packages/reactivity/src/baseHandlers.ts", "type": "replace", "edit_start_line_idx": 167 }
import { toRaw, reactive, readonly } from './reactive' import { track, trigger, ITERATE_KEY } from './effect' import { TrackOpTypes, TriggerOpTypes } from './operations' import { LOCKED } from './lock' import { isObject, capitalize, hasOwn, hasChanged } from '@vue/shared' export type CollectionTypes = IterableCollections | WeakCollections type IterableCollections = Map<any, any> | Set<any> type WeakCollections = WeakMap<any, any> | WeakSet<any> type MapTypes = Map<any, any> | WeakMap<any, any> type SetTypes = Set<any> | WeakSet<any> const toReactive = <T extends unknown>(value: T): T => isObject(value) ? reactive(value) : value const toReadonly = <T extends unknown>(value: T): T => isObject(value) ? readonly(value) : value const getProto = <T extends CollectionTypes>(v: T): any => Reflect.getPrototypeOf(v) function get( target: MapTypes, key: unknown, wrap: typeof toReactive | typeof toReadonly ) { target = toRaw(target) key = toRaw(key) track(target, TrackOpTypes.GET, key) return wrap(getProto(target).get.call(target, key)) } function has(this: CollectionTypes, key: unknown): boolean { const target = toRaw(this) key = toRaw(key) track(target, TrackOpTypes.HAS, key) return getProto(target).has.call(target, key) } function size(target: IterableCollections) { target = toRaw(target) track(target, TrackOpTypes.ITERATE, ITERATE_KEY) return Reflect.get(getProto(target), 'size', target) } function add(this: SetTypes, value: unknown) { value = toRaw(value) const target = toRaw(this) const proto = getProto(target) const hadKey = proto.has.call(target, value) const result = proto.add.call(target, value) if (!hadKey) { /* istanbul ignore else */ if (__DEV__) { trigger(target, TriggerOpTypes.ADD, value, { newValue: value }) } else { trigger(target, TriggerOpTypes.ADD, value) } } return result } function set(this: MapTypes, key: unknown, value: unknown) { value = toRaw(value) key = toRaw(key) const target = toRaw(this) const proto = getProto(target) const hadKey = proto.has.call(target, key) const oldValue = proto.get.call(target, key) const result = proto.set.call(target, key, value) /* istanbul ignore else */ if (__DEV__) { const extraInfo = { oldValue, newValue: value } if (!hadKey) { trigger(target, TriggerOpTypes.ADD, key, extraInfo) } else if (hasChanged(value, oldValue)) { trigger(target, TriggerOpTypes.SET, key, extraInfo) } } else { if (!hadKey) { trigger(target, TriggerOpTypes.ADD, key) } else if (hasChanged(value, oldValue)) { trigger(target, TriggerOpTypes.SET, key) } } return result } function deleteEntry(this: CollectionTypes, key: unknown) { key = toRaw(key) const target = toRaw(this) const proto = getProto(target) const hadKey = proto.has.call(target, key) const oldValue = proto.get ? proto.get.call(target, key) : undefined // forward the operation before queueing reactions const result = proto.delete.call(target, key) if (hadKey) { /* istanbul ignore else */ if (__DEV__) { trigger(target, TriggerOpTypes.DELETE, key, { oldValue }) } else { trigger(target, TriggerOpTypes.DELETE, key) } } return result } function clear(this: IterableCollections) { const target = toRaw(this) const hadItems = target.size !== 0 const oldTarget = __DEV__ ? target instanceof Map ? new Map(target) : new Set(target) : undefined // forward the operation before queueing reactions const result = getProto(target).clear.call(target) if (hadItems) { /* istanbul ignore else */ if (__DEV__) { trigger(target, TriggerOpTypes.CLEAR, void 0, { oldTarget }) } else { trigger(target, TriggerOpTypes.CLEAR) } } return result } function createForEach(isReadonly: boolean) { return function forEach( this: IterableCollections, callback: Function, thisArg?: unknown ) { const observed = this const target = toRaw(observed) const wrap = isReadonly ? toReadonly : toReactive track(target, TrackOpTypes.ITERATE, ITERATE_KEY) // important: create sure the callback is // 1. invoked with the reactive map as `this` and 3rd arg // 2. the value received should be a corresponding reactive/readonly. function wrappedCallback(value: unknown, key: unknown) { return callback.call(observed, wrap(value), wrap(key), observed) } return getProto(target).forEach.call(target, wrappedCallback, thisArg) } } function createIterableMethod(method: string | symbol, isReadonly: boolean) { return function(this: IterableCollections, ...args: unknown[]) { const target = toRaw(this) const isPair = method === 'entries' || (method === Symbol.iterator && target instanceof Map) const innerIterator = getProto(target)[method].apply(target, args) const wrap = isReadonly ? toReadonly : toReactive track(target, TrackOpTypes.ITERATE, ITERATE_KEY) // return a wrapped iterator which returns observed versions of the // values emitted from the real iterator return { // iterator protocol next() { const { value, done } = innerIterator.next() return done ? { value, done } : { value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), done } }, // iterable protocol [Symbol.iterator]() { return this } } } } function createReadonlyMethod( method: Function, type: TriggerOpTypes ): Function { return function(this: CollectionTypes, ...args: unknown[]) { if (LOCKED) { if (__DEV__) { const key = args[0] ? `on key "${args[0]}" ` : `` console.warn( `${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this) ) } return type === TriggerOpTypes.DELETE ? false : this } else { return method.apply(this, args) } } } const mutableInstrumentations: Record<string, Function> = { get(this: MapTypes, key: unknown) { return get(this, key, toReactive) }, get size(this: IterableCollections) { return size(this) }, has, add, set, delete: deleteEntry, clear, forEach: createForEach(false) } const readonlyInstrumentations: Record<string, Function> = { get(this: MapTypes, key: unknown) { return get(this, key, toReadonly) }, get size(this: IterableCollections) { return size(this) }, has, add: createReadonlyMethod(add, TriggerOpTypes.ADD), set: createReadonlyMethod(set, TriggerOpTypes.SET), delete: createReadonlyMethod(deleteEntry, TriggerOpTypes.DELETE), clear: createReadonlyMethod(clear, TriggerOpTypes.CLEAR), forEach: createForEach(true) } const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator] iteratorMethods.forEach(method => { mutableInstrumentations[method as string] = createIterableMethod( method, false ) readonlyInstrumentations[method as string] = createIterableMethod( method, true ) }) function createInstrumentationGetter( instrumentations: Record<string, Function> ) { return ( target: CollectionTypes, key: string | symbol, receiver: CollectionTypes ) => Reflect.get( hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver ) } export const mutableCollectionHandlers: ProxyHandler<CollectionTypes> = { get: createInstrumentationGetter(mutableInstrumentations) } export const readonlyCollectionHandlers: ProxyHandler<CollectionTypes> = { get: createInstrumentationGetter(readonlyInstrumentations) }
packages/reactivity/src/collectionHandlers.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.9336942434310913, 0.035257283598184586, 0.00016292613872792572, 0.00017098734679166228, 0.17620797455310822 ]
{ "id": 1, "code_window": [ " return {\n", " _isRef: true,\n", " // expose effect so computed can be stopped\n", " effect: runner,\n", " get value() {\n", " if (__SSR__) {\n", " return getter()\n", " }\n", "\n", " if (dirty) {\n", " value = runner()\n", " dirty = false\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/computed.ts", "type": "replace", "edit_start_line_idx": 58 }
import { track, trigger } from './effect' import { TrackOpTypes, TriggerOpTypes } from './operations' import { isObject } from '@vue/shared' import { reactive, isReactive } from './reactive' import { ComputedRef } from './computed' import { CollectionTypes } from './collectionHandlers' const isRefSymbol = Symbol() export interface Ref<T = any> { // This field is necessary to allow TS to differentiate a Ref from a plain // object that happens to have a "value" field. // However, checking a symbol on an arbitrary object is much slower than // checking a plain property, so we use a _isRef plain property for isRef() // check in the actual implementation. // The reason for not just declaring _isRef in the interface is because we // don't want this internal field to leak into userland autocompletion - // a private symbol, on the other hand, achieves just that. [isRefSymbol]: true value: UnwrapRef<T> } const convert = <T extends unknown>(val: T): T => isObject(val) ? reactive(val) : val export function isRef<T>(r: Ref<T> | T): r is Ref<T> export function isRef(r: any): r is Ref { return r ? r._isRef === true : false } export function ref<T extends Ref>(value: T): T export function ref<T>(value: T): Ref<T> export function ref<T = any>(): Ref<T> export function ref(value?: unknown) { if (isRef(value)) { return value } value = convert(value) if (__SSR__) { return { _isRef: true, value } } const r = { _isRef: true, get value() { track(r, TrackOpTypes.GET, 'value') return value }, set value(newVal) { value = convert(newVal) trigger( r, TriggerOpTypes.SET, 'value', __DEV__ ? { newValue: newVal } : void 0 ) } } return r } export function toRefs<T extends object>( object: T ): { [K in keyof T]: Ref<T[K]> } { if (__DEV__ && !__SSR__ && !isReactive(object)) { console.warn(`toRefs() expects a reactive object but received a plain one.`) } const ret: any = {} for (const key in object) { ret[key] = toProxyRef(object, key) } return ret } function toProxyRef<T extends object, K extends keyof T>( object: T, key: K ): Ref<T[K]> { return { _isRef: true, get value(): any { return object[key] }, set value(newVal) { object[key] = newVal } } as any } type UnwrapArray<T> = { [P in keyof T]: UnwrapRef<T[P]> } // corner case when use narrows type // Ex. type RelativePath = string & { __brand: unknown } // RelativePath extends object -> true type BaseTypes = string | number | boolean // Recursively unwraps nested value bindings. export type UnwrapRef<T> = { cRef: T extends ComputedRef<infer V> ? UnwrapRef<V> : T ref: T extends Ref<infer V> ? UnwrapRef<V> : T array: T extends Array<infer V> ? Array<UnwrapRef<V>> & UnwrapArray<T> : T object: { [K in keyof T]: UnwrapRef<T[K]> } }[T extends ComputedRef<any> ? 'cRef' : T extends Array<any> ? 'array' : T extends Ref | Function | CollectionTypes | BaseTypes ? 'ref' // bail out on types that shouldn't be unwrapped : T extends object ? 'object' : 'ref']
packages/reactivity/src/ref.ts
1
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.01380304154008627, 0.002030039206147194, 0.00016694828809704632, 0.00040678505320101976, 0.0038209022022783756 ]
{ "id": 1, "code_window": [ " return {\n", " _isRef: true,\n", " // expose effect so computed can be stopped\n", " effect: runner,\n", " get value() {\n", " if (__SSR__) {\n", " return getter()\n", " }\n", "\n", " if (dirty) {\n", " value = runner()\n", " dirty = false\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/computed.ts", "type": "replace", "edit_start_line_idx": 58 }
import { HMRRuntime } from '../src/hmr' import '../src/hmr' import { ComponentOptions, RenderFunction } from '../src/component' import { render, nodeOps, h, serializeInner, triggerEvent, TestElement, nextTick } from '@vue/runtime-test' import * as runtimeTest from '@vue/runtime-test' import { baseCompile } from '@vue/compiler-core' declare var __VUE_HMR_RUNTIME__: HMRRuntime const { createRecord, rerender, reload } = __VUE_HMR_RUNTIME__ function compileToFunction(template: string) { const { code } = baseCompile(template) const render = new Function('Vue', code)(runtimeTest) as RenderFunction render.isRuntimeCompiled = true return render } describe('hot module replacement', () => { test('inject global runtime', () => { expect(createRecord).toBeDefined() expect(rerender).toBeDefined() expect(reload).toBeDefined() }) test('createRecord', () => { expect(createRecord('test1', {})).toBe(true) // if id has already been created, should return false expect(createRecord('test1', {})).toBe(false) }) test('rerender', async () => { const root = nodeOps.createElement('div') const parentId = 'test2-parent' const childId = 'test2-child' const Child: ComponentOptions = { __hmrId: childId, render: compileToFunction(`<slot/>`) } createRecord(childId, Child) const Parent: ComponentOptions = { __hmrId: parentId, data() { return { count: 0 } }, components: { Child }, render: compileToFunction( `<div @click="count++">{{ count }}<Child>{{ count }}</Child></div>` ) } createRecord(parentId, Parent) render(h(Parent), root) expect(serializeInner(root)).toBe(`<div>0<!---->0<!----></div>`) // Perform some state change. This change should be preserved after the // re-render! triggerEvent(root.children[0] as TestElement, 'click') await nextTick() expect(serializeInner(root)).toBe(`<div>1<!---->1<!----></div>`) // Update text while preserving state rerender( parentId, compileToFunction( `<div @click="count++">{{ count }}!<Child>{{ count }}</Child></div>` ) ) expect(serializeInner(root)).toBe(`<div>1!<!---->1<!----></div>`) // Should force child update on slot content change rerender( parentId, compileToFunction( `<div @click="count++">{{ count }}!<Child>{{ count }}!</Child></div>` ) ) expect(serializeInner(root)).toBe(`<div>1!<!---->1!<!----></div>`) // Should force update element children despite block optimization rerender( parentId, compileToFunction( `<div @click="count++">{{ count }}<span>{{ count }}</span> <Child>{{ count }}!</Child> </div>` ) ) expect(serializeInner(root)).toBe( `<div>1<span>1</span><!---->1!<!----></div>` ) // Should force update child slot elements rerender( parentId, compileToFunction( `<div @click="count++"> <Child><span>{{ count }}</span></Child> </div>` ) ) expect(serializeInner(root)).toBe(`<div><!----><span>1</span><!----></div>`) }) test('reload', async () => { const root = nodeOps.createElement('div') const childId = 'test3-child' const unmoutSpy = jest.fn() const mountSpy = jest.fn() const Child: ComponentOptions = { __hmrId: childId, data() { return { count: 0 } }, unmounted: unmoutSpy, render: compileToFunction(`<div @click="count++">{{ count }}</div>`) } createRecord(childId, Child) const Parent: ComponentOptions = { render: () => h(Child) } render(h(Parent), root) expect(serializeInner(root)).toBe(`<div>0</div>`) reload(childId, { __hmrId: childId, data() { return { count: 1 } }, mounted: mountSpy, render: compileToFunction(`<div @click="count++">{{ count }}</div>`) }) await nextTick() expect(serializeInner(root)).toBe(`<div>1</div>`) expect(unmoutSpy).toHaveBeenCalledTimes(1) expect(mountSpy).toHaveBeenCalledTimes(1) }) })
packages/runtime-core/__tests__/hmr.spec.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00017696639406494796, 0.00017396837938576937, 0.00016696244711056352, 0.0001749949879013002, 0.000002579242618594435 ]
{ "id": 1, "code_window": [ " return {\n", " _isRef: true,\n", " // expose effect so computed can be stopped\n", " effect: runner,\n", " get value() {\n", " if (__SSR__) {\n", " return getter()\n", " }\n", "\n", " if (dirty) {\n", " value = runner()\n", " dirty = false\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/computed.ts", "type": "replace", "edit_start_line_idx": 58 }
import { currentInstance } from './component' import { currentRenderingInstance } from './componentRenderUtils' import { warn } from './warning' export interface InjectionKey<T> extends Symbol {} export function provide<T>(key: InjectionKey<T> | string, value: T) { if (!currentInstance) { if (__DEV__) { warn(`provide() can only be used inside setup().`) } } else { let provides = currentInstance.provides // by default an instance inherits its parent's provides object // but when it needs to provide values of its own, it creates its // own provides object using parent provides object as prototype. // this way in `inject` we can simply look up injections from direct // parent and let the prototype chain do the work. const parentProvides = currentInstance.parent && currentInstance.parent.provides if (parentProvides === provides) { provides = currentInstance.provides = Object.create(parentProvides) } // TS doesn't allow symbol as index type provides[key as string] = value } } export function inject<T>(key: InjectionKey<T> | string): T | undefined export function inject<T>(key: InjectionKey<T> | string, defaultValue: T): T export function inject( key: InjectionKey<any> | string, defaultValue?: unknown ) { // fallback to `currentRenderingInstance` so that this can be called in // a functional component const instance = currentInstance || currentRenderingInstance if (instance) { const provides = instance.provides if (key in provides) { // TS doesn't allow symbol as index type return provides[key as string] } else if (defaultValue !== undefined) { return defaultValue } else if (__DEV__) { warn(`injection "${String(key)}" not found.`) } } else if (__DEV__) { warn(`inject() can only be used inside setup() or functional components.`) } }
packages/runtime-core/src/apiInject.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00017350261623505503, 0.00016884150682017207, 0.00016562813834752887, 0.00016866798978298903, 0.000002809576699291938 ]
{ "id": 1, "code_window": [ " return {\n", " _isRef: true,\n", " // expose effect so computed can be stopped\n", " effect: runner,\n", " get value() {\n", " if (__SSR__) {\n", " return getter()\n", " }\n", "\n", " if (dirty) {\n", " value = runner()\n", " dirty = false\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/computed.ts", "type": "replace", "edit_start_line_idx": 58 }
import { Data } from '../component' import { Slot } from '../componentSlots' import { VNodeChildren, openBlock, createBlock, Fragment, VNode } from '../vnode' import { PatchFlags } from '@vue/shared' export function renderSlot( slots: Record<string, Slot>, name: string, props: Data = {}, // this is not a user-facing function, so the fallback is always generated by // the compiler and guaranteed to be an array fallback?: VNodeChildren ): VNode { const slot = slots[name] return ( openBlock(), createBlock( Fragment, { key: props.key }, slot ? slot(props) : fallback || [], slots._compiled ? 0 : PatchFlags.BAIL ) ) }
packages/runtime-core/src/helpers/renderSlot.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00017537597159389406, 0.00017356639727950096, 0.00017069072055164725, 0.0001740994630381465, 0.00000174470255842607 ]
{ "id": 2, "code_window": [ "import { isObject, toRawType, EMPTY_OBJ } from '@vue/shared'\n", "import {\n", " mutableHandlers,\n", " readonlyHandlers,\n", " shallowReadonlyHandlers\n", "} from './baseHandlers'\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isObject, toRawType } from '@vue/shared'\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 0 }
import { reactive, readonly, toRaw } from './reactive' import { TrackOpTypes, TriggerOpTypes } from './operations' import { track, trigger, ITERATE_KEY } from './effect' import { LOCKED } from './lock' import { isObject, hasOwn, isSymbol, hasChanged, isArray } from '@vue/shared' import { isRef } from './ref' const builtInSymbols = new Set( Object.getOwnPropertyNames(Symbol) .map(key => (Symbol as any)[key]) .filter(isSymbol) ) const get = /*#__PURE__*/ createGetter() const readonlyGet = /*#__PURE__*/ createGetter(true) const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true) const arrayIdentityInstrumentations: Record<string, Function> = {} ;['includes', 'indexOf', 'lastIndexOf'].forEach(key => { arrayIdentityInstrumentations[key] = function( value: unknown, ...args: any[] ): any { return toRaw(this)[key](toRaw(value), ...args) } }) function createGetter(isReadonly = false, shallow = false) { return function get(target: object, key: string | symbol, receiver: object) { if (isArray(target) && hasOwn(arrayIdentityInstrumentations, key)) { return Reflect.get(arrayIdentityInstrumentations, key, receiver) } const res = Reflect.get(target, key, receiver) if (isSymbol(key) && builtInSymbols.has(key)) { return res } if (shallow) { track(target, TrackOpTypes.GET, key) // TODO strict mode that returns a shallow-readonly version of the value return res } if (isRef(res)) { return res.value } track(target, TrackOpTypes.GET, key) return isObject(res) ? isReadonly ? // need to lazy access readonly and reactive here to avoid // circular dependency readonly(res) : reactive(res) : res } } const set = /*#__PURE__*/ createSetter() const readonlySet = /*#__PURE__*/ createSetter(true) const shallowReadonlySet = /*#__PURE__*/ createSetter(true, true) function createSetter(isReadonly = false, shallow = false) { return function set( target: object, key: string | symbol, value: unknown, receiver: object ): boolean { if (isReadonly && LOCKED) { if (__DEV__) { console.warn( `Set operation on key "${String(key)}" failed: target is readonly.`, target ) } return true } const oldValue = (target as any)[key] if (!shallow) { value = toRaw(value) if (isRef(oldValue) && !isRef(value)) { oldValue.value = value return true } } else { // in shallow mode, objects are set as-is regardless of reactive or not } const hadKey = hasOwn(target, key) const result = Reflect.set(target, key, value, receiver) // don't trigger if target is something up in the prototype chain of original if (target === toRaw(receiver)) { /* istanbul ignore else */ if (__DEV__) { const extraInfo = { oldValue, newValue: value } if (!hadKey) { trigger(target, TriggerOpTypes.ADD, key, extraInfo) } else if (hasChanged(value, oldValue)) { trigger(target, TriggerOpTypes.SET, key, extraInfo) } } else { if (!hadKey) { trigger(target, TriggerOpTypes.ADD, key) } else if (hasChanged(value, oldValue)) { trigger(target, TriggerOpTypes.SET, key) } } } return result } } function deleteProperty(target: object, key: string | symbol): boolean { const hadKey = hasOwn(target, key) const oldValue = (target as any)[key] const result = Reflect.deleteProperty(target, key) if (result && hadKey) { /* istanbul ignore else */ if (__DEV__) { trigger(target, TriggerOpTypes.DELETE, key, { oldValue }) } else { trigger(target, TriggerOpTypes.DELETE, key) } } return result } function has(target: object, key: string | symbol): boolean { const result = Reflect.has(target, key) track(target, TrackOpTypes.HAS, key) return result } function ownKeys(target: object): (string | number | symbol)[] { track(target, TrackOpTypes.ITERATE, ITERATE_KEY) return Reflect.ownKeys(target) } export const mutableHandlers: ProxyHandler<object> = { get, set, deleteProperty, has, ownKeys } export const readonlyHandlers: ProxyHandler<object> = { get: readonlyGet, set: readonlySet, has, ownKeys, deleteProperty(target: object, key: string | symbol): boolean { if (LOCKED) { if (__DEV__) { console.warn( `Delete operation on key "${String( key )}" failed: target is readonly.`, target ) } return true } else { return deleteProperty(target, key) } } } // props handlers are special in the sense that it should not unwrap top-level // refs (in order to allow refs to be explicitly passed down), but should // retain the reactivity of the normal readonly object. export const shallowReadonlyHandlers: ProxyHandler<object> = { ...readonlyHandlers, get: shallowReadonlyGet, set: shallowReadonlySet }
packages/reactivity/src/baseHandlers.ts
1
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.006030894350260496, 0.0013239599065855145, 0.00016351582598872483, 0.0002159680298063904, 0.0018033063970506191 ]
{ "id": 2, "code_window": [ "import { isObject, toRawType, EMPTY_OBJ } from '@vue/shared'\n", "import {\n", " mutableHandlers,\n", " readonlyHandlers,\n", " shallowReadonlyHandlers\n", "} from './baseHandlers'\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isObject, toRawType } from '@vue/shared'\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 0 }
# @vue/runtime-test ``` js import { h, render, nodeOps, dumpOps } from '@vue/runtime-test' const App = { data () { return { msg: 'Hello World!' } } render () { return h('div', this.msg) } } // root is of type `TestElement` as defined in src/nodeOps.ts const root = nodeOps.createElement('div') render(h(App), root) const ops = dumpOps() console.log(ops) ```
packages/runtime-test/README.md
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00017179630231112242, 0.00016904428775887936, 0.00016702534048818052, 0.00016831120592541993, 0.0000020155348465777934 ]
{ "id": 2, "code_window": [ "import { isObject, toRawType, EMPTY_OBJ } from '@vue/shared'\n", "import {\n", " mutableHandlers,\n", " readonlyHandlers,\n", " shallowReadonlyHandlers\n", "} from './baseHandlers'\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isObject, toRawType } from '@vue/shared'\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 0 }
import { parse } from '../src' import { mockWarn } from '@vue/shared' import { baseParse, baseCompile } from '@vue/compiler-core' describe('compiler:sfc', () => { mockWarn() describe('source map', () => { test('style block', () => { const style = parse(`<style>\n.color {\n color: red;\n }\n</style>\n`) .descriptor.styles[0] // TODO need to actually test this with SourceMapConsumer expect(style.map).not.toBeUndefined() }) test('script block', () => { const script = parse(`<script>\nconsole.log(1)\n }\n</script>\n`) .descriptor.script // TODO need to actually test this with SourceMapConsumer expect(script!.map).not.toBeUndefined() }) }) test('pad content', () => { const content = ` <template> <div></div> </template> <script> export default {} </script> <style> h1 { color: red } </style>` const padFalse = parse(content.trim(), { pad: false }).descriptor expect(padFalse.template!.content).toBe('\n<div></div>\n') expect(padFalse.script!.content).toBe('\nexport default {}\n') expect(padFalse.styles[0].content).toBe('\nh1 { color: red }\n') const padTrue = parse(content.trim(), { pad: true }).descriptor expect(padTrue.script!.content).toBe( Array(3 + 1).join('//\n') + '\nexport default {}\n' ) expect(padTrue.styles[0].content).toBe( Array(6 + 1).join('\n') + '\nh1 { color: red }\n' ) const padLine = parse(content.trim(), { pad: 'line' }).descriptor expect(padLine.script!.content).toBe( Array(3 + 1).join('//\n') + '\nexport default {}\n' ) expect(padLine.styles[0].content).toBe( Array(6 + 1).join('\n') + '\nh1 { color: red }\n' ) const padSpace = parse(content.trim(), { pad: 'space' }).descriptor expect(padSpace.script!.content).toBe( `<template>\n<div></div>\n</template>\n<script>`.replace(/./g, ' ') + '\nexport default {}\n' ) expect(padSpace.styles[0].content).toBe( `<template>\n<div></div>\n</template>\n<script>\nexport default {}\n</script>\n<style>`.replace( /./g, ' ' ) + '\nh1 { color: red }\n' ) }) test('should ignore nodes with no content', () => { expect(parse(`<template/>`).descriptor.template).toBe(null) expect(parse(`<script/>`).descriptor.script).toBe(null) expect(parse(`<style/>`).descriptor.styles.length).toBe(0) expect(parse(`<custom/>`).descriptor.customBlocks.length).toBe(0) }) test('nested templates', () => { const content = ` <template v-if="ok">ok</template> <div><div></div></div> ` const { descriptor } = parse(`<template>${content}</template>`) expect(descriptor.template!.content).toBe(content) }) test('error tolerance', () => { const { errors } = parse(`<template>`) expect(errors.length).toBe(1) }) test('should parse as DOM by default', () => { const { errors } = parse(`<template><input></template>`) expect(errors.length).toBe(0) }) test('custom compiler', () => { const { errors } = parse(`<template><input></template>`, { compiler: { parse: baseParse, compile: baseCompile } }) expect(errors.length).toBe(1) }) test('treat custom blocks as raw text', () => { const { errors, descriptor } = parse(`<foo> <-& </foo>`) expect(errors.length).toBe(0) expect(descriptor.customBlocks[0].content).toBe(` <-& `) }) describe('warnings', () => { test('should only allow single template element', () => { parse(`<template><div/></template><template><div/></template>`) expect( `Single file component can contain only one template element` ).toHaveBeenWarned() }) test('should only allow single script element', () => { parse(`<script>console.log(1)</script><script>console.log(1)</script>`) expect( `Single file component can contain only one script element` ).toHaveBeenWarned() }) }) })
packages/compiler-sfc/__tests__/parse.spec.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00021218598703853786, 0.00017495540669187903, 0.00016727286856621504, 0.00017220451263710856, 0.00001117242754844483 ]
{ "id": 2, "code_window": [ "import { isObject, toRawType, EMPTY_OBJ } from '@vue/shared'\n", "import {\n", " mutableHandlers,\n", " readonlyHandlers,\n", " shallowReadonlyHandlers\n", "} from './baseHandlers'\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isObject, toRawType } from '@vue/shared'\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 0 }
import { NodeTypes, ElementNode, SourceLocation, CompilerError, TextModes } from '@vue/compiler-core' import { RawSourceMap, SourceMapGenerator } from 'source-map' import LRUCache from 'lru-cache' import { generateCodeFrame } from '@vue/shared' import { TemplateCompiler } from './compileTemplate' export interface SFCParseOptions { filename?: string sourceMap?: boolean sourceRoot?: string pad?: boolean | 'line' | 'space' compiler?: TemplateCompiler } export interface SFCBlock { type: string content: string attrs: Record<string, string | true> loc: SourceLocation map?: RawSourceMap lang?: string src?: string } export interface SFCTemplateBlock extends SFCBlock { type: 'template' functional?: boolean } export interface SFCScriptBlock extends SFCBlock { type: 'script' } export interface SFCStyleBlock extends SFCBlock { type: 'style' scoped?: boolean module?: string | boolean } export interface SFCDescriptor { filename: string template: SFCTemplateBlock | null script: SFCScriptBlock | null styles: SFCStyleBlock[] customBlocks: SFCBlock[] } export interface SFCParseResult { descriptor: SFCDescriptor errors: CompilerError[] } const SFC_CACHE_MAX_SIZE = 500 const sourceToSFC = new LRUCache<string, SFCParseResult>(SFC_CACHE_MAX_SIZE) export function parse( source: string, { sourceMap = true, filename = 'component.vue', sourceRoot = '', pad = false, compiler = require('@vue/compiler-dom') }: SFCParseOptions = {} ): SFCParseResult { const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse const cache = sourceToSFC.get(sourceKey) if (cache) { return cache } const descriptor: SFCDescriptor = { filename, template: null, script: null, styles: [], customBlocks: [] } const errors: CompilerError[] = [] const ast = compiler.parse(source, { // there are no components at SFC parsing level isNativeTag: () => true, // preserve all whitespaces isPreTag: () => true, getTextMode: (tag, _ns, parent) => { // all top level elements except <template> are parsed as raw text // containers if (!parent && tag !== 'template') { return TextModes.RAWTEXT } else { return TextModes.DATA } }, onError: e => { errors.push(e) } }) ast.children.forEach(node => { if (node.type !== NodeTypes.ELEMENT) { return } if (!node.children.length) { return } switch (node.tag) { case 'template': if (!descriptor.template) { descriptor.template = createBlock( node, source, pad ) as SFCTemplateBlock } else { warnDuplicateBlock(source, filename, node) } break case 'script': if (!descriptor.script) { descriptor.script = createBlock(node, source, pad) as SFCScriptBlock } else { warnDuplicateBlock(source, filename, node) } break case 'style': descriptor.styles.push(createBlock(node, source, pad) as SFCStyleBlock) break default: descriptor.customBlocks.push(createBlock(node, source, pad)) break } }) if (sourceMap) { const genMap = (block: SFCBlock | null) => { if (block && !block.src) { block.map = generateSourceMap( filename, source, block.content, sourceRoot, pad ? 0 : block.loc.start.line - 1 ) } } genMap(descriptor.template) genMap(descriptor.script) descriptor.styles.forEach(genMap) } const result = { descriptor, errors } sourceToSFC.set(sourceKey, result) return result } function warnDuplicateBlock( source: string, filename: string, node: ElementNode ) { const codeFrame = generateCodeFrame( source, node.loc.start.offset, node.loc.end.offset ) const location = `${filename}:${node.loc.start.line}:${node.loc.start.column}` console.warn( `Single file component can contain only one ${ node.tag } element (${location}):\n\n${codeFrame}` ) } function createBlock( node: ElementNode, source: string, pad: SFCParseOptions['pad'] ): SFCBlock { const type = node.tag const start = node.children[0].loc.start const end = node.children[node.children.length - 1].loc.end const content = source.slice(start.offset, end.offset) const loc = { source: content, start, end } const attrs: Record<string, string | true> = {} const block: SFCBlock = { type, content, loc, attrs } if (node.tag !== 'template' && pad) { block.content = padContent(source, block, pad) + block.content } node.props.forEach(p => { if (p.type === NodeTypes.ATTRIBUTE) { attrs[p.name] = p.value ? p.value.content || true : true if (p.name === 'lang') { block.lang = p.value && p.value.content } else if (p.name === 'src') { block.src = p.value && p.value.content } else if (type === 'style') { if (p.name === 'scoped') { ;(block as SFCStyleBlock).scoped = true } else if (p.name === 'module') { ;(block as SFCStyleBlock).module = attrs[p.name] } } else if (type === 'template' && p.name === 'functional') { ;(block as SFCTemplateBlock).functional = true } } }) return block } const splitRE = /\r?\n/g const emptyRE = /^(?:\/\/)?\s*$/ const replaceRE = /./g function generateSourceMap( filename: string, source: string, generated: string, sourceRoot: string, lineOffset: number ): RawSourceMap { const map = new SourceMapGenerator({ file: filename.replace(/\\/g, '/'), sourceRoot: sourceRoot.replace(/\\/g, '/') }) map.setSourceContent(filename, source) generated.split(splitRE).forEach((line, index) => { if (!emptyRE.test(line)) { map.addMapping({ source: filename, original: { line: index + 1 + lineOffset, column: 0 }, generated: { line: index + 1, column: 0 } }) } }) return JSON.parse(map.toString()) } function padContent( content: string, block: SFCBlock, pad: SFCParseOptions['pad'] ): string { content = content.slice(0, block.loc.start.offset) if (pad === 'space') { return content.replace(replaceRE, ' ') } else { const offset = content.split(splitRE).length const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n' return Array(offset).join(padChar) } }
packages/compiler-sfc/src/parse.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.000553782214410603, 0.00018808314052876085, 0.00016572924505453557, 0.000170278872246854, 0.0000728300292394124 ]
{ "id": 3, "code_window": [ " )\n", "}\n", "\n", "// @internal\n", "// Return a reactive-copy of the original object, where only the root level\n", "// properties are readonly, and does not recursively convert returned properties.\n", "// This is used for creating the props proxy object for stateful components.\n", "export function shallowReadonly<T extends object>(\n", " target: T\n", "): Readonly<{ [K in keyof T]: UnwrapNestedRefs<T[K]> }> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "// properties are readonly, and does NOT unwrap refs nor recursively convert\n", "// returned properties.\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 79 }
import { track, trigger } from './effect' import { TrackOpTypes, TriggerOpTypes } from './operations' import { isObject } from '@vue/shared' import { reactive, isReactive } from './reactive' import { ComputedRef } from './computed' import { CollectionTypes } from './collectionHandlers' const isRefSymbol = Symbol() export interface Ref<T = any> { // This field is necessary to allow TS to differentiate a Ref from a plain // object that happens to have a "value" field. // However, checking a symbol on an arbitrary object is much slower than // checking a plain property, so we use a _isRef plain property for isRef() // check in the actual implementation. // The reason for not just declaring _isRef in the interface is because we // don't want this internal field to leak into userland autocompletion - // a private symbol, on the other hand, achieves just that. [isRefSymbol]: true value: UnwrapRef<T> } const convert = <T extends unknown>(val: T): T => isObject(val) ? reactive(val) : val export function isRef<T>(r: Ref<T> | T): r is Ref<T> export function isRef(r: any): r is Ref { return r ? r._isRef === true : false } export function ref<T extends Ref>(value: T): T export function ref<T>(value: T): Ref<T> export function ref<T = any>(): Ref<T> export function ref(value?: unknown) { if (isRef(value)) { return value } value = convert(value) if (__SSR__) { return { _isRef: true, value } } const r = { _isRef: true, get value() { track(r, TrackOpTypes.GET, 'value') return value }, set value(newVal) { value = convert(newVal) trigger( r, TriggerOpTypes.SET, 'value', __DEV__ ? { newValue: newVal } : void 0 ) } } return r } export function toRefs<T extends object>( object: T ): { [K in keyof T]: Ref<T[K]> } { if (__DEV__ && !__SSR__ && !isReactive(object)) { console.warn(`toRefs() expects a reactive object but received a plain one.`) } const ret: any = {} for (const key in object) { ret[key] = toProxyRef(object, key) } return ret } function toProxyRef<T extends object, K extends keyof T>( object: T, key: K ): Ref<T[K]> { return { _isRef: true, get value(): any { return object[key] }, set value(newVal) { object[key] = newVal } } as any } type UnwrapArray<T> = { [P in keyof T]: UnwrapRef<T[P]> } // corner case when use narrows type // Ex. type RelativePath = string & { __brand: unknown } // RelativePath extends object -> true type BaseTypes = string | number | boolean // Recursively unwraps nested value bindings. export type UnwrapRef<T> = { cRef: T extends ComputedRef<infer V> ? UnwrapRef<V> : T ref: T extends Ref<infer V> ? UnwrapRef<V> : T array: T extends Array<infer V> ? Array<UnwrapRef<V>> & UnwrapArray<T> : T object: { [K in keyof T]: UnwrapRef<T[K]> } }[T extends ComputedRef<any> ? 'cRef' : T extends Array<any> ? 'array' : T extends Ref | Function | CollectionTypes | BaseTypes ? 'ref' // bail out on types that shouldn't be unwrapped : T extends object ? 'object' : 'ref']
packages/reactivity/src/ref.ts
1
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.014145515859127045, 0.0036193877458572388, 0.00016646980657242239, 0.0018118696752935648, 0.004357938189059496 ]
{ "id": 3, "code_window": [ " )\n", "}\n", "\n", "// @internal\n", "// Return a reactive-copy of the original object, where only the root level\n", "// properties are readonly, and does not recursively convert returned properties.\n", "// This is used for creating the props proxy object for stateful components.\n", "export function shallowReadonly<T extends object>(\n", " target: T\n", "): Readonly<{ [K in keyof T]: UnwrapNestedRefs<T[K]> }> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "// properties are readonly, and does NOT unwrap refs nor recursively convert\n", "// returned properties.\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 79 }
import { h, TestElement, nodeOps, render, ref, KeepAlive, serializeInner, nextTick, ComponentOptions } from '@vue/runtime-test' import { KeepAliveProps } from '../../src/components/KeepAlive' describe('KeepAlive', () => { let one: ComponentOptions let two: ComponentOptions let views: Record<string, ComponentOptions> let root: TestElement beforeEach(() => { root = nodeOps.createElement('div') one = { name: 'one', data: () => ({ msg: 'one' }), render(this: any) { return h('div', this.msg) }, created: jest.fn(), mounted: jest.fn(), activated: jest.fn(), deactivated: jest.fn(), unmounted: jest.fn() } two = { name: 'two', data: () => ({ msg: 'two' }), render(this: any) { return h('div', this.msg) }, created: jest.fn(), mounted: jest.fn(), activated: jest.fn(), deactivated: jest.fn(), unmounted: jest.fn() } views = { one, two } }) function assertHookCalls(component: any, callCounts: number[]) { expect([ component.created.mock.calls.length, component.mounted.mock.calls.length, component.activated.mock.calls.length, component.deactivated.mock.calls.length, component.unmounted.mock.calls.length ]).toEqual(callCounts) } test('should preserve state', async () => { const viewRef = ref('one') const instanceRef = ref<any>(null) const App = { render() { return h(KeepAlive, null, { default: () => h(views[viewRef.value], { ref: instanceRef }) }) } } render(h(App), root) expect(serializeInner(root)).toBe(`<div>one</div>`) instanceRef.value.msg = 'changed' await nextTick() expect(serializeInner(root)).toBe(`<div>changed</div>`) viewRef.value = 'two' await nextTick() expect(serializeInner(root)).toBe(`<div>two</div>`) viewRef.value = 'one' await nextTick() expect(serializeInner(root)).toBe(`<div>changed</div>`) }) test('should call correct lifecycle hooks', async () => { const toggle = ref(true) const viewRef = ref('one') const App = { render() { return toggle.value ? h(KeepAlive, () => h(views[viewRef.value])) : null } } render(h(App), root) expect(serializeInner(root)).toBe(`<div>one</div>`) assertHookCalls(one, [1, 1, 1, 0, 0]) assertHookCalls(two, [0, 0, 0, 0, 0]) // toggle kept-alive component viewRef.value = 'two' await nextTick() expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 1, 1, 0]) assertHookCalls(two, [1, 1, 1, 0, 0]) viewRef.value = 'one' await nextTick() expect(serializeInner(root)).toBe(`<div>one</div>`) assertHookCalls(one, [1, 1, 2, 1, 0]) assertHookCalls(two, [1, 1, 1, 1, 0]) viewRef.value = 'two' await nextTick() expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 2, 2, 0]) assertHookCalls(two, [1, 1, 2, 1, 0]) // teardown keep-alive, should unmount all components including cached toggle.value = false await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 2, 2, 1]) assertHookCalls(two, [1, 1, 2, 2, 1]) }) test('should call lifecycle hooks on nested components', async () => { one.render = () => h(two) const toggle = ref(true) const App = { render() { return h(KeepAlive, () => (toggle.value ? h(one) : null)) } } render(h(App), root) expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 1, 0, 0]) assertHookCalls(two, [1, 1, 1, 0, 0]) toggle.value = false await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 1, 1, 0]) assertHookCalls(two, [1, 1, 1, 1, 0]) toggle.value = true await nextTick() expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 2, 1, 0]) assertHookCalls(two, [1, 1, 2, 1, 0]) toggle.value = false await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 2, 2, 0]) assertHookCalls(two, [1, 1, 2, 2, 0]) }) test('should call correct hooks for nested keep-alive', async () => { const toggle2 = ref(true) one.render = () => h(KeepAlive, () => (toggle2.value ? h(two) : null)) const toggle1 = ref(true) const App = { render() { return h(KeepAlive, () => (toggle1.value ? h(one) : null)) } } render(h(App), root) expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 1, 0, 0]) assertHookCalls(two, [1, 1, 1, 0, 0]) toggle1.value = false await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 1, 1, 0]) assertHookCalls(two, [1, 1, 1, 1, 0]) toggle1.value = true await nextTick() expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 2, 1, 0]) assertHookCalls(two, [1, 1, 2, 1, 0]) // toggle nested instance toggle2.value = false await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 2, 1, 0]) assertHookCalls(two, [1, 1, 2, 2, 0]) toggle2.value = true await nextTick() expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 2, 1, 0]) assertHookCalls(two, [1, 1, 3, 2, 0]) toggle1.value = false await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 2, 2, 0]) assertHookCalls(two, [1, 1, 3, 3, 0]) // toggle nested instance when parent is deactivated toggle2.value = false await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 2, 2, 0]) assertHookCalls(two, [1, 1, 3, 3, 0]) // should not be affected toggle2.value = true await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 2, 2, 0]) assertHookCalls(two, [1, 1, 3, 3, 0]) // should not be affected toggle1.value = true await nextTick() expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 3, 2, 0]) assertHookCalls(two, [1, 1, 4, 3, 0]) toggle1.value = false toggle2.value = false await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 3, 3, 0]) assertHookCalls(two, [1, 1, 4, 4, 0]) toggle1.value = true await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 4, 3, 0]) assertHookCalls(two, [1, 1, 4, 4, 0]) // should remain inactive }) async function assertNameMatch(props: KeepAliveProps) { const outerRef = ref(true) const viewRef = ref('one') const App = { render() { return outerRef.value ? h(KeepAlive, props, () => h(views[viewRef.value])) : null } } render(h(App), root) expect(serializeInner(root)).toBe(`<div>one</div>`) assertHookCalls(one, [1, 1, 1, 0, 0]) assertHookCalls(two, [0, 0, 0, 0, 0]) viewRef.value = 'two' await nextTick() expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 1, 1, 0]) assertHookCalls(two, [1, 1, 0, 0, 0]) viewRef.value = 'one' await nextTick() expect(serializeInner(root)).toBe(`<div>one</div>`) assertHookCalls(one, [1, 1, 2, 1, 0]) assertHookCalls(two, [1, 1, 0, 0, 1]) viewRef.value = 'two' await nextTick() expect(serializeInner(root)).toBe(`<div>two</div>`) assertHookCalls(one, [1, 1, 2, 2, 0]) assertHookCalls(two, [2, 2, 0, 0, 1]) // teardown outerRef.value = false await nextTick() expect(serializeInner(root)).toBe(`<!---->`) assertHookCalls(one, [1, 1, 2, 2, 1]) assertHookCalls(two, [2, 2, 0, 0, 2]) } describe('props', () => { test('include (string)', async () => { await assertNameMatch({ include: 'one' }) }) test('include (regex)', async () => { await assertNameMatch({ include: /^one$/ }) }) test('include (array)', async () => { await assertNameMatch({ include: ['one'] }) }) test('exclude (string)', async () => { await assertNameMatch({ exclude: 'two' }) }) test('exclude (regex)', async () => { await assertNameMatch({ exclude: /^two$/ }) }) test('exclude (array)', async () => { await assertNameMatch({ exclude: ['two'] }) }) test('include + exclude', async () => { await assertNameMatch({ include: 'one,two', exclude: 'two' }) }) test('max', async () => { const spyA = jest.fn() const spyB = jest.fn() const spyC = jest.fn() const spyAD = jest.fn() const spyBD = jest.fn() const spyCD = jest.fn() function assertCount(calls: number[]) { expect([ spyA.mock.calls.length, spyAD.mock.calls.length, spyB.mock.calls.length, spyBD.mock.calls.length, spyC.mock.calls.length, spyCD.mock.calls.length ]).toEqual(calls) } const viewRef = ref('a') const views: Record<string, ComponentOptions> = { a: { render: () => `one`, created: spyA, unmounted: spyAD }, b: { render: () => `two`, created: spyB, unmounted: spyBD }, c: { render: () => `three`, created: spyC, unmounted: spyCD } } const App = { render() { return h(KeepAlive, { max: 2 }, () => { return h(views[viewRef.value]) }) } } render(h(App), root) assertCount([1, 0, 0, 0, 0, 0]) viewRef.value = 'b' await nextTick() assertCount([1, 0, 1, 0, 0, 0]) viewRef.value = 'c' await nextTick() // should prune A because max cache reached assertCount([1, 1, 1, 0, 1, 0]) viewRef.value = 'b' await nextTick() // B should be reused, and made latest assertCount([1, 1, 1, 0, 1, 0]) viewRef.value = 'a' await nextTick() // C should be pruned because B was used last so C is the oldest cached assertCount([2, 1, 1, 0, 1, 1]) }) }) describe('cache invalidation', () => { function setup() { const viewRef = ref('one') const includeRef = ref('one,two') const App = { render() { return h( KeepAlive, { include: includeRef.value }, () => h(views[viewRef.value]) ) } } render(h(App), root) return { viewRef, includeRef } } test('on include/exclude change', async () => { const { viewRef, includeRef } = setup() viewRef.value = 'two' await nextTick() assertHookCalls(one, [1, 1, 1, 1, 0]) assertHookCalls(two, [1, 1, 1, 0, 0]) includeRef.value = 'two' await nextTick() assertHookCalls(one, [1, 1, 1, 1, 1]) assertHookCalls(two, [1, 1, 1, 0, 0]) viewRef.value = 'one' await nextTick() assertHookCalls(one, [2, 2, 1, 1, 1]) assertHookCalls(two, [1, 1, 1, 1, 0]) }) test('on include/exclude change + view switch', async () => { const { viewRef, includeRef } = setup() viewRef.value = 'two' await nextTick() assertHookCalls(one, [1, 1, 1, 1, 0]) assertHookCalls(two, [1, 1, 1, 0, 0]) includeRef.value = 'one' viewRef.value = 'one' await nextTick() assertHookCalls(one, [1, 1, 2, 1, 0]) // two should be pruned assertHookCalls(two, [1, 1, 1, 1, 1]) }) test('should not prune current active instance', async () => { const { viewRef, includeRef } = setup() includeRef.value = 'two' await nextTick() assertHookCalls(one, [1, 1, 1, 0, 0]) assertHookCalls(two, [0, 0, 0, 0, 0]) viewRef.value = 'two' await nextTick() assertHookCalls(one, [1, 1, 1, 0, 1]) assertHookCalls(two, [1, 1, 1, 0, 0]) }) async function assertAnonymous(include: boolean) { const one = { name: 'one', created: jest.fn(), render: () => 'one' } const two = { // anonymous created: jest.fn(), render: () => 'two' } const views: any = { one, two } const viewRef = ref('one') const App = { render() { return h( KeepAlive, { include: include ? 'one' : undefined }, () => h(views[viewRef.value]) ) } } render(h(App), root) function assert(oneCreateCount: number, twoCreateCount: number) { expect(one.created.mock.calls.length).toBe(oneCreateCount) expect(two.created.mock.calls.length).toBe(twoCreateCount) } assert(1, 0) viewRef.value = 'two' await nextTick() assert(1, 1) viewRef.value = 'one' await nextTick() assert(1, 1) viewRef.value = 'two' await nextTick() // two should be re-created if include is specified, since it's not matched // otherwise it should be cached. assert(1, include ? 2 : 1) } // 2.x #6938 test('should not cache anonymous component when include is specified', async () => { await assertAnonymous(true) }) test('should cache anonymous components if include is not specified', async () => { await assertAnonymous(false) }) // 2.x #7105 test('should not destroy active instance when pruning cache', async () => { const Foo = { render: () => 'foo', unmounted: jest.fn() } const includeRef = ref(['foo']) const App = { render() { return h( KeepAlive, { include: includeRef.value }, () => h(Foo) ) } } render(h(App), root) // condition: a render where a previous component is reused includeRef.value = ['foo', 'bar'] await nextTick() includeRef.value = [] await nextTick() expect(Foo.unmounted).not.toHaveBeenCalled() }) }) })
packages/runtime-core/__tests__/components/KeepAlive.spec.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.0002585558104328811, 0.00017436059715691954, 0.0001644127769395709, 0.00017318417667411268, 0.000013002387277083471 ]
{ "id": 3, "code_window": [ " )\n", "}\n", "\n", "// @internal\n", "// Return a reactive-copy of the original object, where only the root level\n", "// properties are readonly, and does not recursively convert returned properties.\n", "// This is used for creating the props proxy object for stateful components.\n", "export function shallowReadonly<T extends object>(\n", " target: T\n", "): Readonly<{ [K in keyof T]: UnwrapNestedRefs<T[K]> }> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "// properties are readonly, and does NOT unwrap refs nor recursively convert\n", "// returned properties.\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 79 }
import { withDirectives, defineComponent, h, nextTick, VNode } from '@vue/runtime-core' import { render, vShow } from '@vue/runtime-dom' const withVShow = (node: VNode, exp: any) => withDirectives(node, [[vShow, exp]]) let root: any beforeEach(() => { root = document.createElement('div') }) describe('runtime-dom: v-show directive', () => { test('should check show value is truthy', async () => { const component = defineComponent({ data() { return { value: true } }, render() { return [withVShow(h('div'), this.value)] } }) render(h(component), root) const $div = root.querySelector('div') expect($div.style.display).toEqual('') }) test('should check show value is falsy', async () => { const component = defineComponent({ data() { return { value: false } }, render() { return [withVShow(h('div'), this.value)] } }) render(h(component), root) const $div = root.querySelector('div') expect($div.style.display).toEqual('none') }) it('should update show value changed', async () => { const component = defineComponent({ data() { return { value: true } }, render() { return [withVShow(h('div'), this.value)] } }) render(h(component), root) const $div = root.querySelector('div') const data = root._vnode.component.data expect($div.style.display).toEqual('') data.value = false await nextTick() expect($div.style.display).toEqual('none') data.value = {} await nextTick() expect($div.style.display).toEqual('') data.value = 0 await nextTick() expect($div.style.display).toEqual('none') data.value = [] await nextTick() expect($div.style.display).toEqual('') data.value = null await nextTick() expect($div.style.display).toEqual('none') data.value = '0' await nextTick() expect($div.style.display).toEqual('') data.value = undefined await nextTick() expect($div.style.display).toEqual('none') data.value = 1 await nextTick() expect($div.style.display).toEqual('') }) test('should respect display value in style attribute', async () => { const component = defineComponent({ data() { return { value: true } }, render() { return [ withVShow(h('div', { style: { display: 'block' } }), this.value) ] } }) render(h(component), root) const $div = root.querySelector('div') const data = root._vnode.component.data expect($div.style.display).toEqual('block') data.value = false await nextTick() expect($div.style.display).toEqual('none') data.value = true await nextTick() expect($div.style.display).toEqual('block') }) })
packages/runtime-dom/__tests__/directives/vShow.spec.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.0001842929341364652, 0.00017309676331933588, 0.00016596658679191023, 0.00017256678256671876, 0.000005644708835461643 ]
{ "id": 3, "code_window": [ " )\n", "}\n", "\n", "// @internal\n", "// Return a reactive-copy of the original object, where only the root level\n", "// properties are readonly, and does not recursively convert returned properties.\n", "// This is used for creating the props proxy object for stateful components.\n", "export function shallowReadonly<T extends object>(\n", " target: T\n", "): Readonly<{ [K in keyof T]: UnwrapNestedRefs<T[K]> }> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "// properties are readonly, and does NOT unwrap refs nor recursively convert\n", "// returned properties.\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 79 }
import { reactive, effect, isReactive, toRaw } from '../../src' describe('reactivity/collections', () => { describe('Set', () => { it('instanceof', () => { const original = new Set() const observed = reactive(original) expect(isReactive(observed)).toBe(true) expect(original instanceof Set).toBe(true) expect(observed instanceof Set).toBe(true) }) it('should observe mutations', () => { let dummy const set = reactive(new Set()) effect(() => (dummy = set.has('value'))) expect(dummy).toBe(false) set.add('value') expect(dummy).toBe(true) set.delete('value') expect(dummy).toBe(false) }) it('should observe mutations with observed value', () => { let dummy const value = reactive({}) const set = reactive(new Set()) effect(() => (dummy = set.has(value))) expect(dummy).toBe(false) set.add(value) expect(dummy).toBe(true) set.delete(value) expect(dummy).toBe(false) }) it('should observe for of iteration', () => { let dummy const set = reactive(new Set() as Set<number>) effect(() => { dummy = 0 for (let num of set) { dummy += num } }) expect(dummy).toBe(0) set.add(2) set.add(1) expect(dummy).toBe(3) set.delete(2) expect(dummy).toBe(1) set.clear() expect(dummy).toBe(0) }) it('should observe forEach iteration', () => { let dummy: any const set = reactive(new Set()) effect(() => { dummy = 0 set.forEach(num => (dummy += num)) }) expect(dummy).toBe(0) set.add(2) set.add(1) expect(dummy).toBe(3) set.delete(2) expect(dummy).toBe(1) set.clear() expect(dummy).toBe(0) }) it('should observe values iteration', () => { let dummy const set = reactive(new Set() as Set<number>) effect(() => { dummy = 0 for (let num of set.values()) { dummy += num } }) expect(dummy).toBe(0) set.add(2) set.add(1) expect(dummy).toBe(3) set.delete(2) expect(dummy).toBe(1) set.clear() expect(dummy).toBe(0) }) it('should observe keys iteration', () => { let dummy const set = reactive(new Set() as Set<number>) effect(() => { dummy = 0 for (let num of set.keys()) { dummy += num } }) expect(dummy).toBe(0) set.add(2) set.add(1) expect(dummy).toBe(3) set.delete(2) expect(dummy).toBe(1) set.clear() expect(dummy).toBe(0) }) it('should observe entries iteration', () => { let dummy const set = reactive(new Set<number>()) effect(() => { dummy = 0 // eslint-disable-next-line no-unused-vars for (let [key, num] of set.entries()) { key dummy += num } }) expect(dummy).toBe(0) set.add(2) set.add(1) expect(dummy).toBe(3) set.delete(2) expect(dummy).toBe(1) set.clear() expect(dummy).toBe(0) }) it('should be triggered by clearing', () => { let dummy const set = reactive(new Set()) effect(() => (dummy = set.has('key'))) expect(dummy).toBe(false) set.add('key') expect(dummy).toBe(true) set.clear() expect(dummy).toBe(false) }) it('should not observe custom property mutations', () => { let dummy const set: any = reactive(new Set()) effect(() => (dummy = set.customProp)) expect(dummy).toBe(undefined) set.customProp = 'Hello World' expect(dummy).toBe(undefined) }) it('should observe size mutations', () => { let dummy const set = reactive(new Set()) effect(() => (dummy = set.size)) expect(dummy).toBe(0) set.add('value') set.add('value2') expect(dummy).toBe(2) set.delete('value') expect(dummy).toBe(1) set.clear() expect(dummy).toBe(0) }) it('should not observe non value changing mutations', () => { let dummy const set = reactive(new Set()) const setSpy = jest.fn(() => (dummy = set.has('value'))) effect(setSpy) expect(dummy).toBe(false) expect(setSpy).toHaveBeenCalledTimes(1) set.add('value') expect(dummy).toBe(true) expect(setSpy).toHaveBeenCalledTimes(2) set.add('value') expect(dummy).toBe(true) expect(setSpy).toHaveBeenCalledTimes(2) set.delete('value') expect(dummy).toBe(false) expect(setSpy).toHaveBeenCalledTimes(3) set.delete('value') expect(dummy).toBe(false) expect(setSpy).toHaveBeenCalledTimes(3) set.clear() expect(dummy).toBe(false) expect(setSpy).toHaveBeenCalledTimes(3) }) it('should not observe raw data', () => { let dummy const set = reactive(new Set()) effect(() => (dummy = toRaw(set).has('value'))) expect(dummy).toBe(false) set.add('value') expect(dummy).toBe(false) }) it('should not observe raw iterations', () => { let dummy = 0 const set = reactive(new Set<number>()) effect(() => { dummy = 0 for (let [num] of toRaw(set).entries()) { dummy += num } for (let num of toRaw(set).keys()) { dummy += num } for (let num of toRaw(set).values()) { dummy += num } toRaw(set).forEach(num => { dummy += num }) for (let num of toRaw(set)) { dummy += num } }) expect(dummy).toBe(0) set.add(2) set.add(3) expect(dummy).toBe(0) set.delete(2) expect(dummy).toBe(0) }) it('should not be triggered by raw mutations', () => { let dummy const set = reactive(new Set()) effect(() => (dummy = set.has('value'))) expect(dummy).toBe(false) toRaw(set).add('value') expect(dummy).toBe(false) dummy = true toRaw(set).delete('value') expect(dummy).toBe(true) toRaw(set).clear() expect(dummy).toBe(true) }) it('should not observe raw size mutations', () => { let dummy const set = reactive(new Set()) effect(() => (dummy = toRaw(set).size)) expect(dummy).toBe(0) set.add('value') expect(dummy).toBe(0) }) it('should not be triggered by raw size mutations', () => { let dummy const set = reactive(new Set()) effect(() => (dummy = set.size)) expect(dummy).toBe(0) toRaw(set).add('value') expect(dummy).toBe(0) }) it('should support objects as key', () => { let dummy const key = {} const set = reactive(new Set()) const setSpy = jest.fn(() => (dummy = set.has(key))) effect(setSpy) expect(dummy).toBe(false) expect(setSpy).toHaveBeenCalledTimes(1) set.add({}) expect(dummy).toBe(false) expect(setSpy).toHaveBeenCalledTimes(1) set.add(key) expect(dummy).toBe(true) expect(setSpy).toHaveBeenCalledTimes(2) }) it('should not pollute original Set with Proxies', () => { const set = new Set() const observed = reactive(set) const value = reactive({}) observed.add(value) expect(observed.has(value)).toBe(true) expect(set.has(value)).toBe(false) }) it('should observe nested values in iterations (forEach)', () => { const set = reactive(new Set([{ foo: 1 }])) let dummy: any effect(() => { dummy = 0 set.forEach(value => { expect(isReactive(value)).toBe(true) dummy += value.foo }) }) expect(dummy).toBe(1) set.forEach(value => { value.foo++ }) expect(dummy).toBe(2) }) it('should observe nested values in iterations (values)', () => { const set = reactive(new Set([{ foo: 1 }])) let dummy: any effect(() => { dummy = 0 for (const value of set.values()) { expect(isReactive(value)).toBe(true) dummy += value.foo } }) expect(dummy).toBe(1) set.forEach(value => { value.foo++ }) expect(dummy).toBe(2) }) it('should observe nested values in iterations (entries)', () => { const set = reactive(new Set([{ foo: 1 }])) let dummy: any effect(() => { dummy = 0 for (const [key, value] of set.entries()) { expect(isReactive(key)).toBe(true) expect(isReactive(value)).toBe(true) dummy += value.foo } }) expect(dummy).toBe(1) set.forEach(value => { value.foo++ }) expect(dummy).toBe(2) }) it('should observe nested values in iterations (for...of)', () => { const set = reactive(new Set([{ foo: 1 }])) let dummy: any effect(() => { dummy = 0 for (const value of set) { expect(isReactive(value)).toBe(true) dummy += value.foo } }) expect(dummy).toBe(1) set.forEach(value => { value.foo++ }) expect(dummy).toBe(2) }) }) })
packages/reactivity/__tests__/collections/Set.spec.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00035192089853808284, 0.0001969887816812843, 0.0001659058325458318, 0.00017829886928666383, 0.00004096644988749176 ]
{ "id": 4, "code_window": [ " // only a whitelist of value types can be observed.\n", " if (!canObserve(target)) {\n", " return target\n", " }\n", " const handlers = __SSR__\n", " ? // disable reactivity in SSR.\n", " // NOTE: a potential caveat here is isReactive check may return different\n", " // values on nested values on client/server. This should be very rare but\n", " // we should keep an eye on this.\n", " EMPTY_OBJ\n", " : collectionTypes.has(target.constructor)\n", " ? collectionHandlers\n", " : baseHandlers\n", " observed = new Proxy(target, handlers)\n", " toProxy.set(target, observed)\n", " toRaw.set(observed, target)\n", " return observed\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const handlers = collectionTypes.has(target.constructor)\n", " ? collectionHandlers\n", " : baseHandlers\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 119 }
import { isObject, toRawType, EMPTY_OBJ } from '@vue/shared' import { mutableHandlers, readonlyHandlers, shallowReadonlyHandlers } from './baseHandlers' import { mutableCollectionHandlers, readonlyCollectionHandlers } from './collectionHandlers' import { UnwrapRef, Ref } from './ref' import { makeMap } from '@vue/shared' // WeakMaps that store {raw <-> observed} pairs. const rawToReactive = new WeakMap<any, any>() const reactiveToRaw = new WeakMap<any, any>() const rawToReadonly = new WeakMap<any, any>() const readonlyToRaw = new WeakMap<any, any>() // WeakSets for values that are marked readonly or non-reactive during // observable creation. const readonlyValues = new WeakSet<any>() const nonReactiveValues = new WeakSet<any>() const collectionTypes = new Set<Function>([Set, Map, WeakMap, WeakSet]) const isObservableType = /*#__PURE__*/ makeMap( 'Object,Array,Map,Set,WeakMap,WeakSet' ) const canObserve = (value: any): boolean => { return ( !value._isVue && !value._isVNode && isObservableType(toRawType(value)) && !nonReactiveValues.has(value) ) } // only unwrap nested ref type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRef<T> export function reactive<T extends object>(target: T): UnwrapNestedRefs<T> export function reactive(target: object) { // if trying to observe a readonly proxy, return the readonly version. if (readonlyToRaw.has(target)) { return target } // target is explicitly marked as readonly by user if (readonlyValues.has(target)) { return readonly(target) } return createReactiveObject( target, rawToReactive, reactiveToRaw, mutableHandlers, mutableCollectionHandlers ) } export function readonly<T extends object>( target: T ): Readonly<UnwrapNestedRefs<T>> { // value is a mutable observable, retrieve its original and return // a readonly version. if (reactiveToRaw.has(target)) { target = reactiveToRaw.get(target) } return createReactiveObject( target, rawToReadonly, readonlyToRaw, readonlyHandlers, readonlyCollectionHandlers ) } // @internal // Return a reactive-copy of the original object, where only the root level // properties are readonly, and does not recursively convert returned properties. // This is used for creating the props proxy object for stateful components. export function shallowReadonly<T extends object>( target: T ): Readonly<{ [K in keyof T]: UnwrapNestedRefs<T[K]> }> { return createReactiveObject( target, rawToReadonly, readonlyToRaw, shallowReadonlyHandlers, readonlyCollectionHandlers ) } function createReactiveObject( target: unknown, toProxy: WeakMap<any, any>, toRaw: WeakMap<any, any>, baseHandlers: ProxyHandler<any>, collectionHandlers: ProxyHandler<any> ) { if (!isObject(target)) { if (__DEV__) { console.warn(`value cannot be made reactive: ${String(target)}`) } return target } // target already has corresponding Proxy let observed = toProxy.get(target) if (observed !== void 0) { return observed } // target is already a Proxy if (toRaw.has(target)) { return target } // only a whitelist of value types can be observed. if (!canObserve(target)) { return target } const handlers = __SSR__ ? // disable reactivity in SSR. // NOTE: a potential caveat here is isReactive check may return different // values on nested values on client/server. This should be very rare but // we should keep an eye on this. EMPTY_OBJ : collectionTypes.has(target.constructor) ? collectionHandlers : baseHandlers observed = new Proxy(target, handlers) toProxy.set(target, observed) toRaw.set(observed, target) return observed } export function isReactive(value: unknown): boolean { return reactiveToRaw.has(value) || readonlyToRaw.has(value) } export function isReadonly(value: unknown): boolean { return readonlyToRaw.has(value) } export function toRaw<T>(observed: T): T { return reactiveToRaw.get(observed) || readonlyToRaw.get(observed) || observed } export function markReadonly<T>(value: T): T { readonlyValues.add(value) return value } export function markNonReactive<T>(value: T): T { nonReactiveValues.add(value) return value }
packages/reactivity/src/reactive.ts
1
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.9981135129928589, 0.12543903291225433, 0.00016076411702670157, 0.0007726782932877541, 0.3294750452041626 ]
{ "id": 4, "code_window": [ " // only a whitelist of value types can be observed.\n", " if (!canObserve(target)) {\n", " return target\n", " }\n", " const handlers = __SSR__\n", " ? // disable reactivity in SSR.\n", " // NOTE: a potential caveat here is isReactive check may return different\n", " // values on nested values on client/server. This should be very rare but\n", " // we should keep an eye on this.\n", " EMPTY_OBJ\n", " : collectionTypes.has(target.constructor)\n", " ? collectionHandlers\n", " : baseHandlers\n", " observed = new Proxy(target, handlers)\n", " toProxy.set(target, observed)\n", " toRaw.set(observed, target)\n", " return observed\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const handlers = collectionTypes.has(target.constructor)\n", " ? collectionHandlers\n", " : baseHandlers\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 119 }
import { ComponentInternalInstance, currentInstance } from './component' import { VNode, NormalizedChildren, normalizeVNode, VNodeChild } from './vnode' import { isArray, isFunction, EMPTY_OBJ } from '@vue/shared' import { ShapeFlags } from './shapeFlags' import { warn } from './warning' import { isKeepAlive } from './components/KeepAlive' export type Slot = (...args: any[]) => VNode[] export type InternalSlots = { [name: string]: Slot } export type Slots = Readonly<InternalSlots> export type RawSlots = { [name: string]: unknown // manual render fn hint to skip forced children updates $stable?: boolean // internal, indicates compiler generated slots = can skip normalization _compiled?: boolean } const normalizeSlotValue = (value: unknown): VNode[] => isArray(value) ? value.map(normalizeVNode) : [normalizeVNode(value as VNodeChild)] const normalizeSlot = (key: string, rawSlot: Function): Slot => ( props: any ) => { if (__DEV__ && currentInstance != null) { warn( `Slot "${key}" invoked outside of the render function: ` + `this will not track dependencies used in the slot. ` + `Invoke the slot function inside the render function instead.` ) } return normalizeSlotValue(rawSlot(props)) } export function resolveSlots( instance: ComponentInternalInstance, children: NormalizedChildren ) { let slots: InternalSlots | void if (instance.vnode.shapeFlag & ShapeFlags.SLOTS_CHILDREN) { const rawSlots = children as RawSlots if (rawSlots._compiled) { // pre-normalized slots object generated by compiler slots = children as Slots } else { slots = {} for (const key in rawSlots) { if (key === '$stable') continue const value = rawSlots[key] if (isFunction(value)) { slots[key] = normalizeSlot(key, value) } else if (value != null) { if (__DEV__) { warn( `Non-function value encountered for slot "${key}". ` + `Prefer function slots for better performance.` ) } const normalized = normalizeSlotValue(value) slots[key] = () => normalized } } } } else if (children !== null) { // non slot object children (direct value) passed to a component if (__DEV__ && !isKeepAlive(instance.vnode)) { warn( `Non-function value encountered for default slot. ` + `Prefer function slots for better performance.` ) } const normalized = normalizeSlotValue(children) slots = { default: () => normalized } } instance.slots = slots || EMPTY_OBJ }
packages/runtime-core/src/componentSlots.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00019756329129450023, 0.0001719236752251163, 0.00016532250447198749, 0.00016864712233655155, 0.000009509808478469495 ]
{ "id": 4, "code_window": [ " // only a whitelist of value types can be observed.\n", " if (!canObserve(target)) {\n", " return target\n", " }\n", " const handlers = __SSR__\n", " ? // disable reactivity in SSR.\n", " // NOTE: a potential caveat here is isReactive check may return different\n", " // values on nested values on client/server. This should be very rare but\n", " // we should keep an eye on this.\n", " EMPTY_OBJ\n", " : collectionTypes.has(target.constructor)\n", " ? collectionHandlers\n", " : baseHandlers\n", " observed = new Proxy(target, handlers)\n", " toProxy.set(target, observed)\n", " toRaw.set(observed, target)\n", " return observed\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const handlers = collectionTypes.has(target.constructor)\n", " ? collectionHandlers\n", " : baseHandlers\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 119 }
# @vue/compiler-core
packages/compiler-core/README.md
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.000163739881827496, 0.000163739881827496, 0.000163739881827496, 0.000163739881827496, 0 ]
{ "id": 4, "code_window": [ " // only a whitelist of value types can be observed.\n", " if (!canObserve(target)) {\n", " return target\n", " }\n", " const handlers = __SSR__\n", " ? // disable reactivity in SSR.\n", " // NOTE: a potential caveat here is isReactive check may return different\n", " // values on nested values on client/server. This should be very rare but\n", " // we should keep an eye on this.\n", " EMPTY_OBJ\n", " : collectionTypes.has(target.constructor)\n", " ? collectionHandlers\n", " : baseHandlers\n", " observed = new Proxy(target, handlers)\n", " toProxy.set(target, observed)\n", " toRaw.set(observed, target)\n", " return observed\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const handlers = collectionTypes.has(target.constructor)\n", " ? collectionHandlers\n", " : baseHandlers\n" ], "file_path": "packages/reactivity/src/reactive.ts", "type": "replace", "edit_start_line_idx": 119 }
import { makeMap } from './makeMap' const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' + 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' + 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl' export const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED)
packages/shared/src/globalsWhitelist.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.003276949981227517, 0.003276949981227517, 0.003276949981227517, 0.003276949981227517, 0 ]
{ "id": 5, "code_window": [ " return value\n", " }\n", " value = convert(value)\n", "\n", " if (__SSR__) {\n", " return {\n", " _isRef: true,\n", " value\n", " }\n", " }\n", "\n", " const r = {\n", " _isRef: true,\n", " get value() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 38 }
import { isObject, toRawType, EMPTY_OBJ } from '@vue/shared' import { mutableHandlers, readonlyHandlers, shallowReadonlyHandlers } from './baseHandlers' import { mutableCollectionHandlers, readonlyCollectionHandlers } from './collectionHandlers' import { UnwrapRef, Ref } from './ref' import { makeMap } from '@vue/shared' // WeakMaps that store {raw <-> observed} pairs. const rawToReactive = new WeakMap<any, any>() const reactiveToRaw = new WeakMap<any, any>() const rawToReadonly = new WeakMap<any, any>() const readonlyToRaw = new WeakMap<any, any>() // WeakSets for values that are marked readonly or non-reactive during // observable creation. const readonlyValues = new WeakSet<any>() const nonReactiveValues = new WeakSet<any>() const collectionTypes = new Set<Function>([Set, Map, WeakMap, WeakSet]) const isObservableType = /*#__PURE__*/ makeMap( 'Object,Array,Map,Set,WeakMap,WeakSet' ) const canObserve = (value: any): boolean => { return ( !value._isVue && !value._isVNode && isObservableType(toRawType(value)) && !nonReactiveValues.has(value) ) } // only unwrap nested ref type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRef<T> export function reactive<T extends object>(target: T): UnwrapNestedRefs<T> export function reactive(target: object) { // if trying to observe a readonly proxy, return the readonly version. if (readonlyToRaw.has(target)) { return target } // target is explicitly marked as readonly by user if (readonlyValues.has(target)) { return readonly(target) } return createReactiveObject( target, rawToReactive, reactiveToRaw, mutableHandlers, mutableCollectionHandlers ) } export function readonly<T extends object>( target: T ): Readonly<UnwrapNestedRefs<T>> { // value is a mutable observable, retrieve its original and return // a readonly version. if (reactiveToRaw.has(target)) { target = reactiveToRaw.get(target) } return createReactiveObject( target, rawToReadonly, readonlyToRaw, readonlyHandlers, readonlyCollectionHandlers ) } // @internal // Return a reactive-copy of the original object, where only the root level // properties are readonly, and does not recursively convert returned properties. // This is used for creating the props proxy object for stateful components. export function shallowReadonly<T extends object>( target: T ): Readonly<{ [K in keyof T]: UnwrapNestedRefs<T[K]> }> { return createReactiveObject( target, rawToReadonly, readonlyToRaw, shallowReadonlyHandlers, readonlyCollectionHandlers ) } function createReactiveObject( target: unknown, toProxy: WeakMap<any, any>, toRaw: WeakMap<any, any>, baseHandlers: ProxyHandler<any>, collectionHandlers: ProxyHandler<any> ) { if (!isObject(target)) { if (__DEV__) { console.warn(`value cannot be made reactive: ${String(target)}`) } return target } // target already has corresponding Proxy let observed = toProxy.get(target) if (observed !== void 0) { return observed } // target is already a Proxy if (toRaw.has(target)) { return target } // only a whitelist of value types can be observed. if (!canObserve(target)) { return target } const handlers = __SSR__ ? // disable reactivity in SSR. // NOTE: a potential caveat here is isReactive check may return different // values on nested values on client/server. This should be very rare but // we should keep an eye on this. EMPTY_OBJ : collectionTypes.has(target.constructor) ? collectionHandlers : baseHandlers observed = new Proxy(target, handlers) toProxy.set(target, observed) toRaw.set(observed, target) return observed } export function isReactive(value: unknown): boolean { return reactiveToRaw.has(value) || readonlyToRaw.has(value) } export function isReadonly(value: unknown): boolean { return readonlyToRaw.has(value) } export function toRaw<T>(observed: T): T { return reactiveToRaw.get(observed) || readonlyToRaw.get(observed) || observed } export function markReadonly<T>(value: T): T { readonlyValues.add(value) return value } export function markNonReactive<T>(value: T): T { nonReactiveValues.add(value) return value }
packages/reactivity/src/reactive.ts
1
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.014000077731907368, 0.001106634153984487, 0.0001612899941392243, 0.0001710865180939436, 0.00333424168638885 ]
{ "id": 5, "code_window": [ " return value\n", " }\n", " value = convert(value)\n", "\n", " if (__SSR__) {\n", " return {\n", " _isRef: true,\n", " value\n", " }\n", " }\n", "\n", " const r = {\n", " _isRef: true,\n", " get value() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 38 }
import { TransformOptions } from './options' import { RootNode, NodeTypes, ParentNode, TemplateChildNode, ElementNode, DirectiveNode, Property, ExpressionNode, createSimpleExpression, JSChildNode, SimpleExpressionNode, ElementTypes, ElementCodegenNode, ComponentCodegenNode, createCallExpression, CacheExpression, createCacheExpression } from './ast' import { isString, isArray, NOOP, PatchFlags, PatchFlagNames } from '@vue/shared' import { defaultOnError } from './errors' import { TO_DISPLAY_STRING, FRAGMENT, helperNameMap, WITH_DIRECTIVES, CREATE_BLOCK, CREATE_COMMENT } from './runtimeHelpers' import { isVSlot, createBlockExpression } from './utils' import { hoistStatic, isSingleElementRoot } from './transforms/hoistStatic' // There are two types of transforms: // // - NodeTransform: // Transforms that operate directly on a ChildNode. NodeTransforms may mutate, // replace or remove the node being processed. export type NodeTransform = ( node: RootNode | TemplateChildNode, context: TransformContext ) => void | (() => void) | (() => void)[] // - DirectiveTransform: // Transforms that handles a single directive attribute on an element. // It translates the raw directive into actual props for the VNode. export type DirectiveTransform = ( dir: DirectiveNode, node: ElementNode, context: TransformContext, // a platform specific compiler can import the base transform and augment // it by passing in this optional argument. augmentor?: (ret: DirectiveTransformResult) => DirectiveTransformResult ) => DirectiveTransformResult export interface DirectiveTransformResult { props: Property[] needRuntime: boolean | symbol } // A structural directive transform is a technically a NodeTransform; // Only v-if and v-for fall into this category. export type StructuralDirectiveTransform = ( node: ElementNode, dir: DirectiveNode, context: TransformContext ) => void | (() => void) export interface ImportItem { exp: string | ExpressionNode path: string } export interface TransformContext extends Required<TransformOptions> { root: RootNode helpers: Set<symbol> components: Set<string> directives: Set<string> hoists: JSChildNode[] imports: Set<ImportItem> cached: number identifiers: { [name: string]: number | undefined } scopes: { vFor: number vSlot: number vPre: number vOnce: number } parent: ParentNode | null childIndex: number currentNode: RootNode | TemplateChildNode | null helper<T extends symbol>(name: T): T helperString(name: symbol): string replaceNode(node: TemplateChildNode): void removeNode(node?: TemplateChildNode): void onNodeRemoved(): void addIdentifiers(exp: ExpressionNode | string): void removeIdentifiers(exp: ExpressionNode | string): void hoist(exp: JSChildNode): SimpleExpressionNode cache<T extends JSChildNode>(exp: T, isVNode?: boolean): CacheExpression | T } function createTransformContext( root: RootNode, { prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, isBuiltInComponent = NOOP, onError = defaultOnError }: TransformOptions ): TransformContext { const context: TransformContext = { // options prefixIdentifiers, hoistStatic, cacheHandlers, nodeTransforms, directiveTransforms, isBuiltInComponent, onError, // state root, helpers: new Set(), components: new Set(), directives: new Set(), hoists: [], imports: new Set(), cached: 0, identifiers: {}, scopes: { vFor: 0, vSlot: 0, vPre: 0, vOnce: 0 }, parent: null, currentNode: root, childIndex: 0, // methods helper(name) { context.helpers.add(name) return name }, helperString(name) { return ( (context.prefixIdentifiers ? `` : `_`) + helperNameMap[context.helper(name)] ) }, replaceNode(node) { /* istanbul ignore if */ if (__DEV__) { if (!context.currentNode) { throw new Error(`Node being replaced is already removed.`) } if (!context.parent) { throw new Error(`Cannot replace root node.`) } } context.parent!.children[context.childIndex] = context.currentNode = node }, removeNode(node) { if (__DEV__ && !context.parent) { throw new Error(`Cannot remove root node.`) } const list = context.parent!.children const removalIndex = node ? list.indexOf(node) : context.currentNode ? context.childIndex : -1 /* istanbul ignore if */ if (__DEV__ && removalIndex < 0) { throw new Error(`node being removed is not a child of current parent`) } if (!node || node === context.currentNode) { // current node removed context.currentNode = null context.onNodeRemoved() } else { // sibling node removed if (context.childIndex > removalIndex) { context.childIndex-- context.onNodeRemoved() } } context.parent!.children.splice(removalIndex, 1) }, onNodeRemoved: () => {}, addIdentifiers(exp) { // identifier tracking only happens in non-browser builds. if (!__BROWSER__) { if (isString(exp)) { addId(exp) } else if (exp.identifiers) { exp.identifiers.forEach(addId) } else if (exp.type === NodeTypes.SIMPLE_EXPRESSION) { addId(exp.content) } } }, removeIdentifiers(exp) { if (!__BROWSER__) { if (isString(exp)) { removeId(exp) } else if (exp.identifiers) { exp.identifiers.forEach(removeId) } else if (exp.type === NodeTypes.SIMPLE_EXPRESSION) { removeId(exp.content) } } }, hoist(exp) { context.hoists.push(exp) return createSimpleExpression( `_hoisted_${context.hoists.length}`, false, exp.loc, true ) }, cache(exp, isVNode = false) { return createCacheExpression(++context.cached, exp, isVNode) } } function addId(id: string) { const { identifiers } = context if (identifiers[id] === undefined) { identifiers[id] = 0 } identifiers[id]!++ } function removeId(id: string) { context.identifiers[id]!-- } return context } export function transform(root: RootNode, options: TransformOptions) { const context = createTransformContext(root, options) traverseNode(root, context) if (options.hoistStatic) { hoistStatic(root, context) } finalizeRoot(root, context) } function finalizeRoot(root: RootNode, context: TransformContext) { const { helper } = context const { children } = root const child = children[0] if (children.length === 1) { // if the single child is an element, turn it into a block. if (isSingleElementRoot(root, child) && child.codegenNode) { // single element root is never hoisted so codegenNode will never be // SimpleExpressionNode const codegenNode = child.codegenNode as | ElementCodegenNode | ComponentCodegenNode | CacheExpression if (codegenNode.type !== NodeTypes.JS_CACHE_EXPRESSION) { if (codegenNode.callee === WITH_DIRECTIVES) { codegenNode.arguments[0].callee = helper(CREATE_BLOCK) } else { codegenNode.callee = helper(CREATE_BLOCK) } root.codegenNode = createBlockExpression(codegenNode, context) } else { root.codegenNode = codegenNode } } else { // - single <slot/>, IfNode, ForNode: already blocks. // - single text node: always patched. // root codegen falls through via genNode() root.codegenNode = child } } else if (children.length > 1) { // root has multiple nodes - return a fragment block. root.codegenNode = createBlockExpression( createCallExpression(helper(CREATE_BLOCK), [ helper(FRAGMENT), `null`, root.children, `${PatchFlags.STABLE_FRAGMENT} /* ${ PatchFlagNames[PatchFlags.STABLE_FRAGMENT] } */` ]), context ) } else { // no children = noop. codegen will return null. } // finalize meta information root.helpers = [...context.helpers] root.components = [...context.components] root.directives = [...context.directives] root.imports = [...context.imports] root.hoists = context.hoists root.cached = context.cached } export function traverseChildren( parent: ParentNode, context: TransformContext ) { let i = 0 const nodeRemoved = () => { i-- } for (; i < parent.children.length; i++) { const child = parent.children[i] if (isString(child)) continue context.currentNode = child context.parent = parent context.childIndex = i context.onNodeRemoved = nodeRemoved traverseNode(child, context) } } export function traverseNode( node: RootNode | TemplateChildNode, context: TransformContext ) { // apply transform plugins const { nodeTransforms } = context const exitFns = [] for (let i = 0; i < nodeTransforms.length; i++) { const onExit = nodeTransforms[i](node, context) if (onExit) { if (isArray(onExit)) { exitFns.push(...onExit) } else { exitFns.push(onExit) } } if (!context.currentNode) { // node was removed return } else { // node may have been replaced node = context.currentNode } } switch (node.type) { case NodeTypes.COMMENT: // inject import for the Comment symbol, which is needed for creating // comment nodes with `createVNode` context.helper(CREATE_COMMENT) break case NodeTypes.INTERPOLATION: // no need to traverse, but we need to inject toString helper context.helper(TO_DISPLAY_STRING) break // for container types, further traverse downwards case NodeTypes.IF: for (let i = 0; i < node.branches.length; i++) { traverseChildren(node.branches[i], context) } break case NodeTypes.FOR: case NodeTypes.ELEMENT: case NodeTypes.ROOT: traverseChildren(node, context) break } // exit transforms let i = exitFns.length while (i--) { exitFns[i]() } } export function createStructuralDirectiveTransform( name: string | RegExp, fn: StructuralDirectiveTransform ): NodeTransform { const matches = isString(name) ? (n: string) => n === name : (n: string) => name.test(n) return (node, context) => { if (node.type === NodeTypes.ELEMENT) { const { props } = node // structural directive transforms are not concerned with slots // as they are handled separately in vSlot.ts if (node.tagType === ElementTypes.TEMPLATE && props.some(isVSlot)) { return } const exitFns = [] for (let i = 0; i < props.length; i++) { const prop = props[i] if (prop.type === NodeTypes.DIRECTIVE && matches(prop.name)) { // structural directives are removed to avoid infinite recursion // also we remove them *before* applying so that it can further // traverse itself in case it moves the node around props.splice(i, 1) i-- const onExit = fn(node, prop, context) if (onExit) exitFns.push(onExit) } } return exitFns } } }
packages/compiler-core/src/transform.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00021598853345494717, 0.0001725439797155559, 0.00016433611745014787, 0.0001721225999062881, 0.0000071653203121968545 ]
{ "id": 5, "code_window": [ " return value\n", " }\n", " value = convert(value)\n", "\n", " if (__SSR__) {\n", " return {\n", " _isRef: true,\n", " value\n", " }\n", " }\n", "\n", " const r = {\n", " _isRef: true,\n", " get value() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 38 }
// this the shared base config for all packages. { "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", "apiReport": { "enabled": true, "reportFolder": "<projectFolder>/temp/" }, "docModel": { "enabled": true }, "dtsRollup": { "enabled": true }, "tsdocMetadata": { "enabled": false }, "messages": { "compilerMessageReporting": { "default": { "logLevel": "warning" } }, "extractorMessageReporting": { "default": { "logLevel": "warning", "addToApiReportFile": true }, "ae-missing-release-tag": { "logLevel": "none" } }, "tsdocMessageReporting": { "default": { "logLevel": "warning" } } } }
api-extractor.json
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00017276864673476666, 0.00017246458446606994, 0.0001715136313578114, 0.00017270637908950448, 4.784973270943738e-7 ]
{ "id": 5, "code_window": [ " return value\n", " }\n", " value = convert(value)\n", "\n", " if (__SSR__) {\n", " return {\n", " _isRef: true,\n", " value\n", " }\n", " }\n", "\n", " const r = {\n", " _isRef: true,\n", " get value() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 38 }
import { getCurrentInstance } from '../component' import { EMPTY_OBJ } from '@vue/shared' import { warn } from '../warning' export function useCSSModule(name = '$style'): Record<string, string> { const instance = getCurrentInstance()! if (!instance) { __DEV__ && warn(`useCSSModule must be called inside setup()`) return EMPTY_OBJ } const modules = instance.type.__cssModules if (!modules) { __DEV__ && warn(`Current instance does not have CSS modules injected.`) return EMPTY_OBJ } const mod = modules[name] if (!mod) { __DEV__ && warn(`Current instance does not have CSS module named "${name}".`) return EMPTY_OBJ } return mod as Record<string, string> }
packages/runtime-core/src/helpers/useCssModule.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00016704796871636063, 0.00016575411427766085, 0.00016336573753505945, 0.00016684866568539292, 0.0000016908030602280633 ]
{ "id": 6, "code_window": [ "\n", "export function toRefs<T extends object>(\n", " object: T\n", "): { [K in keyof T]: Ref<T[K]> } {\n", " if (__DEV__ && !__SSR__ && !isReactive(object)) {\n", " console.warn(`toRefs() expects a reactive object but received a plain one.`)\n", " }\n", " const ret: any = {}\n", " for (const key in object) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (__DEV__ && !isReactive(object)) {\n" ], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 68 }
import { track, trigger } from './effect' import { TrackOpTypes, TriggerOpTypes } from './operations' import { isObject } from '@vue/shared' import { reactive, isReactive } from './reactive' import { ComputedRef } from './computed' import { CollectionTypes } from './collectionHandlers' const isRefSymbol = Symbol() export interface Ref<T = any> { // This field is necessary to allow TS to differentiate a Ref from a plain // object that happens to have a "value" field. // However, checking a symbol on an arbitrary object is much slower than // checking a plain property, so we use a _isRef plain property for isRef() // check in the actual implementation. // The reason for not just declaring _isRef in the interface is because we // don't want this internal field to leak into userland autocompletion - // a private symbol, on the other hand, achieves just that. [isRefSymbol]: true value: UnwrapRef<T> } const convert = <T extends unknown>(val: T): T => isObject(val) ? reactive(val) : val export function isRef<T>(r: Ref<T> | T): r is Ref<T> export function isRef(r: any): r is Ref { return r ? r._isRef === true : false } export function ref<T extends Ref>(value: T): T export function ref<T>(value: T): Ref<T> export function ref<T = any>(): Ref<T> export function ref(value?: unknown) { if (isRef(value)) { return value } value = convert(value) if (__SSR__) { return { _isRef: true, value } } const r = { _isRef: true, get value() { track(r, TrackOpTypes.GET, 'value') return value }, set value(newVal) { value = convert(newVal) trigger( r, TriggerOpTypes.SET, 'value', __DEV__ ? { newValue: newVal } : void 0 ) } } return r } export function toRefs<T extends object>( object: T ): { [K in keyof T]: Ref<T[K]> } { if (__DEV__ && !__SSR__ && !isReactive(object)) { console.warn(`toRefs() expects a reactive object but received a plain one.`) } const ret: any = {} for (const key in object) { ret[key] = toProxyRef(object, key) } return ret } function toProxyRef<T extends object, K extends keyof T>( object: T, key: K ): Ref<T[K]> { return { _isRef: true, get value(): any { return object[key] }, set value(newVal) { object[key] = newVal } } as any } type UnwrapArray<T> = { [P in keyof T]: UnwrapRef<T[P]> } // corner case when use narrows type // Ex. type RelativePath = string & { __brand: unknown } // RelativePath extends object -> true type BaseTypes = string | number | boolean // Recursively unwraps nested value bindings. export type UnwrapRef<T> = { cRef: T extends ComputedRef<infer V> ? UnwrapRef<V> : T ref: T extends Ref<infer V> ? UnwrapRef<V> : T array: T extends Array<infer V> ? Array<UnwrapRef<V>> & UnwrapArray<T> : T object: { [K in keyof T]: UnwrapRef<T[K]> } }[T extends ComputedRef<any> ? 'cRef' : T extends Array<any> ? 'array' : T extends Ref | Function | CollectionTypes | BaseTypes ? 'ref' // bail out on types that shouldn't be unwrapped : T extends object ? 'object' : 'ref']
packages/reactivity/src/ref.ts
1
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.9967845678329468, 0.25433021783828735, 0.00016815417620819062, 0.011073262430727482, 0.4245682954788208 ]
{ "id": 6, "code_window": [ "\n", "export function toRefs<T extends object>(\n", " object: T\n", "): { [K in keyof T]: Ref<T[K]> } {\n", " if (__DEV__ && !__SSR__ && !isReactive(object)) {\n", " console.warn(`toRefs() expects a reactive object but received a plain one.`)\n", " }\n", " const ret: any = {}\n", " for (const key in object) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (__DEV__ && !isReactive(object)) {\n" ], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 68 }
import { DirectiveTransform } from 'packages/compiler-core/src/transform' export const transformCloak: DirectiveTransform = (node, context) => { return { props: [], needRuntime: false } }
packages/compiler-dom/src/transforms/vCloak.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.00017342089267913252, 0.00017342089267913252, 0.00017342089267913252, 0.00017342089267913252, 0 ]
{ "id": 6, "code_window": [ "\n", "export function toRefs<T extends object>(\n", " object: T\n", "): { [K in keyof T]: Ref<T[K]> } {\n", " if (__DEV__ && !__SSR__ && !isReactive(object)) {\n", " console.warn(`toRefs() expects a reactive object but received a plain one.`)\n", " }\n", " const ret: any = {}\n", " for (const key in object) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (__DEV__ && !isReactive(object)) {\n" ], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 68 }
import { queueJob, nextTick, queuePostFlushCb } from '../src/scheduler' describe('scheduler', () => { it('nextTick', async () => { const calls: string[] = [] const dummyThen = Promise.resolve().then() const job1 = () => { calls.push('job1') } const job2 = () => { calls.push('job2') } nextTick(job1) job2() expect(calls.length).toBe(1) await dummyThen // job1 will be pushed in nextTick expect(calls.length).toBe(2) expect(calls).toMatchObject(['job2', 'job1']) }) describe('queueJob', () => { it('basic usage', async () => { const calls: string[] = [] const job1 = () => { calls.push('job1') } const job2 = () => { calls.push('job2') } queueJob(job1) queueJob(job2) expect(calls).toEqual([]) await nextTick() expect(calls).toEqual(['job1', 'job2']) }) it('should dedupe queued jobs', async () => { const calls: string[] = [] const job1 = () => { calls.push('job1') } const job2 = () => { calls.push('job2') } queueJob(job1) queueJob(job2) queueJob(job1) queueJob(job2) expect(calls).toEqual([]) await nextTick() expect(calls).toEqual(['job1', 'job2']) }) it('queueJob while flushing', async () => { const calls: string[] = [] const job1 = () => { calls.push('job1') // job2 will be excuted after job1 at the same tick queueJob(job2) } const job2 = () => { calls.push('job2') } queueJob(job1) await nextTick() expect(calls).toEqual(['job1', 'job2']) }) }) describe('queuePostFlushCb', () => { it('basic usage', async () => { const calls: string[] = [] const cb1 = () => { calls.push('cb1') } const cb2 = () => { calls.push('cb2') } const cb3 = () => { calls.push('cb3') } queuePostFlushCb([cb1, cb2]) queuePostFlushCb(cb3) expect(calls).toEqual([]) await nextTick() expect(calls).toEqual(['cb1', 'cb2', 'cb3']) }) it('should dedupe queued postFlushCb', async () => { const calls: string[] = [] const cb1 = () => { calls.push('cb1') } const cb2 = () => { calls.push('cb2') } const cb3 = () => { calls.push('cb3') } queuePostFlushCb([cb1, cb2]) queuePostFlushCb(cb3) queuePostFlushCb([cb1, cb3]) queuePostFlushCb(cb2) expect(calls).toEqual([]) await nextTick() expect(calls).toEqual(['cb1', 'cb2', 'cb3']) }) it('queuePostFlushCb while flushing', async () => { const calls: string[] = [] const cb1 = () => { calls.push('cb1') // cb2 will be excuted after cb1 at the same tick queuePostFlushCb(cb2) } const cb2 = () => { calls.push('cb2') } queuePostFlushCb(cb1) await nextTick() expect(calls).toEqual(['cb1', 'cb2']) }) }) describe('queueJob w/ queuePostFlushCb', () => { it('queueJob inside postFlushCb', async () => { const calls: string[] = [] const job1 = () => { calls.push('job1') } const cb1 = () => { // queueJob in postFlushCb calls.push('cb1') queueJob(job1) } queuePostFlushCb(cb1) await nextTick() expect(calls).toEqual(['cb1', 'job1']) }) it('queueJob & postFlushCb inside postFlushCb', async () => { const calls: string[] = [] const job1 = () => { calls.push('job1') } const cb1 = () => { calls.push('cb1') queuePostFlushCb(cb2) // job1 will executed before cb2 // Job has higher priority than postFlushCb queueJob(job1) } const cb2 = () => { calls.push('cb2') } queuePostFlushCb(cb1) await nextTick() expect(calls).toEqual(['cb1', 'job1', 'cb2']) }) it('postFlushCb inside queueJob', async () => { const calls: string[] = [] const job1 = () => { calls.push('job1') // postFlushCb in queueJob queuePostFlushCb(cb1) } const cb1 = () => { calls.push('cb1') } queueJob(job1) await nextTick() expect(calls).toEqual(['job1', 'cb1']) }) it('queueJob & postFlushCb inside queueJob', async () => { const calls: string[] = [] const job1 = () => { calls.push('job1') // cb1 will executed after job2 // Job has higher priority than postFlushCb queuePostFlushCb(cb1) queueJob(job2) } const job2 = () => { calls.push('job2') } const cb1 = () => { calls.push('cb1') } queueJob(job1) await nextTick() expect(calls).toEqual(['job1', 'job2', 'cb1']) }) it('nested queueJob w/ postFlushCb', async () => { const calls: string[] = [] const job1 = () => { calls.push('job1') queuePostFlushCb(cb1) queueJob(job2) } const job2 = () => { calls.push('job2') queuePostFlushCb(cb2) } const cb1 = () => { calls.push('cb1') } const cb2 = () => { calls.push('cb2') } queueJob(job1) await nextTick() expect(calls).toEqual(['job1', 'job2', 'cb1', 'cb2']) }) }) })
packages/runtime-core/__tests__/scheduler.spec.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.0001752241951180622, 0.00017275259597226977, 0.0001689382770564407, 0.0001729553914628923, 0.0000016394111526096822 ]
{ "id": 6, "code_window": [ "\n", "export function toRefs<T extends object>(\n", " object: T\n", "): { [K in keyof T]: Ref<T[K]> } {\n", " if (__DEV__ && !__SSR__ && !isReactive(object)) {\n", " console.warn(`toRefs() expects a reactive object but received a plain one.`)\n", " }\n", " const ret: any = {}\n", " for (const key in object) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (__DEV__ && !isReactive(object)) {\n" ], "file_path": "packages/reactivity/src/ref.ts", "type": "replace", "edit_start_line_idx": 68 }
// reference: https://github.com/vuejs/vue/blob/dev/test/unit/modules/vdom/patch/children.spec.js import { h, render, nodeOps, NodeTypes, TestElement, serialize, serializeInner } from '@vue/runtime-test' import { mockWarn } from '@vue/shared' mockWarn() function toSpan(content: any) { if (typeof content === 'string') { return h('span', content.toString()) } else { return h('span', { key: content }, content.toString()) } } const inner = (c: TestElement) => serializeInner(c) function shuffle(array: Array<any>) { let currentIndex = array.length let temporaryValue let randomIndex // while there remain elements to shuffle... while (currentIndex !== 0) { // pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex) currentIndex -= 1 // and swap it with the current element. temporaryValue = array[currentIndex] array[currentIndex] = array[randomIndex] array[randomIndex] = temporaryValue } return array } it('should patch previously empty children', () => { const root = nodeOps.createElement('div') render(h('div', []), root) expect(inner(root)).toBe('<div></div>') render(h('div', ['hello']), root) expect(inner(root)).toBe('<div>hello</div>') }) it('should patch previously null children', () => { const root = nodeOps.createElement('div') render(h('div'), root) expect(inner(root)).toBe('<div></div>') render(h('div', ['hello']), root) expect(inner(root)).toBe('<div>hello</div>') }) describe('renderer: keyed children', () => { let root: TestElement let elm: TestElement const renderChildren = (arr: number[]) => { render(h('div', arr.map(toSpan)), root) return root.children[0] as TestElement } beforeEach(() => { root = nodeOps.createElement('div') render(h('div', { id: 1 }, 'hello'), root) }) test('append', () => { elm = renderChildren([1]) expect(elm.children.length).toBe(1) elm = renderChildren([1, 2, 3]) expect(elm.children.length).toBe(3) expect(serialize(elm.children[1])).toBe('<span>2</span>') expect(serialize(elm.children[2])).toBe('<span>3</span>') }) test('prepend', () => { elm = renderChildren([4, 5]) expect(elm.children.length).toBe(2) elm = renderChildren([1, 2, 3, 4, 5]) expect(elm.children.length).toBe(5) expect((elm.children as TestElement[]).map(inner)).toEqual([ '1', '2', '3', '4', '5' ]) }) test('insert in middle', () => { elm = renderChildren([1, 2, 4, 5]) expect(elm.children.length).toBe(4) elm = renderChildren([1, 2, 3, 4, 5]) expect(elm.children.length).toBe(5) expect((elm.children as TestElement[]).map(inner)).toEqual([ '1', '2', '3', '4', '5' ]) }) test('insert at beginning and end', () => { elm = renderChildren([2, 3, 4]) expect(elm.children.length).toBe(3) elm = renderChildren([1, 2, 3, 4, 5]) expect(elm.children.length).toBe(5) expect((elm.children as TestElement[]).map(inner)).toEqual([ '1', '2', '3', '4', '5' ]) }) test('insert to empty parent', () => { elm = renderChildren([]) expect(elm.children.length).toBe(0) elm = renderChildren([1, 2, 3, 4, 5]) expect(elm.children.length).toBe(5) expect((elm.children as TestElement[]).map(inner)).toEqual([ '1', '2', '3', '4', '5' ]) }) test('remove all children from parent', () => { elm = renderChildren([1, 2, 3, 4, 5]) expect(elm.children.length).toBe(5) expect((elm.children as TestElement[]).map(inner)).toEqual([ '1', '2', '3', '4', '5' ]) render(h('div'), root) expect(elm.children.length).toBe(0) }) test('remove from beginning', () => { elm = renderChildren([1, 2, 3, 4, 5]) expect(elm.children.length).toBe(5) elm = renderChildren([3, 4, 5]) expect(elm.children.length).toBe(3) expect((elm.children as TestElement[]).map(inner)).toEqual(['3', '4', '5']) }) test('remove from end', () => { elm = renderChildren([1, 2, 3, 4, 5]) expect(elm.children.length).toBe(5) elm = renderChildren([1, 2, 3]) expect(elm.children.length).toBe(3) expect((elm.children as TestElement[]).map(inner)).toEqual(['1', '2', '3']) }) test('remove from middle', () => { elm = renderChildren([1, 2, 3, 4, 5]) expect(elm.children.length).toBe(5) elm = renderChildren([1, 2, 4, 5]) expect(elm.children.length).toBe(4) expect((elm.children as TestElement[]).map(inner)).toEqual([ '1', '2', '4', '5' ]) }) test('moving single child forward', () => { elm = renderChildren([1, 2, 3, 4]) expect(elm.children.length).toBe(4) elm = renderChildren([2, 3, 1, 4]) expect(elm.children.length).toBe(4) expect((elm.children as TestElement[]).map(inner)).toEqual([ '2', '3', '1', '4' ]) }) test('moving single child backwards', () => { elm = renderChildren([1, 2, 3, 4]) expect(elm.children.length).toBe(4) elm = renderChildren([1, 4, 2, 3]) expect(elm.children.length).toBe(4) expect((elm.children as TestElement[]).map(inner)).toEqual([ '1', '4', '2', '3' ]) }) test('moving single child to end', () => { elm = renderChildren([1, 2, 3]) expect(elm.children.length).toBe(3) elm = renderChildren([2, 3, 1]) expect(elm.children.length).toBe(3) expect((elm.children as TestElement[]).map(inner)).toEqual(['2', '3', '1']) }) test('swap first and last', () => { elm = renderChildren([1, 2, 3, 4]) expect(elm.children.length).toBe(4) elm = renderChildren([4, 2, 3, 1]) expect(elm.children.length).toBe(4) expect((elm.children as TestElement[]).map(inner)).toEqual([ '4', '2', '3', '1' ]) }) test('move to left & replace', () => { elm = renderChildren([1, 2, 3, 4, 5]) expect(elm.children.length).toBe(5) elm = renderChildren([4, 1, 2, 3, 6]) expect(elm.children.length).toBe(5) expect((elm.children as TestElement[]).map(inner)).toEqual([ '4', '1', '2', '3', '6' ]) }) test('move to left and leaves hold', () => { elm = renderChildren([1, 4, 5]) expect(elm.children.length).toBe(3) elm = renderChildren([4, 6]) expect((elm.children as TestElement[]).map(inner)).toEqual(['4', '6']) }) test('moved and set to undefined element ending at the end', () => { elm = renderChildren([2, 4, 5]) expect(elm.children.length).toBe(3) elm = renderChildren([4, 5, 3]) expect(elm.children.length).toBe(3) expect((elm.children as TestElement[]).map(inner)).toEqual(['4', '5', '3']) }) test('reverse element', () => { elm = renderChildren([1, 2, 3, 4, 5, 6, 7, 8]) expect(elm.children.length).toBe(8) elm = renderChildren([8, 7, 6, 5, 4, 3, 2, 1]) expect((elm.children as TestElement[]).map(inner)).toEqual([ '8', '7', '6', '5', '4', '3', '2', '1' ]) }) test('something', () => { elm = renderChildren([0, 1, 2, 3, 4, 5]) expect(elm.children.length).toBe(6) elm = renderChildren([4, 3, 2, 1, 5, 0]) expect((elm.children as TestElement[]).map(inner)).toEqual([ '4', '3', '2', '1', '5', '0' ]) }) test('random shuffle', () => { const elms = 14 const samples = 5 const arr = [...Array(elms).keys()] const opacities: string[] = [] function spanNumWithOpacity(n: number, o: string) { return h('span', { key: n, style: { opacity: o } }, n.toString()) } for (let n = 0; n < samples; ++n) { render(h('span', arr.map(n => spanNumWithOpacity(n, '1'))), root) elm = root.children[0] as TestElement for (let i = 0; i < elms; ++i) { expect(serializeInner(elm.children[i] as TestElement)).toBe( i.toString() ) opacities[i] = Math.random() .toFixed(5) .toString() } const shufArr = shuffle(arr.slice(0)) render( h('span', arr.map(n => spanNumWithOpacity(shufArr[n], opacities[n]))), root ) elm = root.children[0] as TestElement for (let i = 0; i < elms; ++i) { expect(serializeInner(elm.children[i] as TestElement)).toBe( shufArr[i].toString() ) expect(elm.children[i]).toMatchObject({ props: { style: { opacity: opacities[i] } } }) } } }) test('children with the same key but with different tag', () => { render( h('div', [ h('div', { key: 1 }, 'one'), h('div', { key: 2 }, 'two'), h('div', { key: 3 }, 'three'), h('div', { key: 4 }, 'four') ]), root ) elm = root.children[0] as TestElement expect((elm.children as TestElement[]).map(c => c.tag)).toEqual([ 'div', 'div', 'div', 'div' ]) expect((elm.children as TestElement[]).map(inner)).toEqual([ 'one', 'two', 'three', 'four' ]) render( h('div', [ h('div', { key: 4 }, 'four'), h('span', { key: 3 }, 'three'), h('span', { key: 2 }, 'two'), h('div', { key: 1 }, 'one') ]), root ) expect((elm.children as TestElement[]).map(c => c.tag)).toEqual([ 'div', 'span', 'span', 'div' ]) expect((elm.children as TestElement[]).map(inner)).toEqual([ 'four', 'three', 'two', 'one' ]) }) test('children with the same tag, same key, but one with data and one without data', () => { render(h('div', [h('div', { class: 'hi' }, 'one')]), root) elm = root.children[0] as TestElement expect(elm.children[0]).toMatchObject({ props: { class: 'hi' } }) render(h('div', [h('div', 'four')]), root) elm = root.children[0] as TestElement expect(elm.children[0] as TestElement).toMatchObject({ props: { // in the DOM renderer this will be '' // but the test renderer simply sets whatever value it receives. class: null } }) expect(serialize(elm.children[0])).toBe(`<div>four</div>`) }) test('should warn with duplicate keys', () => { renderChildren([1, 2, 3, 4, 5]) renderChildren([1, 6, 6, 3, 5]) expect(`Duplicate keys`).toHaveBeenWarned() }) }) describe('renderer: unkeyed children', () => { let root: TestElement let elm: TestElement const renderChildren = (arr: Array<number | string>) => { render(h('div', arr.map(toSpan)), root) return root.children[0] as TestElement } beforeEach(() => { root = nodeOps.createElement('div') render(h('div', { id: 1 }, 'hello'), root) }) test('move a key in non-keyed nodes with a size up', () => { elm = renderChildren([1, 'a', 'b', 'c']) expect(elm.children.length).toBe(4) expect((elm.children as TestElement[]).map(inner)).toEqual([ '1', 'a', 'b', 'c' ]) elm = renderChildren(['d', 'a', 'b', 'c', 1, 'e']) expect(elm.children.length).toBe(6) expect((elm.children as TestElement[]).map(inner)).toEqual([ 'd', 'a', 'b', 'c', '1', 'e' ]) }) test('append elements with updating children without keys', () => { elm = renderChildren(['hello']) expect((elm.children as TestElement[]).map(inner)).toEqual(['hello']) elm = renderChildren(['hello', 'world']) expect((elm.children as TestElement[]).map(inner)).toEqual([ 'hello', 'world' ]) }) test('unmoved text nodes with updating children without keys', () => { render(h('div', ['text', h('span', ['hello'])]), root) elm = root.children[0] as TestElement expect(elm.children[0]).toMatchObject({ type: NodeTypes.TEXT, text: 'text' }) render(h('div', ['text', h('span', ['hello'])]), root) elm = root.children[0] as TestElement expect(elm.children[0]).toMatchObject({ type: NodeTypes.TEXT, text: 'text' }) }) test('changing text children with updating children without keys', () => { render(h('div', ['text', h('span', ['hello'])]), root) elm = root.children[0] as TestElement expect(elm.children[0]).toMatchObject({ type: NodeTypes.TEXT, text: 'text' }) render(h('div', ['text2', h('span', ['hello'])]), root) elm = root.children[0] as TestElement expect(elm.children[0]).toMatchObject({ type: NodeTypes.TEXT, text: 'text2' }) }) test('prepend element with updating children without keys', () => { render(h('div', [h('span', ['world'])]), root) elm = root.children[0] as TestElement expect((elm.children as TestElement[]).map(inner)).toEqual(['world']) render(h('div', [h('span', ['hello']), h('span', ['world'])]), root) expect((elm.children as TestElement[]).map(inner)).toEqual([ 'hello', 'world' ]) }) test('prepend element of different tag type with updating children without keys', () => { render(h('div', [h('span', ['world'])]), root) elm = root.children[0] as TestElement expect((elm.children as TestElement[]).map(inner)).toEqual(['world']) render(h('div', [h('div', ['hello']), h('span', ['world'])]), root) expect((elm.children as TestElement[]).map(c => c.tag)).toEqual([ 'div', 'span' ]) expect((elm.children as TestElement[]).map(inner)).toEqual([ 'hello', 'world' ]) }) test('remove elements with updating children without keys', () => { render( h('div', [h('span', ['one']), h('span', ['two']), h('span', ['three'])]), root ) elm = root.children[0] as TestElement expect((elm.children as TestElement[]).map(inner)).toEqual([ 'one', 'two', 'three' ]) render(h('div', [h('span', ['one']), h('span', ['three'])]), root) elm = root.children[0] as TestElement expect((elm.children as TestElement[]).map(inner)).toEqual(['one', 'three']) }) test('remove a single text node with updating children without keys', () => { render(h('div', ['one']), root) elm = root.children[0] as TestElement expect(serializeInner(elm)).toBe('one') render(h('div'), root) expect(serializeInner(elm)).toBe('') }) test('remove a single text node when children are updated', () => { render(h('div', ['one']), root) elm = root.children[0] as TestElement expect(serializeInner(elm)).toBe('one') render(h('div', [h('div', ['two']), h('span', ['three'])]), root) elm = root.children[0] as TestElement expect((elm.children as TestElement[]).map(inner)).toEqual(['two', 'three']) }) test('remove a text node among other elements', () => { render(h('div', ['one', h('span', ['two'])]), root) elm = root.children[0] as TestElement expect((elm.children as TestElement[]).map(c => serialize(c))).toEqual([ 'one', '<span>two</span>' ]) render(h('div', [h('div', ['three'])]), root) elm = root.children[0] as TestElement expect(elm.children.length).toBe(1) expect(serialize(elm.children[0])).toBe('<div>three</div>') }) test('reorder elements', () => { render( h('div', [h('span', ['one']), h('div', ['two']), h('b', ['three'])]), root ) elm = root.children[0] as TestElement expect((elm.children as TestElement[]).map(inner)).toEqual([ 'one', 'two', 'three' ]) render( h('div', [h('b', ['three']), h('div', ['two']), h('span', ['one'])]), root ) elm = root.children[0] as TestElement expect((elm.children as TestElement[]).map(inner)).toEqual([ 'three', 'two', 'one' ]) }) // #6502 test('should not de-opt when both head and tail change', () => { render(h('div', [null, h('div'), null]), root) elm = root.children[0] as TestElement const original = elm.children[1] render(h('div', [h('p'), h('div'), h('p')]), root) elm = root.children[0] as TestElement const postPatch = elm.children[1] expect(postPatch).toBe(original) }) })
packages/runtime-core/__tests__/rendererChildren.spec.ts
0
https://github.com/vuejs/core/commit/763faac18268ad98bca5e3cb36e209c03e566d45
[ 0.0004866499803029001, 0.00018031385843642056, 0.0001666459284024313, 0.00017429105355404317, 0.00004043391891173087 ]
{ "id": 0, "code_window": [ "\t\tthis._tracer.traceResponse(response, callback.startTime);\n", "\t\tif (response.success) {\n", "\t\t\tcallback.onSuccess(response);\n", "\t\t} else if (response.message === 'No content available.') {\n", "\t\t\t// Special case where response itself is successful but there is not any data to return.\n", "\t\t\tcallback.onSuccess(new NoContentResponse());\n", "\t\t} else {\n", "\t\t\tcallback.onError(new TypeScriptServerError(this._version, response));\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tcallback.onSuccess(NoContentResponse);\n" ], "file_path": "extensions/typescript-language-features/src/tsServer/server.ts", "type": "replace", "edit_start_line_idx": 303 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as cp from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; import * as Proto from '../protocol'; import { CancelledResponse, NoContentResponse } from '../typescriptService'; import API from '../utils/api'; import { TsServerLogLevel, TypeScriptServiceConfiguration } from '../utils/configuration'; import { Disposable } from '../utils/dispose'; import * as electron from '../utils/electron'; import LogDirectoryProvider from '../utils/logDirectoryProvider'; import Logger from '../utils/logger'; import { TypeScriptPluginPathsProvider } from '../utils/pluginPathsProvider'; import { PluginManager } from '../utils/plugins'; import TelemetryReporter from '../utils/telemetry'; import Tracer from '../utils/tracer'; import { TypeScriptVersion, TypeScriptVersionProvider } from '../utils/versionProvider'; import { Reader } from '../utils/wireProtocol'; import { CallbackMap } from './callbackMap'; import { RequestItem, RequestQueue, RequestQueueingType } from './requestQueue'; class TypeScriptServerError extends Error { constructor( version: TypeScriptVersion, public readonly response: Proto.Response, ) { super(`TypeScript Server Error (${version.versionString})\n${response.message}`); } } export class TypeScriptServerSpawner { public constructor( private readonly _versionProvider: TypeScriptVersionProvider, private readonly _logDirectoryProvider: LogDirectoryProvider, private readonly _pluginPathsProvider: TypeScriptPluginPathsProvider, private readonly _logger: Logger, private readonly _telemetryReporter: TelemetryReporter, private readonly _tracer: Tracer, ) { } public spawn( version: TypeScriptVersion, configuration: TypeScriptServiceConfiguration, pluginManager: PluginManager ): TypeScriptServer { const apiVersion = version.version || API.defaultVersion; const { args, cancellationPipeName, tsServerLogFile } = this.getTsServerArgs(configuration, version, apiVersion, pluginManager); if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) { if (tsServerLogFile) { this._logger.info(`TSServer log file: ${tsServerLogFile}`); } else { this._logger.error('Could not create TSServer log directory'); } } this._logger.info('Forking TSServer'); const childProcess = electron.fork(version.tsServerPath, args, this.getForkOptions()); this._logger.info('Started TSServer'); return new TypeScriptServer(childProcess, tsServerLogFile, cancellationPipeName, version, this._telemetryReporter, this._tracer); } private getForkOptions() { const debugPort = TypeScriptServerSpawner.getDebugPort(); const tsServerForkOptions: electron.ForkOptions = { execArgv: debugPort ? [`--inspect=${debugPort}`] : [], }; return tsServerForkOptions; } private getTsServerArgs( configuration: TypeScriptServiceConfiguration, currentVersion: TypeScriptVersion, apiVersion: API, pluginManager: PluginManager, ): { args: string[], cancellationPipeName: string | undefined, tsServerLogFile: string | undefined } { const args: string[] = []; let cancellationPipeName: string | undefined; let tsServerLogFile: string | undefined; if (apiVersion.gte(API.v206)) { if (apiVersion.gte(API.v250)) { args.push('--useInferredProjectPerProjectRoot'); } else { args.push('--useSingleInferredProject'); } if (configuration.disableAutomaticTypeAcquisition) { args.push('--disableAutomaticTypingAcquisition'); } } if (apiVersion.gte(API.v208)) { args.push('--enableTelemetry'); } if (apiVersion.gte(API.v222)) { cancellationPipeName = electron.getTempFile('tscancellation'); args.push('--cancellationPipeName', cancellationPipeName + '*'); } if (TypeScriptServerSpawner.isLoggingEnabled(apiVersion, configuration)) { const logDir = this._logDirectoryProvider.getNewLogDirectory(); if (logDir) { tsServerLogFile = path.join(logDir, `tsserver.log`); args.push('--logVerbosity', TsServerLogLevel.toString(configuration.tsServerLogLevel)); args.push('--logFile', tsServerLogFile); } } if (apiVersion.gte(API.v230)) { const pluginPaths = this._pluginPathsProvider.getPluginPaths(); if (pluginManager.plugins.length) { args.push('--globalPlugins', pluginManager.plugins.map(x => x.name).join(',')); const isUsingBundledTypeScriptVersion = currentVersion.path === this._versionProvider.defaultVersion.path; for (const plugin of pluginManager.plugins) { if (isUsingBundledTypeScriptVersion || plugin.enableForWorkspaceTypeScriptVersions) { pluginPaths.push(plugin.path); } } } if (pluginPaths.length !== 0) { args.push('--pluginProbeLocations', pluginPaths.join(',')); } } if (apiVersion.gte(API.v234)) { if (configuration.npmLocation) { args.push('--npmLocation', `"${configuration.npmLocation}"`); } } if (apiVersion.gte(API.v260)) { args.push('--locale', TypeScriptServerSpawner.getTsLocale(configuration)); } if (apiVersion.gte(API.v291)) { args.push('--noGetErrOnBackgroundUpdate'); } return { args, cancellationPipeName, tsServerLogFile }; } private static getDebugPort(): number | undefined { const value = process.env['TSS_DEBUG']; if (value) { const port = parseInt(value); if (!isNaN(port)) { return port; } } return undefined; } private static isLoggingEnabled(apiVersion: API, configuration: TypeScriptServiceConfiguration) { return apiVersion.gte(API.v222) && configuration.tsServerLogLevel !== TsServerLogLevel.Off; } private static getTsLocale(configuration: TypeScriptServiceConfiguration): string { return configuration.locale ? configuration.locale : vscode.env.language; } } export class TypeScriptServer extends Disposable { private readonly _reader: Reader<Proto.Response>; private readonly _requestQueue = new RequestQueue(); private readonly _callbacks = new CallbackMap<Proto.Response>(); private readonly _pendingResponses = new Set<number>(); constructor( private readonly _childProcess: cp.ChildProcess, private readonly _tsServerLogFile: string | undefined, private readonly _cancellationPipeName: string | undefined, private readonly _version: TypeScriptVersion, private readonly _telemetryReporter: TelemetryReporter, private readonly _tracer: Tracer, ) { super(); this._reader = this._register(new Reader<Proto.Response>(this._childProcess.stdout)); this._reader.onData(msg => this.dispatchMessage(msg)); this._childProcess.on('exit', code => this.handleExit(code)); this._childProcess.on('error', error => this.handleError(error)); } private readonly _onEvent = this._register(new vscode.EventEmitter<Proto.Event>()); public readonly onEvent = this._onEvent.event; private readonly _onExit = this._register(new vscode.EventEmitter<any>()); public readonly onExit = this._onExit.event; private readonly _onError = this._register(new vscode.EventEmitter<any>()); public readonly onError = this._onError.event; public get onReaderError() { return this._reader.onError; } public get tsServerLogFile() { return this._tsServerLogFile; } public write(serverRequest: Proto.Request) { this._childProcess.stdin.write(JSON.stringify(serverRequest) + '\r\n', 'utf8'); } public dispose() { super.dispose(); this._callbacks.destroy('server disposed'); this._pendingResponses.clear(); } public kill() { this._childProcess.kill(); } private handleExit(error: any) { this._onExit.fire(error); this._callbacks.destroy('server exited'); } private handleError(error: any) { this._onError.fire(error); this._callbacks.destroy('server errored'); } private dispatchMessage(message: Proto.Message) { try { switch (message.type) { case 'response': this.dispatchResponse(message as Proto.Response); break; case 'event': const event = message as Proto.Event; if (event.event === 'requestCompleted') { const seq = (event as Proto.RequestCompletedEvent).body.request_seq; const p = this._callbacks.fetch(seq); if (p) { this._tracer.traceRequestCompleted('requestCompleted', seq, p.startTime); p.onSuccess(undefined); } } else { this._tracer.traceEvent(event); this._onEvent.fire(event); } break; default: throw new Error(`Unknown message type ${message.type} received`); } } finally { this.sendNextRequests(); } } private tryCancelRequest(seq: number, command: string): boolean { try { if (this._requestQueue.tryDeletePendingRequest(seq)) { this._tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`); return true; } if (this._cancellationPipeName) { this._tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`); try { fs.writeFileSync(this._cancellationPipeName + seq, ''); } catch { // noop } return true; } this._tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`); return false; } finally { const callback = this.fetchCallback(seq); if (callback) { callback.onSuccess(new CancelledResponse(`Cancelled request ${seq} - ${command}`)); } } } private dispatchResponse(response: Proto.Response) { const callback = this.fetchCallback(response.request_seq); if (!callback) { return; } this._tracer.traceResponse(response, callback.startTime); if (response.success) { callback.onSuccess(response); } else if (response.message === 'No content available.') { // Special case where response itself is successful but there is not any data to return. callback.onSuccess(new NoContentResponse()); } else { callback.onError(new TypeScriptServerError(this._version, response)); } } public executeImpl(command: string, args: any, executeInfo: { isAsync: boolean, token?: vscode.CancellationToken, expectsResult: boolean, lowPriority?: boolean }): Promise<any> { const request = this._requestQueue.createRequest(command, args); const requestInfo: RequestItem = { request, expectsResponse: executeInfo.expectsResult, isAsync: executeInfo.isAsync, queueingType: getQueueingType(command, executeInfo.lowPriority) }; let result: Promise<any>; if (executeInfo.expectsResult) { result = new Promise<any>((resolve, reject) => { this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync); if (executeInfo.token) { executeInfo.token.onCancellationRequested(() => { this.tryCancelRequest(request.seq, command); }); } }).catch((err: Error) => { if (err instanceof TypeScriptServerError) { if (!executeInfo.token || !executeInfo.token.isCancellationRequested) { const properties = this.parseErrorText(err.response.message, err.response.command); /* __GDPR__ "languageServiceErrorResponse" : { "command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "message" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" }, "stack" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" }, "errortext" : { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" }, "${include}": [ "${TypeScriptCommonProperties}" ] } */ this._telemetryReporter.logTelemetry('languageServiceErrorResponse', properties); } } throw err; }); } else { result = Promise.resolve(null); } this._requestQueue.enqueue(requestInfo); this.sendNextRequests(); return result; } /** * Given a `errorText` from a tsserver request indicating failure in handling a request, * prepares a payload for telemetry-logging. */ private parseErrorText(errorText: string | undefined, command: string) { const properties: ObjectMap<string> = Object.create(null); properties['command'] = command; if (errorText) { properties['errorText'] = errorText; const errorPrefix = 'Error processing request. '; if (errorText.startsWith(errorPrefix)) { const prefixFreeErrorText = errorText.substr(errorPrefix.length); const newlineIndex = prefixFreeErrorText.indexOf('\n'); if (newlineIndex >= 0) { // Newline expected between message and stack. properties['message'] = prefixFreeErrorText.substring(0, newlineIndex); properties['stack'] = prefixFreeErrorText.substring(newlineIndex + 1); } } } return properties; } private sendNextRequests(): void { while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) { const item = this._requestQueue.dequeue(); if (item) { this.sendRequest(item); } } } private sendRequest(requestItem: RequestItem): void { const serverRequest = requestItem.request; this._tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length); if (requestItem.expectsResponse && !requestItem.isAsync) { this._pendingResponses.add(requestItem.request.seq); } try { this.write(serverRequest); } catch (err) { const callback = this.fetchCallback(serverRequest.seq); if (callback) { callback.onError(err); } } } private fetchCallback(seq: number) { const callback = this._callbacks.fetch(seq); if (!callback) { return undefined; } this._pendingResponses.delete(seq); return callback; } } const fenceCommands = new Set(['change', 'close', 'open']); function getQueueingType( command: string, lowPriority?: boolean ): RequestQueueingType { if (fenceCommands.has(command)) { return RequestQueueingType.Fence; } return lowPriority ? RequestQueueingType.LowPriority : RequestQueueingType.Normal; }
extensions/typescript-language-features/src/tsServer/server.ts
1
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.9976285099983215, 0.02355492301285267, 0.00016280780255328864, 0.00017207040218636394, 0.14856068789958954 ]
{ "id": 0, "code_window": [ "\t\tthis._tracer.traceResponse(response, callback.startTime);\n", "\t\tif (response.success) {\n", "\t\t\tcallback.onSuccess(response);\n", "\t\t} else if (response.message === 'No content available.') {\n", "\t\t\t// Special case where response itself is successful but there is not any data to return.\n", "\t\t\tcallback.onSuccess(new NoContentResponse());\n", "\t\t} else {\n", "\t\t\tcallback.onError(new TypeScriptServerError(this._version, response));\n", "\t\t}\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tcallback.onSuccess(NoContentResponse);\n" ], "file_path": "extensions/typescript-language-features/src/tsServer/server.ts", "type": "replace", "edit_start_line_idx": 303 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ok } from 'vs/base/common/assert'; import { Schemas } from 'vs/base/common/network'; import { regExpLeadsToEndlessLoop } from 'vs/base/common/strings'; import { URI } from 'vs/base/common/uri'; import { MirrorTextModel } from 'vs/editor/common/model/mirrorTextModel'; import { ensureValidWordDefinition, getWordAtText } from 'vs/editor/common/model/wordHelper'; import { MainThreadDocumentsShape } from 'vs/workbench/api/node/extHost.protocol'; import { EndOfLine, Position, Range } from 'vs/workbench/api/node/extHostTypes'; import * as vscode from 'vscode'; const _modeId2WordDefinition = new Map<string, RegExp>(); export function setWordDefinitionFor(modeId: string, wordDefinition: RegExp): void { _modeId2WordDefinition.set(modeId, wordDefinition); } export function getWordDefinitionFor(modeId: string): RegExp { return _modeId2WordDefinition.get(modeId); } export class ExtHostDocumentData extends MirrorTextModel { private _proxy: MainThreadDocumentsShape; private _languageId: string; private _isDirty: boolean; private _document: vscode.TextDocument; private _textLines: vscode.TextLine[] = []; private _isDisposed: boolean = false; constructor(proxy: MainThreadDocumentsShape, uri: URI, lines: string[], eol: string, languageId: string, versionId: number, isDirty: boolean ) { super(uri, lines, eol, versionId); this._proxy = proxy; this._languageId = languageId; this._isDirty = isDirty; } dispose(): void { // we don't really dispose documents but let // extensions still read from them. some // operations, live saving, will now error tho ok(!this._isDisposed); this._isDisposed = true; this._isDirty = false; } equalLines(lines: string[]): boolean { const len = lines.length; if (len !== this._lines.length) { return false; } for (let i = 0; i < len; i++) { if (lines[i] !== this._lines[i]) { return false; } } return true; } get document(): vscode.TextDocument { if (!this._document) { const data = this; this._document = { get uri() { return data._uri; }, get fileName() { return data._uri.fsPath; }, get isUntitled() { return data._uri.scheme === Schemas.untitled; }, get languageId() { return data._languageId; }, get version() { return data._versionId; }, get isClosed() { return data._isDisposed; }, get isDirty() { return data._isDirty; }, save() { return data._save(); }, getText(range?) { return range ? data._getTextInRange(range) : data.getText(); }, get eol() { return data._eol === '\n' ? EndOfLine.LF : EndOfLine.CRLF; }, get lineCount() { return data._lines.length; }, lineAt(lineOrPos: number | vscode.Position) { return data._lineAt(lineOrPos); }, offsetAt(pos) { return data._offsetAt(pos); }, positionAt(offset) { return data._positionAt(offset); }, validateRange(ran) { return data._validateRange(ran); }, validatePosition(pos) { return data._validatePosition(pos); }, getWordRangeAtPosition(pos, regexp?) { return data._getWordRangeAtPosition(pos, regexp); } }; } return Object.freeze(this._document); } _acceptLanguageId(newLanguageId: string): void { ok(!this._isDisposed); this._languageId = newLanguageId; } _acceptIsDirty(isDirty: boolean): void { ok(!this._isDisposed); this._isDirty = isDirty; } private _save(): Promise<boolean> { if (this._isDisposed) { return Promise.reject(new Error('Document has been closed')); } return this._proxy.$trySaveDocument(this._uri); } private _getTextInRange(_range: vscode.Range): string { let range = this._validateRange(_range); if (range.isEmpty) { return ''; } if (range.isSingleLine) { return this._lines[range.start.line].substring(range.start.character, range.end.character); } let lineEnding = this._eol, startLineIndex = range.start.line, endLineIndex = range.end.line, resultLines: string[] = []; resultLines.push(this._lines[startLineIndex].substring(range.start.character)); for (let i = startLineIndex + 1; i < endLineIndex; i++) { resultLines.push(this._lines[i]); } resultLines.push(this._lines[endLineIndex].substring(0, range.end.character)); return resultLines.join(lineEnding); } private _lineAt(lineOrPosition: number | vscode.Position): vscode.TextLine { let line: number; if (lineOrPosition instanceof Position) { line = lineOrPosition.line; } else if (typeof lineOrPosition === 'number') { line = lineOrPosition; } if (line < 0 || line >= this._lines.length) { throw new Error('Illegal value for `line`'); } let result = this._textLines[line]; if (!result || result.lineNumber !== line || result.text !== this._lines[line]) { const text = this._lines[line]; const firstNonWhitespaceCharacterIndex = /^(\s*)/.exec(text)[1].length; const range = new Range(line, 0, line, text.length); const rangeIncludingLineBreak = line < this._lines.length - 1 ? new Range(line, 0, line + 1, 0) : range; result = Object.freeze({ lineNumber: line, range, rangeIncludingLineBreak, text, firstNonWhitespaceCharacterIndex, //TODO@api, rename to 'leadingWhitespaceLength' isEmptyOrWhitespace: firstNonWhitespaceCharacterIndex === text.length }); this._textLines[line] = result; } return result; } private _offsetAt(position: vscode.Position): number { position = this._validatePosition(position); this._ensureLineStarts(); return this._lineStarts.getAccumulatedValue(position.line - 1) + position.character; } private _positionAt(offset: number): vscode.Position { offset = Math.floor(offset); offset = Math.max(0, offset); this._ensureLineStarts(); let out = this._lineStarts.getIndexOf(offset); let lineLength = this._lines[out.index].length; // Ensure we return a valid position return new Position(out.index, Math.min(out.remainder, lineLength)); } // ---- range math private _validateRange(range: vscode.Range): vscode.Range { if (!(range instanceof Range)) { throw new Error('Invalid argument'); } let start = this._validatePosition(range.start); let end = this._validatePosition(range.end); if (start === range.start && end === range.end) { return range; } return new Range(start.line, start.character, end.line, end.character); } private _validatePosition(position: vscode.Position): vscode.Position { if (!(position instanceof Position)) { throw new Error('Invalid argument'); } let { line, character } = position; let hasChanged = false; if (line < 0) { line = 0; character = 0; hasChanged = true; } else if (line >= this._lines.length) { line = this._lines.length - 1; character = this._lines[line].length; hasChanged = true; } else { let maxCharacter = this._lines[line].length; if (character < 0) { character = 0; hasChanged = true; } else if (character > maxCharacter) { character = maxCharacter; hasChanged = true; } } if (!hasChanged) { return position; } return new Position(line, character); } private _getWordRangeAtPosition(_position: vscode.Position, regexp?: RegExp): vscode.Range { let position = this._validatePosition(_position); if (!regexp) { // use default when custom-regexp isn't provided regexp = getWordDefinitionFor(this._languageId); } else if (regExpLeadsToEndlessLoop(regexp)) { // use default when custom-regexp is bad console.warn(`[getWordRangeAtPosition]: ignoring custom regexp '${regexp.source}' because it matches the empty string.`); regexp = getWordDefinitionFor(this._languageId); } let wordAtText = getWordAtText( position.character + 1, ensureValidWordDefinition(regexp), this._lines[position.line], 0 ); if (wordAtText) { return new Range(position.line, wordAtText.startColumn - 1, position.line, wordAtText.endColumn - 1); } return undefined; } }
src/vs/workbench/api/node/extHostDocumentData.ts
0
https://github.com/microsoft/vscode/commit/2f5d88899d9575d165aad0a3b6aa6514cdccd696
[ 0.00017600483261048794, 0.00017146985919680446, 0.00016309913189616054, 0.00017176158144138753, 0.000003108898226855672 ]