hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
" border-top: none;\n",
" }\n",
"\n",
" > .item:last-child,\n",
" > ion-item-sliding:last-child .item {\n",
" border-bottom-right-radius: $list-inset-ios-border-radius;\n",
" border-bottom-left-radius: $list-inset-ios-border-radius;\n",
" border-bottom: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "ionic/components/list/modes/ios.scss",
"type": "replace",
"edit_start_line_idx": 152
}
|
// Search Bar
// --------------------------------------------------
ion-searchbar {
position: relative;
display: flex;
align-items: center;
width: 100%;
}
.searchbar-icon {
// Don't let them tap on the icon
pointer-events: none;
}
.searchbar-input-container {
position: relative;
display: block;
flex-shrink: 1;
width: 100%;
}
input[type="search"].searchbar-input {
display: block;
width: 100%;
height: 100%;
border: none;
font-family: inherit;
line-height: 3rem;
@include appearance(none);
}
.searchbar-close-icon {
min-height: 0;
padding: 0;
margin: 0;
}
|
ionic/components/searchbar/searchbar.scss
| 0 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.00018061792070511729,
0.00017299938190262765,
0.00016542436787858605,
0.00017297762678936124,
0.000006827895049354993
] |
{
"id": 2,
"code_window": [
" border-top: none;\n",
" }\n",
"\n",
" > .item:last-child,\n",
" > ion-item-sliding:last-child .item {\n",
" border-bottom-right-radius: $list-inset-ios-border-radius;\n",
" border-bottom-left-radius: $list-inset-ios-border-radius;\n",
" border-bottom: none;\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "ionic/components/list/modes/ios.scss",
"type": "replace",
"edit_start_line_idx": 152
}
|
import {Injectable} from 'angular2/angular2';
import {OverlayController} from '../overlay/overlay-controller';
import {Config} from '../../config/config';
import {Animation} from '../../animations/animation';
import * as util from 'ionic/util';
/**
* The Modal is a content pane that can go over the user's main view temporarily.
* Usually used for making a choice or editing an item.
*
* @usage
* ```ts
* class MyApp {
*
* constructor(modal: Modal, app: IonicApp, Config: Config) {
* this.modal = modal;
* }
*
* openModal() {
* this.modal.open(ContactModal, {
* enterAnimation: 'my-fade-in',
* leaveAnimation: 'my-fade-out',
* handle: 'my-modal'
* });
* }
* }
* ```
*/
@Injectable()
export class Modal {
constructor(ctrl: OverlayController, config: Config) {
this.ctrl = ctrl;
this._defaults = {
enterAnimation: config.get('modalEnter') || 'modal-slide-in',
leaveAnimation: config.get('modalLeave') || 'modal-slide-out',
};
}
/**
* TODO
* @param {Type} componentType TODO
* @param {Object} [opts={}] TODO
* @returns {TODO} TODO
*/
open(componentType: Type, opts={}) {
return this.ctrl.open(OVERLAY_TYPE, componentType, util.extend(this._defaults, opts));
}
/**
* TODO
* @param {TODO} handle TODO
* @returns {TODO} TODO
*/
get(handle) {
if (handle) {
return this.ctrl.getByHandle(handle, OVERLAY_TYPE);
}
return this.ctrl.getByType(OVERLAY_TYPE);
}
}
const OVERLAY_TYPE = 'modal';
/**
* Animations for modals
*/
class ModalSlideIn extends Animation {
constructor(element) {
super(element);
this
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(400)
.fromTo('translateY', '100%', '0%');
}
}
Animation.register('modal-slide-in', ModalSlideIn);
class ModalSlideOut extends Animation {
constructor(element) {
super(element);
this
.easing('ease-out')
.duration(250)
.fromTo('translateY', '0%', '100%');
}
}
Animation.register('modal-slide-out', ModalSlideOut);
class ModalMDSlideIn extends Animation {
constructor(element) {
super(element);
this
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(280)
.fromTo('translateY', '40px', '0px')
.fadeIn();
}
}
Animation.register('modal-md-slide-in', ModalMDSlideIn);
class ModalMDSlideOut extends Animation {
constructor(element) {
super(element);
this
.duration(200)
.easing('cubic-bezier(0.47,0,0.745,0.715)')
.fromTo('translateY', '0px', '40px')
.fadeOut();
}
}
Animation.register('modal-md-slide-out', ModalMDSlideOut);
|
ionic/components/modal/modal.ts
| 0 |
https://github.com/ionic-team/ionic-framework/commit/10672b062ead488c1dc96d34dc3d81fa2bdff1c6
|
[
0.0001847572420956567,
0.0001720702857710421,
0.00016758257697802037,
0.00017044588457792997,
0.000005006841092836112
] |
{
"id": 0,
"code_window": [
"\n",
"export interface SubAPI {\n",
" findRef: (source: string) => ComposedRef;\n",
" setRef: (id: string, data: SetRefData, ready?: boolean) => void;\n",
" getRefs: () => Refs;\n",
" checkRef: (ref: SetRefData) => Promise<void>;\n",
" changeRefVersion: (id: string, url: string) => void;\n",
" changeRefState: (id: string, ready: boolean) => void;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" updateRef: (id: string, ref: ComposedRefUpdate) => void;\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 26
}
|
import { location, fetch } from 'global';
import dedent from 'ts-dedent';
import {
transformStoriesRawToStoriesHash,
StoriesRaw,
StoryInput,
StoriesHash,
} from '../lib/stories';
import { ModuleFn } from '../index';
export interface SubState {
refs: Refs;
}
type Versions = Record<string, string>;
export type SetRefData = Partial<
Omit<ComposedRef, 'stories'> & {
stories?: StoriesRaw;
}
>;
export interface SubAPI {
findRef: (source: string) => ComposedRef;
setRef: (id: string, data: SetRefData, ready?: boolean) => void;
getRefs: () => Refs;
checkRef: (ref: SetRefData) => Promise<void>;
changeRefVersion: (id: string, url: string) => void;
changeRefState: (id: string, ready: boolean) => void;
}
export type StoryMapper = (ref: ComposedRef, story: StoryInput) => StoryInput;
export interface ComposedRef {
id: string;
title?: string;
url: string;
type?: 'auto-inject' | 'unknown' | 'lazy';
stories: StoriesHash;
versions?: Versions;
loginUrl?: string;
ready?: boolean;
error?: any;
}
export type Refs = Record<string, ComposedRef>;
export type RefId = string;
export type RefUrl = string;
// eslint-disable-next-line no-useless-escape
const findFilename = /(\/((?:[^\/]+?)\.[^\/]+?)|\/)$/;
const allSettled = (promises: Promise<Response>[]): Promise<(Response | false)[]> =>
Promise.all(
promises.map((promise) =>
promise.then(
(r) => (r.ok ? r : (false as const)),
() => false as const
)
)
);
export const getSourceType = (source: string) => {
const { origin: localOrigin, pathname: localPathname } = location;
const { origin: sourceOrigin, pathname: sourcePathname } = new URL(source);
const localFull = `${localOrigin + localPathname}`.replace(findFilename, '');
const sourceFull = `${sourceOrigin + sourcePathname}`.replace(findFilename, '');
if (localFull === sourceFull) {
return ['local', sourceFull];
}
if (source) {
return ['external', sourceFull];
}
return [null, null];
};
export const defaultStoryMapper: StoryMapper = (b, a) => {
return { ...a, kind: a.kind.replace('|', '/') };
};
const addRefIds = (input: StoriesHash, ref: ComposedRef): StoriesHash => {
return Object.entries(input).reduce((acc, [id, item]) => {
return { ...acc, [id]: { ...item, refId: ref.id } };
}, {} as StoriesHash);
};
const map = (
input: StoriesRaw,
ref: ComposedRef,
options: { storyMapper?: StoryMapper }
): StoriesRaw => {
const { storyMapper } = options;
if (storyMapper) {
return Object.entries(input).reduce((acc, [id, item]) => {
return { ...acc, [id]: storyMapper(ref, item) };
}, {} as StoriesRaw);
}
return input;
};
export const init: ModuleFn = ({ store, provider, fullAPI }, { runCheck = true } = {}) => {
const api: SubAPI = {
findRef: (source) => {
const refs = api.getRefs();
return Object.values(refs).find(({ url }) => url.match(source));
},
changeRefVersion: (id, url) => {
const { versions, title } = api.getRefs()[id];
const ref = { id, url, versions, title, stories: {} } as SetRefData;
api.checkRef(ref);
},
changeRefState: (id, ready) => {
const refs = api.getRefs();
store.setState({
refs: {
...refs,
[id]: { ...refs[id], ready },
},
});
},
checkRef: async (ref) => {
const { id, url } = ref;
const loadedData: { error?: Error; stories?: StoriesRaw; loginUrl?: string } = {};
const [included, omitted, iframe] = await allSettled([
fetch(`${url}/stories.json`, {
headers: {
Accept: 'application/json',
},
credentials: 'include',
}),
fetch(`${url}/stories.json`, {
headers: {
Accept: 'application/json',
},
credentials: 'omit',
}),
fetch(`${url}/iframe.html`, {
cors: 'no-cors',
credentials: 'omit',
}),
]);
const handle = async (request: Response | false): Promise<SetRefData> => {
if (request) {
return Promise.resolve(request)
.then((response) => (response.ok ? response.json() : {}))
.catch((error) => ({ error }));
}
return {};
};
if (!included && !omitted && !iframe) {
loadedData.error = {
message: dedent`
Error: Loading of ref failed
at fetch (lib/api/src/modules/refs.ts)
URL: ${url}
We weren't able to load the above URL,
it's possible a CORS error happened.
Please check your dev-tools network tab.
`,
} as Error;
} else if (omitted || included) {
const credentials = included ? 'include' : 'omit';
const [stories, metadata] = await Promise.all([
included ? handle(included) : handle(omitted),
handle(
fetch(`${url}/metadata.json`, {
headers: {
Accept: 'application/json',
},
credentials,
cache: 'no-cache',
}).catch(() => false)
),
]);
Object.assign(loadedData, { ...stories, ...metadata });
}
await api.setRef(id, {
id,
url,
...loadedData,
error: loadedData.error,
type: !loadedData.stories ? 'auto-inject' : 'lazy',
});
},
getRefs: () => {
const { refs = {} } = store.getState();
return refs;
},
setRef: (id, { stories, ...rest }, ready = false) => {
const { storyMapper = defaultStoryMapper } = provider.getConfig();
const ref = api.getRefs()[id];
const after = stories
? addRefIds(
transformStoriesRawToStoriesHash(map(stories, ref, { storyMapper }), {}, { provider }),
ref
)
: undefined;
const result = { ...ref, stories: after, ...rest, ready };
store.setState({
refs: {
...api.getRefs(),
[id]: result,
},
});
},
};
const refs = provider.getConfig().refs || {};
const initialState: SubState['refs'] = refs;
Object.values(refs).forEach((r) => {
// eslint-disable-next-line no-param-reassign
r.type = 'unknown';
});
if (runCheck) {
Object.entries(refs).forEach(([k, v]) => {
api.checkRef(v as SetRefData);
});
}
return {
api,
state: {
refs: initialState,
},
};
};
|
lib/api/src/modules/refs.ts
| 1 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.9990342855453491,
0.12484990805387497,
0.00016583609976805747,
0.00023900771338958293,
0.32047855854034424
] |
{
"id": 0,
"code_window": [
"\n",
"export interface SubAPI {\n",
" findRef: (source: string) => ComposedRef;\n",
" setRef: (id: string, data: SetRefData, ready?: boolean) => void;\n",
" getRefs: () => Refs;\n",
" checkRef: (ref: SetRefData) => Promise<void>;\n",
" changeRefVersion: (id: string, url: string) => void;\n",
" changeRefState: (id: string, ready: boolean) => void;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" updateRef: (id: string, ref: ComposedRefUpdate) => void;\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 26
}
|
import global from 'global';
import configure from '../configure';
import hasDependency from '../hasDependency';
import { Loader } from '../Loader';
import { StoryshotsOptions } from '../../api/StoryshotsOptions';
function test(options: StoryshotsOptions): boolean {
return options.framework === 'rax' || (!options.framework && hasDependency('@storybook/rax'));
}
function load(options: StoryshotsOptions) {
global.STORYBOOK_ENV = 'rax';
const storybook = jest.requireActual('@storybook/rax');
configure({ ...options, storybook });
return {
framework: 'rax' as const,
renderTree: jest.requireActual('./renderTree').default,
renderShallowTree: () => {
throw new Error('Shallow renderer is not supported for rax');
},
storybook,
};
}
const raxLoader: Loader = {
load,
test,
};
export default raxLoader;
|
addons/storyshots/storyshots-core/src/frameworks/rax/loader.ts
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017914237105287611,
0.00017574289813637733,
0.00016821574536152184,
0.00017780675261747092,
0.000004404114406497683
] |
{
"id": 0,
"code_window": [
"\n",
"export interface SubAPI {\n",
" findRef: (source: string) => ComposedRef;\n",
" setRef: (id: string, data: SetRefData, ready?: boolean) => void;\n",
" getRefs: () => Refs;\n",
" checkRef: (ref: SetRefData) => Promise<void>;\n",
" changeRefVersion: (id: string, url: string) => void;\n",
" changeRefState: (id: string, ready: boolean) => void;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" updateRef: (id: string, ref: ComposedRefUpdate) => void;\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 26
}
|
<style>
#preview-head-not-loaded {
display: none;
}
#dotenv-file-not-loaded {
display: %DOTENV_DISPLAY_WARNING%;
}
.sbdocs.sbdocs-content {
max-width: 600px;
}
</style>
|
examples/official-storybook/preview-head.html
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017830343858804554,
0.0001782039471436292,
0.00017810445569921285,
0.0001782039471436292,
9.949144441634417e-8
] |
{
"id": 0,
"code_window": [
"\n",
"export interface SubAPI {\n",
" findRef: (source: string) => ComposedRef;\n",
" setRef: (id: string, data: SetRefData, ready?: boolean) => void;\n",
" getRefs: () => Refs;\n",
" checkRef: (ref: SetRefData) => Promise<void>;\n",
" changeRefVersion: (id: string, url: string) => void;\n",
" changeRefState: (id: string, ready: boolean) => void;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" updateRef: (id: string, ref: ComposedRefUpdate) => void;\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 26
}
|
require('./dist/register');
|
addons/links/register.js
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017782345821615309,
0.00017782345821615309,
0.00017782345821615309,
0.00017782345821615309,
0
] |
{
"id": 1,
"code_window": [
" ready?: boolean;\n",
" error?: any;\n",
"}\n",
"\n",
"export type Refs = Record<string, ComposedRef>;\n",
"export type RefId = string;\n",
"export type RefUrl = string;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface ComposedRefUpdate {\n",
" title?: string;\n",
" type?: 'auto-inject' | 'unknown' | 'lazy';\n",
" stories?: StoriesHash;\n",
" versions?: Versions;\n",
" loginUrl?: string;\n",
" ready?: boolean;\n",
" error?: any;\n",
"}\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 44
}
|
/* eslint-disable no-fallthrough */
import { DOCS_MODE } from 'global';
import { toId, sanitize } from '@storybook/csf';
import {
UPDATE_STORY_ARGS,
STORY_ARGS_UPDATED,
STORY_CHANGED,
SELECT_STORY,
SET_STORIES,
CURRENT_STORY_WAS_SET,
} from '@storybook/core-events';
import deprecate from 'util-deprecate';
import { logger } from '@storybook/client-logger';
import {
denormalizeStoryParameters,
transformStoriesRawToStoriesHash,
StoriesHash,
Story,
Group,
SetStoriesPayload,
StoryId,
isStory,
Root,
isRoot,
StoriesRaw,
SetStoriesPayloadV2,
} from '../lib/stories';
import { Args, ModuleFn } from '../index';
import { getSourceType } from './refs';
type Direction = -1 | 1;
type ParameterName = string;
type ViewMode = 'story' | 'info' | 'settings' | string | undefined;
export interface SubState {
storiesHash: StoriesHash;
storyId: StoryId;
viewMode: ViewMode;
storiesConfigured: boolean;
storiesFailed?: Error;
}
export interface SubAPI {
storyId: typeof toId;
resolveStory: (storyId: StoryId, refsId?: string) => Story | Group | Root;
selectStory: (
kindOrId: string,
story?: string,
obj?: { ref?: string; viewMode?: ViewMode }
) => void;
getCurrentStoryData: () => Story | Group;
setStories: (stories: StoriesRaw, failed?: Error) => Promise<void>;
jumpToComponent: (direction: Direction) => void;
jumpToStory: (direction: Direction) => void;
getData: (storyId: StoryId, refId?: string) => Story | Group;
getParameters: (
storyId: StoryId | { storyId: StoryId; refId: string },
parameterName?: ParameterName
) => Story['parameters'] | any;
getCurrentParameter<S>(parameterName?: ParameterName): S;
updateStoryArgs(story: Story, newArgs: Args): void;
findLeafStoryId(StoriesHash: StoriesHash, storyId: StoryId): StoryId;
}
const deprecatedOptionsParameterWarnings: Record<string, () => void> = [
'sidebarAnimations',
'enableShortcuts',
'theme',
'showRoots',
].reduce((acc, option: string) => {
acc[option] = deprecate(
() => {},
`parameters.options.${option} is deprecated and will be removed in Storybook 7.0.
To change this setting, use \`addons.setConfig\`. See https://github.com/storybookjs/storybook/MIGRATION.md#deprecated-immutable-options-parameters
`
);
return acc;
}, {} as Record<string, () => void>);
function checkDeprecatedOptionParameters(options?: Record<string, any>) {
if (!options) {
return;
}
Object.keys(options).forEach((option: string) => {
if (deprecatedOptionsParameterWarnings[option]) {
deprecatedOptionsParameterWarnings[option]();
}
});
}
export const init: ModuleFn = ({
fullAPI,
store,
navigate,
provider,
storyId: initialStoryId,
viewMode: initialViewMode,
}) => {
const api: SubAPI = {
storyId: toId,
getData: (storyId, refId) => {
const result = api.resolveStory(storyId, refId);
return isRoot(result) ? undefined : result;
},
resolveStory: (storyId, refId) => {
const { refs, storiesHash } = store.getState();
if (refId) {
return refs[refId].stories ? refs[refId].stories[storyId] : undefined;
}
return storiesHash ? storiesHash[storyId] : undefined;
},
getCurrentStoryData: () => {
const { storyId, refId } = store.getState();
return api.getData(storyId, refId);
},
getParameters: (storyIdOrCombo, parameterName) => {
const { storyId, refId } =
typeof storyIdOrCombo === 'string'
? { storyId: storyIdOrCombo, refId: undefined }
: storyIdOrCombo;
const data = api.getData(storyId, refId);
if (isStory(data)) {
const { parameters } = data;
return parameterName ? parameters[parameterName] : parameters;
}
return null;
},
getCurrentParameter: (parameterName) => {
const { storyId, refId } = store.getState();
const parameters = api.getParameters({ storyId, refId }, parameterName);
if (parameters) {
return parameters;
}
return undefined;
},
jumpToComponent: (direction) => {
const { storiesHash, storyId, refs, refId } = store.getState();
const story = api.getData(storyId, refId);
// cannot navigate when there's no current selection
if (!story) {
return;
}
const hash = refId ? refs[refId].stories || {} : storiesHash;
const lookupList = Object.entries(hash).reduce((acc, i) => {
const value = i[1];
if (value.isComponent) {
acc.push([...i[1].children]);
}
return acc;
}, []);
const index = lookupList.findIndex((i) => i.includes(storyId));
// cannot navigate beyond fist or last
if (index === lookupList.length - 1 && direction > 0) {
return;
}
if (index === 0 && direction < 0) {
return;
}
const result = lookupList[index + direction][0];
if (result) {
api.selectStory(result, undefined, { ref: refId });
}
},
jumpToStory: (direction) => {
const { storiesHash, storyId, refs, refId } = store.getState();
const story = api.getData(storyId, refId);
if (DOCS_MODE) {
api.jumpToComponent(direction);
return;
}
// cannot navigate when there's no current selection
if (!story) {
return;
}
const hash = story.refId ? refs[story.refId].stories : storiesHash;
const lookupList = Object.keys(hash).filter(
(k) => !(hash[k].children || Array.isArray(hash[k]))
);
const index = lookupList.indexOf(storyId);
// cannot navigate beyond fist or last
if (index === lookupList.length - 1 && direction > 0) {
return;
}
if (index === 0 && direction < 0) {
return;
}
const result = lookupList[index + direction];
if (result) {
api.selectStory(result, undefined, { ref: refId });
}
},
setStories: async (input, error) => {
// Now create storiesHash by reordering the above by group
const existing = store.getState().storiesHash;
const hash = transformStoriesRawToStoriesHash(input, existing, {
provider,
});
await store.setState({
storiesHash: hash,
storiesConfigured: true,
storiesFailed: error,
});
},
selectStory: (kindOrId, story = undefined, options = {}) => {
const { ref, viewMode: viewModeFromArgs } = options;
const {
viewMode: viewModeFromState = 'story',
storyId,
storiesHash,
refs,
} = store.getState();
const hash = ref ? refs[ref].stories : storiesHash;
if (!story) {
const s = hash[kindOrId] || hash[sanitize(kindOrId)];
// eslint-disable-next-line no-nested-ternary
const id = s ? (s.children ? s.children[0] : s.id) : kindOrId;
let viewMode =
viewModeFromArgs || (s && s.parameters.viewMode)
? s.parameters.viewMode
: viewModeFromState;
// In some cases, the viewMode could be something other than docs/story
// ('settings', for example) and therefore we should make sure we go back
// to the 'story' viewMode when navigating away from those pages.
if (!viewMode.match(/docs|story/)) {
viewMode = 'story';
}
const p = s && s.refId ? `/${viewMode}/${s.refId}_${id}` : `/${viewMode}/${id}`;
navigate(p);
} else if (!kindOrId) {
// This is a slugified version of the kind, but that's OK, our toId function is idempotent
const kind = storyId.split('--', 2)[0];
const id = toId(kind, story);
api.selectStory(id, undefined, options);
} else {
const id = ref ? `${ref}_${toId(kindOrId, story)}` : toId(kindOrId, story);
if (hash[id]) {
api.selectStory(id, undefined, options);
} else {
// Support legacy API with component permalinks, where kind is `x/y` but permalink is 'z'
const k = hash[sanitize(kindOrId)];
if (k && k.children) {
const foundId = k.children.find((childId) => hash[childId].name === story);
if (foundId) {
api.selectStory(foundId, undefined, options);
}
}
}
}
},
findLeafStoryId(storiesHash, storyId) {
if (storiesHash[storyId].isLeaf) {
return storyId;
}
const childStoryId = storiesHash[storyId].children[0];
return api.findLeafStoryId(storiesHash, childStoryId);
},
updateStoryArgs: (story, updatedArgs) => {
const { id: storyId, refId } = story;
fullAPI.emit(UPDATE_STORY_ARGS, {
storyId,
updatedArgs,
options: {
target: refId ? `storybook-ref-${refId}` : 'storybook-preview-iframe',
},
});
},
};
const initModule = () => {
// On initial load, the local iframe will select the first story (or other "selection specifier")
// and emit CURRENT_STORY_WAS_SET with the id. We need to ensure we respond to this change.
// Later when we change story via the manager (or SELECT_STORY below), we'll already be at the
// correct path before CURRENT_STORY_WAS_SET is emitted, so this is less important (the navigate is a no-op)
// Note this is the case for refs also.
fullAPI.on(CURRENT_STORY_WAS_SET, function handleCurrentStoryWasSet({ storyId, viewMode }) {
const { source }: { source: string } = this;
const [sourceType] = getSourceType(source);
if (sourceType === 'local' && storyId && viewMode) {
navigate(`/${viewMode}/${storyId}`);
}
});
fullAPI.on(STORY_CHANGED, function handleStoryChange(storyId: string) {
const { source }: { source: string } = this;
const [sourceType] = getSourceType(source);
if (sourceType === 'local') {
const options = fullAPI.getCurrentParameter('options');
if (options) {
checkDeprecatedOptionParameters(options);
fullAPI.setOptions(options);
}
}
});
fullAPI.on(SET_STORIES, function handleSetStories(data: SetStoriesPayload) {
// the event originates from an iframe, event.source is the iframe's location origin + pathname
const { source }: { source: string } = this;
const [sourceType, sourceLocation] = getSourceType(source);
// TODO: what is the mechanism where we warn here?
if (data.v && data.v > 2) {
// eslint-disable-next-line no-console
console.warn(`Received SET_STORIES event with version ${data.v}, we'll try and handle it`);
}
const stories = data.v
? denormalizeStoryParameters(data as SetStoriesPayloadV2)
: data.stories;
// @ts-ignore
const error = data.error || undefined;
switch (sourceType) {
// if it's a local source, we do nothing special
case 'local': {
if (!data.v) {
throw new Error('Unexpected legacy SET_STORIES event from local source');
}
fullAPI.setStories(stories, error);
const { options } = (data as SetStoriesPayloadV2).globalParameters;
checkDeprecatedOptionParameters(options);
fullAPI.setOptions(options);
break;
}
// if it's a ref, we need to map the incoming stories to a prefixed version, so it cannot conflict with others
case 'external': {
const ref = fullAPI.findRef(sourceLocation);
if (ref) {
fullAPI.setRef(ref.id, { ...ref, ...data, stories }, true);
break;
}
}
// if we couldn't find the source, something risky happened, we ignore the input, and log a warning
default: {
logger.warn('received a SET_STORIES frame that was not configured as a ref');
break;
}
}
});
fullAPI.on(SELECT_STORY, function selectStoryHandler({
kind,
story,
...rest
}: {
kind: string;
story: string;
[k: string]: any;
}) {
const { source }: { source: string } = this;
const [sourceType, sourceLocation] = getSourceType(source);
switch (sourceType) {
case 'local': {
fullAPI.selectStory(kind, story, rest);
break;
}
case 'external': {
const ref = fullAPI.findRef(sourceLocation);
fullAPI.selectStory(kind, story, { ...rest, ref: ref.id });
break;
}
default: {
logger.warn('received a SET_STORIES frame that was not configured as a ref');
break;
}
}
});
fullAPI.on(STORY_ARGS_UPDATED, function handleStoryArgsUpdated({
storyId,
args,
}: {
storyId: StoryId;
args: Args;
}) {
// the event originates from an iframe, event.source is the iframe's location origin + pathname
const { source }: { source: string } = this;
const [sourceType, sourceLocation] = getSourceType(source);
switch (sourceType) {
case 'local': {
const { storiesHash } = store.getState();
(storiesHash[storyId] as Story).args = args;
store.setState({ storiesHash });
break;
}
case 'external': {
const refs = fullAPI.getRefs();
const ref = fullAPI.findRef(sourceLocation);
(ref.stories[storyId] as Story).args = args;
store.setState({ refs: { ...refs, [ref.id]: ref } });
break;
}
default: {
logger.warn('received a STORY_ARGS_UPDATED frame that was not configured as a ref');
break;
}
}
});
};
return {
api,
state: {
storiesHash: {},
storyId: initialStoryId,
viewMode: initialViewMode,
storiesConfigured: false,
},
init: initModule,
};
};
|
lib/api/src/modules/stories.ts
| 1 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.9960232973098755,
0.08538194000720978,
0.00016367244825232774,
0.00017455083434469998,
0.267152339220047
] |
{
"id": 1,
"code_window": [
" ready?: boolean;\n",
" error?: any;\n",
"}\n",
"\n",
"export type Refs = Record<string, ComposedRef>;\n",
"export type RefId = string;\n",
"export type RefUrl = string;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface ComposedRefUpdate {\n",
" title?: string;\n",
" type?: 'auto-inject' | 'unknown' | 'lazy';\n",
" stories?: StoriesHash;\n",
" versions?: Versions;\n",
" loginUrl?: string;\n",
" ready?: boolean;\n",
" error?: any;\n",
"}\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 44
}
|
# Storybook UI
Storybook UI the core UI of [storybook](https://storybook.js.org).
It's a React based UI which you can initialize with a function.
You can configure it by providing a provider API.
## Table of Contents
- [Usage](#usage)
- [API](#api)
- [.setOptions()](#setoptions)
- [.setStories()](#setstories)
- [.onStory()](#onstory)
- [Hacking Guide](#hacking-guide)
- [The App](#the-app)
- [Changing UI](#changing-ui)
- [Mounting](#mounting)
- [App Context](#app-context)
- [Actions](#actions)
- [Core API](#core-api)
- [Keyboard Shortcuts](#keyboard-shortcuts)
- [URL Changes](#url-changes)
## Usage
First you need to install `@storybook/ui` into your app.
```sh
yarn add @storybook/ui --dev
```
Then you need to create a Provider class like this:
```js
import React from 'react';
import { Provider } from '@storybook/ui';
export default class MyProvider extends Provider {
getElements(type) {
return {};
}
renderPreview() {
return <p>This is the Preview</p>;
}
handleAPI(api) {
// no need to do anything for now.
}
}
```
Then you need to initialize the UI like this:
```js
import { document } from 'global';
import renderStorybookUI from '@storybook/ui';
import Provider from './provider';
const roolEl = document.getElementById('root');
renderStorybookUI(roolEl, new Provider());
```
## API
### .setOptions()
```js
import { Provider } from '@storybook/ui';
class ReactProvider extends Provider {
handleAPI(api) {
api.setOptions({
// see available options in
// https://github.com/storybookjs/storybook/tree/master/addons/options#getting-started
});
}
}
```
## .setStories()
This API is used to pass the`kind` and `stories` list to storybook-ui.
```js
import { Provider } from '@storybook/ui';
class ReactProvider extends Provider {
handleAPI(api) {
api.setStories([
{
kind: 'Component 1',
stories: ['State 1', 'State 2'],
},
{
kind: 'Component 2',
stories: ['State a', 'State b'],
},
]);
}
}
```
## .onStory()
You can use to listen to the story change and update the preview.
```js
import { Provider } from '@storybook/ui';
class ReactProvider extends Provider {
handleAPI(api) {
api.onStory((kind, story) => {
this.globalState.emit('change', kind, story);
});
}
}
```
## Hacking Guide
If you like to add features to the Storybook UI or fix bugs, this is the guide you need to follow.
First of all, you can need to start the [example](./example) app to see your changes.
### The App
This is a Redux app written based on the [Mantra architecture](https://github.com/kadirahq/mantra/).
It's a set of modules. You can see those modules at `src/modules` directory.
### Changing UI
If you like to change the appearance of the UI, you need to look at the `ui` module. Change components at the `components` directory for UI tweaks.
You can also change containers(which are written with [react-komposer](https://github.com/kadirahq/react-komposer/)) to add more data from the redux state.
### Mounting
The UI is mounted in the `src/modules/ui/routes.js`. Inside that, we have injected dependencies as well. Refer [mantra-core](https://github.com/mantrajs/mantra-core) for that.
We've injected the context and actions.
### App Context
App context is the app which application context you initialize when creating the UI. It is initialized in the `src/index.js` file. It's a non serializable state. You can access the app context from containers and basically most of the place in the app.
So, that's the place to put app wide configurations and objects which won't changed after initialized. Our redux store is also stayed inside the app context.
### Actions
Actions are the place we implement app logic in a Mantra app. Each module has a set of actions and they are globally accessible. These actions are located at `<module>/actions` directory.
They got injected into the app(when mounting) and you can access them via containers. If you are familiar with redux, this is exactly action creators. But they are not only limited to do redux stuff. Actions has the access to the app context, so literally it can do anything.
### Core API
Core API (which is passed to the Provider with `handleAPI` method) is implemented in the `api` module. We put the provider passed by the user in the app context. Then api module access it and use it as needed.
### Keyboard Shortcuts
Keyboard shortcuts are implemented in a bit different way. The final state of keyboard shortcuts is managed by the `shortcuts` module. But they are implemented in the `ui` module with `src/modules/ui/configs/handle_routing.js`
These shortcuts also can be called from main API using the `handleShortcut` method. Check the example app for the usage. That's implemented as an action in the `shortcuts` module.
The above action(or the `handleShortcut` method) accepts events as a constant defined by this module. They are defined in the `src/libs/key_events.js`. This is basically to serialize these events.
> In react-storybook we need to pass these events from the preview iframe to the main app. That's the core reason for this.
### URL Changes
TODO: state we use reach/router customized to query params
### Story Order
Stories are sorted in the order in which they were imported. This can be overridden by adding storySort to the Parameters for the stories in `.storybook/preview.js`:
```js
addParameters({
options: {
storySort: (a, b) => a[1].id.localeCompare(b[1].id),
},
});
```
|
lib/ui/README.md
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017482199473306537,
0.0001698540145298466,
0.00016546570986974984,
0.0001695793034741655,
0.000003193839575033053
] |
{
"id": 1,
"code_window": [
" ready?: boolean;\n",
" error?: any;\n",
"}\n",
"\n",
"export type Refs = Record<string, ComposedRef>;\n",
"export type RefId = string;\n",
"export type RefUrl = string;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface ComposedRefUpdate {\n",
" title?: string;\n",
" type?: 'auto-inject' | 'unknown' | 'lazy';\n",
" stories?: StoriesHash;\n",
" versions?: Versions;\n",
" loginUrl?: string;\n",
" ready?: boolean;\n",
" error?: any;\n",
"}\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 44
}
|
{
"name": "ember-fixture",
"version": "0.0.0",
"private": true,
"description": "Small description for ember-fixture goes here",
"repository": "",
"license": "MIT",
"author": "",
"directories": {
"doc": "doc",
"test": "tests"
},
"scripts": {
"build": "ember build",
"lint:hbs": "ember-template-lint .",
"lint:js": "eslint .",
"start": "ember serve",
"test": "ember test"
},
"dependencies": {},
"devDependencies": {
"@ember/jquery": "^0.5.2",
"@ember/optional-features": "^0.6.3",
"broccoli-asset-rev": "^2.7.0",
"ember-ajax": "^3.1.0",
"ember-cli": "~3.4.3",
"ember-cli-app-version": "^3.2.0",
"ember-cli-babel": "^6.16.0",
"ember-cli-dependency-checker": "^3.0.0",
"ember-cli-eslint": "^4.2.3",
"ember-cli-htmlbars": "^3.0.0",
"ember-cli-inject-live-reload": "^1.8.2",
"ember-cli-qunit": "^4.3.2",
"ember-cli-sri": "^2.1.1",
"ember-cli-template-lint": "^1.0.0-beta.1",
"ember-cli-uglify": "^2.1.0",
"ember-data": "~3.4.0",
"ember-export-application-global": "^2.0.0",
"ember-load-initializers": "^1.1.0",
"ember-maybe-import-regenerator": "^0.1.6",
"ember-resolver": "^5.0.1",
"ember-source": "~3.4.0",
"ember-welcome-page": "^3.2.0",
"eslint-plugin-ember": "^5.2.0",
"loader.js": "^4.7.0",
"qunit-dom": "^0.7.1"
},
"engines": {
"node": "6.* || 8.* || >= 10.*"
}
}
|
lib/cli/test/fixtures/ember-cli/package.json
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.0001795687130652368,
0.0001729212235659361,
0.00016601770767010748,
0.00017431849846616387,
0.000004599403837346472
] |
{
"id": 1,
"code_window": [
" ready?: boolean;\n",
" error?: any;\n",
"}\n",
"\n",
"export type Refs = Record<string, ComposedRef>;\n",
"export type RefId = string;\n",
"export type RefUrl = string;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface ComposedRefUpdate {\n",
" title?: string;\n",
" type?: 'auto-inject' | 'unknown' | 'lazy';\n",
" stories?: StoriesHash;\n",
" versions?: Versions;\n",
" loginUrl?: string;\n",
" ready?: boolean;\n",
" error?: any;\n",
"}\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 44
}
|
import React from 'react';
import BaseButton from '../components/BaseButton';
export default {
title: 'Addons/Backgrounds',
parameters: {
backgrounds: {
default: 'dark',
values: [
{ name: 'white', value: '#ffffff' },
{ name: 'light', value: '#eeeeee' },
{ name: 'gray', value: '#cccccc' },
{ name: 'dark', value: '#222222' },
{ name: 'black', value: '#000000' },
],
},
},
};
export const Story1 = () => (
<BaseButton label="You should be able to switch backgrounds for this story" />
);
Story1.storyName = 'story 1';
export const Story2 = () => <BaseButton label="This one too!" />;
Story2.storyName = 'story 2';
export const Overridden = () => <BaseButton label="This one should have different backgrounds" />;
Overridden.parameters = {
backgrounds: {
default: 'blue',
values: [
{ name: 'pink', value: 'hotpink' },
{ name: 'blue', value: 'deepskyblue' },
],
},
};
export const SkippedViaDisableTrue = () => (
<BaseButton label="This one should not use backgrounds" />
);
SkippedViaDisableTrue.storyName = 'skipped via disable: true';
SkippedViaDisableTrue.parameters = {
backgrounds: { disable: true },
};
export const GridCellSize = () => (
<BaseButton label="This one should have a different grid cell size" />
);
GridCellSize.parameters = {
grid: { cellSize: 10 },
};
|
examples/official-storybook/stories/addon-backgrounds.stories.js
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017820434004534036,
0.00017024356930051,
0.00016484585648868233,
0.0001703429443296045,
0.0000047715775508549996
] |
{
"id": 2,
"code_window": [
" ref\n",
" )\n",
" : undefined;\n",
"\n",
" const result = { ...ref, stories: after, ...rest, ready };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" api.updateRef(id, { stories: after, ...rest, ready });\n",
" },\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "replace",
"edit_start_line_idx": 215
}
|
import { location, fetch } from 'global';
import dedent from 'ts-dedent';
import {
transformStoriesRawToStoriesHash,
StoriesRaw,
StoryInput,
StoriesHash,
} from '../lib/stories';
import { ModuleFn } from '../index';
export interface SubState {
refs: Refs;
}
type Versions = Record<string, string>;
export type SetRefData = Partial<
Omit<ComposedRef, 'stories'> & {
stories?: StoriesRaw;
}
>;
export interface SubAPI {
findRef: (source: string) => ComposedRef;
setRef: (id: string, data: SetRefData, ready?: boolean) => void;
getRefs: () => Refs;
checkRef: (ref: SetRefData) => Promise<void>;
changeRefVersion: (id: string, url: string) => void;
changeRefState: (id: string, ready: boolean) => void;
}
export type StoryMapper = (ref: ComposedRef, story: StoryInput) => StoryInput;
export interface ComposedRef {
id: string;
title?: string;
url: string;
type?: 'auto-inject' | 'unknown' | 'lazy';
stories: StoriesHash;
versions?: Versions;
loginUrl?: string;
ready?: boolean;
error?: any;
}
export type Refs = Record<string, ComposedRef>;
export type RefId = string;
export type RefUrl = string;
// eslint-disable-next-line no-useless-escape
const findFilename = /(\/((?:[^\/]+?)\.[^\/]+?)|\/)$/;
const allSettled = (promises: Promise<Response>[]): Promise<(Response | false)[]> =>
Promise.all(
promises.map((promise) =>
promise.then(
(r) => (r.ok ? r : (false as const)),
() => false as const
)
)
);
export const getSourceType = (source: string) => {
const { origin: localOrigin, pathname: localPathname } = location;
const { origin: sourceOrigin, pathname: sourcePathname } = new URL(source);
const localFull = `${localOrigin + localPathname}`.replace(findFilename, '');
const sourceFull = `${sourceOrigin + sourcePathname}`.replace(findFilename, '');
if (localFull === sourceFull) {
return ['local', sourceFull];
}
if (source) {
return ['external', sourceFull];
}
return [null, null];
};
export const defaultStoryMapper: StoryMapper = (b, a) => {
return { ...a, kind: a.kind.replace('|', '/') };
};
const addRefIds = (input: StoriesHash, ref: ComposedRef): StoriesHash => {
return Object.entries(input).reduce((acc, [id, item]) => {
return { ...acc, [id]: { ...item, refId: ref.id } };
}, {} as StoriesHash);
};
const map = (
input: StoriesRaw,
ref: ComposedRef,
options: { storyMapper?: StoryMapper }
): StoriesRaw => {
const { storyMapper } = options;
if (storyMapper) {
return Object.entries(input).reduce((acc, [id, item]) => {
return { ...acc, [id]: storyMapper(ref, item) };
}, {} as StoriesRaw);
}
return input;
};
export const init: ModuleFn = ({ store, provider, fullAPI }, { runCheck = true } = {}) => {
const api: SubAPI = {
findRef: (source) => {
const refs = api.getRefs();
return Object.values(refs).find(({ url }) => url.match(source));
},
changeRefVersion: (id, url) => {
const { versions, title } = api.getRefs()[id];
const ref = { id, url, versions, title, stories: {} } as SetRefData;
api.checkRef(ref);
},
changeRefState: (id, ready) => {
const refs = api.getRefs();
store.setState({
refs: {
...refs,
[id]: { ...refs[id], ready },
},
});
},
checkRef: async (ref) => {
const { id, url } = ref;
const loadedData: { error?: Error; stories?: StoriesRaw; loginUrl?: string } = {};
const [included, omitted, iframe] = await allSettled([
fetch(`${url}/stories.json`, {
headers: {
Accept: 'application/json',
},
credentials: 'include',
}),
fetch(`${url}/stories.json`, {
headers: {
Accept: 'application/json',
},
credentials: 'omit',
}),
fetch(`${url}/iframe.html`, {
cors: 'no-cors',
credentials: 'omit',
}),
]);
const handle = async (request: Response | false): Promise<SetRefData> => {
if (request) {
return Promise.resolve(request)
.then((response) => (response.ok ? response.json() : {}))
.catch((error) => ({ error }));
}
return {};
};
if (!included && !omitted && !iframe) {
loadedData.error = {
message: dedent`
Error: Loading of ref failed
at fetch (lib/api/src/modules/refs.ts)
URL: ${url}
We weren't able to load the above URL,
it's possible a CORS error happened.
Please check your dev-tools network tab.
`,
} as Error;
} else if (omitted || included) {
const credentials = included ? 'include' : 'omit';
const [stories, metadata] = await Promise.all([
included ? handle(included) : handle(omitted),
handle(
fetch(`${url}/metadata.json`, {
headers: {
Accept: 'application/json',
},
credentials,
cache: 'no-cache',
}).catch(() => false)
),
]);
Object.assign(loadedData, { ...stories, ...metadata });
}
await api.setRef(id, {
id,
url,
...loadedData,
error: loadedData.error,
type: !loadedData.stories ? 'auto-inject' : 'lazy',
});
},
getRefs: () => {
const { refs = {} } = store.getState();
return refs;
},
setRef: (id, { stories, ...rest }, ready = false) => {
const { storyMapper = defaultStoryMapper } = provider.getConfig();
const ref = api.getRefs()[id];
const after = stories
? addRefIds(
transformStoriesRawToStoriesHash(map(stories, ref, { storyMapper }), {}, { provider }),
ref
)
: undefined;
const result = { ...ref, stories: after, ...rest, ready };
store.setState({
refs: {
...api.getRefs(),
[id]: result,
},
});
},
};
const refs = provider.getConfig().refs || {};
const initialState: SubState['refs'] = refs;
Object.values(refs).forEach((r) => {
// eslint-disable-next-line no-param-reassign
r.type = 'unknown';
});
if (runCheck) {
Object.entries(refs).forEach(([k, v]) => {
api.checkRef(v as SetRefData);
});
}
return {
api,
state: {
refs: initialState,
},
};
};
|
lib/api/src/modules/refs.ts
| 1 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.9977883100509644,
0.08068986237049103,
0.00016659669927321374,
0.00020358491747174412,
0.27043378353118896
] |
{
"id": 2,
"code_window": [
" ref\n",
" )\n",
" : undefined;\n",
"\n",
" const result = { ...ref, stories: after, ...rest, ready };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" api.updateRef(id, { stories: after, ...rest, ready });\n",
" },\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "replace",
"edit_start_line_idx": 215
}
|
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "192x192",
"type": "image/png"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
|
lib/cli/test/fixtures/update_package_organisations/public/manifest.json
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017153553199023008,
0.00017107643361669034,
0.0001706173352431506,
0.00017107643361669034,
4.590983735397458e-7
] |
{
"id": 2,
"code_window": [
" ref\n",
" )\n",
" : undefined;\n",
"\n",
" const result = { ...ref, stories: after, ...rest, ready };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" api.updateRef(id, { stories: after, ...rest, ready });\n",
" },\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "replace",
"edit_start_line_idx": 215
}
|
---
id: 'cli-options'
title: 'CLI Options'
---
React Storybook comes with two CLI utilities. They are `start-storybook` and `build-storybook`.
They have some options you can pass to alter the storybook behaviors. We have seen some of them in previous docs.
Here are all those options:
## For start-storybook
```plaintext
Usage: start-storybook [options]
Options:
--help output usage information
-V, --version output the version number
-p, --port [number] Port to run Storybook
-h, --host [string] Host to run Storybook
-s, --static-dir <dir-names> Directory where to load static files from, comma-separated list
-c, --config-dir [dir-name] Directory where to load Storybook configurations from
--https Serve Storybook over HTTPS. Note: You must provide your own certificate information.
--ssl-ca <ca> Provide an SSL certificate authority. (Optional with --https, required if using a self-signed certificate)
--ssl-cert <cert> Provide an SSL certificate. (Required with --https)
--ssl-key <key> Provide an SSL key. (Required with --https)
--smoke-test Exit after successful start
--ci CI mode (skip interactive prompts, don't open browser)
--quiet Suppress verbose build output
--no-dll Do not use dll reference
--debug-webpack Display final webpack configurations for debugging purposes
```
## For build-storybook
```plaintext
Usage: build-storybook [options]
Options:
-h, --help output usage information
-V, --version output the version number
-s, --static-dir <dir-names> Directory where to load static files from, comma-separated list
-o, --output-dir [dir-name] Directory where to store built files
-c, --config-dir [dir-name] Directory where to load Storybook configurations from
-w, --watch Enable watch mode
--loglevel [level] Control level of logging during build. Can be one of: [silly, verbose, info (default), warn, error, silent]
--quiet Suppress verbose build output
--no-dll Do not use dll reference
--debug-webpack Display final webpack configurations for debugging purposes
```
|
docs/src/pages/configurations/cli-options/index.md
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017294383724220097,
0.00016710393538232893,
0.00016302372387144715,
0.0001666958414716646,
0.000003188808250342845
] |
{
"id": 2,
"code_window": [
" ref\n",
" )\n",
" : undefined;\n",
"\n",
" const result = { ...ref, stories: after, ...rest, ready };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" api.updateRef(id, { stories: after, ...rest, ready });\n",
" },\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "replace",
"edit_start_line_idx": 215
}
|
# example addon: parameter
This addon listens to changes in story parameters, and displays them in your preferred way.
This can be useful to display metadata on component/stories.
Parameters are static data associated with a story.
Uses include:
- showing notes/documentation about your story/component
- showing a dependency graph
- showing the source code of your component and or story
- displaying a list of assets or links that belong with your component
|
dev-kits/addon-parameter/README.md
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.000172902611666359,
0.00016865352517925203,
0.00016440445324406028,
0.00016865352517925203,
0.000004249079211149365
] |
{
"id": 3,
"code_window": [
"\n",
" store.setState({\n",
" refs: {\n"
],
"labels": [
"add",
"keep",
"keep"
],
"after_edit": [
" updateRef: (id, data) => {\n",
" const { [id]: ref, ...refs } = api.getRefs();\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 217
}
|
import { location, fetch } from 'global';
import dedent from 'ts-dedent';
import {
transformStoriesRawToStoriesHash,
StoriesRaw,
StoryInput,
StoriesHash,
} from '../lib/stories';
import { ModuleFn } from '../index';
export interface SubState {
refs: Refs;
}
type Versions = Record<string, string>;
export type SetRefData = Partial<
Omit<ComposedRef, 'stories'> & {
stories?: StoriesRaw;
}
>;
export interface SubAPI {
findRef: (source: string) => ComposedRef;
setRef: (id: string, data: SetRefData, ready?: boolean) => void;
getRefs: () => Refs;
checkRef: (ref: SetRefData) => Promise<void>;
changeRefVersion: (id: string, url: string) => void;
changeRefState: (id: string, ready: boolean) => void;
}
export type StoryMapper = (ref: ComposedRef, story: StoryInput) => StoryInput;
export interface ComposedRef {
id: string;
title?: string;
url: string;
type?: 'auto-inject' | 'unknown' | 'lazy';
stories: StoriesHash;
versions?: Versions;
loginUrl?: string;
ready?: boolean;
error?: any;
}
export type Refs = Record<string, ComposedRef>;
export type RefId = string;
export type RefUrl = string;
// eslint-disable-next-line no-useless-escape
const findFilename = /(\/((?:[^\/]+?)\.[^\/]+?)|\/)$/;
const allSettled = (promises: Promise<Response>[]): Promise<(Response | false)[]> =>
Promise.all(
promises.map((promise) =>
promise.then(
(r) => (r.ok ? r : (false as const)),
() => false as const
)
)
);
export const getSourceType = (source: string) => {
const { origin: localOrigin, pathname: localPathname } = location;
const { origin: sourceOrigin, pathname: sourcePathname } = new URL(source);
const localFull = `${localOrigin + localPathname}`.replace(findFilename, '');
const sourceFull = `${sourceOrigin + sourcePathname}`.replace(findFilename, '');
if (localFull === sourceFull) {
return ['local', sourceFull];
}
if (source) {
return ['external', sourceFull];
}
return [null, null];
};
export const defaultStoryMapper: StoryMapper = (b, a) => {
return { ...a, kind: a.kind.replace('|', '/') };
};
const addRefIds = (input: StoriesHash, ref: ComposedRef): StoriesHash => {
return Object.entries(input).reduce((acc, [id, item]) => {
return { ...acc, [id]: { ...item, refId: ref.id } };
}, {} as StoriesHash);
};
const map = (
input: StoriesRaw,
ref: ComposedRef,
options: { storyMapper?: StoryMapper }
): StoriesRaw => {
const { storyMapper } = options;
if (storyMapper) {
return Object.entries(input).reduce((acc, [id, item]) => {
return { ...acc, [id]: storyMapper(ref, item) };
}, {} as StoriesRaw);
}
return input;
};
export const init: ModuleFn = ({ store, provider, fullAPI }, { runCheck = true } = {}) => {
const api: SubAPI = {
findRef: (source) => {
const refs = api.getRefs();
return Object.values(refs).find(({ url }) => url.match(source));
},
changeRefVersion: (id, url) => {
const { versions, title } = api.getRefs()[id];
const ref = { id, url, versions, title, stories: {} } as SetRefData;
api.checkRef(ref);
},
changeRefState: (id, ready) => {
const refs = api.getRefs();
store.setState({
refs: {
...refs,
[id]: { ...refs[id], ready },
},
});
},
checkRef: async (ref) => {
const { id, url } = ref;
const loadedData: { error?: Error; stories?: StoriesRaw; loginUrl?: string } = {};
const [included, omitted, iframe] = await allSettled([
fetch(`${url}/stories.json`, {
headers: {
Accept: 'application/json',
},
credentials: 'include',
}),
fetch(`${url}/stories.json`, {
headers: {
Accept: 'application/json',
},
credentials: 'omit',
}),
fetch(`${url}/iframe.html`, {
cors: 'no-cors',
credentials: 'omit',
}),
]);
const handle = async (request: Response | false): Promise<SetRefData> => {
if (request) {
return Promise.resolve(request)
.then((response) => (response.ok ? response.json() : {}))
.catch((error) => ({ error }));
}
return {};
};
if (!included && !omitted && !iframe) {
loadedData.error = {
message: dedent`
Error: Loading of ref failed
at fetch (lib/api/src/modules/refs.ts)
URL: ${url}
We weren't able to load the above URL,
it's possible a CORS error happened.
Please check your dev-tools network tab.
`,
} as Error;
} else if (omitted || included) {
const credentials = included ? 'include' : 'omit';
const [stories, metadata] = await Promise.all([
included ? handle(included) : handle(omitted),
handle(
fetch(`${url}/metadata.json`, {
headers: {
Accept: 'application/json',
},
credentials,
cache: 'no-cache',
}).catch(() => false)
),
]);
Object.assign(loadedData, { ...stories, ...metadata });
}
await api.setRef(id, {
id,
url,
...loadedData,
error: loadedData.error,
type: !loadedData.stories ? 'auto-inject' : 'lazy',
});
},
getRefs: () => {
const { refs = {} } = store.getState();
return refs;
},
setRef: (id, { stories, ...rest }, ready = false) => {
const { storyMapper = defaultStoryMapper } = provider.getConfig();
const ref = api.getRefs()[id];
const after = stories
? addRefIds(
transformStoriesRawToStoriesHash(map(stories, ref, { storyMapper }), {}, { provider }),
ref
)
: undefined;
const result = { ...ref, stories: after, ...rest, ready };
store.setState({
refs: {
...api.getRefs(),
[id]: result,
},
});
},
};
const refs = provider.getConfig().refs || {};
const initialState: SubState['refs'] = refs;
Object.values(refs).forEach((r) => {
// eslint-disable-next-line no-param-reassign
r.type = 'unknown';
});
if (runCheck) {
Object.entries(refs).forEach(([k, v]) => {
api.checkRef(v as SetRefData);
});
}
return {
api,
state: {
refs: initialState,
},
};
};
|
lib/api/src/modules/refs.ts
| 1 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.9964922070503235,
0.159160777926445,
0.0001658291439525783,
0.00018602042109705508,
0.34989842772483826
] |
{
"id": 3,
"code_window": [
"\n",
" store.setState({\n",
" refs: {\n"
],
"labels": [
"add",
"keep",
"keep"
],
"after_edit": [
" updateRef: (id, data) => {\n",
" const { [id]: ref, ...refs } = api.getRefs();\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 217
}
|
import m from 'mithril';
const BaseButton = {
view: ({ attrs }) =>
m(
'button',
{ disabled: attrs.disabled, onclick: attrs.onclick, style: attrs.style },
attrs.label
),
};
export default BaseButton;
|
examples/mithril-kitchen-sink/src/BaseButton.js
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017508456949144602,
0.00017262187611777335,
0.0001701591827441007,
0.00017262187611777335,
0.000002462693373672664
] |
{
"id": 3,
"code_window": [
"\n",
" store.setState({\n",
" refs: {\n"
],
"labels": [
"add",
"keep",
"keep"
],
"after_edit": [
" updateRef: (id, data) => {\n",
" const { [id]: ref, ...refs } = api.getRefs();\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 217
}
|
export {
storiesOf,
setAddon,
addDecorator,
addParameters,
configure,
getStorybook,
forceReRender,
raw,
} from './preview';
if (module && module.hot && module.hot.decline) {
module.hot.decline();
}
|
app/html/src/client/index.ts
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00016811824752949178,
0.00016723778389859945,
0.0001663573202677071,
0.00016723778389859945,
8.804636308923364e-7
] |
{
"id": 3,
"code_window": [
"\n",
" store.setState({\n",
" refs: {\n"
],
"labels": [
"add",
"keep",
"keep"
],
"after_edit": [
" updateRef: (id, data) => {\n",
" const { [id]: ref, ...refs } = api.getRefs();\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "add",
"edit_start_line_idx": 217
}
|
import { baseGenerator, Generator } from '../baseGenerator';
import { writePackageJson } from '../../js-package-manager';
const generator: Generator = async (packageManager, npmOptions, options) => {
const [latestRaxVersion] = await packageManager.getVersions('rax');
const packageJson = packageManager.retrievePackageJson();
const raxVersion = packageJson.dependencies.rax || latestRaxVersion;
// in case Rax project is not detected, `rax` package is not available either
packageJson.dependencies.rax = packageJson.dependencies.rax || raxVersion;
// these packages are required for Welcome story
packageJson.dependencies['rax-image'] = packageJson.dependencies['rax-image'] || raxVersion;
packageJson.dependencies['rax-link'] = packageJson.dependencies['rax-link'] || raxVersion;
packageJson.dependencies['rax-text'] = packageJson.dependencies['rax-text'] || raxVersion;
packageJson.dependencies['rax-view'] = packageJson.dependencies['rax-view'] || raxVersion;
writePackageJson(packageJson);
baseGenerator(packageManager, npmOptions, options, 'rax', {
extraPackages: ['rax'],
});
};
export default generator;
|
lib/cli/src/generators/RAX/index.ts
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017201578884851187,
0.00017106957966461778,
0.00016933144070208073,
0.00017186152399517596,
0.0000012306657026783796
] |
{
"id": 4,
"code_window": [
" store.setState({\n",
" refs: {\n",
" ...api.getRefs(),\n",
" [id]: result,\n",
" },\n",
" });\n",
" },\n",
" };\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...refs,\n",
" [id]: { ...ref, ...data },\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "replace",
"edit_start_line_idx": 219
}
|
import EventEmitter from 'events';
import {
STORY_ARGS_UPDATED,
UPDATE_STORY_ARGS,
SET_STORIES,
CURRENT_STORY_WAS_SET,
} from '@storybook/core-events';
import { location } from 'global';
import { init as initStories } from '../modules/stories';
function createMockStore(initialState) {
let state = initialState || {};
return {
getState: jest.fn(() => state),
setState: jest.fn((s) => {
state = { ...state, ...s };
return Promise.resolve(state);
}),
};
}
const provider = { getConfig: jest.fn() };
beforeEach(() => {
provider.getConfig.mockReturnValue({});
});
const mockSource = jest.fn();
class LocalEventEmitter extends EventEmitter {
on(event, callback) {
return super.on(event, (...args) => {
callback.apply({ source: mockSource() }, args);
});
}
}
beforeEach(() => {
mockSource.mockReturnValue(location.toString());
});
describe('stories API', () => {
it('sets a sensible initialState', () => {
const { state } = initStories({
storyId: 'id',
viewMode: 'story',
});
expect(state).toEqual({
storiesConfigured: false,
storiesHash: {},
storyId: 'id',
viewMode: 'story',
});
});
const parameters = {};
const storiesHash = {
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: {} },
'a--2': { kind: 'a', name: '2', parameters, path: 'a--2', id: 'a--2', args: {} },
'b-c--1': {
kind: 'b/c',
name: '1',
parameters,
path: 'b-c--1',
id: 'b-c--1',
args: {},
},
'b-d--1': {
kind: 'b/d',
name: '1',
parameters,
path: 'b-d--1',
id: 'b-d--1',
args: {},
},
'b-d--2': {
kind: 'b/d',
name: '2',
parameters,
path: 'b-d--2',
id: 'b-d--2',
args: { a: 'b' },
},
'custom-id--1': {
kind: 'b/e',
name: '1',
parameters,
path: 'custom-id--1',
id: 'custom-id--1',
args: {},
},
};
describe('setStories', () => {
it('stores basic kinds and stories w/ correct keys', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
provider.getConfig.mockReturnValue({ showRoots: false });
setStories(storiesHash);
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual([
'a',
'a--1',
'a--2',
'b',
'b-c',
'b-c--1',
'b-d',
'b-d--1',
'b-d--2',
'b-e',
'custom-id--1',
]);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a--1', 'a--2'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['a--1']).toMatchObject({
id: 'a--1',
parent: 'a',
kind: 'a',
name: '1',
parameters,
args: {},
});
expect(storedStoriesHash['a--2']).toMatchObject({
id: 'a--2',
parent: 'a',
kind: 'a',
name: '2',
parameters,
args: {},
});
expect(storedStoriesHash.b).toMatchObject({
id: 'b',
children: ['b-c', 'b-d', 'b-e'],
isRoot: false,
isComponent: false,
});
expect(storedStoriesHash['b-c']).toMatchObject({
id: 'b-c',
parent: 'b',
children: ['b-c--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['b-c--1']).toMatchObject({
id: 'b-c--1',
parent: 'b-c',
kind: 'b/c',
name: '1',
parameters,
args: {},
});
expect(storedStoriesHash['b-d']).toMatchObject({
id: 'b-d',
parent: 'b',
children: ['b-d--1', 'b-d--2'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['b-d--1']).toMatchObject({
id: 'b-d--1',
parent: 'b-d',
kind: 'b/d',
name: '1',
parameters,
args: {},
});
expect(storedStoriesHash['b-d--2']).toMatchObject({
id: 'b-d--2',
parent: 'b-d',
kind: 'b/d',
name: '2',
parameters,
args: { a: 'b' },
});
expect(storedStoriesHash['b-e']).toMatchObject({
id: 'b-e',
parent: 'b',
children: ['custom-id--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['custom-id--1']).toMatchObject({
id: 'custom-id--1',
parent: 'b-e',
kind: 'b/e',
name: '1',
parameters,
args: {},
});
});
it('sets roots when showRoots = true', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
provider.getConfig.mockReturnValue({ showRoots: true });
setStories({
'a-b--1': {
kind: 'a/b',
name: '1',
parameters,
path: 'a-b--1',
id: 'a-b--1',
args: {},
},
});
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual(['a', 'a-b', 'a-b--1']);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a-b'],
isRoot: true,
isComponent: false,
});
expect(storedStoriesHash['a-b']).toMatchObject({
id: 'a-b',
parent: 'a',
children: ['a-b--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['a-b--1']).toMatchObject({
id: 'a-b--1',
parent: 'a-b',
kind: 'a/b',
name: '1',
parameters,
args: {},
});
});
it('does not put bare stories into a root when showRoots = true', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
provider.getConfig.mockReturnValue({ showRoots: true });
setStories({
'a--1': {
kind: 'a',
name: '1',
parameters,
path: 'a--1',
id: 'a--1',
args: {},
},
});
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual(['a', 'a--1']);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['a--1']).toMatchObject({
id: 'a--1',
parent: 'a',
kind: 'a',
name: '1',
parameters,
args: {},
});
});
// Stories can get out of order for a few reasons -- see reproductions on
// https://github.com/storybookjs/storybook/issues/5518
it('does the right thing for out of order stories', async () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
await setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: {} },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: {} },
'a--2': { kind: 'a', name: '2', parameters, path: 'a--2', id: 'a--2', args: {} },
});
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual(['a', 'a--1', 'a--2', 'b', 'b--1']);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a--1', 'a--2'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash.b).toMatchObject({
id: 'b',
children: ['b--1'],
isRoot: false,
isComponent: true,
});
});
});
// Can't currently run these tests as cannot set this on the events
describe('CURRENT_STORY_WAS_SET event', () => {
it('navigates to the story', async () => {
const navigate = jest.fn();
const api = new LocalEventEmitter();
const store = createMockStore({});
const { init } = initStories({ store, navigate, provider, fullAPI: api });
init();
api.emit(CURRENT_STORY_WAS_SET, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('DOES not navigate if a settings page was selected', async () => {
const navigate = jest.fn();
const api = new LocalEventEmitter();
const store = createMockStore({ viewMode: 'settings', storyId: 'about' });
initStories({ store, navigate, provider, fullAPI: api });
api.emit(CURRENT_STORY_WAS_SET, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).not.toHaveBeenCalled();
});
});
describe('args handling', () => {
it('changes args properly, per story when receiving STORY_ARGS_UPDATED', () => {
const navigate = jest.fn();
const store = createMockStore();
const api = new LocalEventEmitter();
const {
api: { setStories },
init,
} = initStories({ store, navigate, provider, fullAPI: api });
setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: { a: 'b' } },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: { x: 'y' } },
});
const { storiesHash: initialStoriesHash } = store.getState();
expect(initialStoriesHash['a--1'].args).toEqual({ a: 'b' });
expect(initialStoriesHash['b--1'].args).toEqual({ x: 'y' });
init();
api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });
const { storiesHash: changedStoriesHash } = store.getState();
expect(changedStoriesHash['a--1'].args).toEqual({ foo: 'bar' });
expect(changedStoriesHash['b--1'].args).toEqual({ x: 'y' });
});
it('changes reffed args properly, per story when receiving STORY_ARGS_UPDATED', () => {
const navigate = jest.fn();
const store = createMockStore();
const api = new LocalEventEmitter();
const ref = { id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } };
api.findRef = () => ref;
api.getRefs = () => ({ refId: ref });
const { init } = initStories({ store, navigate, provider, fullAPI: api });
init();
mockSource.mockReturnValueOnce('http://refId/');
api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });
const { refs } = store.getState();
expect(refs).toEqual({
refId: { id: 'refId', stories: { 'a--1': { args: { foo: 'bar' } } } },
});
});
it('updateStoryArgs emits UPDATE_STORY_ARGS to the local frame and does not change anything', () => {
const navigate = jest.fn();
const emit = jest.fn();
const on = jest.fn();
const store = createMockStore();
const {
api: { setStories, updateStoryArgs },
init,
} = initStories({ store, navigate, provider, fullAPI: { emit, on } });
setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: { a: 'b' } },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: { x: 'y' } },
});
init();
updateStoryArgs({ id: 'a--1' }, { foo: 'bar' });
expect(emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {
storyId: 'a--1',
updatedArgs: { foo: 'bar' },
options: {
target: 'storybook-preview-iframe',
},
});
const { storiesHash: changedStoriesHash } = store.getState();
expect(changedStoriesHash['a--1'].args).toEqual({ a: 'b' });
expect(changedStoriesHash['b--1'].args).toEqual({ x: 'y' });
});
it('updateStoryArgs emits UPDATE_STORY_ARGS to the right frame', () => {
const navigate = jest.fn();
const emit = jest.fn();
const on = jest.fn();
const store = createMockStore();
const {
api: { setStories, updateStoryArgs },
init,
} = initStories({ store, navigate, provider, fullAPI: { emit, on } });
setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: { a: 'b' } },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: { x: 'y' } },
});
init();
updateStoryArgs({ id: 'a--1', refId: 'refId' }, { foo: 'bar' });
expect(emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {
storyId: 'a--1',
updatedArgs: { foo: 'bar' },
options: {
target: 'storybook-ref-refId',
},
});
});
});
describe('jumpToStory', () => {
it('works forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'a--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(1);
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('works backwards', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'a--2', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(-1);
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('does nothing if you are at the last story and go forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'custom-id--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you are at the first story and go backward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'a--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(-1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you have not selected a story', () => {
const navigate = jest.fn();
const store = { getState: () => ({ storiesHash }) };
const {
api: { jumpToStory },
} = initStories({ store, navigate, provider });
jumpToStory(1);
expect(navigate).not.toHaveBeenCalled();
});
});
describe('jumpToComponent', () => {
it('works forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'a--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(1);
expect(navigate).toHaveBeenCalledWith('/story/b-c--1');
});
it('works backwards', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'b-c--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(-1);
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('does nothing if you are in the last component and go forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'custom-id--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you are at the first component and go backward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'a--2', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(-1);
expect(navigate).not.toHaveBeenCalled();
});
});
describe('selectStory', () => {
it('navigates', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'story', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory('a--2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to kind/storyname (legacy api)', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'story', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory('a', '2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to storyname, without kind (legacy api)', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'story', storyId: 'a--1', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory(null, '2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating away from the settings pages', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'settings', storyId: 'about', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory('a--2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to first story in kind on call by kind', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('a');
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
describe('compnonent permalinks', () => {
it('allows navigating to kind/storyname (legacy api)', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('b/e', '1');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
it('allows navigating to component permalink/storyname (legacy api)', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('custom-id', '1');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
it('allows navigating to first story in kind on call by kind', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('b/e');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
});
});
describe('v2 SET_STORIES event', () => {
it('normalizes parameters and calls setStories for local stories', () => {
const fullAPI = { on: jest.fn(), setStories: jest.fn(), setOptions: jest.fn() };
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: { 'a--1': { kind: 'a', parameters: { story: 'story' } } },
};
onSetStories.call({ source: 'http://localhost' }, setStoriesPayload);
expect(fullAPI.setStories).toHaveBeenCalledWith(
{
'a--1': { kind: 'a', parameters: { global: 'global', kind: 'kind', story: 'story' } },
},
undefined
);
});
it('normalizes parameters and calls setRef for external stories', () => {
const fullAPI = {
on: jest.fn(),
findRef: jest.fn().mockReturnValue({ id: 'ref' }),
setRef: jest.fn(),
};
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: { 'a--1': { kind: 'a', parameters: { story: 'story' } } },
};
onSetStories.call({ source: 'http://external' }, setStoriesPayload);
expect(fullAPI.setRef).toHaveBeenCalledWith(
'ref',
{
id: 'ref',
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: {
'a--1': { kind: 'a', parameters: { global: 'global', kind: 'kind', story: 'story' } },
},
},
true
);
});
it('calls setOptions with global options parameters', () => {
const fullAPI = { on: jest.fn(), setStories: jest.fn(), setOptions: jest.fn() };
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
v: 2,
globalParameters: { options: 'options' },
kindParameters: { a: { options: 'should-be-ignored' } },
stories: { 'a--1': { kind: 'a', parameters: { options: 'should-be-ignored-also' } } },
};
onSetStories.call({ source: 'http://localhost' }, setStoriesPayload);
expect(fullAPI.setOptions).toHaveBeenCalledWith('options');
});
});
describe('legacy (v1) SET_STORIES event', () => {
it('calls setRef with stories', () => {
const fullAPI = {
on: jest.fn(),
findRef: jest.fn().mockReturnValue({ id: 'ref' }),
setRef: jest.fn(),
};
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
stories: { 'a--1': {} },
};
onSetStories.call({ source: 'http://external' }, setStoriesPayload);
expect(fullAPI.setRef).toHaveBeenCalledWith(
'ref',
{
id: 'ref',
stories: {
'a--1': {},
},
},
true
);
});
});
});
|
lib/api/src/tests/stories.test.js
| 1 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.007939004339277744,
0.00119257892947644,
0.00016362407768610865,
0.00022822251776233315,
0.0014495605137199163
] |
{
"id": 4,
"code_window": [
" store.setState({\n",
" refs: {\n",
" ...api.getRefs(),\n",
" [id]: result,\n",
" },\n",
" });\n",
" },\n",
" };\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...refs,\n",
" [id]: { ...ref, ...data },\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "replace",
"edit_start_line_idx": 219
}
|
button Testing the a11y addon
|
examples/server-kitchen-sink/views/addons/a11y/label.pug
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017245131311938167,
0.00017245131311938167,
0.00017245131311938167,
0.00017245131311938167,
0
] |
{
"id": 4,
"code_window": [
" store.setState({\n",
" refs: {\n",
" ...api.getRefs(),\n",
" [id]: result,\n",
" },\n",
" });\n",
" },\n",
" };\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...refs,\n",
" [id]: { ...ref, ...data },\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "replace",
"edit_start_line_idx": 219
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>ember-example</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{content-for "head"}}
<link integrity="" rel="stylesheet" href="{{rootURL}}assets/vendor.css">
<link integrity="" rel="stylesheet" href="{{rootURL}}assets/ember-example.css">
{{content-for "head-footer"}}
</head>
<body>
{{content-for "body"}}
<script src="{{rootURL}}assets/vendor.js"></script>
<script src="{{rootURL}}assets/ember-example.js"></script>
{{content-for "body-footer"}}
</body>
</html>
|
examples/ember-cli/app/index.html
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017209698853548616,
0.00017096060037147254,
0.00016916169261094183,
0.00017162307631224394,
0.0000012866391898569418
] |
{
"id": 4,
"code_window": [
" store.setState({\n",
" refs: {\n",
" ...api.getRefs(),\n",
" [id]: result,\n",
" },\n",
" });\n",
" },\n",
" };\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ...refs,\n",
" [id]: { ...ref, ...data },\n"
],
"file_path": "lib/api/src/modules/refs.ts",
"type": "replace",
"edit_start_line_idx": 219
}
|
require('./dist/manager').register();
|
addons/storysource/register.js
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017259015294257551,
0.00017259015294257551,
0.00017259015294257551,
0.00017259015294257551,
0
] |
{
"id": 5,
"code_window": [
" store.setState({ storiesHash });\n",
" break;\n",
" }\n",
" case 'external': {\n",
" const refs = fullAPI.getRefs();\n",
" const ref = fullAPI.findRef(sourceLocation);\n",
" (ref.stories[storyId] as Story).args = args;\n",
" store.setState({ refs: { ...refs, [ref.id]: ref } });\n",
" break;\n",
" }\n",
" default: {\n",
" logger.warn('received a STORY_ARGS_UPDATED frame that was not configured as a ref');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { id: refId, stories } = fullAPI.findRef(sourceLocation);\n",
" (stories[storyId] as Story).args = args;\n",
" fullAPI.updateRef(refId, { stories });\n"
],
"file_path": "lib/api/src/modules/stories.ts",
"type": "replace",
"edit_start_line_idx": 425
}
|
import EventEmitter from 'events';
import {
STORY_ARGS_UPDATED,
UPDATE_STORY_ARGS,
SET_STORIES,
CURRENT_STORY_WAS_SET,
} from '@storybook/core-events';
import { location } from 'global';
import { init as initStories } from '../modules/stories';
function createMockStore(initialState) {
let state = initialState || {};
return {
getState: jest.fn(() => state),
setState: jest.fn((s) => {
state = { ...state, ...s };
return Promise.resolve(state);
}),
};
}
const provider = { getConfig: jest.fn() };
beforeEach(() => {
provider.getConfig.mockReturnValue({});
});
const mockSource = jest.fn();
class LocalEventEmitter extends EventEmitter {
on(event, callback) {
return super.on(event, (...args) => {
callback.apply({ source: mockSource() }, args);
});
}
}
beforeEach(() => {
mockSource.mockReturnValue(location.toString());
});
describe('stories API', () => {
it('sets a sensible initialState', () => {
const { state } = initStories({
storyId: 'id',
viewMode: 'story',
});
expect(state).toEqual({
storiesConfigured: false,
storiesHash: {},
storyId: 'id',
viewMode: 'story',
});
});
const parameters = {};
const storiesHash = {
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: {} },
'a--2': { kind: 'a', name: '2', parameters, path: 'a--2', id: 'a--2', args: {} },
'b-c--1': {
kind: 'b/c',
name: '1',
parameters,
path: 'b-c--1',
id: 'b-c--1',
args: {},
},
'b-d--1': {
kind: 'b/d',
name: '1',
parameters,
path: 'b-d--1',
id: 'b-d--1',
args: {},
},
'b-d--2': {
kind: 'b/d',
name: '2',
parameters,
path: 'b-d--2',
id: 'b-d--2',
args: { a: 'b' },
},
'custom-id--1': {
kind: 'b/e',
name: '1',
parameters,
path: 'custom-id--1',
id: 'custom-id--1',
args: {},
},
};
describe('setStories', () => {
it('stores basic kinds and stories w/ correct keys', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
provider.getConfig.mockReturnValue({ showRoots: false });
setStories(storiesHash);
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual([
'a',
'a--1',
'a--2',
'b',
'b-c',
'b-c--1',
'b-d',
'b-d--1',
'b-d--2',
'b-e',
'custom-id--1',
]);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a--1', 'a--2'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['a--1']).toMatchObject({
id: 'a--1',
parent: 'a',
kind: 'a',
name: '1',
parameters,
args: {},
});
expect(storedStoriesHash['a--2']).toMatchObject({
id: 'a--2',
parent: 'a',
kind: 'a',
name: '2',
parameters,
args: {},
});
expect(storedStoriesHash.b).toMatchObject({
id: 'b',
children: ['b-c', 'b-d', 'b-e'],
isRoot: false,
isComponent: false,
});
expect(storedStoriesHash['b-c']).toMatchObject({
id: 'b-c',
parent: 'b',
children: ['b-c--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['b-c--1']).toMatchObject({
id: 'b-c--1',
parent: 'b-c',
kind: 'b/c',
name: '1',
parameters,
args: {},
});
expect(storedStoriesHash['b-d']).toMatchObject({
id: 'b-d',
parent: 'b',
children: ['b-d--1', 'b-d--2'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['b-d--1']).toMatchObject({
id: 'b-d--1',
parent: 'b-d',
kind: 'b/d',
name: '1',
parameters,
args: {},
});
expect(storedStoriesHash['b-d--2']).toMatchObject({
id: 'b-d--2',
parent: 'b-d',
kind: 'b/d',
name: '2',
parameters,
args: { a: 'b' },
});
expect(storedStoriesHash['b-e']).toMatchObject({
id: 'b-e',
parent: 'b',
children: ['custom-id--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['custom-id--1']).toMatchObject({
id: 'custom-id--1',
parent: 'b-e',
kind: 'b/e',
name: '1',
parameters,
args: {},
});
});
it('sets roots when showRoots = true', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
provider.getConfig.mockReturnValue({ showRoots: true });
setStories({
'a-b--1': {
kind: 'a/b',
name: '1',
parameters,
path: 'a-b--1',
id: 'a-b--1',
args: {},
},
});
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual(['a', 'a-b', 'a-b--1']);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a-b'],
isRoot: true,
isComponent: false,
});
expect(storedStoriesHash['a-b']).toMatchObject({
id: 'a-b',
parent: 'a',
children: ['a-b--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['a-b--1']).toMatchObject({
id: 'a-b--1',
parent: 'a-b',
kind: 'a/b',
name: '1',
parameters,
args: {},
});
});
it('does not put bare stories into a root when showRoots = true', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
provider.getConfig.mockReturnValue({ showRoots: true });
setStories({
'a--1': {
kind: 'a',
name: '1',
parameters,
path: 'a--1',
id: 'a--1',
args: {},
},
});
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual(['a', 'a--1']);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['a--1']).toMatchObject({
id: 'a--1',
parent: 'a',
kind: 'a',
name: '1',
parameters,
args: {},
});
});
// Stories can get out of order for a few reasons -- see reproductions on
// https://github.com/storybookjs/storybook/issues/5518
it('does the right thing for out of order stories', async () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
await setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: {} },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: {} },
'a--2': { kind: 'a', name: '2', parameters, path: 'a--2', id: 'a--2', args: {} },
});
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual(['a', 'a--1', 'a--2', 'b', 'b--1']);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a--1', 'a--2'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash.b).toMatchObject({
id: 'b',
children: ['b--1'],
isRoot: false,
isComponent: true,
});
});
});
// Can't currently run these tests as cannot set this on the events
describe('CURRENT_STORY_WAS_SET event', () => {
it('navigates to the story', async () => {
const navigate = jest.fn();
const api = new LocalEventEmitter();
const store = createMockStore({});
const { init } = initStories({ store, navigate, provider, fullAPI: api });
init();
api.emit(CURRENT_STORY_WAS_SET, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('DOES not navigate if a settings page was selected', async () => {
const navigate = jest.fn();
const api = new LocalEventEmitter();
const store = createMockStore({ viewMode: 'settings', storyId: 'about' });
initStories({ store, navigate, provider, fullAPI: api });
api.emit(CURRENT_STORY_WAS_SET, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).not.toHaveBeenCalled();
});
});
describe('args handling', () => {
it('changes args properly, per story when receiving STORY_ARGS_UPDATED', () => {
const navigate = jest.fn();
const store = createMockStore();
const api = new LocalEventEmitter();
const {
api: { setStories },
init,
} = initStories({ store, navigate, provider, fullAPI: api });
setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: { a: 'b' } },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: { x: 'y' } },
});
const { storiesHash: initialStoriesHash } = store.getState();
expect(initialStoriesHash['a--1'].args).toEqual({ a: 'b' });
expect(initialStoriesHash['b--1'].args).toEqual({ x: 'y' });
init();
api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });
const { storiesHash: changedStoriesHash } = store.getState();
expect(changedStoriesHash['a--1'].args).toEqual({ foo: 'bar' });
expect(changedStoriesHash['b--1'].args).toEqual({ x: 'y' });
});
it('changes reffed args properly, per story when receiving STORY_ARGS_UPDATED', () => {
const navigate = jest.fn();
const store = createMockStore();
const api = new LocalEventEmitter();
const ref = { id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } };
api.findRef = () => ref;
api.getRefs = () => ({ refId: ref });
const { init } = initStories({ store, navigate, provider, fullAPI: api });
init();
mockSource.mockReturnValueOnce('http://refId/');
api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });
const { refs } = store.getState();
expect(refs).toEqual({
refId: { id: 'refId', stories: { 'a--1': { args: { foo: 'bar' } } } },
});
});
it('updateStoryArgs emits UPDATE_STORY_ARGS to the local frame and does not change anything', () => {
const navigate = jest.fn();
const emit = jest.fn();
const on = jest.fn();
const store = createMockStore();
const {
api: { setStories, updateStoryArgs },
init,
} = initStories({ store, navigate, provider, fullAPI: { emit, on } });
setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: { a: 'b' } },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: { x: 'y' } },
});
init();
updateStoryArgs({ id: 'a--1' }, { foo: 'bar' });
expect(emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {
storyId: 'a--1',
updatedArgs: { foo: 'bar' },
options: {
target: 'storybook-preview-iframe',
},
});
const { storiesHash: changedStoriesHash } = store.getState();
expect(changedStoriesHash['a--1'].args).toEqual({ a: 'b' });
expect(changedStoriesHash['b--1'].args).toEqual({ x: 'y' });
});
it('updateStoryArgs emits UPDATE_STORY_ARGS to the right frame', () => {
const navigate = jest.fn();
const emit = jest.fn();
const on = jest.fn();
const store = createMockStore();
const {
api: { setStories, updateStoryArgs },
init,
} = initStories({ store, navigate, provider, fullAPI: { emit, on } });
setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: { a: 'b' } },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: { x: 'y' } },
});
init();
updateStoryArgs({ id: 'a--1', refId: 'refId' }, { foo: 'bar' });
expect(emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {
storyId: 'a--1',
updatedArgs: { foo: 'bar' },
options: {
target: 'storybook-ref-refId',
},
});
});
});
describe('jumpToStory', () => {
it('works forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'a--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(1);
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('works backwards', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'a--2', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(-1);
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('does nothing if you are at the last story and go forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'custom-id--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you are at the first story and go backward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'a--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(-1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you have not selected a story', () => {
const navigate = jest.fn();
const store = { getState: () => ({ storiesHash }) };
const {
api: { jumpToStory },
} = initStories({ store, navigate, provider });
jumpToStory(1);
expect(navigate).not.toHaveBeenCalled();
});
});
describe('jumpToComponent', () => {
it('works forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'a--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(1);
expect(navigate).toHaveBeenCalledWith('/story/b-c--1');
});
it('works backwards', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'b-c--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(-1);
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('does nothing if you are in the last component and go forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'custom-id--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you are at the first component and go backward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'a--2', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(-1);
expect(navigate).not.toHaveBeenCalled();
});
});
describe('selectStory', () => {
it('navigates', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'story', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory('a--2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to kind/storyname (legacy api)', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'story', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory('a', '2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to storyname, without kind (legacy api)', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'story', storyId: 'a--1', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory(null, '2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating away from the settings pages', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'settings', storyId: 'about', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory('a--2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to first story in kind on call by kind', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('a');
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
describe('compnonent permalinks', () => {
it('allows navigating to kind/storyname (legacy api)', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('b/e', '1');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
it('allows navigating to component permalink/storyname (legacy api)', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('custom-id', '1');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
it('allows navigating to first story in kind on call by kind', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('b/e');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
});
});
describe('v2 SET_STORIES event', () => {
it('normalizes parameters and calls setStories for local stories', () => {
const fullAPI = { on: jest.fn(), setStories: jest.fn(), setOptions: jest.fn() };
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: { 'a--1': { kind: 'a', parameters: { story: 'story' } } },
};
onSetStories.call({ source: 'http://localhost' }, setStoriesPayload);
expect(fullAPI.setStories).toHaveBeenCalledWith(
{
'a--1': { kind: 'a', parameters: { global: 'global', kind: 'kind', story: 'story' } },
},
undefined
);
});
it('normalizes parameters and calls setRef for external stories', () => {
const fullAPI = {
on: jest.fn(),
findRef: jest.fn().mockReturnValue({ id: 'ref' }),
setRef: jest.fn(),
};
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: { 'a--1': { kind: 'a', parameters: { story: 'story' } } },
};
onSetStories.call({ source: 'http://external' }, setStoriesPayload);
expect(fullAPI.setRef).toHaveBeenCalledWith(
'ref',
{
id: 'ref',
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: {
'a--1': { kind: 'a', parameters: { global: 'global', kind: 'kind', story: 'story' } },
},
},
true
);
});
it('calls setOptions with global options parameters', () => {
const fullAPI = { on: jest.fn(), setStories: jest.fn(), setOptions: jest.fn() };
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
v: 2,
globalParameters: { options: 'options' },
kindParameters: { a: { options: 'should-be-ignored' } },
stories: { 'a--1': { kind: 'a', parameters: { options: 'should-be-ignored-also' } } },
};
onSetStories.call({ source: 'http://localhost' }, setStoriesPayload);
expect(fullAPI.setOptions).toHaveBeenCalledWith('options');
});
});
describe('legacy (v1) SET_STORIES event', () => {
it('calls setRef with stories', () => {
const fullAPI = {
on: jest.fn(),
findRef: jest.fn().mockReturnValue({ id: 'ref' }),
setRef: jest.fn(),
};
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
stories: { 'a--1': {} },
};
onSetStories.call({ source: 'http://external' }, setStoriesPayload);
expect(fullAPI.setRef).toHaveBeenCalledWith(
'ref',
{
id: 'ref',
stories: {
'a--1': {},
},
},
true
);
});
});
});
|
lib/api/src/tests/stories.test.js
| 1 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.007197466678917408,
0.0013296061661094427,
0.0001635573134990409,
0.0012342435074970126,
0.001338835689239204
] |
{
"id": 5,
"code_window": [
" store.setState({ storiesHash });\n",
" break;\n",
" }\n",
" case 'external': {\n",
" const refs = fullAPI.getRefs();\n",
" const ref = fullAPI.findRef(sourceLocation);\n",
" (ref.stories[storyId] as Story).args = args;\n",
" store.setState({ refs: { ...refs, [ref.id]: ref } });\n",
" break;\n",
" }\n",
" default: {\n",
" logger.warn('received a STORY_ARGS_UPDATED frame that was not configured as a ref');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { id: refId, stories } = fullAPI.findRef(sourceLocation);\n",
" (stories[storyId] as Story).args = args;\n",
" fullAPI.updateRef(refId, { stories });\n"
],
"file_path": "lib/api/src/modules/stories.ts",
"type": "replace",
"edit_start_line_idx": 425
}
|
import { setInterval } from 'global';
import React, { Component, FunctionComponent } from 'react';
import { styled } from '@storybook/theming';
import { Collection } from '@storybook/addons';
import Sidebar, { SidebarProps } from '../sidebar/Sidebar';
import Panel from '../panel/panel';
import { Preview } from '../preview/preview';
import { previewProps } from '../preview/preview.mockdata';
import { mockDataset } from '../sidebar/mockdata';
import { DesktopProps } from './desktop';
export const panels: Collection = {
test1: {
title: 'Test 1',
render: ({ active, key }) =>
active ? (
<div id="test1" key={key}>
TEST 1
</div>
) : null,
},
test2: {
title: 'Test 2',
render: ({ active, key }) =>
active ? (
<div id="test2" key={key}>
TEST 2
</div>
) : null,
},
};
const realSidebarProps: SidebarProps = {
stories: mockDataset.withRoot,
menu: [],
refs: {},
storiesConfigured: true,
};
const PlaceholderBlock = styled.div(({ color }) => ({
background: color || 'hotpink',
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
width: '100%',
height: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
overflow: 'hidden',
}));
class PlaceholderClock extends Component<{ color: string }, { count: number }> {
state = {
count: 1,
};
interval: ReturnType<typeof setTimeout>;
componentDidMount() {
this.interval = setInterval(() => {
const { count } = this.state;
this.setState({ count: count + 1 });
}, 1000);
}
componentWillUnmount() {
const { interval } = this;
clearInterval(interval);
}
render() {
const { children, color } = this.props;
const { count } = this.state;
return (
<PlaceholderBlock color={color}>
<h2
style={{
position: 'absolute',
bottom: 0,
right: 0,
color: 'rgba(0,0,0,0.2)',
fontSize: '150px',
lineHeight: '150px',
margin: '-20px',
}}
>
{count}
</h2>
{children}
</PlaceholderBlock>
);
}
}
const MockSidebar: FunctionComponent<any> = (props) => (
<PlaceholderClock color="hotpink">
<pre>{JSON.stringify(props, null, 2)}</pre>
</PlaceholderClock>
);
const MockPreview: FunctionComponent<any> = (props) => (
<PlaceholderClock color="deepskyblue">
<pre>{JSON.stringify(props, null, 2)}</pre>
</PlaceholderClock>
);
const MockPanel: FunctionComponent<any> = (props) => (
<PlaceholderClock color="orangered">
<pre>{JSON.stringify(props, null, 2)}</pre>
</PlaceholderClock>
);
export const MockPage: FunctionComponent<any> = (props) => (
<PlaceholderClock color="cyan">
<pre>{JSON.stringify(props, null, 2)}</pre>
</PlaceholderClock>
);
export const mockProps: DesktopProps = {
Sidebar: MockSidebar,
Preview: MockPreview,
Panel: MockPanel,
Notifications: () => null,
pages: [],
options: {
isFullscreen: false,
showNav: true,
showPanel: true,
panelPosition: 'right',
isToolshown: true,
initialActive: 'canvas',
},
viewMode: 'story',
panelCount: 2,
width: 900,
height: 600,
docsOnly: false,
};
export const realProps: DesktopProps = {
Sidebar: () => <Sidebar {...realSidebarProps} />,
Preview: () => <Preview {...previewProps} />,
Notifications: () => null,
Panel: () => (
<Panel
panels={panels}
actions={{ onSelect: () => {}, toggleVisibility: () => {}, togglePosition: () => {} }}
selectedPanel="test2"
panelPosition="bottom"
absolute={false}
/>
),
pages: [],
options: {
isFullscreen: false,
showNav: true,
showPanel: true,
panelPosition: 'right',
isToolshown: true,
initialActive: 'canvas',
},
viewMode: 'story',
panelCount: 2,
width: 900,
height: 600,
docsOnly: false,
};
|
lib/ui/src/components/layout/app.mockdata.tsx
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017574189405422658,
0.00017110617773141712,
0.00016214998322539032,
0.00017143825243692845,
0.000003407929398235865
] |
{
"id": 5,
"code_window": [
" store.setState({ storiesHash });\n",
" break;\n",
" }\n",
" case 'external': {\n",
" const refs = fullAPI.getRefs();\n",
" const ref = fullAPI.findRef(sourceLocation);\n",
" (ref.stories[storyId] as Story).args = args;\n",
" store.setState({ refs: { ...refs, [ref.id]: ref } });\n",
" break;\n",
" }\n",
" default: {\n",
" logger.warn('received a STORY_ARGS_UPDATED frame that was not configured as a ref');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { id: refId, stories } = fullAPI.findRef(sourceLocation);\n",
" (stories[storyId] as Story).args = args;\n",
" fullAPI.updateRef(refId, { stories });\n"
],
"file_path": "lib/api/src/modules/stories.ts",
"type": "replace",
"edit_start_line_idx": 425
}
|
import addons from '@storybook/addons';
import { EVENTS } from './constants';
jest.mock('@storybook/addons');
const mockedAddons = addons as jest.Mocked<typeof addons>;
describe('a11yRunner', () => {
let mockChannel: { on: jest.Mock; emit?: jest.Mock };
beforeEach(() => {
mockedAddons.getChannel.mockReset();
mockChannel = { on: jest.fn(), emit: jest.fn() };
mockedAddons.getChannel.mockReturnValue(mockChannel as any);
});
it('should listen to events', () => {
// eslint-disable-next-line global-require
require('./a11yRunner');
expect(mockedAddons.getChannel).toHaveBeenCalled();
expect(mockChannel.on).toHaveBeenCalledWith(EVENTS.REQUEST, expect.any(Function));
expect(mockChannel.on).toHaveBeenCalledWith(EVENTS.MANUAL, expect.any(Function));
});
});
|
addons/a11y/src/a11yRunner.test.ts
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.0001750915835145861,
0.0001743014872772619,
0.00017383031081408262,
0.00017398252384737134,
5.621378704745439e-7
] |
{
"id": 5,
"code_window": [
" store.setState({ storiesHash });\n",
" break;\n",
" }\n",
" case 'external': {\n",
" const refs = fullAPI.getRefs();\n",
" const ref = fullAPI.findRef(sourceLocation);\n",
" (ref.stories[storyId] as Story).args = args;\n",
" store.setState({ refs: { ...refs, [ref.id]: ref } });\n",
" break;\n",
" }\n",
" default: {\n",
" logger.warn('received a STORY_ARGS_UPDATED frame that was not configured as a ref');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { id: refId, stories } = fullAPI.findRef(sourceLocation);\n",
" (stories[storyId] as Story).args = args;\n",
" fullAPI.updateRef(refId, { stories });\n"
],
"file_path": "lib/api/src/modules/stories.ts",
"type": "replace",
"edit_start_line_idx": 425
}
|
import { buildDev } from '@storybook/core/server';
import options from './options';
buildDev(options);
|
app/aurelia/src/server/index.ts
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017058008234016597,
0.00017058008234016597,
0.00017058008234016597,
0.00017058008234016597,
0
] |
{
"id": 6,
"code_window": [
" const navigate = jest.fn();\n",
" const store = createMockStore();\n",
" const api = new LocalEventEmitter();\n",
" const ref = { id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } };\n",
" api.findRef = () => ref;\n",
" api.getRefs = () => ({ refId: ref });\n",
"\n",
" const { init } = initStories({ store, navigate, provider, fullAPI: api });\n",
"\n",
" init();\n",
" mockSource.mockReturnValueOnce('http://refId/');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" api.updateRef = jest.fn();\n",
" api.findRef = () => ({ id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } });\n"
],
"file_path": "lib/api/src/tests/stories.test.js",
"type": "replace",
"edit_start_line_idx": 394
}
|
import EventEmitter from 'events';
import {
STORY_ARGS_UPDATED,
UPDATE_STORY_ARGS,
SET_STORIES,
CURRENT_STORY_WAS_SET,
} from '@storybook/core-events';
import { location } from 'global';
import { init as initStories } from '../modules/stories';
function createMockStore(initialState) {
let state = initialState || {};
return {
getState: jest.fn(() => state),
setState: jest.fn((s) => {
state = { ...state, ...s };
return Promise.resolve(state);
}),
};
}
const provider = { getConfig: jest.fn() };
beforeEach(() => {
provider.getConfig.mockReturnValue({});
});
const mockSource = jest.fn();
class LocalEventEmitter extends EventEmitter {
on(event, callback) {
return super.on(event, (...args) => {
callback.apply({ source: mockSource() }, args);
});
}
}
beforeEach(() => {
mockSource.mockReturnValue(location.toString());
});
describe('stories API', () => {
it('sets a sensible initialState', () => {
const { state } = initStories({
storyId: 'id',
viewMode: 'story',
});
expect(state).toEqual({
storiesConfigured: false,
storiesHash: {},
storyId: 'id',
viewMode: 'story',
});
});
const parameters = {};
const storiesHash = {
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: {} },
'a--2': { kind: 'a', name: '2', parameters, path: 'a--2', id: 'a--2', args: {} },
'b-c--1': {
kind: 'b/c',
name: '1',
parameters,
path: 'b-c--1',
id: 'b-c--1',
args: {},
},
'b-d--1': {
kind: 'b/d',
name: '1',
parameters,
path: 'b-d--1',
id: 'b-d--1',
args: {},
},
'b-d--2': {
kind: 'b/d',
name: '2',
parameters,
path: 'b-d--2',
id: 'b-d--2',
args: { a: 'b' },
},
'custom-id--1': {
kind: 'b/e',
name: '1',
parameters,
path: 'custom-id--1',
id: 'custom-id--1',
args: {},
},
};
describe('setStories', () => {
it('stores basic kinds and stories w/ correct keys', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
provider.getConfig.mockReturnValue({ showRoots: false });
setStories(storiesHash);
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual([
'a',
'a--1',
'a--2',
'b',
'b-c',
'b-c--1',
'b-d',
'b-d--1',
'b-d--2',
'b-e',
'custom-id--1',
]);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a--1', 'a--2'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['a--1']).toMatchObject({
id: 'a--1',
parent: 'a',
kind: 'a',
name: '1',
parameters,
args: {},
});
expect(storedStoriesHash['a--2']).toMatchObject({
id: 'a--2',
parent: 'a',
kind: 'a',
name: '2',
parameters,
args: {},
});
expect(storedStoriesHash.b).toMatchObject({
id: 'b',
children: ['b-c', 'b-d', 'b-e'],
isRoot: false,
isComponent: false,
});
expect(storedStoriesHash['b-c']).toMatchObject({
id: 'b-c',
parent: 'b',
children: ['b-c--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['b-c--1']).toMatchObject({
id: 'b-c--1',
parent: 'b-c',
kind: 'b/c',
name: '1',
parameters,
args: {},
});
expect(storedStoriesHash['b-d']).toMatchObject({
id: 'b-d',
parent: 'b',
children: ['b-d--1', 'b-d--2'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['b-d--1']).toMatchObject({
id: 'b-d--1',
parent: 'b-d',
kind: 'b/d',
name: '1',
parameters,
args: {},
});
expect(storedStoriesHash['b-d--2']).toMatchObject({
id: 'b-d--2',
parent: 'b-d',
kind: 'b/d',
name: '2',
parameters,
args: { a: 'b' },
});
expect(storedStoriesHash['b-e']).toMatchObject({
id: 'b-e',
parent: 'b',
children: ['custom-id--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['custom-id--1']).toMatchObject({
id: 'custom-id--1',
parent: 'b-e',
kind: 'b/e',
name: '1',
parameters,
args: {},
});
});
it('sets roots when showRoots = true', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
provider.getConfig.mockReturnValue({ showRoots: true });
setStories({
'a-b--1': {
kind: 'a/b',
name: '1',
parameters,
path: 'a-b--1',
id: 'a-b--1',
args: {},
},
});
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual(['a', 'a-b', 'a-b--1']);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a-b'],
isRoot: true,
isComponent: false,
});
expect(storedStoriesHash['a-b']).toMatchObject({
id: 'a-b',
parent: 'a',
children: ['a-b--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['a-b--1']).toMatchObject({
id: 'a-b--1',
parent: 'a-b',
kind: 'a/b',
name: '1',
parameters,
args: {},
});
});
it('does not put bare stories into a root when showRoots = true', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
provider.getConfig.mockReturnValue({ showRoots: true });
setStories({
'a--1': {
kind: 'a',
name: '1',
parameters,
path: 'a--1',
id: 'a--1',
args: {},
},
});
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual(['a', 'a--1']);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a--1'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash['a--1']).toMatchObject({
id: 'a--1',
parent: 'a',
kind: 'a',
name: '1',
parameters,
args: {},
});
});
// Stories can get out of order for a few reasons -- see reproductions on
// https://github.com/storybookjs/storybook/issues/5518
it('does the right thing for out of order stories', async () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories },
} = initStories({ store, navigate, provider });
await setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: {} },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: {} },
'a--2': { kind: 'a', name: '2', parameters, path: 'a--2', id: 'a--2', args: {} },
});
const { storiesHash: storedStoriesHash } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(storedStoriesHash)).toEqual(['a', 'a--1', 'a--2', 'b', 'b--1']);
expect(storedStoriesHash.a).toMatchObject({
id: 'a',
children: ['a--1', 'a--2'],
isRoot: false,
isComponent: true,
});
expect(storedStoriesHash.b).toMatchObject({
id: 'b',
children: ['b--1'],
isRoot: false,
isComponent: true,
});
});
});
// Can't currently run these tests as cannot set this on the events
describe('CURRENT_STORY_WAS_SET event', () => {
it('navigates to the story', async () => {
const navigate = jest.fn();
const api = new LocalEventEmitter();
const store = createMockStore({});
const { init } = initStories({ store, navigate, provider, fullAPI: api });
init();
api.emit(CURRENT_STORY_WAS_SET, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('DOES not navigate if a settings page was selected', async () => {
const navigate = jest.fn();
const api = new LocalEventEmitter();
const store = createMockStore({ viewMode: 'settings', storyId: 'about' });
initStories({ store, navigate, provider, fullAPI: api });
api.emit(CURRENT_STORY_WAS_SET, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).not.toHaveBeenCalled();
});
});
describe('args handling', () => {
it('changes args properly, per story when receiving STORY_ARGS_UPDATED', () => {
const navigate = jest.fn();
const store = createMockStore();
const api = new LocalEventEmitter();
const {
api: { setStories },
init,
} = initStories({ store, navigate, provider, fullAPI: api });
setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: { a: 'b' } },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: { x: 'y' } },
});
const { storiesHash: initialStoriesHash } = store.getState();
expect(initialStoriesHash['a--1'].args).toEqual({ a: 'b' });
expect(initialStoriesHash['b--1'].args).toEqual({ x: 'y' });
init();
api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });
const { storiesHash: changedStoriesHash } = store.getState();
expect(changedStoriesHash['a--1'].args).toEqual({ foo: 'bar' });
expect(changedStoriesHash['b--1'].args).toEqual({ x: 'y' });
});
it('changes reffed args properly, per story when receiving STORY_ARGS_UPDATED', () => {
const navigate = jest.fn();
const store = createMockStore();
const api = new LocalEventEmitter();
const ref = { id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } };
api.findRef = () => ref;
api.getRefs = () => ({ refId: ref });
const { init } = initStories({ store, navigate, provider, fullAPI: api });
init();
mockSource.mockReturnValueOnce('http://refId/');
api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });
const { refs } = store.getState();
expect(refs).toEqual({
refId: { id: 'refId', stories: { 'a--1': { args: { foo: 'bar' } } } },
});
});
it('updateStoryArgs emits UPDATE_STORY_ARGS to the local frame and does not change anything', () => {
const navigate = jest.fn();
const emit = jest.fn();
const on = jest.fn();
const store = createMockStore();
const {
api: { setStories, updateStoryArgs },
init,
} = initStories({ store, navigate, provider, fullAPI: { emit, on } });
setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: { a: 'b' } },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: { x: 'y' } },
});
init();
updateStoryArgs({ id: 'a--1' }, { foo: 'bar' });
expect(emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {
storyId: 'a--1',
updatedArgs: { foo: 'bar' },
options: {
target: 'storybook-preview-iframe',
},
});
const { storiesHash: changedStoriesHash } = store.getState();
expect(changedStoriesHash['a--1'].args).toEqual({ a: 'b' });
expect(changedStoriesHash['b--1'].args).toEqual({ x: 'y' });
});
it('updateStoryArgs emits UPDATE_STORY_ARGS to the right frame', () => {
const navigate = jest.fn();
const emit = jest.fn();
const on = jest.fn();
const store = createMockStore();
const {
api: { setStories, updateStoryArgs },
init,
} = initStories({ store, navigate, provider, fullAPI: { emit, on } });
setStories({
'a--1': { kind: 'a', name: '1', parameters, path: 'a--1', id: 'a--1', args: { a: 'b' } },
'b--1': { kind: 'b', name: '1', parameters, path: 'b--1', id: 'b--1', args: { x: 'y' } },
});
init();
updateStoryArgs({ id: 'a--1', refId: 'refId' }, { foo: 'bar' });
expect(emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {
storyId: 'a--1',
updatedArgs: { foo: 'bar' },
options: {
target: 'storybook-ref-refId',
},
});
});
});
describe('jumpToStory', () => {
it('works forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'a--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(1);
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('works backwards', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'a--2', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(-1);
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('does nothing if you are at the last story and go forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'custom-id--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you are at the first story and go backward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToStory },
state,
} = initStories({ store, navigate, storyId: 'a--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToStory(-1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you have not selected a story', () => {
const navigate = jest.fn();
const store = { getState: () => ({ storiesHash }) };
const {
api: { jumpToStory },
} = initStories({ store, navigate, provider });
jumpToStory(1);
expect(navigate).not.toHaveBeenCalled();
});
});
describe('jumpToComponent', () => {
it('works forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'a--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(1);
expect(navigate).toHaveBeenCalledWith('/story/b-c--1');
});
it('works backwards', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'b-c--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(-1);
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('does nothing if you are in the last component and go forward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'custom-id--1', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you are at the first component and go backward', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { setStories, jumpToComponent },
state,
} = initStories({ store, navigate, storyId: 'a--2', viewMode: 'story', provider });
store.setState(state);
setStories(storiesHash);
jumpToComponent(-1);
expect(navigate).not.toHaveBeenCalled();
});
});
describe('selectStory', () => {
it('navigates', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'story', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory('a--2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to kind/storyname (legacy api)', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'story', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory('a', '2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to storyname, without kind (legacy api)', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'story', storyId: 'a--1', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory(null, '2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating away from the settings pages', () => {
const navigate = jest.fn();
const store = {
getState: () => ({ viewMode: 'settings', storyId: 'about', storiesHash }),
};
const {
api: { selectStory },
} = initStories({ store, navigate, provider });
selectStory('a--2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to first story in kind on call by kind', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('a');
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
describe('compnonent permalinks', () => {
it('allows navigating to kind/storyname (legacy api)', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('b/e', '1');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
it('allows navigating to component permalink/storyname (legacy api)', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('custom-id', '1');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
it('allows navigating to first story in kind on call by kind', () => {
const navigate = jest.fn();
const store = createMockStore();
const {
api: { selectStory, setStories },
state,
} = initStories({ store, navigate, provider });
store.setState(state);
setStories(storiesHash);
selectStory('b/e');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
});
});
describe('v2 SET_STORIES event', () => {
it('normalizes parameters and calls setStories for local stories', () => {
const fullAPI = { on: jest.fn(), setStories: jest.fn(), setOptions: jest.fn() };
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: { 'a--1': { kind: 'a', parameters: { story: 'story' } } },
};
onSetStories.call({ source: 'http://localhost' }, setStoriesPayload);
expect(fullAPI.setStories).toHaveBeenCalledWith(
{
'a--1': { kind: 'a', parameters: { global: 'global', kind: 'kind', story: 'story' } },
},
undefined
);
});
it('normalizes parameters and calls setRef for external stories', () => {
const fullAPI = {
on: jest.fn(),
findRef: jest.fn().mockReturnValue({ id: 'ref' }),
setRef: jest.fn(),
};
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: { 'a--1': { kind: 'a', parameters: { story: 'story' } } },
};
onSetStories.call({ source: 'http://external' }, setStoriesPayload);
expect(fullAPI.setRef).toHaveBeenCalledWith(
'ref',
{
id: 'ref',
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: {
'a--1': { kind: 'a', parameters: { global: 'global', kind: 'kind', story: 'story' } },
},
},
true
);
});
it('calls setOptions with global options parameters', () => {
const fullAPI = { on: jest.fn(), setStories: jest.fn(), setOptions: jest.fn() };
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
v: 2,
globalParameters: { options: 'options' },
kindParameters: { a: { options: 'should-be-ignored' } },
stories: { 'a--1': { kind: 'a', parameters: { options: 'should-be-ignored-also' } } },
};
onSetStories.call({ source: 'http://localhost' }, setStoriesPayload);
expect(fullAPI.setOptions).toHaveBeenCalledWith('options');
});
});
describe('legacy (v1) SET_STORIES event', () => {
it('calls setRef with stories', () => {
const fullAPI = {
on: jest.fn(),
findRef: jest.fn().mockReturnValue({ id: 'ref' }),
setRef: jest.fn(),
};
const navigate = jest.fn();
const store = createMockStore();
const { init } = initStories({ store, navigate, provider, fullAPI });
init();
const onSetStories = fullAPI.on.mock.calls.find(([event]) => event === SET_STORIES)[1];
const setStoriesPayload = {
stories: { 'a--1': {} },
};
onSetStories.call({ source: 'http://external' }, setStoriesPayload);
expect(fullAPI.setRef).toHaveBeenCalledWith(
'ref',
{
id: 'ref',
stories: {
'a--1': {},
},
},
true
);
});
});
});
|
lib/api/src/tests/stories.test.js
| 1 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.9983108043670654,
0.2537510395050049,
0.00016398110892623663,
0.01374899223446846,
0.39823684096336365
] |
{
"id": 6,
"code_window": [
" const navigate = jest.fn();\n",
" const store = createMockStore();\n",
" const api = new LocalEventEmitter();\n",
" const ref = { id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } };\n",
" api.findRef = () => ref;\n",
" api.getRefs = () => ({ refId: ref });\n",
"\n",
" const { init } = initStories({ store, navigate, provider, fullAPI: api });\n",
"\n",
" init();\n",
" mockSource.mockReturnValueOnce('http://refId/');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" api.updateRef = jest.fn();\n",
" api.findRef = () => ({ id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } });\n"
],
"file_path": "lib/api/src/tests/stories.test.js",
"type": "replace",
"edit_start_line_idx": 394
}
|
import React, { AnchorHTMLAttributes, ButtonHTMLAttributes, DetailedHTMLProps } from 'react';
import { styled, isPropValid } from '@storybook/theming';
interface ButtonProps
extends DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> {
href?: void;
}
interface LinkProps
extends DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement> {
href: string;
}
const ButtonOrLink = ({ children, ...restProps }: ButtonProps | LinkProps) =>
restProps.href != null ? (
<a {...(restProps as LinkProps)}>{children}</a>
) : (
<button type="button" {...(restProps as ButtonProps)}>
{children}
</button>
);
export interface TabButtonProps {
active?: boolean;
textColor?: string;
}
export const TabButton = styled(ButtonOrLink, { shouldForwardProp: isPropValid })<TabButtonProps>(
{
whiteSpace: 'normal',
display: 'inline-flex',
overflow: 'hidden',
verticalAlign: 'top',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
textDecoration: 'none',
'&:empty': {
display: 'none',
},
},
({ theme }) => ({
padding: '0 15px',
transition: 'color 0.2s linear, border-bottom-color 0.2s linear',
height: 40,
lineHeight: '12px',
cursor: 'pointer',
background: 'transparent',
border: '0 solid transparent',
borderTop: '3px solid transparent',
borderBottom: '3px solid transparent',
fontWeight: 'bold',
fontSize: 13,
'&:focus': {
outline: '0 none',
borderBottomColor: theme.color.secondary,
},
}),
({ active, textColor, theme }) =>
active
? {
color: textColor || theme.barSelectedColor,
borderBottomColor: theme.barSelectedColor,
}
: {
color: textColor || 'inherit',
borderBottomColor: 'transparent',
}
);
TabButton.displayName = 'TabButton';
export interface IconButtonProps {
active?: boolean;
}
export const IconButton = styled(ButtonOrLink, { shouldForwardProp: isPropValid })<IconButtonProps>(
({ theme }) => ({
display: 'inline-flex',
justifyContent: 'center',
alignItems: 'center',
height: 40,
background: 'none',
color: 'inherit',
padding: 0,
cursor: 'pointer',
border: '0 solid transparent',
borderTop: '3px solid transparent',
borderBottom: '3px solid transparent',
transition: 'color 0.2s linear, border-bottom-color 0.2s linear',
'&:hover, &:focus': {
outline: '0 none',
color: theme.color.secondary,
},
'& > svg': {
width: 15,
},
}),
({ active, theme }) =>
active
? {
outline: '0 none',
borderBottomColor: theme.color.secondary,
}
: {}
);
IconButton.displayName = 'IconButton';
|
lib/components/src/bar/button.tsx
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.000177484835148789,
0.0001748191425576806,
0.00017007677524816245,
0.00017479952657595277,
0.000001939388994287583
] |
{
"id": 6,
"code_window": [
" const navigate = jest.fn();\n",
" const store = createMockStore();\n",
" const api = new LocalEventEmitter();\n",
" const ref = { id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } };\n",
" api.findRef = () => ref;\n",
" api.getRefs = () => ({ refId: ref });\n",
"\n",
" const { init } = initStories({ store, navigate, provider, fullAPI: api });\n",
"\n",
" init();\n",
" mockSource.mockReturnValueOnce('http://refId/');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" api.updateRef = jest.fn();\n",
" api.findRef = () => ({ id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } });\n"
],
"file_path": "lib/api/src/tests/stories.test.js",
"type": "replace",
"edit_start_line_idx": 394
}
|
node_modules/
|
lib/cli/test/fixtures/meteor/.gitignore
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.0001716004917398095,
0.0001716004917398095,
0.0001716004917398095,
0.0001716004917398095,
0
] |
{
"id": 6,
"code_window": [
" const navigate = jest.fn();\n",
" const store = createMockStore();\n",
" const api = new LocalEventEmitter();\n",
" const ref = { id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } };\n",
" api.findRef = () => ref;\n",
" api.getRefs = () => ({ refId: ref });\n",
"\n",
" const { init } = initStories({ store, navigate, provider, fullAPI: api });\n",
"\n",
" init();\n",
" mockSource.mockReturnValueOnce('http://refId/');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" api.updateRef = jest.fn();\n",
" api.findRef = () => ({ id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } });\n"
],
"file_path": "lib/api/src/tests/stories.test.js",
"type": "replace",
"edit_start_line_idx": 394
}
|
# ember-fixture
This README outlines the details of collaborating on this Ember application.
A short introduction of this app could go here.
## Prerequisites
You will need the following things properly installed on your computer.
* [Git](https://git-scm.com/)
* [Node.js](https://nodejs.org/) (with npm)
* [Ember CLI](https://ember-cli.com/)
* [Google Chrome](https://google.com/chrome/)
## Installation
* `git clone <repository-url>` this repository
* `cd ember-fixture`
* `npm install`
## Running / Development
* `ember serve`
* Visit your app at [http://localhost:4200](http://localhost:4200).
* Visit your tests at [http://localhost:4200/tests](http://localhost:4200/tests).
### Code Generators
Make use of the many generators for code, try `ember help generate` for more details
### Running Tests
* `ember test`
* `ember test --server`
### Linting
* `npm run lint:hbs`
* `npm run lint:js`
* `npm run lint:js -- --fix`
### Building
* `ember build` (development)
* `ember build --environment production` (production)
### Deploying
Specify what it takes to deploy your app.
## Further Reading / Useful Links
* [ember.js](https://emberjs.com/)
* [ember-cli](https://ember-cli.com/)
* Development Browser Extensions
* [ember inspector for chrome](https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi)
* [ember inspector for firefox](https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/)
|
lib/cli/test/fixtures/ember-cli/README.md
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017367341206409037,
0.00017107864550780505,
0.00016762364248279482,
0.0001711149961920455,
0.0000018825672896127799
] |
{
"id": 7,
"code_window": [
" const { init } = initStories({ store, navigate, provider, fullAPI: api });\n",
"\n",
" init();\n",
" mockSource.mockReturnValueOnce('http://refId/');\n",
" api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });\n",
"\n",
" const { refs } = store.getState();\n",
" expect(refs).toEqual({\n",
" refId: { id: 'refId', stories: { 'a--1': { args: { foo: 'bar' } } } },\n",
" });\n",
" });\n",
"\n",
" it('updateStoryArgs emits UPDATE_STORY_ARGS to the local frame and does not change anything', () => {\n",
" const navigate = jest.fn();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(api.updateRef).toHaveBeenCalledWith('refId', {\n",
" stories: { 'a--1': { args: { foo: 'bar' } } },\n"
],
"file_path": "lib/api/src/tests/stories.test.js",
"type": "replace",
"edit_start_line_idx": 403
}
|
import { location, fetch } from 'global';
import dedent from 'ts-dedent';
import {
transformStoriesRawToStoriesHash,
StoriesRaw,
StoryInput,
StoriesHash,
} from '../lib/stories';
import { ModuleFn } from '../index';
export interface SubState {
refs: Refs;
}
type Versions = Record<string, string>;
export type SetRefData = Partial<
Omit<ComposedRef, 'stories'> & {
stories?: StoriesRaw;
}
>;
export interface SubAPI {
findRef: (source: string) => ComposedRef;
setRef: (id: string, data: SetRefData, ready?: boolean) => void;
getRefs: () => Refs;
checkRef: (ref: SetRefData) => Promise<void>;
changeRefVersion: (id: string, url: string) => void;
changeRefState: (id: string, ready: boolean) => void;
}
export type StoryMapper = (ref: ComposedRef, story: StoryInput) => StoryInput;
export interface ComposedRef {
id: string;
title?: string;
url: string;
type?: 'auto-inject' | 'unknown' | 'lazy';
stories: StoriesHash;
versions?: Versions;
loginUrl?: string;
ready?: boolean;
error?: any;
}
export type Refs = Record<string, ComposedRef>;
export type RefId = string;
export type RefUrl = string;
// eslint-disable-next-line no-useless-escape
const findFilename = /(\/((?:[^\/]+?)\.[^\/]+?)|\/)$/;
const allSettled = (promises: Promise<Response>[]): Promise<(Response | false)[]> =>
Promise.all(
promises.map((promise) =>
promise.then(
(r) => (r.ok ? r : (false as const)),
() => false as const
)
)
);
export const getSourceType = (source: string) => {
const { origin: localOrigin, pathname: localPathname } = location;
const { origin: sourceOrigin, pathname: sourcePathname } = new URL(source);
const localFull = `${localOrigin + localPathname}`.replace(findFilename, '');
const sourceFull = `${sourceOrigin + sourcePathname}`.replace(findFilename, '');
if (localFull === sourceFull) {
return ['local', sourceFull];
}
if (source) {
return ['external', sourceFull];
}
return [null, null];
};
export const defaultStoryMapper: StoryMapper = (b, a) => {
return { ...a, kind: a.kind.replace('|', '/') };
};
const addRefIds = (input: StoriesHash, ref: ComposedRef): StoriesHash => {
return Object.entries(input).reduce((acc, [id, item]) => {
return { ...acc, [id]: { ...item, refId: ref.id } };
}, {} as StoriesHash);
};
const map = (
input: StoriesRaw,
ref: ComposedRef,
options: { storyMapper?: StoryMapper }
): StoriesRaw => {
const { storyMapper } = options;
if (storyMapper) {
return Object.entries(input).reduce((acc, [id, item]) => {
return { ...acc, [id]: storyMapper(ref, item) };
}, {} as StoriesRaw);
}
return input;
};
export const init: ModuleFn = ({ store, provider, fullAPI }, { runCheck = true } = {}) => {
const api: SubAPI = {
findRef: (source) => {
const refs = api.getRefs();
return Object.values(refs).find(({ url }) => url.match(source));
},
changeRefVersion: (id, url) => {
const { versions, title } = api.getRefs()[id];
const ref = { id, url, versions, title, stories: {} } as SetRefData;
api.checkRef(ref);
},
changeRefState: (id, ready) => {
const refs = api.getRefs();
store.setState({
refs: {
...refs,
[id]: { ...refs[id], ready },
},
});
},
checkRef: async (ref) => {
const { id, url } = ref;
const loadedData: { error?: Error; stories?: StoriesRaw; loginUrl?: string } = {};
const [included, omitted, iframe] = await allSettled([
fetch(`${url}/stories.json`, {
headers: {
Accept: 'application/json',
},
credentials: 'include',
}),
fetch(`${url}/stories.json`, {
headers: {
Accept: 'application/json',
},
credentials: 'omit',
}),
fetch(`${url}/iframe.html`, {
cors: 'no-cors',
credentials: 'omit',
}),
]);
const handle = async (request: Response | false): Promise<SetRefData> => {
if (request) {
return Promise.resolve(request)
.then((response) => (response.ok ? response.json() : {}))
.catch((error) => ({ error }));
}
return {};
};
if (!included && !omitted && !iframe) {
loadedData.error = {
message: dedent`
Error: Loading of ref failed
at fetch (lib/api/src/modules/refs.ts)
URL: ${url}
We weren't able to load the above URL,
it's possible a CORS error happened.
Please check your dev-tools network tab.
`,
} as Error;
} else if (omitted || included) {
const credentials = included ? 'include' : 'omit';
const [stories, metadata] = await Promise.all([
included ? handle(included) : handle(omitted),
handle(
fetch(`${url}/metadata.json`, {
headers: {
Accept: 'application/json',
},
credentials,
cache: 'no-cache',
}).catch(() => false)
),
]);
Object.assign(loadedData, { ...stories, ...metadata });
}
await api.setRef(id, {
id,
url,
...loadedData,
error: loadedData.error,
type: !loadedData.stories ? 'auto-inject' : 'lazy',
});
},
getRefs: () => {
const { refs = {} } = store.getState();
return refs;
},
setRef: (id, { stories, ...rest }, ready = false) => {
const { storyMapper = defaultStoryMapper } = provider.getConfig();
const ref = api.getRefs()[id];
const after = stories
? addRefIds(
transformStoriesRawToStoriesHash(map(stories, ref, { storyMapper }), {}, { provider }),
ref
)
: undefined;
const result = { ...ref, stories: after, ...rest, ready };
store.setState({
refs: {
...api.getRefs(),
[id]: result,
},
});
},
};
const refs = provider.getConfig().refs || {};
const initialState: SubState['refs'] = refs;
Object.values(refs).forEach((r) => {
// eslint-disable-next-line no-param-reassign
r.type = 'unknown';
});
if (runCheck) {
Object.entries(refs).forEach(([k, v]) => {
api.checkRef(v as SetRefData);
});
}
return {
api,
state: {
refs: initialState,
},
};
};
|
lib/api/src/modules/refs.ts
| 1 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.9699409604072571,
0.06207603961229324,
0.00016449227405246347,
0.0001713964156806469,
0.2107495367527008
] |
{
"id": 7,
"code_window": [
" const { init } = initStories({ store, navigate, provider, fullAPI: api });\n",
"\n",
" init();\n",
" mockSource.mockReturnValueOnce('http://refId/');\n",
" api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });\n",
"\n",
" const { refs } = store.getState();\n",
" expect(refs).toEqual({\n",
" refId: { id: 'refId', stories: { 'a--1': { args: { foo: 'bar' } } } },\n",
" });\n",
" });\n",
"\n",
" it('updateStoryArgs emits UPDATE_STORY_ARGS to the local frame and does not change anything', () => {\n",
" const navigate = jest.fn();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(api.updateRef).toHaveBeenCalledWith('refId', {\n",
" stories: { 'a--1': { args: { foo: 'bar' } } },\n"
],
"file_path": "lib/api/src/tests/stories.test.js",
"type": "replace",
"edit_start_line_idx": 403
}
|
import React, { FC, useState } from 'react';
import { styled } from '@storybook/theming';
import memoize from 'memoizerific';
import { PropSummaryValue } from './types';
import { WithTooltipPure } from '../../tooltip/WithTooltip';
import { Icons } from '../../icon/icon';
import { SyntaxHighlighter } from '../../syntaxhighlighter/syntaxhighlighter';
import { codeCommon } from '../../typography/shared';
interface ArgValueProps {
value?: PropSummaryValue;
}
interface ArgTextProps {
text: string;
}
interface ArgSummaryProps {
value: PropSummaryValue;
}
const Text = styled.span(({ theme }) => ({
fontFamily: theme.typography.fonts.mono,
fontSize: theme.typography.size.s2 - 1,
}));
const Expandable = styled.div<{}>(codeCommon, ({ theme }) => ({
fontFamily: theme.typography.fonts.mono,
color: theme.color.secondary,
margin: 0,
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
}));
const Detail = styled.div<{ width: string }>(({ theme, width }) => ({
width,
minWidth: 200,
maxWidth: 800,
padding: 15,
// Dont remove the mono fontFamily here even if it seem useless, this is used by the browser to calculate the length of a "ch" unit.
fontFamily: theme.typography.fonts.mono,
fontSize: theme.typography.size.s2 - 1,
// Most custom stylesheet will reset the box-sizing to "border-box" and will break the tooltip.
boxSizing: 'content-box',
'& code': {
padding: '0 !important',
},
}));
const ArrowIcon = styled(Icons)({
height: 10,
width: 10,
minWidth: 10,
marginLeft: 4,
});
const EmptyArg = () => {
return <span>-</span>;
};
const ArgText: FC<ArgTextProps> = ({ text }) => {
return <Text>{text}</Text>;
};
const calculateDetailWidth = memoize(1000)((detail: string): string => {
const lines = detail.split(/\r?\n/);
return `${Math.max(...lines.map((x) => x.length))}ch`;
});
const ArgSummary: FC<ArgSummaryProps> = ({ value }) => {
const { summary, detail } = value;
const [isOpen, setIsOpen] = useState(false);
// summary is used for the default value
// below check fixes not displaying default values for boolean typescript vars
const summaryAsString =
summary !== undefined && summary !== null && typeof summary.toString === 'function'
? summary.toString()
: summary;
if (detail == null) {
return <ArgText text={summaryAsString} />;
}
return (
<WithTooltipPure
closeOnClick
trigger="click"
placement="bottom"
tooltipShown={isOpen}
onVisibilityChange={(isVisible) => {
setIsOpen(isVisible);
}}
tooltip={
<Detail width={calculateDetailWidth(detail)}>
<SyntaxHighlighter language="jsx" format={false}>
{detail}
</SyntaxHighlighter>
</Detail>
}
>
<Expandable className="sbdocs-expandable">
<span>{summaryAsString}</span>
<ArrowIcon icon={isOpen ? 'arrowup' : 'arrowdown'} />
</Expandable>
</WithTooltipPure>
);
};
export const ArgValue: FC<ArgValueProps> = ({ value }) => {
return value == null ? <EmptyArg /> : <ArgSummary value={value} />;
};
|
lib/components/src/blocks/ArgsTable/ArgValue.tsx
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017711088003125042,
0.00017271550314035267,
0.00016918749315664172,
0.00017220506560988724,
0.000002560221901148907
] |
{
"id": 7,
"code_window": [
" const { init } = initStories({ store, navigate, provider, fullAPI: api });\n",
"\n",
" init();\n",
" mockSource.mockReturnValueOnce('http://refId/');\n",
" api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });\n",
"\n",
" const { refs } = store.getState();\n",
" expect(refs).toEqual({\n",
" refId: { id: 'refId', stories: { 'a--1': { args: { foo: 'bar' } } } },\n",
" });\n",
" });\n",
"\n",
" it('updateStoryArgs emits UPDATE_STORY_ARGS to the local frame and does not change anything', () => {\n",
" const navigate = jest.fn();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(api.updateRef).toHaveBeenCalledWith('refId', {\n",
" stories: { 'a--1': { args: { foo: 'bar' } } },\n"
],
"file_path": "lib/api/src/tests/stories.test.js",
"type": "replace",
"edit_start_line_idx": 403
}
|
{
"extends": [
"plugin:cypress/recommended"
],
"rules": {
"import/no-extraneous-dependencies": [
"error", { "devDependencies": true }
]
}
}
|
cypress/.eslintrc.json
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.0001737277489155531,
0.00016900248010642827,
0.00016427721129730344,
0.00016900248010642827,
0.000004725268809124827
] |
{
"id": 7,
"code_window": [
" const { init } = initStories({ store, navigate, provider, fullAPI: api });\n",
"\n",
" init();\n",
" mockSource.mockReturnValueOnce('http://refId/');\n",
" api.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });\n",
"\n",
" const { refs } = store.getState();\n",
" expect(refs).toEqual({\n",
" refId: { id: 'refId', stories: { 'a--1': { args: { foo: 'bar' } } } },\n",
" });\n",
" });\n",
"\n",
" it('updateStoryArgs emits UPDATE_STORY_ARGS to the local frame and does not change anything', () => {\n",
" const navigate = jest.fn();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(api.updateRef).toHaveBeenCalledWith('refId', {\n",
" stories: { 'a--1': { args: { foo: 'bar' } } },\n"
],
"file_path": "lib/api/src/tests/stories.test.js",
"type": "replace",
"edit_start_line_idx": 403
}
|
import addons from '@storybook/addons';
import EVENTS, { ADDON_ID } from './constants';
addons.register(ADDON_ID, (api) => {
const channel = addons.getChannel();
channel.on(EVENTS.REQUEST, ({ kind, name }) => {
const id = api.storyId(kind, name);
api.emit(EVENTS.RECEIVE, id);
});
});
|
addons/links/src/register.ts
| 0 |
https://github.com/storybookjs/storybook/commit/38e66ad7cb59885eb1b6da7fd47aae7c3376a314
|
[
0.00017515286162961274,
0.0001713117235340178,
0.0001674705999903381,
0.0001713117235340178,
0.000003841130819637328
] |
{
"id": 0,
"code_window": [
"export class StorageDataCleaner extends Disposable {\n",
"\n",
"\t// Workspace/Folder storage names are MD5 hashes (128bits / 4 due to hex presentation)\n",
"\tprivate static readonly NON_EMPTY_WORKSPACE_ID_LENGTH = 128 / 4;\n",
"\n",
"\tconstructor(\n",
"\t\tprivate readonly backupWorkspacesPath: string,\n",
"\t\t@INativeEnvironmentService private readonly environmentService: INativeEnvironmentService,\n",
"\t\t@ILogService private readonly logService: ILogService\n",
"\t) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// Reserved empty window workspace storage name when in extension development\n",
"\tprivate static readonly EXTENSION_DEV_EMPTY_WINDOW_ID = 'ext-dev';\n",
"\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "add",
"edit_start_line_idx": 19
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import product from 'vs/platform/product/common/product';
import { zoomLevelToZoomFactor } from 'vs/platform/windows/common/windows';
import { Workbench } from 'vs/workbench/browser/workbench';
import { NativeWindow } from 'vs/workbench/electron-sandbox/window';
import { setZoomLevel, setZoomFactor, setFullscreen } from 'vs/base/browser/browser';
import { domContentLoaded } from 'vs/base/browser/dom';
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
import { INativeWorkbenchConfiguration, INativeWorkbenchEnvironmentService, NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier, IWorkspaceInitializationPayload, reviveIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { ILoggerService, ILogService } from 'vs/platform/log/common/log';
import { NativeStorageService } from 'vs/platform/storage/electron-sandbox/storageService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { Disposable } from 'vs/base/common/lifecycle';
import { IMainProcessService, ISharedProcessService } from 'vs/platform/ipc/electron-sandbox/services';
import { SharedProcessService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessService';
import { RemoteAuthorityResolverService } from 'vs/platform/remote/electron-sandbox/remoteAuthorityResolverService';
import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { RemoteAgentService } from 'vs/workbench/services/remote/electron-sandbox/remoteAgentServiceImpl';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { FileService } from 'vs/platform/files/common/fileService';
import { IFileService } from 'vs/platform/files/common/files';
import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel';
import { ConfigurationCache } from 'vs/workbench/services/configuration/electron-sandbox/configurationCache';
import { ISignService } from 'vs/platform/sign/common/sign';
import { basename } from 'vs/base/common/path';
import { IProductService } from 'vs/platform/product/common/productService';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { NativeHostService } from 'vs/platform/native/electron-sandbox/nativeHostService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService';
import { KeyboardLayoutService } from 'vs/workbench/services/keybinding/electron-sandbox/nativeKeyboardLayout';
import { IKeyboardLayoutService } from 'vs/platform/keyboardLayout/common/keyboardLayout';
import { ElectronIPCMainProcessService } from 'vs/platform/ipc/electron-sandbox/mainProcessService';
import { LoggerChannelClient, LogLevelChannelClient } from 'vs/platform/log/common/logIpc';
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { NativeLogService } from 'vs/workbench/services/log/electron-sandbox/logService';
import { WorkspaceTrustEnablementService, WorkspaceTrustManagementService } from 'vs/workbench/services/workspaces/common/workspaceTrust';
import { IWorkspaceTrustEnablementService, IWorkspaceTrustManagementService } from 'vs/platform/workspace/common/workspaceTrust';
import { registerWindowDriver } from 'vs/platform/driver/electron-sandbox/driver';
import { safeStringify } from 'vs/base/common/objects';
import { ISharedProcessWorkerWorkbenchService, SharedProcessWorkerWorkbenchService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessWorkerWorkbenchService';
import { isMacintosh } from 'vs/base/common/platform';
export abstract class SharedDesktopMain extends Disposable {
constructor(
protected readonly configuration: INativeWorkbenchConfiguration
) {
super();
this.init();
}
private init(): void {
// Massage configuration file URIs
this.reviveUris();
// Browser config
const zoomLevel = this.configuration.zoomLevel || 0;
setZoomFactor(zoomLevelToZoomFactor(zoomLevel));
setZoomLevel(zoomLevel, true /* isTrusted */);
setFullscreen(!!this.configuration.fullscreen);
}
private reviveUris() {
// Workspace
const workspace = reviveIdentifier(this.configuration.workspace);
if (isWorkspaceIdentifier(workspace) || isSingleFolderWorkspaceIdentifier(workspace)) {
this.configuration.workspace = workspace;
}
// Files
const filesToWait = this.configuration.filesToWait;
const filesToWaitPaths = filesToWait?.paths;
[filesToWaitPaths, this.configuration.filesToOpenOrCreate, this.configuration.filesToDiff].forEach(paths => {
if (Array.isArray(paths)) {
paths.forEach(path => {
if (path.fileUri) {
path.fileUri = URI.revive(path.fileUri);
}
});
}
});
if (filesToWait) {
filesToWait.waitMarkerFileUri = URI.revive(filesToWait.waitMarkerFileUri);
}
}
async open(): Promise<void> {
// Init services and wait for DOM to be ready in parallel
const [services] = await Promise.all([this.initServices(), domContentLoaded()]);
// Create Workbench
const workbench = new Workbench(document.body, { extraClasses: this.getExtraClasses() }, services.serviceCollection, services.logService);
// Listeners
this.registerListeners(workbench, services.storageService);
// Startup
const instantiationService = workbench.startup();
// Window
this._register(instantiationService.createInstance(NativeWindow));
// Logging
services.logService.trace('workbench configuration', safeStringify(this.configuration));
// Driver
if (this.configuration.driver) {
instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor, this.configuration.windowId)));
}
}
private getExtraClasses(): string[] {
if (isMacintosh) {
if (this.configuration.os.release > '20.0.0') {
return ['macos-bigsur-or-newer'];
}
}
return [];
}
private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
// Workbench Lifecycle
this._register(workbench.onWillShutdown(event => event.join(storageService.close(), 'join.closeStorage')));
this._register(workbench.onDidShutdown(() => this.dispose()));
}
protected abstract registerFileSystemProviders(
mainProcessService: IMainProcessService,
sharedProcessWorkerWorkbenchService: ISharedProcessWorkerWorkbenchService,
fileService: IFileService,
logService: ILogService,
nativeHostService: INativeHostService
): void;
private async initServices(): Promise<{ serviceCollection: ServiceCollection, logService: ILogService, storageService: NativeStorageService }> {
const serviceCollection = new ServiceCollection();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Main Process
const mainProcessService = this._register(new ElectronIPCMainProcessService(this.configuration.windowId));
serviceCollection.set(IMainProcessService, mainProcessService);
// Product
const productService: IProductService = { _serviceBrand: undefined, ...product };
serviceCollection.set(IProductService, productService);
// Environment
const environmentService = new NativeWorkbenchEnvironmentService(this.configuration, productService);
serviceCollection.set(INativeWorkbenchEnvironmentService, environmentService);
// Logger
const logLevelChannelClient = new LogLevelChannelClient(mainProcessService.getChannel('logLevel'));
const loggerService = new LoggerChannelClient(environmentService.configuration.logLevel, logLevelChannelClient.onDidChangeLogLevel, mainProcessService.getChannel('logger'));
serviceCollection.set(ILoggerService, loggerService);
// Log
const logService = this._register(new NativeLogService(`renderer${this.configuration.windowId}`, environmentService.configuration.logLevel, loggerService, logLevelChannelClient, environmentService));
serviceCollection.set(ILogService, logService);
// Shared Process
const sharedProcessService = new SharedProcessService(this.configuration.windowId, logService);
serviceCollection.set(ISharedProcessService, sharedProcessService);
// Shared Process Worker
const sharedProcessWorkerWorkbenchService = new SharedProcessWorkerWorkbenchService(this.configuration.windowId, logService, sharedProcessService);
serviceCollection.set(ISharedProcessWorkerWorkbenchService, sharedProcessWorkerWorkbenchService);
// Remote
const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Sign
const signService = ProxyChannel.toService<ISignService>(mainProcessService.getChannel('sign'));
serviceCollection.set(ISignService, signService);
// Remote Agent
const remoteAgentService = this._register(new RemoteAgentService(environmentService, productService, remoteAuthorityResolverService, signService, logService));
serviceCollection.set(IRemoteAgentService, remoteAgentService);
// Native Host
const nativeHostService = new NativeHostService(this.configuration.windowId, mainProcessService) as INativeHostService;
serviceCollection.set(INativeHostService, nativeHostService);
// Files
const fileService = this._register(new FileService(logService));
serviceCollection.set(IFileService, fileService);
this.registerFileSystemProviders(mainProcessService, sharedProcessWorkerWorkbenchService, fileService, logService, nativeHostService);
// URI Identity
const uriIdentityService = new UriIdentityService(fileService);
serviceCollection.set(IUriIdentityService, uriIdentityService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Remote file system
this._register(RemoteFileSystemProvider.register(remoteAgentService, fileService, logService));
const payload = this.resolveWorkspaceInitializationPayload(environmentService);
const [configurationService, storageService] = await Promise.all([
this.createWorkspaceService(payload, environmentService, fileService, remoteAgentService, uriIdentityService, logService).then(service => {
// Workspace
serviceCollection.set(IWorkspaceContextService, service);
// Configuration
serviceCollection.set(IWorkbenchConfigurationService, service);
return service;
}),
this.createStorageService(payload, environmentService, mainProcessService).then(service => {
// Storage
serviceCollection.set(IStorageService, service);
return service;
}),
this.createKeyboardLayoutService(mainProcessService).then(service => {
// KeyboardLayout
serviceCollection.set(IKeyboardLayoutService, service);
return service;
})
]);
// Workspace Trust Service
const workspaceTrustEnablementService = new WorkspaceTrustEnablementService(configurationService, environmentService);
serviceCollection.set(IWorkspaceTrustEnablementService, workspaceTrustEnablementService);
const workspaceTrustManagementService = new WorkspaceTrustManagementService(configurationService, remoteAuthorityResolverService, storageService, uriIdentityService, environmentService, configurationService, workspaceTrustEnablementService);
serviceCollection.set(IWorkspaceTrustManagementService, workspaceTrustManagementService);
// Update workspace trust so that configuration is updated accordingly
configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted());
this._register(workspaceTrustManagementService.onDidChangeTrust(() => configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted())));
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return { serviceCollection, logService, storageService };
}
private resolveWorkspaceInitializationPayload(environmentService: INativeWorkbenchEnvironmentService): IWorkspaceInitializationPayload {
let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined = this.configuration.workspace;
// Fallback to empty workspace if we have no payload yet.
if (!workspaceInitializationPayload) {
let id: string;
if (this.configuration.backupPath) {
id = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID
} else if (environmentService.isExtensionDevelopment) {
id = 'ext-dev'; // extension development window never stores backups and is a singleton
} else {
throw new Error('Unexpected window configuration without backupPath');
}
workspaceInitializationPayload = { id };
}
return workspaceInitializationPayload;
}
private async createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, fileService: FileService, remoteAgentService: IRemoteAgentService, uriIdentityService: IUriIdentityService, logService: ILogService): Promise<WorkspaceService> {
const workspaceService = new WorkspaceService({ remoteAuthority: environmentService.remoteAuthority, configurationCache: new ConfigurationCache(URI.file(environmentService.userDataPath), fileService) }, environmentService, fileService, remoteAgentService, uriIdentityService, logService);
try {
await workspaceService.initialize(payload);
return workspaceService;
} catch (error) {
onUnexpectedError(error);
return workspaceService;
}
}
private async createStorageService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
const storageService = new NativeStorageService(payload, mainProcessService, environmentService);
try {
await storageService.initialize();
return storageService;
} catch (error) {
onUnexpectedError(error);
return storageService;
}
}
private async createKeyboardLayoutService(mainProcessService: IMainProcessService): Promise<KeyboardLayoutService> {
const keyboardLayoutService = new KeyboardLayoutService(mainProcessService);
try {
await keyboardLayoutService.initialize();
return keyboardLayoutService;
} catch (error) {
onUnexpectedError(error);
return keyboardLayoutService;
}
}
}
|
src/vs/workbench/electron-sandbox/shared.desktop.main.ts
| 1 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.010798096656799316,
0.0010848805541172624,
0.00016458860773127526,
0.00025198335060849786,
0.002028438728302717
] |
{
"id": 0,
"code_window": [
"export class StorageDataCleaner extends Disposable {\n",
"\n",
"\t// Workspace/Folder storage names are MD5 hashes (128bits / 4 due to hex presentation)\n",
"\tprivate static readonly NON_EMPTY_WORKSPACE_ID_LENGTH = 128 / 4;\n",
"\n",
"\tconstructor(\n",
"\t\tprivate readonly backupWorkspacesPath: string,\n",
"\t\t@INativeEnvironmentService private readonly environmentService: INativeEnvironmentService,\n",
"\t\t@ILogService private readonly logService: ILogService\n",
"\t) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// Reserved empty window workspace storage name when in extension development\n",
"\tprivate static readonly EXTENSION_DEV_EMPTY_WINDOW_ID = 'ext-dev';\n",
"\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "add",
"edit_start_line_idx": 19
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { URI } from 'vs/base/common/uri';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IFileService, FileSystemProviderCapabilities, IFileSystemProviderCapabilitiesChangeEvent, IFileSystemProviderRegistrationEvent } from 'vs/platform/files/common/files';
import { ExtUri, IExtUri, normalizePath } from 'vs/base/common/resources';
import { SkipList } from 'vs/base/common/skipList';
import { Event } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
class Entry {
static _clock = 0;
time: number = Entry._clock++;
constructor(readonly uri: URI) { }
touch() {
this.time = Entry._clock++;
return this;
}
}
export class UriIdentityService implements IUriIdentityService {
declare readonly _serviceBrand: undefined;
readonly extUri: IExtUri;
private readonly _dispooables = new DisposableStore();
private readonly _canonicalUris: SkipList<URI, Entry>;
private readonly _limit = 2 ** 16;
constructor(@IFileService private readonly _fileService: IFileService) {
const schemeIgnoresPathCasingCache = new Map<string, boolean>();
// assume path casing matters unless the file system provider spec'ed the opposite.
// for all other cases path casing matters, e.g for
// * virtual documents
// * in-memory uris
// * all kind of "private" schemes
const ignorePathCasing = (uri: URI): boolean => {
let ignorePathCasing = schemeIgnoresPathCasingCache.get(uri.scheme);
if (ignorePathCasing === undefined) {
// retrieve once and then case per scheme until a change happens
ignorePathCasing = _fileService.hasProvider(uri) && !this._fileService.hasCapability(uri, FileSystemProviderCapabilities.PathCaseSensitive);
schemeIgnoresPathCasingCache.set(uri.scheme, ignorePathCasing);
}
return ignorePathCasing;
};
this._dispooables.add(Event.any<IFileSystemProviderCapabilitiesChangeEvent | IFileSystemProviderRegistrationEvent>(
_fileService.onDidChangeFileSystemProviderRegistrations,
_fileService.onDidChangeFileSystemProviderCapabilities
)(e => {
// remove from cache
schemeIgnoresPathCasingCache.delete(e.scheme);
}));
this.extUri = new ExtUri(ignorePathCasing);
this._canonicalUris = new SkipList((a, b) => this.extUri.compare(a, b, true), this._limit);
}
dispose(): void {
this._dispooables.dispose();
this._canonicalUris.clear();
}
asCanonicalUri(uri: URI): URI {
// (1) normalize URI
if (this._fileService.hasProvider(uri)) {
uri = normalizePath(uri);
}
// (2) find the uri in its canonical form or use this uri to define it
let item = this._canonicalUris.get(uri);
if (item) {
return item.touch().uri.with({ fragment: uri.fragment });
}
// this uri is first and defines the canonical form
this._canonicalUris.set(uri, new Entry(uri));
this._checkTrim();
return uri;
}
private _checkTrim(): void {
if (this._canonicalUris.size < this._limit) {
return;
}
// get all entries, sort by touch (MRU) and re-initalize
// the uri cache and the entry clock. this is an expensive
// operation and should happen rarely
const entries = [...this._canonicalUris.entries()].sort((a, b) => {
if (a[1].touch < b[1].touch) {
return 1;
} else if (a[1].touch > b[1].touch) {
return -1;
} else {
return 0;
}
});
Entry._clock = 0;
this._canonicalUris.clear();
const newSize = this._limit * 0.5;
for (let i = 0; i < newSize; i++) {
this._canonicalUris.set(entries[i][0], entries[i][1].touch());
}
}
}
registerSingleton(IUriIdentityService, UriIdentityService, true);
|
src/vs/platform/uriIdentity/common/uriIdentityService.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.000495589105412364,
0.0002214659034507349,
0.00016382937610615045,
0.00016771425725892186,
0.00012108329246984795
] |
{
"id": 0,
"code_window": [
"export class StorageDataCleaner extends Disposable {\n",
"\n",
"\t// Workspace/Folder storage names are MD5 hashes (128bits / 4 due to hex presentation)\n",
"\tprivate static readonly NON_EMPTY_WORKSPACE_ID_LENGTH = 128 / 4;\n",
"\n",
"\tconstructor(\n",
"\t\tprivate readonly backupWorkspacesPath: string,\n",
"\t\t@INativeEnvironmentService private readonly environmentService: INativeEnvironmentService,\n",
"\t\t@ILogService private readonly logService: ILogService\n",
"\t) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// Reserved empty window workspace storage name when in extension development\n",
"\tprivate static readonly EXTENSION_DEV_EMPTY_WINDOW_ID = 'ext-dev';\n",
"\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "add",
"edit_start_line_idx": 19
}
|
{
"name": "vscode-html-languageserver",
"description": "HTML language server",
"version": "1.0.0",
"author": "Microsoft Corporation",
"license": "MIT",
"engines": {
"node": "*"
},
"main": "./out/node/htmlServerMain",
"dependencies": {
"vscode-css-languageservice": "^5.1.8",
"vscode-html-languageservice": "^4.1.1",
"vscode-languageserver": "^7.0.0",
"vscode-languageserver-textdocument": "^1.0.1",
"vscode-nls": "^5.0.0",
"vscode-uri": "^3.0.2"
},
"devDependencies": {
"@types/mocha": "^8.2.0",
"@types/node": "14.x"
},
"scripts": {
"compile": "npx gulp compile-extension:html-language-features-server",
"watch": "npx gulp watch-extension:html-language-features-server",
"install-service-next": "yarn add vscode-css-languageservice@next && yarn add vscode-html-languageservice@next",
"install-service-local": "yarn link vscode-css-languageservice && yarn link vscode-html-languageservice",
"install-server-next": "yarn add vscode-languageserver@next",
"install-server-local": "yarn link vscode-languageserver",
"test": "yarn compile && node ./test/index.js"
}
}
|
extensions/html-language-features/server/package.json
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00017305863730143756,
0.00017226155614480376,
0.00017101915727835149,
0.00017248420044779778,
7.547283757958212e-7
] |
{
"id": 0,
"code_window": [
"export class StorageDataCleaner extends Disposable {\n",
"\n",
"\t// Workspace/Folder storage names are MD5 hashes (128bits / 4 due to hex presentation)\n",
"\tprivate static readonly NON_EMPTY_WORKSPACE_ID_LENGTH = 128 / 4;\n",
"\n",
"\tconstructor(\n",
"\t\tprivate readonly backupWorkspacesPath: string,\n",
"\t\t@INativeEnvironmentService private readonly environmentService: INativeEnvironmentService,\n",
"\t\t@ILogService private readonly logService: ILogService\n",
"\t) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// Reserved empty window workspace storage name when in extension development\n",
"\tprivate static readonly EXTENSION_DEV_EMPTY_WINDOW_ID = 'ext-dev';\n",
"\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "add",
"edit_start_line_idx": 19
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
class Node<K, V> {
readonly forward: Node<K, V>[];
constructor(readonly level: number, readonly key: K, public value: V) {
this.forward = [];
}
}
const NIL: undefined = undefined;
interface Comparator<K> {
(a: K, b: K): number;
}
export class SkipList<K, V> implements Map<K, V> {
readonly [Symbol.toStringTag] = 'SkipList';
private _maxLevel: number;
private _level: number = 0;
private _header: Node<K, V>;
private _size: number = 0;
/**
*
* @param capacity Capacity at which the list performs best
*/
constructor(
readonly comparator: (a: K, b: K) => number,
capacity: number = 2 ** 16
) {
this._maxLevel = Math.max(1, Math.log2(capacity) | 0);
this._header = <any>new Node(this._maxLevel, NIL, NIL);
}
get size(): number {
return this._size;
}
clear(): void {
this._header = <any>new Node(this._maxLevel, NIL, NIL);
}
has(key: K): boolean {
return Boolean(SkipList._search(this, key, this.comparator));
}
get(key: K): V | undefined {
return SkipList._search(this, key, this.comparator)?.value;
}
set(key: K, value: V): this {
if (SkipList._insert(this, key, value, this.comparator)) {
this._size += 1;
}
return this;
}
delete(key: K): boolean {
const didDelete = SkipList._delete(this, key, this.comparator);
if (didDelete) {
this._size -= 1;
}
return didDelete;
}
// --- iteration
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void {
let node = this._header.forward[0];
while (node) {
callbackfn.call(thisArg, node.value, node.key, this);
node = node.forward[0];
}
}
[Symbol.iterator](): IterableIterator<[K, V]> {
return this.entries();
}
*entries(): IterableIterator<[K, V]> {
let node = this._header.forward[0];
while (node) {
yield [node.key, node.value];
node = node.forward[0];
}
}
*keys(): IterableIterator<K> {
let node = this._header.forward[0];
while (node) {
yield node.key;
node = node.forward[0];
}
}
*values(): IterableIterator<V> {
let node = this._header.forward[0];
while (node) {
yield node.value;
node = node.forward[0];
}
}
toString(): string {
// debug string...
let result = '[SkipList]:';
let node = this._header.forward[0];
while (node) {
result += `node(${node.key}, ${node.value}, lvl:${node.level})`;
node = node.forward[0];
}
return result;
}
// from https://www.epaperpress.com/sortsearch/download/skiplist.pdf
private static _search<K, V>(list: SkipList<K, V>, searchKey: K, comparator: Comparator<K>) {
let x = list._header;
for (let i = list._level - 1; i >= 0; i--) {
while (x.forward[i] && comparator(x.forward[i].key, searchKey) < 0) {
x = x.forward[i];
}
}
x = x.forward[0];
if (x && comparator(x.key, searchKey) === 0) {
return x;
}
return undefined;
}
private static _insert<K, V>(list: SkipList<K, V>, searchKey: K, value: V, comparator: Comparator<K>) {
let update: Node<K, V>[] = [];
let x = list._header;
for (let i = list._level - 1; i >= 0; i--) {
while (x.forward[i] && comparator(x.forward[i].key, searchKey) < 0) {
x = x.forward[i];
}
update[i] = x;
}
x = x.forward[0];
if (x && comparator(x.key, searchKey) === 0) {
// update
x.value = value;
return false;
} else {
// insert
let lvl = SkipList._randomLevel(list);
if (lvl > list._level) {
for (let i = list._level; i < lvl; i++) {
update[i] = list._header;
}
list._level = lvl;
}
x = new Node<K, V>(lvl, searchKey, value);
for (let i = 0; i < lvl; i++) {
x.forward[i] = update[i].forward[i];
update[i].forward[i] = x;
}
return true;
}
}
private static _randomLevel(list: SkipList<any, any>, p: number = 0.5): number {
let lvl = 1;
while (Math.random() < p && lvl < list._maxLevel) {
lvl += 1;
}
return lvl;
}
private static _delete<K, V>(list: SkipList<K, V>, searchKey: K, comparator: Comparator<K>) {
let update: Node<K, V>[] = [];
let x = list._header;
for (let i = list._level - 1; i >= 0; i--) {
while (x.forward[i] && comparator(x.forward[i].key, searchKey) < 0) {
x = x.forward[i];
}
update[i] = x;
}
x = x.forward[0];
if (!x || comparator(x.key, searchKey) !== 0) {
// not found
return false;
}
for (let i = 0; i < list._level; i++) {
if (update[i].forward[i] !== x) {
break;
}
update[i].forward[i] = x.forward[i];
}
while (list._level > 0 && list._header.forward[list._level - 1] === NIL) {
list._level -= 1;
}
return true;
}
}
|
src/vs/base/common/skipList.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00023074836644809693,
0.0001756982965162024,
0.00016764106112532318,
0.00017077455413527787,
0.00001666123716859147
] |
{
"id": 1,
"code_window": [
"\n",
"\t\t\tconst workspaces = JSON.parse(contents) as IBackupWorkspacesFormat;\n",
"\t\t\tconst emptyWorkspaces = workspaces.emptyWorkspaceInfos.map(emptyWorkspace => emptyWorkspace.backupFolder);\n",
"\n",
"\t\t\t// Read all workspace storage folders that exist\n",
"\t\t\tconst storageFolders = await Promises.readdir(this.environmentService.workspaceStorageHome.fsPath);\n",
"\t\t\tawait Promise.all(storageFolders.map(async storageFolder => {\n",
"\t\t\t\tif (storageFolder.length === StorageDataCleaner.NON_EMPTY_WORKSPACE_ID_LENGTH) {\n",
"\t\t\t\t\treturn;\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Read all workspace storage folders that exist & cleanup unused\n",
"\t\t\tconst workspaceStorageFolders = await Promises.readdir(this.environmentService.workspaceStorageHome.fsPath);\n",
"\t\t\tawait Promise.all(workspaceStorageFolders.map(async workspaceStorageFolder => {\n",
"\t\t\t\tif (\n",
"\t\t\t\t\tworkspaceStorageFolder.length === StorageDataCleaner.NON_EMPTY_WORKSPACE_ID_LENGTH || \t// keep non-empty workspaces\n",
"\t\t\t\t\tworkspaceStorageFolder === StorageDataCleaner.EXTENSION_DEV_EMPTY_WINDOW_ID ||\t\t\t// keep empty extension dev workspaces\n",
"\t\t\t\t\temptyWorkspaces.indexOf(workspaceStorageFolder) >= 0\t\t\t\t\t\t\t\t\t// keep empty workspaces that are in use\n",
"\t\t\t\t) {\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 44
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import product from 'vs/platform/product/common/product';
import { zoomLevelToZoomFactor } from 'vs/platform/windows/common/windows';
import { Workbench } from 'vs/workbench/browser/workbench';
import { NativeWindow } from 'vs/workbench/electron-sandbox/window';
import { setZoomLevel, setZoomFactor, setFullscreen } from 'vs/base/browser/browser';
import { domContentLoaded } from 'vs/base/browser/dom';
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
import { INativeWorkbenchConfiguration, INativeWorkbenchEnvironmentService, NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier, IWorkspaceInitializationPayload, reviveIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { ILoggerService, ILogService } from 'vs/platform/log/common/log';
import { NativeStorageService } from 'vs/platform/storage/electron-sandbox/storageService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { Disposable } from 'vs/base/common/lifecycle';
import { IMainProcessService, ISharedProcessService } from 'vs/platform/ipc/electron-sandbox/services';
import { SharedProcessService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessService';
import { RemoteAuthorityResolverService } from 'vs/platform/remote/electron-sandbox/remoteAuthorityResolverService';
import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { RemoteAgentService } from 'vs/workbench/services/remote/electron-sandbox/remoteAgentServiceImpl';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { FileService } from 'vs/platform/files/common/fileService';
import { IFileService } from 'vs/platform/files/common/files';
import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel';
import { ConfigurationCache } from 'vs/workbench/services/configuration/electron-sandbox/configurationCache';
import { ISignService } from 'vs/platform/sign/common/sign';
import { basename } from 'vs/base/common/path';
import { IProductService } from 'vs/platform/product/common/productService';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { NativeHostService } from 'vs/platform/native/electron-sandbox/nativeHostService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService';
import { KeyboardLayoutService } from 'vs/workbench/services/keybinding/electron-sandbox/nativeKeyboardLayout';
import { IKeyboardLayoutService } from 'vs/platform/keyboardLayout/common/keyboardLayout';
import { ElectronIPCMainProcessService } from 'vs/platform/ipc/electron-sandbox/mainProcessService';
import { LoggerChannelClient, LogLevelChannelClient } from 'vs/platform/log/common/logIpc';
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { NativeLogService } from 'vs/workbench/services/log/electron-sandbox/logService';
import { WorkspaceTrustEnablementService, WorkspaceTrustManagementService } from 'vs/workbench/services/workspaces/common/workspaceTrust';
import { IWorkspaceTrustEnablementService, IWorkspaceTrustManagementService } from 'vs/platform/workspace/common/workspaceTrust';
import { registerWindowDriver } from 'vs/platform/driver/electron-sandbox/driver';
import { safeStringify } from 'vs/base/common/objects';
import { ISharedProcessWorkerWorkbenchService, SharedProcessWorkerWorkbenchService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessWorkerWorkbenchService';
import { isMacintosh } from 'vs/base/common/platform';
export abstract class SharedDesktopMain extends Disposable {
constructor(
protected readonly configuration: INativeWorkbenchConfiguration
) {
super();
this.init();
}
private init(): void {
// Massage configuration file URIs
this.reviveUris();
// Browser config
const zoomLevel = this.configuration.zoomLevel || 0;
setZoomFactor(zoomLevelToZoomFactor(zoomLevel));
setZoomLevel(zoomLevel, true /* isTrusted */);
setFullscreen(!!this.configuration.fullscreen);
}
private reviveUris() {
// Workspace
const workspace = reviveIdentifier(this.configuration.workspace);
if (isWorkspaceIdentifier(workspace) || isSingleFolderWorkspaceIdentifier(workspace)) {
this.configuration.workspace = workspace;
}
// Files
const filesToWait = this.configuration.filesToWait;
const filesToWaitPaths = filesToWait?.paths;
[filesToWaitPaths, this.configuration.filesToOpenOrCreate, this.configuration.filesToDiff].forEach(paths => {
if (Array.isArray(paths)) {
paths.forEach(path => {
if (path.fileUri) {
path.fileUri = URI.revive(path.fileUri);
}
});
}
});
if (filesToWait) {
filesToWait.waitMarkerFileUri = URI.revive(filesToWait.waitMarkerFileUri);
}
}
async open(): Promise<void> {
// Init services and wait for DOM to be ready in parallel
const [services] = await Promise.all([this.initServices(), domContentLoaded()]);
// Create Workbench
const workbench = new Workbench(document.body, { extraClasses: this.getExtraClasses() }, services.serviceCollection, services.logService);
// Listeners
this.registerListeners(workbench, services.storageService);
// Startup
const instantiationService = workbench.startup();
// Window
this._register(instantiationService.createInstance(NativeWindow));
// Logging
services.logService.trace('workbench configuration', safeStringify(this.configuration));
// Driver
if (this.configuration.driver) {
instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor, this.configuration.windowId)));
}
}
private getExtraClasses(): string[] {
if (isMacintosh) {
if (this.configuration.os.release > '20.0.0') {
return ['macos-bigsur-or-newer'];
}
}
return [];
}
private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
// Workbench Lifecycle
this._register(workbench.onWillShutdown(event => event.join(storageService.close(), 'join.closeStorage')));
this._register(workbench.onDidShutdown(() => this.dispose()));
}
protected abstract registerFileSystemProviders(
mainProcessService: IMainProcessService,
sharedProcessWorkerWorkbenchService: ISharedProcessWorkerWorkbenchService,
fileService: IFileService,
logService: ILogService,
nativeHostService: INativeHostService
): void;
private async initServices(): Promise<{ serviceCollection: ServiceCollection, logService: ILogService, storageService: NativeStorageService }> {
const serviceCollection = new ServiceCollection();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Main Process
const mainProcessService = this._register(new ElectronIPCMainProcessService(this.configuration.windowId));
serviceCollection.set(IMainProcessService, mainProcessService);
// Product
const productService: IProductService = { _serviceBrand: undefined, ...product };
serviceCollection.set(IProductService, productService);
// Environment
const environmentService = new NativeWorkbenchEnvironmentService(this.configuration, productService);
serviceCollection.set(INativeWorkbenchEnvironmentService, environmentService);
// Logger
const logLevelChannelClient = new LogLevelChannelClient(mainProcessService.getChannel('logLevel'));
const loggerService = new LoggerChannelClient(environmentService.configuration.logLevel, logLevelChannelClient.onDidChangeLogLevel, mainProcessService.getChannel('logger'));
serviceCollection.set(ILoggerService, loggerService);
// Log
const logService = this._register(new NativeLogService(`renderer${this.configuration.windowId}`, environmentService.configuration.logLevel, loggerService, logLevelChannelClient, environmentService));
serviceCollection.set(ILogService, logService);
// Shared Process
const sharedProcessService = new SharedProcessService(this.configuration.windowId, logService);
serviceCollection.set(ISharedProcessService, sharedProcessService);
// Shared Process Worker
const sharedProcessWorkerWorkbenchService = new SharedProcessWorkerWorkbenchService(this.configuration.windowId, logService, sharedProcessService);
serviceCollection.set(ISharedProcessWorkerWorkbenchService, sharedProcessWorkerWorkbenchService);
// Remote
const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Sign
const signService = ProxyChannel.toService<ISignService>(mainProcessService.getChannel('sign'));
serviceCollection.set(ISignService, signService);
// Remote Agent
const remoteAgentService = this._register(new RemoteAgentService(environmentService, productService, remoteAuthorityResolverService, signService, logService));
serviceCollection.set(IRemoteAgentService, remoteAgentService);
// Native Host
const nativeHostService = new NativeHostService(this.configuration.windowId, mainProcessService) as INativeHostService;
serviceCollection.set(INativeHostService, nativeHostService);
// Files
const fileService = this._register(new FileService(logService));
serviceCollection.set(IFileService, fileService);
this.registerFileSystemProviders(mainProcessService, sharedProcessWorkerWorkbenchService, fileService, logService, nativeHostService);
// URI Identity
const uriIdentityService = new UriIdentityService(fileService);
serviceCollection.set(IUriIdentityService, uriIdentityService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Remote file system
this._register(RemoteFileSystemProvider.register(remoteAgentService, fileService, logService));
const payload = this.resolveWorkspaceInitializationPayload(environmentService);
const [configurationService, storageService] = await Promise.all([
this.createWorkspaceService(payload, environmentService, fileService, remoteAgentService, uriIdentityService, logService).then(service => {
// Workspace
serviceCollection.set(IWorkspaceContextService, service);
// Configuration
serviceCollection.set(IWorkbenchConfigurationService, service);
return service;
}),
this.createStorageService(payload, environmentService, mainProcessService).then(service => {
// Storage
serviceCollection.set(IStorageService, service);
return service;
}),
this.createKeyboardLayoutService(mainProcessService).then(service => {
// KeyboardLayout
serviceCollection.set(IKeyboardLayoutService, service);
return service;
})
]);
// Workspace Trust Service
const workspaceTrustEnablementService = new WorkspaceTrustEnablementService(configurationService, environmentService);
serviceCollection.set(IWorkspaceTrustEnablementService, workspaceTrustEnablementService);
const workspaceTrustManagementService = new WorkspaceTrustManagementService(configurationService, remoteAuthorityResolverService, storageService, uriIdentityService, environmentService, configurationService, workspaceTrustEnablementService);
serviceCollection.set(IWorkspaceTrustManagementService, workspaceTrustManagementService);
// Update workspace trust so that configuration is updated accordingly
configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted());
this._register(workspaceTrustManagementService.onDidChangeTrust(() => configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted())));
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return { serviceCollection, logService, storageService };
}
private resolveWorkspaceInitializationPayload(environmentService: INativeWorkbenchEnvironmentService): IWorkspaceInitializationPayload {
let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined = this.configuration.workspace;
// Fallback to empty workspace if we have no payload yet.
if (!workspaceInitializationPayload) {
let id: string;
if (this.configuration.backupPath) {
id = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID
} else if (environmentService.isExtensionDevelopment) {
id = 'ext-dev'; // extension development window never stores backups and is a singleton
} else {
throw new Error('Unexpected window configuration without backupPath');
}
workspaceInitializationPayload = { id };
}
return workspaceInitializationPayload;
}
private async createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, fileService: FileService, remoteAgentService: IRemoteAgentService, uriIdentityService: IUriIdentityService, logService: ILogService): Promise<WorkspaceService> {
const workspaceService = new WorkspaceService({ remoteAuthority: environmentService.remoteAuthority, configurationCache: new ConfigurationCache(URI.file(environmentService.userDataPath), fileService) }, environmentService, fileService, remoteAgentService, uriIdentityService, logService);
try {
await workspaceService.initialize(payload);
return workspaceService;
} catch (error) {
onUnexpectedError(error);
return workspaceService;
}
}
private async createStorageService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
const storageService = new NativeStorageService(payload, mainProcessService, environmentService);
try {
await storageService.initialize();
return storageService;
} catch (error) {
onUnexpectedError(error);
return storageService;
}
}
private async createKeyboardLayoutService(mainProcessService: IMainProcessService): Promise<KeyboardLayoutService> {
const keyboardLayoutService = new KeyboardLayoutService(mainProcessService);
try {
await keyboardLayoutService.initialize();
return keyboardLayoutService;
} catch (error) {
onUnexpectedError(error);
return keyboardLayoutService;
}
}
}
|
src/vs/workbench/electron-sandbox/shared.desktop.main.ts
| 1 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.008899237029254436,
0.0005780478240922093,
0.0001618612586753443,
0.000175030087120831,
0.0014351977733895183
] |
{
"id": 1,
"code_window": [
"\n",
"\t\t\tconst workspaces = JSON.parse(contents) as IBackupWorkspacesFormat;\n",
"\t\t\tconst emptyWorkspaces = workspaces.emptyWorkspaceInfos.map(emptyWorkspace => emptyWorkspace.backupFolder);\n",
"\n",
"\t\t\t// Read all workspace storage folders that exist\n",
"\t\t\tconst storageFolders = await Promises.readdir(this.environmentService.workspaceStorageHome.fsPath);\n",
"\t\t\tawait Promise.all(storageFolders.map(async storageFolder => {\n",
"\t\t\t\tif (storageFolder.length === StorageDataCleaner.NON_EMPTY_WORKSPACE_ID_LENGTH) {\n",
"\t\t\t\t\treturn;\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Read all workspace storage folders that exist & cleanup unused\n",
"\t\t\tconst workspaceStorageFolders = await Promises.readdir(this.environmentService.workspaceStorageHome.fsPath);\n",
"\t\t\tawait Promise.all(workspaceStorageFolders.map(async workspaceStorageFolder => {\n",
"\t\t\t\tif (\n",
"\t\t\t\t\tworkspaceStorageFolder.length === StorageDataCleaner.NON_EMPTY_WORKSPACE_ID_LENGTH || \t// keep non-empty workspaces\n",
"\t\t\t\t\tworkspaceStorageFolder === StorageDataCleaner.EXTENSION_DEV_EMPTY_WINDOW_ID ||\t\t\t// keep empty extension dev workspaces\n",
"\t\t\t\t\temptyWorkspaces.indexOf(workspaceStorageFolder) >= 0\t\t\t\t\t\t\t\t\t// keep empty workspaces that are in use\n",
"\t\t\t\t) {\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 44
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var updateGrammar = require('vscode-grammar-updater');
updateGrammar.update('jeff-hykin/cpp-textmate-grammar', 'syntaxes/objc.tmLanguage.json', './syntaxes/objective-c.tmLanguage.json', undefined, 'master', 'source/languages/cpp');
updateGrammar.update('jeff-hykin/cpp-textmate-grammar', 'syntaxes/objcpp.tmLanguage.json', './syntaxes/objective-c++.tmLanguage.json', undefined, 'master', 'source/languages/cpp');
|
extensions/objective-c/build/update-grammars.js
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00017460175149608403,
0.00017382335499860346,
0.0001730449585011229,
0.00017382335499860346,
7.783964974805713e-7
] |
{
"id": 1,
"code_window": [
"\n",
"\t\t\tconst workspaces = JSON.parse(contents) as IBackupWorkspacesFormat;\n",
"\t\t\tconst emptyWorkspaces = workspaces.emptyWorkspaceInfos.map(emptyWorkspace => emptyWorkspace.backupFolder);\n",
"\n",
"\t\t\t// Read all workspace storage folders that exist\n",
"\t\t\tconst storageFolders = await Promises.readdir(this.environmentService.workspaceStorageHome.fsPath);\n",
"\t\t\tawait Promise.all(storageFolders.map(async storageFolder => {\n",
"\t\t\t\tif (storageFolder.length === StorageDataCleaner.NON_EMPTY_WORKSPACE_ID_LENGTH) {\n",
"\t\t\t\t\treturn;\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Read all workspace storage folders that exist & cleanup unused\n",
"\t\t\tconst workspaceStorageFolders = await Promises.readdir(this.environmentService.workspaceStorageHome.fsPath);\n",
"\t\t\tawait Promise.all(workspaceStorageFolders.map(async workspaceStorageFolder => {\n",
"\t\t\t\tif (\n",
"\t\t\t\t\tworkspaceStorageFolder.length === StorageDataCleaner.NON_EMPTY_WORKSPACE_ID_LENGTH || \t// keep non-empty workspaces\n",
"\t\t\t\t\tworkspaceStorageFolder === StorageDataCleaner.EXTENSION_DEV_EMPTY_WINDOW_ID ||\t\t\t// keep empty extension dev workspaces\n",
"\t\t\t\t\temptyWorkspaces.indexOf(workspaceStorageFolder) >= 0\t\t\t\t\t\t\t\t\t// keep empty workspaces that are in use\n",
"\t\t\t\t) {\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 44
}
|
{
"name": "theme-red",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"license": "MIT",
"engines": {
"vscode": "*"
},
"contributes": {
"themes": [
{
"id": "Red",
"label": "%themeLabel%",
"uiTheme": "vs-dark",
"path": "./themes/Red-color-theme.json"
}
]
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
|
extensions/theme-red/package.json
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00017660784942563623,
0.0001738375285640359,
0.00016857139416970313,
0.000176333385752514,
0.000003725414899236057
] |
{
"id": 1,
"code_window": [
"\n",
"\t\t\tconst workspaces = JSON.parse(contents) as IBackupWorkspacesFormat;\n",
"\t\t\tconst emptyWorkspaces = workspaces.emptyWorkspaceInfos.map(emptyWorkspace => emptyWorkspace.backupFolder);\n",
"\n",
"\t\t\t// Read all workspace storage folders that exist\n",
"\t\t\tconst storageFolders = await Promises.readdir(this.environmentService.workspaceStorageHome.fsPath);\n",
"\t\t\tawait Promise.all(storageFolders.map(async storageFolder => {\n",
"\t\t\t\tif (storageFolder.length === StorageDataCleaner.NON_EMPTY_WORKSPACE_ID_LENGTH) {\n",
"\t\t\t\t\treturn;\n",
"\t\t\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Read all workspace storage folders that exist & cleanup unused\n",
"\t\t\tconst workspaceStorageFolders = await Promises.readdir(this.environmentService.workspaceStorageHome.fsPath);\n",
"\t\t\tawait Promise.all(workspaceStorageFolders.map(async workspaceStorageFolder => {\n",
"\t\t\t\tif (\n",
"\t\t\t\t\tworkspaceStorageFolder.length === StorageDataCleaner.NON_EMPTY_WORKSPACE_ID_LENGTH || \t// keep non-empty workspaces\n",
"\t\t\t\t\tworkspaceStorageFolder === StorageDataCleaner.EXTENSION_DEV_EMPTY_WINDOW_ID ||\t\t\t// keep empty extension dev workspaces\n",
"\t\t\t\t\temptyWorkspaces.indexOf(workspaceStorageFolder) >= 0\t\t\t\t\t\t\t\t\t// keep empty workspaces that are in use\n",
"\t\t\t\t) {\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 44
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { URI } from 'vs/base/common/uri';
import { getWorkspaceIdentifier, getSingleFolderWorkspaceIdentifier } from 'vs/workbench/services/workspaces/browser/workspaces';
suite('Workspaces', () => {
test('workspace identifiers are stable', function () {
// workspace identifier
assert.strictEqual(getWorkspaceIdentifier(URI.parse('vscode-remote:/hello/test')).id, '474434e4');
// single folder identifier
assert.strictEqual(getSingleFolderWorkspaceIdentifier(URI.parse('vscode-remote:/hello/test'))?.id, '474434e4');
});
});
|
src/vs/workbench/services/workspaces/test/browser/workspaces.test.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00018392375204712152,
0.00017554298392497003,
0.0001671622012509033,
0.00017554298392497003,
0.000008380775398109108
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\treturn;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tif (emptyWorkspaces.indexOf(storageFolder) === -1) {\n",
"\t\t\t\t\tthis.logService.trace(`[storage cleanup]: Deleting storage folder ${storageFolder}.`);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\tthis.logService.trace(`[storage cleanup]: Deleting workspace storage folder ${workspaceStorageFolder}.`);\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 51
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import product from 'vs/platform/product/common/product';
import { zoomLevelToZoomFactor } from 'vs/platform/windows/common/windows';
import { Workbench } from 'vs/workbench/browser/workbench';
import { NativeWindow } from 'vs/workbench/electron-sandbox/window';
import { setZoomLevel, setZoomFactor, setFullscreen } from 'vs/base/browser/browser';
import { domContentLoaded } from 'vs/base/browser/dom';
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
import { INativeWorkbenchConfiguration, INativeWorkbenchEnvironmentService, NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier, IWorkspaceInitializationPayload, reviveIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { ILoggerService, ILogService } from 'vs/platform/log/common/log';
import { NativeStorageService } from 'vs/platform/storage/electron-sandbox/storageService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { Disposable } from 'vs/base/common/lifecycle';
import { IMainProcessService, ISharedProcessService } from 'vs/platform/ipc/electron-sandbox/services';
import { SharedProcessService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessService';
import { RemoteAuthorityResolverService } from 'vs/platform/remote/electron-sandbox/remoteAuthorityResolverService';
import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { RemoteAgentService } from 'vs/workbench/services/remote/electron-sandbox/remoteAgentServiceImpl';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { FileService } from 'vs/platform/files/common/fileService';
import { IFileService } from 'vs/platform/files/common/files';
import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel';
import { ConfigurationCache } from 'vs/workbench/services/configuration/electron-sandbox/configurationCache';
import { ISignService } from 'vs/platform/sign/common/sign';
import { basename } from 'vs/base/common/path';
import { IProductService } from 'vs/platform/product/common/productService';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { NativeHostService } from 'vs/platform/native/electron-sandbox/nativeHostService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService';
import { KeyboardLayoutService } from 'vs/workbench/services/keybinding/electron-sandbox/nativeKeyboardLayout';
import { IKeyboardLayoutService } from 'vs/platform/keyboardLayout/common/keyboardLayout';
import { ElectronIPCMainProcessService } from 'vs/platform/ipc/electron-sandbox/mainProcessService';
import { LoggerChannelClient, LogLevelChannelClient } from 'vs/platform/log/common/logIpc';
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { NativeLogService } from 'vs/workbench/services/log/electron-sandbox/logService';
import { WorkspaceTrustEnablementService, WorkspaceTrustManagementService } from 'vs/workbench/services/workspaces/common/workspaceTrust';
import { IWorkspaceTrustEnablementService, IWorkspaceTrustManagementService } from 'vs/platform/workspace/common/workspaceTrust';
import { registerWindowDriver } from 'vs/platform/driver/electron-sandbox/driver';
import { safeStringify } from 'vs/base/common/objects';
import { ISharedProcessWorkerWorkbenchService, SharedProcessWorkerWorkbenchService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessWorkerWorkbenchService';
import { isMacintosh } from 'vs/base/common/platform';
export abstract class SharedDesktopMain extends Disposable {
constructor(
protected readonly configuration: INativeWorkbenchConfiguration
) {
super();
this.init();
}
private init(): void {
// Massage configuration file URIs
this.reviveUris();
// Browser config
const zoomLevel = this.configuration.zoomLevel || 0;
setZoomFactor(zoomLevelToZoomFactor(zoomLevel));
setZoomLevel(zoomLevel, true /* isTrusted */);
setFullscreen(!!this.configuration.fullscreen);
}
private reviveUris() {
// Workspace
const workspace = reviveIdentifier(this.configuration.workspace);
if (isWorkspaceIdentifier(workspace) || isSingleFolderWorkspaceIdentifier(workspace)) {
this.configuration.workspace = workspace;
}
// Files
const filesToWait = this.configuration.filesToWait;
const filesToWaitPaths = filesToWait?.paths;
[filesToWaitPaths, this.configuration.filesToOpenOrCreate, this.configuration.filesToDiff].forEach(paths => {
if (Array.isArray(paths)) {
paths.forEach(path => {
if (path.fileUri) {
path.fileUri = URI.revive(path.fileUri);
}
});
}
});
if (filesToWait) {
filesToWait.waitMarkerFileUri = URI.revive(filesToWait.waitMarkerFileUri);
}
}
async open(): Promise<void> {
// Init services and wait for DOM to be ready in parallel
const [services] = await Promise.all([this.initServices(), domContentLoaded()]);
// Create Workbench
const workbench = new Workbench(document.body, { extraClasses: this.getExtraClasses() }, services.serviceCollection, services.logService);
// Listeners
this.registerListeners(workbench, services.storageService);
// Startup
const instantiationService = workbench.startup();
// Window
this._register(instantiationService.createInstance(NativeWindow));
// Logging
services.logService.trace('workbench configuration', safeStringify(this.configuration));
// Driver
if (this.configuration.driver) {
instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor, this.configuration.windowId)));
}
}
private getExtraClasses(): string[] {
if (isMacintosh) {
if (this.configuration.os.release > '20.0.0') {
return ['macos-bigsur-or-newer'];
}
}
return [];
}
private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
// Workbench Lifecycle
this._register(workbench.onWillShutdown(event => event.join(storageService.close(), 'join.closeStorage')));
this._register(workbench.onDidShutdown(() => this.dispose()));
}
protected abstract registerFileSystemProviders(
mainProcessService: IMainProcessService,
sharedProcessWorkerWorkbenchService: ISharedProcessWorkerWorkbenchService,
fileService: IFileService,
logService: ILogService,
nativeHostService: INativeHostService
): void;
private async initServices(): Promise<{ serviceCollection: ServiceCollection, logService: ILogService, storageService: NativeStorageService }> {
const serviceCollection = new ServiceCollection();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Main Process
const mainProcessService = this._register(new ElectronIPCMainProcessService(this.configuration.windowId));
serviceCollection.set(IMainProcessService, mainProcessService);
// Product
const productService: IProductService = { _serviceBrand: undefined, ...product };
serviceCollection.set(IProductService, productService);
// Environment
const environmentService = new NativeWorkbenchEnvironmentService(this.configuration, productService);
serviceCollection.set(INativeWorkbenchEnvironmentService, environmentService);
// Logger
const logLevelChannelClient = new LogLevelChannelClient(mainProcessService.getChannel('logLevel'));
const loggerService = new LoggerChannelClient(environmentService.configuration.logLevel, logLevelChannelClient.onDidChangeLogLevel, mainProcessService.getChannel('logger'));
serviceCollection.set(ILoggerService, loggerService);
// Log
const logService = this._register(new NativeLogService(`renderer${this.configuration.windowId}`, environmentService.configuration.logLevel, loggerService, logLevelChannelClient, environmentService));
serviceCollection.set(ILogService, logService);
// Shared Process
const sharedProcessService = new SharedProcessService(this.configuration.windowId, logService);
serviceCollection.set(ISharedProcessService, sharedProcessService);
// Shared Process Worker
const sharedProcessWorkerWorkbenchService = new SharedProcessWorkerWorkbenchService(this.configuration.windowId, logService, sharedProcessService);
serviceCollection.set(ISharedProcessWorkerWorkbenchService, sharedProcessWorkerWorkbenchService);
// Remote
const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Sign
const signService = ProxyChannel.toService<ISignService>(mainProcessService.getChannel('sign'));
serviceCollection.set(ISignService, signService);
// Remote Agent
const remoteAgentService = this._register(new RemoteAgentService(environmentService, productService, remoteAuthorityResolverService, signService, logService));
serviceCollection.set(IRemoteAgentService, remoteAgentService);
// Native Host
const nativeHostService = new NativeHostService(this.configuration.windowId, mainProcessService) as INativeHostService;
serviceCollection.set(INativeHostService, nativeHostService);
// Files
const fileService = this._register(new FileService(logService));
serviceCollection.set(IFileService, fileService);
this.registerFileSystemProviders(mainProcessService, sharedProcessWorkerWorkbenchService, fileService, logService, nativeHostService);
// URI Identity
const uriIdentityService = new UriIdentityService(fileService);
serviceCollection.set(IUriIdentityService, uriIdentityService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Remote file system
this._register(RemoteFileSystemProvider.register(remoteAgentService, fileService, logService));
const payload = this.resolveWorkspaceInitializationPayload(environmentService);
const [configurationService, storageService] = await Promise.all([
this.createWorkspaceService(payload, environmentService, fileService, remoteAgentService, uriIdentityService, logService).then(service => {
// Workspace
serviceCollection.set(IWorkspaceContextService, service);
// Configuration
serviceCollection.set(IWorkbenchConfigurationService, service);
return service;
}),
this.createStorageService(payload, environmentService, mainProcessService).then(service => {
// Storage
serviceCollection.set(IStorageService, service);
return service;
}),
this.createKeyboardLayoutService(mainProcessService).then(service => {
// KeyboardLayout
serviceCollection.set(IKeyboardLayoutService, service);
return service;
})
]);
// Workspace Trust Service
const workspaceTrustEnablementService = new WorkspaceTrustEnablementService(configurationService, environmentService);
serviceCollection.set(IWorkspaceTrustEnablementService, workspaceTrustEnablementService);
const workspaceTrustManagementService = new WorkspaceTrustManagementService(configurationService, remoteAuthorityResolverService, storageService, uriIdentityService, environmentService, configurationService, workspaceTrustEnablementService);
serviceCollection.set(IWorkspaceTrustManagementService, workspaceTrustManagementService);
// Update workspace trust so that configuration is updated accordingly
configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted());
this._register(workspaceTrustManagementService.onDidChangeTrust(() => configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted())));
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return { serviceCollection, logService, storageService };
}
private resolveWorkspaceInitializationPayload(environmentService: INativeWorkbenchEnvironmentService): IWorkspaceInitializationPayload {
let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined = this.configuration.workspace;
// Fallback to empty workspace if we have no payload yet.
if (!workspaceInitializationPayload) {
let id: string;
if (this.configuration.backupPath) {
id = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID
} else if (environmentService.isExtensionDevelopment) {
id = 'ext-dev'; // extension development window never stores backups and is a singleton
} else {
throw new Error('Unexpected window configuration without backupPath');
}
workspaceInitializationPayload = { id };
}
return workspaceInitializationPayload;
}
private async createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, fileService: FileService, remoteAgentService: IRemoteAgentService, uriIdentityService: IUriIdentityService, logService: ILogService): Promise<WorkspaceService> {
const workspaceService = new WorkspaceService({ remoteAuthority: environmentService.remoteAuthority, configurationCache: new ConfigurationCache(URI.file(environmentService.userDataPath), fileService) }, environmentService, fileService, remoteAgentService, uriIdentityService, logService);
try {
await workspaceService.initialize(payload);
return workspaceService;
} catch (error) {
onUnexpectedError(error);
return workspaceService;
}
}
private async createStorageService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
const storageService = new NativeStorageService(payload, mainProcessService, environmentService);
try {
await storageService.initialize();
return storageService;
} catch (error) {
onUnexpectedError(error);
return storageService;
}
}
private async createKeyboardLayoutService(mainProcessService: IMainProcessService): Promise<KeyboardLayoutService> {
const keyboardLayoutService = new KeyboardLayoutService(mainProcessService);
try {
await keyboardLayoutService.initialize();
return keyboardLayoutService;
} catch (error) {
onUnexpectedError(error);
return keyboardLayoutService;
}
}
}
|
src/vs/workbench/electron-sandbox/shared.desktop.main.ts
| 1 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.005441694986075163,
0.0004043743829242885,
0.00016222606063820422,
0.00017130447668023407,
0.0008608296629972756
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\treturn;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tif (emptyWorkspaces.indexOf(storageFolder) === -1) {\n",
"\t\t\t\t\tthis.logService.trace(`[storage cleanup]: Deleting storage folder ${storageFolder}.`);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\tthis.logService.trace(`[storage cleanup]: Deleting workspace storage folder ${workspaceStorageFolder}.`);\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 51
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CharCode } from 'vs/base/common/charCode';
import { IDisposable } from 'vs/base/common/lifecycle';
import * as strings from 'vs/base/common/strings';
import { DefaultEndOfLine, ITextBuffer, ITextBufferBuilder, ITextBufferFactory } from 'vs/editor/common/model';
import { StringBuffer, createLineStarts, createLineStartsFast } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase';
import { PieceTreeTextBuffer } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer';
export class PieceTreeTextBufferFactory implements ITextBufferFactory {
constructor(
private readonly _chunks: StringBuffer[],
private readonly _bom: string,
private readonly _cr: number,
private readonly _lf: number,
private readonly _crlf: number,
private readonly _containsRTL: boolean,
private readonly _containsUnusualLineTerminators: boolean,
private readonly _isBasicASCII: boolean,
private readonly _normalizeEOL: boolean
) { }
private _getEOL(defaultEOL: DefaultEndOfLine): '\r\n' | '\n' {
const totalEOLCount = this._cr + this._lf + this._crlf;
const totalCRCount = this._cr + this._crlf;
if (totalEOLCount === 0) {
// This is an empty file or a file with precisely one line
return (defaultEOL === DefaultEndOfLine.LF ? '\n' : '\r\n');
}
if (totalCRCount > totalEOLCount / 2) {
// More than half of the file contains \r\n ending lines
return '\r\n';
}
// At least one line more ends in \n
return '\n';
}
public create(defaultEOL: DefaultEndOfLine): { textBuffer: ITextBuffer; disposable: IDisposable; } {
const eol = this._getEOL(defaultEOL);
let chunks = this._chunks;
if (this._normalizeEOL &&
((eol === '\r\n' && (this._cr > 0 || this._lf > 0))
|| (eol === '\n' && (this._cr > 0 || this._crlf > 0)))
) {
// Normalize pieces
for (let i = 0, len = chunks.length; i < len; i++) {
let str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol);
let newLineStart = createLineStartsFast(str);
chunks[i] = new StringBuffer(str, newLineStart);
}
}
const textBuffer = new PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._containsUnusualLineTerminators, this._isBasicASCII, this._normalizeEOL);
return { textBuffer: textBuffer, disposable: textBuffer };
}
public getFirstLineText(lengthLimit: number): string {
return this._chunks[0].buffer.substr(0, lengthLimit).split(/\r\n|\r|\n/)[0];
}
}
export class PieceTreeTextBufferBuilder implements ITextBufferBuilder {
private readonly chunks: StringBuffer[];
private BOM: string;
private _hasPreviousChar: boolean;
private _previousChar: number;
private readonly _tmpLineStarts: number[];
private cr: number;
private lf: number;
private crlf: number;
private containsRTL: boolean;
private containsUnusualLineTerminators: boolean;
private isBasicASCII: boolean;
constructor() {
this.chunks = [];
this.BOM = '';
this._hasPreviousChar = false;
this._previousChar = 0;
this._tmpLineStarts = [];
this.cr = 0;
this.lf = 0;
this.crlf = 0;
this.containsRTL = false;
this.containsUnusualLineTerminators = false;
this.isBasicASCII = true;
}
public acceptChunk(chunk: string): void {
if (chunk.length === 0) {
return;
}
if (this.chunks.length === 0) {
if (strings.startsWithUTF8BOM(chunk)) {
this.BOM = strings.UTF8_BOM_CHARACTER;
chunk = chunk.substr(1);
}
}
const lastChar = chunk.charCodeAt(chunk.length - 1);
if (lastChar === CharCode.CarriageReturn || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
// last character is \r or a high surrogate => keep it back
this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);
this._hasPreviousChar = true;
this._previousChar = lastChar;
} else {
this._acceptChunk1(chunk, false);
this._hasPreviousChar = false;
this._previousChar = lastChar;
}
}
private _acceptChunk1(chunk: string, allowEmptyStrings: boolean): void {
if (!allowEmptyStrings && chunk.length === 0) {
// Nothing to do
return;
}
if (this._hasPreviousChar) {
this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);
} else {
this._acceptChunk2(chunk);
}
}
private _acceptChunk2(chunk: string): void {
const lineStarts = createLineStarts(this._tmpLineStarts, chunk);
this.chunks.push(new StringBuffer(chunk, lineStarts.lineStarts));
this.cr += lineStarts.cr;
this.lf += lineStarts.lf;
this.crlf += lineStarts.crlf;
if (this.isBasicASCII) {
this.isBasicASCII = lineStarts.isBasicASCII;
}
if (!this.isBasicASCII && !this.containsRTL) {
// No need to check if it is basic ASCII
this.containsRTL = strings.containsRTL(chunk);
}
if (!this.isBasicASCII && !this.containsUnusualLineTerminators) {
// No need to check if it is basic ASCII
this.containsUnusualLineTerminators = strings.containsUnusualLineTerminators(chunk);
}
}
public finish(normalizeEOL: boolean = true): PieceTreeTextBufferFactory {
this._finish();
return new PieceTreeTextBufferFactory(
this.chunks,
this.BOM,
this.cr,
this.lf,
this.crlf,
this.containsRTL,
this.containsUnusualLineTerminators,
this.isBasicASCII,
normalizeEOL
);
}
private _finish(): void {
if (this.chunks.length === 0) {
this._acceptChunk1('', true);
}
if (this._hasPreviousChar) {
this._hasPreviousChar = false;
// recreate last chunk
let lastChunk = this.chunks[this.chunks.length - 1];
lastChunk.buffer += String.fromCharCode(this._previousChar);
let newLineStarts = createLineStartsFast(lastChunk.buffer);
lastChunk.lineStarts = newLineStarts;
if (this._previousChar === CharCode.CarriageReturn) {
this.cr++;
}
}
}
}
|
src/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00018550835375208408,
0.00016952819714788347,
0.0001650865306146443,
0.00016897886234801263,
0.0000043747231757151894
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\treturn;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tif (emptyWorkspaces.indexOf(storageFolder) === -1) {\n",
"\t\t\t\t\tthis.logService.trace(`[storage cleanup]: Deleting storage folder ${storageFolder}.`);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\tthis.logService.trace(`[storage cleanup]: Deleting workspace storage folder ${workspaceStorageFolder}.`);\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 51
}
|
{
"name": "log",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"license": "MIT",
"engines": {
"vscode": "*"
},
"scripts": {
"update-grammar": "node ../node_modules/vscode-grammar-updater/bin emilast/vscode-logfile-highlighter syntaxes/log.tmLanguage ./syntaxes/log.tmLanguage.json"
},
"contributes": {
"languages": [
{
"id": "log",
"extensions": [
".log",
"*.log.?"
],
"aliases": [
"Log"
]
}
],
"grammars": [
{
"language": "log",
"scopeName": "text.log",
"path": "./syntaxes/log.tmLanguage.json"
}
]
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
|
extensions/log/package.json
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.0001683258160483092,
0.00016685869195498526,
0.00016574678011238575,
0.00016668110038153827,
0.0000010074717238239828
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\treturn;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tif (emptyWorkspaces.indexOf(storageFolder) === -1) {\n",
"\t\t\t\t\tthis.logService.trace(`[storage cleanup]: Deleting storage folder ${storageFolder}.`);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\tthis.logService.trace(`[storage cleanup]: Deleting workspace storage folder ${workspaceStorageFolder}.`);\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 51
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as fancyLog from 'fancy-log';
import * as ansiColors from 'ansi-colors';
export interface BaseTask {
displayName?: string;
taskName?: string;
_tasks?: Task[];
}
export interface PromiseTask extends BaseTask {
(): Promise<void>;
}
export interface StreamTask extends BaseTask {
(): NodeJS.ReadWriteStream;
}
export interface CallbackTask extends BaseTask {
(cb?: (err?: any) => void): void;
}
export type Task = PromiseTask | StreamTask | CallbackTask;
function _isPromise(p: Promise<void> | NodeJS.ReadWriteStream): p is Promise<void> {
if (typeof (<any>p).then === 'function') {
return true;
}
return false;
}
function _renderTime(time: number): string {
return `${Math.round(time)} ms`;
}
async function _execute(task: Task): Promise<void> {
const name = task.taskName || task.displayName || `<anonymous>`;
if (!task._tasks) {
fancyLog('Starting', ansiColors.cyan(name), '...');
}
const startTime = process.hrtime();
await _doExecute(task);
const elapsedArr = process.hrtime(startTime);
const elapsedNanoseconds = (elapsedArr[0] * 1e9 + elapsedArr[1]);
if (!task._tasks) {
fancyLog(`Finished`, ansiColors.cyan(name), 'after', ansiColors.magenta(_renderTime(elapsedNanoseconds / 1e6)));
}
}
async function _doExecute(task: Task): Promise<void> {
// Always invoke as if it were a callback task
return new Promise((resolve, reject) => {
if (task.length === 1) {
// this is a callback task
task((err) => {
if (err) {
return reject(err);
}
resolve();
});
return;
}
const taskResult = task();
if (typeof taskResult === 'undefined') {
// this is a sync task
resolve();
return;
}
if (_isPromise(taskResult)) {
// this is a promise returning task
taskResult.then(resolve, reject);
return;
}
// this is a stream returning task
taskResult.on('end', _ => resolve());
taskResult.on('error', err => reject(err));
});
}
export function series(...tasks: Task[]): PromiseTask {
const result = async () => {
for (let i = 0; i < tasks.length; i++) {
await _execute(tasks[i]);
}
};
result._tasks = tasks;
return result;
}
export function parallel(...tasks: Task[]): PromiseTask {
const result = async () => {
await Promise.all(tasks.map(t => _execute(t)));
};
result._tasks = tasks;
return result;
}
export function define(name: string, task: Task): Task {
if (task._tasks) {
// This is a composite task
const lastTask = task._tasks[task._tasks.length - 1];
if (lastTask._tasks || lastTask.taskName) {
// This is a composite task without a real task function
// => generate a fake task function
return define(name, series(task, () => Promise.resolve()));
}
lastTask.taskName = name;
task.displayName = name;
return task;
}
// This is a simple task
task.taskName = name;
task.displayName = name;
return task;
}
|
build/lib/task.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00017392149311490357,
0.00017067660519387573,
0.00016720446001272649,
0.00017035560449585319,
0.0000019200645056116628
] |
{
"id": 3,
"code_window": [
"\n",
"\t\t\t\t\tawait Promises.rm(join(this.environmentService.workspaceStorageHome.fsPath, storageFolder));\n",
"\t\t\t\t}\n",
"\t\t\t}));\n",
"\t\t} catch (error) {\n",
"\t\t\tonUnexpectedError(error);\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tawait Promises.rm(join(this.environmentService.workspaceStorageHome.fsPath, workspaceStorageFolder));\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 54
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { RunOnceScheduler } from 'vs/base/common/async';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Disposable } from 'vs/base/common/lifecycle';
import { join } from 'vs/base/common/path';
import { Promises } from 'vs/base/node/pfs';
import { IBackupWorkspacesFormat } from 'vs/platform/backup/node/backup';
import { INativeEnvironmentService } from 'vs/platform/environment/common/environment';
import { ILogService } from 'vs/platform/log/common/log';
export class StorageDataCleaner extends Disposable {
// Workspace/Folder storage names are MD5 hashes (128bits / 4 due to hex presentation)
private static readonly NON_EMPTY_WORKSPACE_ID_LENGTH = 128 / 4;
constructor(
private readonly backupWorkspacesPath: string,
@INativeEnvironmentService private readonly environmentService: INativeEnvironmentService,
@ILogService private readonly logService: ILogService
) {
super();
const scheduler = this._register(new RunOnceScheduler(() => {
this.cleanUpStorage();
}, 30 * 1000 /* after 30s */));
scheduler.schedule();
}
private async cleanUpStorage(): Promise<void> {
this.logService.trace('[storage cleanup]: Starting to clean up storage folders.');
try {
// Leverage the backup workspace file to find out which empty workspace is currently in use to
// determine which empty workspace storage can safely be deleted
const contents = await Promises.readFile(this.backupWorkspacesPath, 'utf8');
const workspaces = JSON.parse(contents) as IBackupWorkspacesFormat;
const emptyWorkspaces = workspaces.emptyWorkspaceInfos.map(emptyWorkspace => emptyWorkspace.backupFolder);
// Read all workspace storage folders that exist
const storageFolders = await Promises.readdir(this.environmentService.workspaceStorageHome.fsPath);
await Promise.all(storageFolders.map(async storageFolder => {
if (storageFolder.length === StorageDataCleaner.NON_EMPTY_WORKSPACE_ID_LENGTH) {
return;
}
if (emptyWorkspaces.indexOf(storageFolder) === -1) {
this.logService.trace(`[storage cleanup]: Deleting storage folder ${storageFolder}.`);
await Promises.rm(join(this.environmentService.workspaceStorageHome.fsPath, storageFolder));
}
}));
} catch (error) {
onUnexpectedError(error);
}
}
}
|
src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts
| 1 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.981137752532959,
0.140945166349411,
0.00016236890223808587,
0.00041864957893267274,
0.3430095314979553
] |
{
"id": 3,
"code_window": [
"\n",
"\t\t\t\t\tawait Promises.rm(join(this.environmentService.workspaceStorageHome.fsPath, storageFolder));\n",
"\t\t\t\t}\n",
"\t\t\t}));\n",
"\t\t} catch (error) {\n",
"\t\t\tonUnexpectedError(error);\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tawait Promises.rm(join(this.environmentService.workspaceStorageHome.fsPath, workspaceStorageFolder));\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 54
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { tmpdir } from 'os';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService } from 'vs/platform/files/common/files';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { Schemas } from 'vs/base/common/network';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { Promises } from 'vs/base/node/pfs';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { FileService } from 'vs/platform/files/common/fileService';
import { NullLogService } from 'vs/platform/log/common/log';
import { flakySuite, getRandomTestPath, getPathFromAmdModule } from 'vs/base/test/node/testUtils';
import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider';
import { detectEncodingByBOM } from 'vs/workbench/services/textfile/test/node/encoding/encoding.test';
import { workbenchInstantiationService, TestNativeTextFileServiceWithEncodingOverrides } from 'vs/workbench/test/electron-browser/workbenchTestServices';
import createSuite from 'vs/workbench/services/textfile/test/common/textFileService.io.test';
import { IWorkingCopyFileService, WorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
import { WorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService';
import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService';
flakySuite('Files - NativeTextFileService i/o', function () {
const disposables = new DisposableStore();
let service: ITextFileService;
let testDir: string;
function readFile(path: string): Promise<Buffer>;
function readFile(path: string, encoding: BufferEncoding): Promise<string>;
function readFile(path: string, encoding?: BufferEncoding): Promise<Buffer | string> {
return Promises.readFile(path, encoding);
}
createSuite({
setup: async () => {
const instantiationService = workbenchInstantiationService(disposables);
const logService = new NullLogService();
const fileService = new FileService(logService);
const fileProvider = new DiskFileSystemProvider(logService);
disposables.add(fileService.registerProvider(Schemas.file, fileProvider));
disposables.add(fileProvider);
const collection = new ServiceCollection();
collection.set(IFileService, fileService);
collection.set(IWorkingCopyFileService, new WorkingCopyFileService(fileService, new WorkingCopyService(), instantiationService, new UriIdentityService(fileService)));
service = instantiationService.createChild(collection).createInstance(TestNativeTextFileServiceWithEncodingOverrides);
testDir = getRandomTestPath(tmpdir(), 'vsctests', 'textfileservice');
const sourceDir = getPathFromAmdModule(require, './fixtures');
await Promises.copy(sourceDir, testDir, { preserveSymlinks: false });
return { service, testDir };
},
teardown: () => {
(<TextFileEditorModelManager>service.files).dispose();
disposables.clear();
return Promises.rm(testDir);
},
exists: Promises.exists,
stat: Promises.stat,
readFile,
detectEncodingByBOM
});
});
|
src/vs/workbench/services/textfile/test/electron-browser/nativeTextFileService.io.test.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00017406466940883547,
0.00017143452714663,
0.0001664341107243672,
0.00017209109500981867,
0.000002277610974488198
] |
{
"id": 3,
"code_window": [
"\n",
"\t\t\t\t\tawait Promises.rm(join(this.environmentService.workspaceStorageHome.fsPath, storageFolder));\n",
"\t\t\t\t}\n",
"\t\t\t}));\n",
"\t\t} catch (error) {\n",
"\t\t\tonUnexpectedError(error);\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tawait Promises.rm(join(this.environmentService.workspaceStorageHome.fsPath, workspaceStorageFolder));\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 54
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { joinPath } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { fixRegexNewline, IRgMatch, IRgMessage, RipgrepParser, unicodeEscapesToPCRE2, fixNewline } from 'vs/workbench/services/search/node/ripgrepTextSearchEngine';
import { Range, TextSearchResult } from 'vs/workbench/services/search/common/searchExtTypes';
suite('RipgrepTextSearchEngine', () => {
test('unicodeEscapesToPCRE2', async () => {
assert.strictEqual(unicodeEscapesToPCRE2('\\u1234'), '\\x{1234}');
assert.strictEqual(unicodeEscapesToPCRE2('\\u1234\\u0001'), '\\x{1234}\\x{0001}');
assert.strictEqual(unicodeEscapesToPCRE2('foo\\u1234bar'), 'foo\\x{1234}bar');
assert.strictEqual(unicodeEscapesToPCRE2('\\\\\\u1234'), '\\\\\\x{1234}');
assert.strictEqual(unicodeEscapesToPCRE2('foo\\\\\\u1234'), 'foo\\\\\\x{1234}');
assert.strictEqual(unicodeEscapesToPCRE2('\\u{1234}'), '\\x{1234}');
assert.strictEqual(unicodeEscapesToPCRE2('\\u{1234}\\u{0001}'), '\\x{1234}\\x{0001}');
assert.strictEqual(unicodeEscapesToPCRE2('foo\\u{1234}bar'), 'foo\\x{1234}bar');
assert.strictEqual(unicodeEscapesToPCRE2('[\\u00A0-\\u00FF]'), '[\\x{00A0}-\\x{00FF}]');
assert.strictEqual(unicodeEscapesToPCRE2('foo\\u{123456}7bar'), 'foo\\u{123456}7bar');
assert.strictEqual(unicodeEscapesToPCRE2('\\u123'), '\\u123');
assert.strictEqual(unicodeEscapesToPCRE2('foo'), 'foo');
assert.strictEqual(unicodeEscapesToPCRE2(''), '');
});
test('fixRegexNewline - src', () => {
const ttable = [
['foo', 'foo'],
['invalid(', 'invalid('],
['fo\\no', 'fo\\r?\\no'],
['f\\no\\no', 'f\\r?\\no\\r?\\no'],
['f[a-z\\n1]', 'f(?:[a-z1]|\\r?\\n)'],
['f[\\n-a]', 'f[\\n-a]'],
['(?<=\\n)\\w', '(?<=\\n)\\w'],
['fo\\n+o', 'fo(?:\\r?\\n)+o'],
['fo[^\\n]o', 'fo(?!\\r?\\n)o'],
['fo[^\\na-z]o', 'fo(?!\\r?\\n|[a-z])o'],
['foo[^\\n]+o', 'foo.+o'],
['foo[^\\nzq]+o', 'foo[^zq]+o'],
];
for (const [input, expected] of ttable) {
assert.strictEqual(fixRegexNewline(input), expected, `${input} -> ${expected}`);
}
});
test('fixRegexNewline - re', () => {
function testFixRegexNewline([inputReg, testStr, shouldMatch]: readonly [string, string, boolean]): void {
const fixed = fixRegexNewline(inputReg);
const reg = new RegExp(fixed);
assert.strictEqual(reg.test(testStr), shouldMatch, `${inputReg} => ${reg}, ${testStr}, ${shouldMatch}`);
}
([
['foo', 'foo', true],
['foo\\n', 'foo\r\n', true],
['foo\\n\\n', 'foo\n\n', true],
['foo\\n\\n', 'foo\r\n\r\n', true],
['foo\\n', 'foo\n', true],
['foo\\nabc', 'foo\r\nabc', true],
['foo\\nabc', 'foo\nabc', true],
['foo\\r\\n', 'foo\r\n', true],
['foo\\n+abc', 'foo\r\nabc', true],
['foo\\n+abc', 'foo\n\n\nabc', true],
['foo\\n+abc', 'foo\r\n\r\n\r\nabc', true],
['foo[\\n-9]+abc', 'foo1abc', true],
] as const).forEach(testFixRegexNewline);
});
test('fixNewline - matching', () => {
function testFixNewline([inputReg, testStr, shouldMatch = true]: readonly [string, string, boolean?]): void {
const fixed = fixNewline(inputReg);
const reg = new RegExp(fixed);
assert.strictEqual(reg.test(testStr), shouldMatch, `${inputReg} => ${reg}, ${testStr}, ${shouldMatch}`);
}
([
['foo', 'foo'],
['foo\n', 'foo\r\n'],
['foo\n', 'foo\n'],
['foo\nabc', 'foo\r\nabc'],
['foo\nabc', 'foo\nabc'],
['foo\r\n', 'foo\r\n'],
['foo\nbarc', 'foobar', false],
['foobar', 'foo\nbar', false],
] as const).forEach(testFixNewline);
});
suite('RipgrepParser', () => {
const TEST_FOLDER = URI.file('/foo/bar');
function testParser(inputData: string[], expectedResults: TextSearchResult[]): void {
const testParser = new RipgrepParser(1000, TEST_FOLDER.fsPath);
const actualResults: TextSearchResult[] = [];
testParser.on('result', r => {
actualResults.push(r);
});
inputData.forEach(d => testParser.handleData(d));
testParser.flush();
assert.deepStrictEqual(actualResults, expectedResults);
}
function makeRgMatch(relativePath: string, text: string, lineNumber: number, matchRanges: { start: number, end: number }[]): string {
return JSON.stringify(<IRgMessage>{
type: 'match',
data: <IRgMatch>{
path: {
text: relativePath
},
lines: {
text
},
line_number: lineNumber,
absolute_offset: 0, // unused
submatches: matchRanges.map(mr => {
return {
...mr,
match: { text: text.substring(mr.start, mr.end) }
};
})
}
}) + '\n';
}
test('single result', () => {
testParser(
[
makeRgMatch('file1.js', 'foobar', 4, [{ start: 3, end: 6 }])
],
[
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'file1.js'),
ranges: [new Range(3, 3, 3, 6)]
}
]);
});
test('multiple results', () => {
testParser(
[
makeRgMatch('file1.js', 'foobar', 4, [{ start: 3, end: 6 }]),
makeRgMatch('app/file2.js', 'foobar', 4, [{ start: 3, end: 6 }]),
makeRgMatch('app2/file3.js', 'foobar', 4, [{ start: 3, end: 6 }]),
],
[
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'file1.js'),
ranges: [new Range(3, 3, 3, 6)]
},
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'app/file2.js'),
ranges: [new Range(3, 3, 3, 6)]
},
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'app2/file3.js'),
ranges: [new Range(3, 3, 3, 6)]
}
]);
});
test('chopped-up input chunks', () => {
const dataStrs = [
makeRgMatch('file1.js', 'foo bar', 4, [{ start: 3, end: 7 }]),
makeRgMatch('app/file2.js', 'foobar', 4, [{ start: 3, end: 6 }]),
makeRgMatch('app2/file3.js', 'foobar', 4, [{ start: 3, end: 6 }]),
];
const dataStr0Space = dataStrs[0].indexOf(' ');
testParser(
[
dataStrs[0].substring(0, dataStr0Space + 1),
dataStrs[0].substring(dataStr0Space + 1),
'\n',
dataStrs[1].trim(),
'\n' + dataStrs[2].substring(0, 25),
dataStrs[2].substring(25)
],
[
{
preview: {
text: 'foo bar',
matches: [new Range(0, 3, 0, 7)]
},
uri: joinPath(TEST_FOLDER, 'file1.js'),
ranges: [new Range(3, 3, 3, 7)]
},
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'app/file2.js'),
ranges: [new Range(3, 3, 3, 6)]
},
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'app2/file3.js'),
ranges: [new Range(3, 3, 3, 6)]
}
]);
});
test('empty result (#100569)', () => {
testParser(
[
makeRgMatch('file1.js', 'foobar', 4, []),
makeRgMatch('file1.js', '', 5, []),
],
[
{
preview: {
text: 'foobar',
matches: [new Range(0, 0, 0, 1)]
},
uri: joinPath(TEST_FOLDER, 'file1.js'),
ranges: [new Range(3, 0, 3, 1)]
},
{
preview: {
text: '',
matches: [new Range(0, 0, 0, 0)]
},
uri: joinPath(TEST_FOLDER, 'file1.js'),
ranges: [new Range(4, 0, 4, 0)]
}
]);
});
});
});
|
src/vs/workbench/services/search/test/node/ripgrepTextSearchEngineUtils.test.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00017813179874792695,
0.00017173969536088407,
0.0001643420837353915,
0.00017170885985251516,
0.000002307257318534539
] |
{
"id": 3,
"code_window": [
"\n",
"\t\t\t\t\tawait Promises.rm(join(this.environmentService.workspaceStorageHome.fsPath, storageFolder));\n",
"\t\t\t\t}\n",
"\t\t\t}));\n",
"\t\t} catch (error) {\n",
"\t\t\tonUnexpectedError(error);\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tawait Promises.rm(join(this.environmentService.workspaceStorageHome.fsPath, workspaceStorageFolder));\n"
],
"file_path": "src/vs/code/electron-browser/sharedProcess/contrib/storageDataCleaner.ts",
"type": "replace",
"edit_start_line_idx": 54
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { getCodiconAriaLabel } from 'vs/base/common/codicons';
suite('Codicon', () => {
test('Can get proper aria labels', () => {
// note, the spaces in the results are important
const testCases = new Map<string, string>([
['', ''],
['asdf', 'asdf'],
['asdf$(squirrel)asdf', 'asdf squirrel asdf'],
['asdf $(squirrel) asdf', 'asdf squirrel asdf'],
['$(rocket)asdf', 'rocket asdf'],
['$(rocket) asdf', 'rocket asdf'],
['$(rocket)$(rocket)$(rocket)asdf', 'rocket rocket rocket asdf'],
['$(rocket) asdf $(rocket)', 'rocket asdf rocket'],
['$(rocket)asdf$(rocket)', 'rocket asdf rocket'],
]);
for (const [input, expected] of testCases) {
assert.strictEqual(getCodiconAriaLabel(input), expected);
}
});
});
|
src/vs/base/test/common/codicons.test.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00017478583322372288,
0.00017311096598859876,
0.00017072830814868212,
0.00017381871293764561,
0.0000017304281527685816
] |
{
"id": 4,
"code_window": [
"\t\tif (!workspaceInitializationPayload) {\n",
"\t\t\tlet id: string;\n",
"\t\t\tif (this.configuration.backupPath) {\n",
"\t\t\t\tid = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID\n",
"\t\t\t} else if (environmentService.isExtensionDevelopment) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t// we know the backupPath must be a unique path so we leverage its name as workspace ID\n",
"\t\t\t\tid = basename(this.configuration.backupPath);\n"
],
"file_path": "src/vs/workbench/electron-sandbox/shared.desktop.main.ts",
"type": "replace",
"edit_start_line_idx": 319
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import product from 'vs/platform/product/common/product';
import { zoomLevelToZoomFactor } from 'vs/platform/windows/common/windows';
import { Workbench } from 'vs/workbench/browser/workbench';
import { NativeWindow } from 'vs/workbench/electron-sandbox/window';
import { setZoomLevel, setZoomFactor, setFullscreen } from 'vs/base/browser/browser';
import { domContentLoaded } from 'vs/base/browser/dom';
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
import { INativeWorkbenchConfiguration, INativeWorkbenchEnvironmentService, NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier, IWorkspaceInitializationPayload, reviveIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { ILoggerService, ILogService } from 'vs/platform/log/common/log';
import { NativeStorageService } from 'vs/platform/storage/electron-sandbox/storageService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { Disposable } from 'vs/base/common/lifecycle';
import { IMainProcessService, ISharedProcessService } from 'vs/platform/ipc/electron-sandbox/services';
import { SharedProcessService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessService';
import { RemoteAuthorityResolverService } from 'vs/platform/remote/electron-sandbox/remoteAuthorityResolverService';
import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { RemoteAgentService } from 'vs/workbench/services/remote/electron-sandbox/remoteAgentServiceImpl';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { FileService } from 'vs/platform/files/common/fileService';
import { IFileService } from 'vs/platform/files/common/files';
import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel';
import { ConfigurationCache } from 'vs/workbench/services/configuration/electron-sandbox/configurationCache';
import { ISignService } from 'vs/platform/sign/common/sign';
import { basename } from 'vs/base/common/path';
import { IProductService } from 'vs/platform/product/common/productService';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { NativeHostService } from 'vs/platform/native/electron-sandbox/nativeHostService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService';
import { KeyboardLayoutService } from 'vs/workbench/services/keybinding/electron-sandbox/nativeKeyboardLayout';
import { IKeyboardLayoutService } from 'vs/platform/keyboardLayout/common/keyboardLayout';
import { ElectronIPCMainProcessService } from 'vs/platform/ipc/electron-sandbox/mainProcessService';
import { LoggerChannelClient, LogLevelChannelClient } from 'vs/platform/log/common/logIpc';
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { NativeLogService } from 'vs/workbench/services/log/electron-sandbox/logService';
import { WorkspaceTrustEnablementService, WorkspaceTrustManagementService } from 'vs/workbench/services/workspaces/common/workspaceTrust';
import { IWorkspaceTrustEnablementService, IWorkspaceTrustManagementService } from 'vs/platform/workspace/common/workspaceTrust';
import { registerWindowDriver } from 'vs/platform/driver/electron-sandbox/driver';
import { safeStringify } from 'vs/base/common/objects';
import { ISharedProcessWorkerWorkbenchService, SharedProcessWorkerWorkbenchService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessWorkerWorkbenchService';
import { isMacintosh } from 'vs/base/common/platform';
export abstract class SharedDesktopMain extends Disposable {
constructor(
protected readonly configuration: INativeWorkbenchConfiguration
) {
super();
this.init();
}
private init(): void {
// Massage configuration file URIs
this.reviveUris();
// Browser config
const zoomLevel = this.configuration.zoomLevel || 0;
setZoomFactor(zoomLevelToZoomFactor(zoomLevel));
setZoomLevel(zoomLevel, true /* isTrusted */);
setFullscreen(!!this.configuration.fullscreen);
}
private reviveUris() {
// Workspace
const workspace = reviveIdentifier(this.configuration.workspace);
if (isWorkspaceIdentifier(workspace) || isSingleFolderWorkspaceIdentifier(workspace)) {
this.configuration.workspace = workspace;
}
// Files
const filesToWait = this.configuration.filesToWait;
const filesToWaitPaths = filesToWait?.paths;
[filesToWaitPaths, this.configuration.filesToOpenOrCreate, this.configuration.filesToDiff].forEach(paths => {
if (Array.isArray(paths)) {
paths.forEach(path => {
if (path.fileUri) {
path.fileUri = URI.revive(path.fileUri);
}
});
}
});
if (filesToWait) {
filesToWait.waitMarkerFileUri = URI.revive(filesToWait.waitMarkerFileUri);
}
}
async open(): Promise<void> {
// Init services and wait for DOM to be ready in parallel
const [services] = await Promise.all([this.initServices(), domContentLoaded()]);
// Create Workbench
const workbench = new Workbench(document.body, { extraClasses: this.getExtraClasses() }, services.serviceCollection, services.logService);
// Listeners
this.registerListeners(workbench, services.storageService);
// Startup
const instantiationService = workbench.startup();
// Window
this._register(instantiationService.createInstance(NativeWindow));
// Logging
services.logService.trace('workbench configuration', safeStringify(this.configuration));
// Driver
if (this.configuration.driver) {
instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor, this.configuration.windowId)));
}
}
private getExtraClasses(): string[] {
if (isMacintosh) {
if (this.configuration.os.release > '20.0.0') {
return ['macos-bigsur-or-newer'];
}
}
return [];
}
private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
// Workbench Lifecycle
this._register(workbench.onWillShutdown(event => event.join(storageService.close(), 'join.closeStorage')));
this._register(workbench.onDidShutdown(() => this.dispose()));
}
protected abstract registerFileSystemProviders(
mainProcessService: IMainProcessService,
sharedProcessWorkerWorkbenchService: ISharedProcessWorkerWorkbenchService,
fileService: IFileService,
logService: ILogService,
nativeHostService: INativeHostService
): void;
private async initServices(): Promise<{ serviceCollection: ServiceCollection, logService: ILogService, storageService: NativeStorageService }> {
const serviceCollection = new ServiceCollection();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Main Process
const mainProcessService = this._register(new ElectronIPCMainProcessService(this.configuration.windowId));
serviceCollection.set(IMainProcessService, mainProcessService);
// Product
const productService: IProductService = { _serviceBrand: undefined, ...product };
serviceCollection.set(IProductService, productService);
// Environment
const environmentService = new NativeWorkbenchEnvironmentService(this.configuration, productService);
serviceCollection.set(INativeWorkbenchEnvironmentService, environmentService);
// Logger
const logLevelChannelClient = new LogLevelChannelClient(mainProcessService.getChannel('logLevel'));
const loggerService = new LoggerChannelClient(environmentService.configuration.logLevel, logLevelChannelClient.onDidChangeLogLevel, mainProcessService.getChannel('logger'));
serviceCollection.set(ILoggerService, loggerService);
// Log
const logService = this._register(new NativeLogService(`renderer${this.configuration.windowId}`, environmentService.configuration.logLevel, loggerService, logLevelChannelClient, environmentService));
serviceCollection.set(ILogService, logService);
// Shared Process
const sharedProcessService = new SharedProcessService(this.configuration.windowId, logService);
serviceCollection.set(ISharedProcessService, sharedProcessService);
// Shared Process Worker
const sharedProcessWorkerWorkbenchService = new SharedProcessWorkerWorkbenchService(this.configuration.windowId, logService, sharedProcessService);
serviceCollection.set(ISharedProcessWorkerWorkbenchService, sharedProcessWorkerWorkbenchService);
// Remote
const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Sign
const signService = ProxyChannel.toService<ISignService>(mainProcessService.getChannel('sign'));
serviceCollection.set(ISignService, signService);
// Remote Agent
const remoteAgentService = this._register(new RemoteAgentService(environmentService, productService, remoteAuthorityResolverService, signService, logService));
serviceCollection.set(IRemoteAgentService, remoteAgentService);
// Native Host
const nativeHostService = new NativeHostService(this.configuration.windowId, mainProcessService) as INativeHostService;
serviceCollection.set(INativeHostService, nativeHostService);
// Files
const fileService = this._register(new FileService(logService));
serviceCollection.set(IFileService, fileService);
this.registerFileSystemProviders(mainProcessService, sharedProcessWorkerWorkbenchService, fileService, logService, nativeHostService);
// URI Identity
const uriIdentityService = new UriIdentityService(fileService);
serviceCollection.set(IUriIdentityService, uriIdentityService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Remote file system
this._register(RemoteFileSystemProvider.register(remoteAgentService, fileService, logService));
const payload = this.resolveWorkspaceInitializationPayload(environmentService);
const [configurationService, storageService] = await Promise.all([
this.createWorkspaceService(payload, environmentService, fileService, remoteAgentService, uriIdentityService, logService).then(service => {
// Workspace
serviceCollection.set(IWorkspaceContextService, service);
// Configuration
serviceCollection.set(IWorkbenchConfigurationService, service);
return service;
}),
this.createStorageService(payload, environmentService, mainProcessService).then(service => {
// Storage
serviceCollection.set(IStorageService, service);
return service;
}),
this.createKeyboardLayoutService(mainProcessService).then(service => {
// KeyboardLayout
serviceCollection.set(IKeyboardLayoutService, service);
return service;
})
]);
// Workspace Trust Service
const workspaceTrustEnablementService = new WorkspaceTrustEnablementService(configurationService, environmentService);
serviceCollection.set(IWorkspaceTrustEnablementService, workspaceTrustEnablementService);
const workspaceTrustManagementService = new WorkspaceTrustManagementService(configurationService, remoteAuthorityResolverService, storageService, uriIdentityService, environmentService, configurationService, workspaceTrustEnablementService);
serviceCollection.set(IWorkspaceTrustManagementService, workspaceTrustManagementService);
// Update workspace trust so that configuration is updated accordingly
configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted());
this._register(workspaceTrustManagementService.onDidChangeTrust(() => configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted())));
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return { serviceCollection, logService, storageService };
}
private resolveWorkspaceInitializationPayload(environmentService: INativeWorkbenchEnvironmentService): IWorkspaceInitializationPayload {
let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined = this.configuration.workspace;
// Fallback to empty workspace if we have no payload yet.
if (!workspaceInitializationPayload) {
let id: string;
if (this.configuration.backupPath) {
id = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID
} else if (environmentService.isExtensionDevelopment) {
id = 'ext-dev'; // extension development window never stores backups and is a singleton
} else {
throw new Error('Unexpected window configuration without backupPath');
}
workspaceInitializationPayload = { id };
}
return workspaceInitializationPayload;
}
private async createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, fileService: FileService, remoteAgentService: IRemoteAgentService, uriIdentityService: IUriIdentityService, logService: ILogService): Promise<WorkspaceService> {
const workspaceService = new WorkspaceService({ remoteAuthority: environmentService.remoteAuthority, configurationCache: new ConfigurationCache(URI.file(environmentService.userDataPath), fileService) }, environmentService, fileService, remoteAgentService, uriIdentityService, logService);
try {
await workspaceService.initialize(payload);
return workspaceService;
} catch (error) {
onUnexpectedError(error);
return workspaceService;
}
}
private async createStorageService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
const storageService = new NativeStorageService(payload, mainProcessService, environmentService);
try {
await storageService.initialize();
return storageService;
} catch (error) {
onUnexpectedError(error);
return storageService;
}
}
private async createKeyboardLayoutService(mainProcessService: IMainProcessService): Promise<KeyboardLayoutService> {
const keyboardLayoutService = new KeyboardLayoutService(mainProcessService);
try {
await keyboardLayoutService.initialize();
return keyboardLayoutService;
} catch (error) {
onUnexpectedError(error);
return keyboardLayoutService;
}
}
}
|
src/vs/workbench/electron-sandbox/shared.desktop.main.ts
| 1 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.997752845287323,
0.059581901878118515,
0.00016239119577221572,
0.00018183700740337372,
0.22263158857822418
] |
{
"id": 4,
"code_window": [
"\t\tif (!workspaceInitializationPayload) {\n",
"\t\t\tlet id: string;\n",
"\t\t\tif (this.configuration.backupPath) {\n",
"\t\t\t\tid = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID\n",
"\t\t\t} else if (environmentService.isExtensionDevelopment) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t// we know the backupPath must be a unique path so we leverage its name as workspace ID\n",
"\t\t\t\tid = basename(this.configuration.backupPath);\n"
],
"file_path": "src/vs/workbench/electron-sandbox/shared.desktop.main.ts",
"type": "replace",
"edit_start_line_idx": 319
}
|
<!DOCTYPE html>
<html>
<head id='headID'>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Strada </title>
<link href="site.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.4.1.js"></script>
<script src="../compiler/dtree.js" type="text/javascript"></script>
<script src="../compiler/typescript.js" type="text/javascript"></script>
<script type="text/javascript">
// Compile strada source into resulting javascript
function compile(prog, libText) {
var outfile = {
source: "",
Write: function (s) { this.source += s; },
WriteLine: function (s) { this.source += s + "\r"; },
}
var parseErrors = []
var compiler=new Tools.TypeScriptCompiler(outfile,true);
compiler.setErrorCallback(function(start,len, message) { parseErrors.push({start:start, len:len, message:message}); });
compiler.addUnit(libText,"lib.ts");
compiler.addUnit(prog,"input.ts");
compiler.typeCheck();
compiler.emit();
if(parseErrors.length > 0 ) {
//throw new Error(parseErrors);
}
while(outfile.source[0] == '/' && outfile.source[1] == '/' && outfile.source[2] == ' ') {
outfile.source = outfile.source.slice(outfile.source.indexOf('\r')+1);
}
var errorPrefix = "";
for(var i = 0;i<parseErrors.length;i++) {
errorPrefix += "// Error: (" + parseErrors[i].start + "," + parseErrors[i].len + ") " + parseErrors[i].message + "\r";
}
return errorPrefix + outfile.source;
}
</script>
<script type="text/javascript">
var libText = "";
$.get("../compiler/lib.ts", function(newLibText) {
libText = newLibText;
});
// execute the javascript in the compiledOutput pane
function execute() {
$('#compilation').text("Running...");
var txt = $('#compiledOutput').val();
var res;
try {
var ret = eval(txt);
res = "Ran successfully!";
} catch(e) {
res = "Exception thrown: " + e;
}
$('#compilation').text(String(res));
}
// recompile the stradaSrc and populate the compiledOutput pane
function srcUpdated() {
var newText = $('#stradaSrc').val();
var compiledSource;
try {
compiledSource = compile(newText, libText);
} catch (e) {
compiledSource = "//Parse error"
for(var i in e)
compiledSource += "\r// " + e[i];
}
$('#compiledOutput').val(compiledSource);
}
// Populate the stradaSrc pane with one of the built in samples
function exampleSelectionChanged() {
var examples = document.getElementById('examples');
var selectedExample = examples.options[examples.selectedIndex].value;
if (selectedExample != "") {
$.get('examples/' + selectedExample, function (srcText) {
$('#stradaSrc').val(srcText);
setTimeout(srcUpdated,100);
}, function (err) {
console.log(err);
});
}
}
</script>
</head>
<body>
<h1>TypeScript</h1>
<br />
<select id="examples" onchange='exampleSelectionChanged()'>
<option value="">Select...</option>
<option value="small.ts">Small</option>
<option value="employee.ts">Employees</option>
<option value="conway.ts">Conway Game of Life</option>
<option value="typescript.ts">TypeScript Compiler</option>
</select>
<div>
<textarea id='stradaSrc' rows='40' cols='80' onchange='srcUpdated()' onkeyup='srcUpdated()' spellcheck="false">
//Type your TypeScript here...
</textarea>
<textarea id='compiledOutput' rows='40' cols='80' spellcheck="false">
//Compiled code will show up here...
</textarea>
<br />
<button onclick='execute()'/>Run</button>
<div id='compilation'>Press 'run' to execute code...</div>
<div id='results'>...write your results into #results...</div>
</div>
<div id='bod' style='display:none'></div>
</body>
</html>
|
src/vs/workbench/services/search/test/node/fixtures/index.html
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00017777140601538122,
0.00017378527263645083,
0.00016935034363996238,
0.00017425116675440222,
0.000002387490440014517
] |
{
"id": 4,
"code_window": [
"\t\tif (!workspaceInitializationPayload) {\n",
"\t\t\tlet id: string;\n",
"\t\t\tif (this.configuration.backupPath) {\n",
"\t\t\t\tid = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID\n",
"\t\t\t} else if (environmentService.isExtensionDevelopment) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t// we know the backupPath must be a unique path so we leverage its name as workspace ID\n",
"\t\t\t\tid = basename(this.configuration.backupPath);\n"
],
"file_path": "src/vs/workbench/electron-sandbox/shared.desktop.main.ts",
"type": "replace",
"edit_start_line_idx": 319
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { compress, CompressedObjectTreeModel, decompress, ICompressedTreeElement, ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel';
import { IList } from 'vs/base/browser/ui/tree/indexTreeModel';
import { IObjectTreeModelSetChildrenOptions } from 'vs/base/browser/ui/tree/objectTreeModel';
import { ITreeNode } from 'vs/base/browser/ui/tree/tree';
import { Iterable } from 'vs/base/common/iterator';
interface IResolvedCompressedTreeElement<T> extends ICompressedTreeElement<T> {
readonly element: T;
readonly children?: ICompressedTreeElement<T>[];
}
function resolve<T>(treeElement: ICompressedTreeElement<T>): IResolvedCompressedTreeElement<T> {
const result: any = { element: treeElement.element };
const children = [...Iterable.map(Iterable.from(treeElement.children), resolve)];
if (treeElement.incompressible) {
result.incompressible = true;
}
if (children.length > 0) {
result.children = children;
}
return result;
}
suite('CompressedObjectTree', function () {
suite('compress & decompress', function () {
test('small', function () {
const decompressed: ICompressedTreeElement<number> = { element: 1 };
const compressed: IResolvedCompressedTreeElement<ICompressedTreeNode<number>> =
{ element: { elements: [1], incompressible: false } };
assert.deepStrictEqual(resolve(compress(decompressed)), compressed);
assert.deepStrictEqual(resolve(decompress(compressed)), decompressed);
});
test('no compression', function () {
const decompressed: ICompressedTreeElement<number> = {
element: 1, children: [
{ element: 11 },
{ element: 12 },
{ element: 13 }
]
};
const compressed: IResolvedCompressedTreeElement<ICompressedTreeNode<number>> = {
element: { elements: [1], incompressible: false },
children: [
{ element: { elements: [11], incompressible: false } },
{ element: { elements: [12], incompressible: false } },
{ element: { elements: [13], incompressible: false } }
]
};
assert.deepStrictEqual(resolve(compress(decompressed)), compressed);
assert.deepStrictEqual(resolve(decompress(compressed)), decompressed);
});
test('single hierarchy', function () {
const decompressed: ICompressedTreeElement<number> = {
element: 1, children: [
{
element: 11, children: [
{
element: 111, children: [
{ element: 1111 }
]
}
]
}
]
};
const compressed: IResolvedCompressedTreeElement<ICompressedTreeNode<number>> = {
element: { elements: [1, 11, 111, 1111], incompressible: false }
};
assert.deepStrictEqual(resolve(compress(decompressed)), compressed);
assert.deepStrictEqual(resolve(decompress(compressed)), decompressed);
});
test('deep compression', function () {
const decompressed: ICompressedTreeElement<number> = {
element: 1, children: [
{
element: 11, children: [
{
element: 111, children: [
{ element: 1111 },
{ element: 1112 },
{ element: 1113 },
{ element: 1114 },
]
}
]
}
]
};
const compressed: IResolvedCompressedTreeElement<ICompressedTreeNode<number>> = {
element: { elements: [1, 11, 111], incompressible: false },
children: [
{ element: { elements: [1111], incompressible: false } },
{ element: { elements: [1112], incompressible: false } },
{ element: { elements: [1113], incompressible: false } },
{ element: { elements: [1114], incompressible: false } },
]
};
assert.deepStrictEqual(resolve(compress(decompressed)), compressed);
assert.deepStrictEqual(resolve(decompress(compressed)), decompressed);
});
test('double deep compression', function () {
const decompressed: ICompressedTreeElement<number> = {
element: 1, children: [
{
element: 11, children: [
{
element: 111, children: [
{ element: 1112 },
{ element: 1113 },
]
}
]
},
{
element: 12, children: [
{
element: 121, children: [
{ element: 1212 },
{ element: 1213 },
]
}
]
}
]
};
const compressed: IResolvedCompressedTreeElement<ICompressedTreeNode<number>> = {
element: { elements: [1], incompressible: false },
children: [
{
element: { elements: [11, 111], incompressible: false },
children: [
{ element: { elements: [1112], incompressible: false } },
{ element: { elements: [1113], incompressible: false } },
]
},
{
element: { elements: [12, 121], incompressible: false },
children: [
{ element: { elements: [1212], incompressible: false } },
{ element: { elements: [1213], incompressible: false } },
]
}
]
};
assert.deepStrictEqual(resolve(compress(decompressed)), compressed);
assert.deepStrictEqual(resolve(decompress(compressed)), decompressed);
});
test('incompressible leaf', function () {
const decompressed: ICompressedTreeElement<number> = {
element: 1, children: [
{
element: 11, children: [
{
element: 111, children: [
{ element: 1111, incompressible: true }
]
}
]
}
]
};
const compressed: IResolvedCompressedTreeElement<ICompressedTreeNode<number>> = {
element: { elements: [1, 11, 111], incompressible: false },
children: [
{ element: { elements: [1111], incompressible: true } }
]
};
assert.deepStrictEqual(resolve(compress(decompressed)), compressed);
assert.deepStrictEqual(resolve(decompress(compressed)), decompressed);
});
test('incompressible branch', function () {
const decompressed: ICompressedTreeElement<number> = {
element: 1, children: [
{
element: 11, children: [
{
element: 111, incompressible: true, children: [
{ element: 1111 }
]
}
]
}
]
};
const compressed: IResolvedCompressedTreeElement<ICompressedTreeNode<number>> = {
element: { elements: [1, 11], incompressible: false },
children: [
{ element: { elements: [111, 1111], incompressible: true } }
]
};
assert.deepStrictEqual(resolve(compress(decompressed)), compressed);
assert.deepStrictEqual(resolve(decompress(compressed)), decompressed);
});
test('incompressible chain', function () {
const decompressed: ICompressedTreeElement<number> = {
element: 1, children: [
{
element: 11, children: [
{
element: 111, incompressible: true, children: [
{ element: 1111, incompressible: true }
]
}
]
}
]
};
const compressed: IResolvedCompressedTreeElement<ICompressedTreeNode<number>> = {
element: { elements: [1, 11], incompressible: false },
children: [
{
element: { elements: [111], incompressible: true },
children: [
{ element: { elements: [1111], incompressible: true } }
]
}
]
};
assert.deepStrictEqual(resolve(compress(decompressed)), compressed);
assert.deepStrictEqual(resolve(decompress(compressed)), decompressed);
});
test('incompressible tree', function () {
const decompressed: ICompressedTreeElement<number> = {
element: 1, children: [
{
element: 11, incompressible: true, children: [
{
element: 111, incompressible: true, children: [
{ element: 1111, incompressible: true }
]
}
]
}
]
};
const compressed: IResolvedCompressedTreeElement<ICompressedTreeNode<number>> = {
element: { elements: [1], incompressible: false },
children: [
{
element: { elements: [11], incompressible: true },
children: [
{
element: { elements: [111], incompressible: true },
children: [
{ element: { elements: [1111], incompressible: true } }
]
}
]
}
]
};
assert.deepStrictEqual(resolve(compress(decompressed)), compressed);
assert.deepStrictEqual(resolve(decompress(compressed)), decompressed);
});
});
function toList<T>(arr: T[]): IList<T> {
return {
splice(start: number, deleteCount: number, elements: T[]): void {
arr.splice(start, deleteCount, ...elements);
},
updateElementHeight() { }
};
}
function toArray<T>(list: ITreeNode<ICompressedTreeNode<T>>[]): T[][] {
return list.map(i => i.element.elements);
}
suite('CompressedObjectTreeModel', function () {
/**
* Calls that test function twice, once with an empty options and
* once with `diffIdentityProvider`.
*/
function withSmartSplice(fn: (options: IObjectTreeModelSetChildrenOptions<number, any>) => void) {
fn({});
fn({ diffIdentityProvider: { getId: n => String(n) } });
}
test('ctor', () => {
const list: ITreeNode<ICompressedTreeNode<number>>[] = [];
const model = new CompressedObjectTreeModel<number>('test', toList(list));
assert(model);
assert.strictEqual(list.length, 0);
assert.strictEqual(model.size, 0);
});
test('flat', () => withSmartSplice(options => {
const list: ITreeNode<ICompressedTreeNode<number>>[] = [];
const model = new CompressedObjectTreeModel<number>('test', toList(list));
model.setChildren(null, [
{ element: 0 },
{ element: 1 },
{ element: 2 }
], options);
assert.deepStrictEqual(toArray(list), [[0], [1], [2]]);
assert.strictEqual(model.size, 3);
model.setChildren(null, [
{ element: 3 },
{ element: 4 },
{ element: 5 },
], options);
assert.deepStrictEqual(toArray(list), [[3], [4], [5]]);
assert.strictEqual(model.size, 3);
model.setChildren(null, [], options);
assert.deepStrictEqual(toArray(list), []);
assert.strictEqual(model.size, 0);
}));
test('nested', () => withSmartSplice(options => {
const list: ITreeNode<ICompressedTreeNode<number>>[] = [];
const model = new CompressedObjectTreeModel<number>('test', toList(list));
model.setChildren(null, [
{
element: 0, children: [
{ element: 10 },
{ element: 11 },
{ element: 12 },
]
},
{ element: 1 },
{ element: 2 }
], options);
assert.deepStrictEqual(toArray(list), [[0], [10], [11], [12], [1], [2]]);
assert.strictEqual(model.size, 6);
model.setChildren(12, [
{ element: 120 },
{ element: 121 }
], options);
assert.deepStrictEqual(toArray(list), [[0], [10], [11], [12], [120], [121], [1], [2]]);
assert.strictEqual(model.size, 8);
model.setChildren(0, [], options);
assert.deepStrictEqual(toArray(list), [[0], [1], [2]]);
assert.strictEqual(model.size, 3);
model.setChildren(null, [], options);
assert.deepStrictEqual(toArray(list), []);
assert.strictEqual(model.size, 0);
}));
test('compressed', () => withSmartSplice(options => {
const list: ITreeNode<ICompressedTreeNode<number>>[] = [];
const model = new CompressedObjectTreeModel<number>('test', toList(list));
model.setChildren(null, [
{
element: 1, children: [{
element: 11, children: [{
element: 111, children: [
{ element: 1111 },
{ element: 1112 },
{ element: 1113 },
]
}]
}]
}
], options);
assert.deepStrictEqual(toArray(list), [[1, 11, 111], [1111], [1112], [1113]]);
assert.strictEqual(model.size, 6);
model.setChildren(11, [
{ element: 111 },
{ element: 112 },
{ element: 113 },
], options);
assert.deepStrictEqual(toArray(list), [[1, 11], [111], [112], [113]]);
assert.strictEqual(model.size, 5);
model.setChildren(113, [
{ element: 1131 }
], options);
assert.deepStrictEqual(toArray(list), [[1, 11], [111], [112], [113, 1131]]);
assert.strictEqual(model.size, 6);
model.setChildren(1131, [
{ element: 1132 }
], options);
assert.deepStrictEqual(toArray(list), [[1, 11], [111], [112], [113, 1131, 1132]]);
assert.strictEqual(model.size, 7);
model.setChildren(1131, [
{ element: 1132 },
{ element: 1133 },
], options);
assert.deepStrictEqual(toArray(list), [[1, 11], [111], [112], [113, 1131], [1132], [1133]]);
assert.strictEqual(model.size, 8);
}));
});
});
|
src/vs/base/test/browser/ui/tree/compressedObjectTreeModel.test.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.00017774496518541127,
0.00017333781579509377,
0.00016669949400238693,
0.0001738062856020406,
0.0000028498491246864432
] |
{
"id": 4,
"code_window": [
"\t\tif (!workspaceInitializationPayload) {\n",
"\t\t\tlet id: string;\n",
"\t\t\tif (this.configuration.backupPath) {\n",
"\t\t\t\tid = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID\n",
"\t\t\t} else if (environmentService.isExtensionDevelopment) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t// we know the backupPath must be a unique path so we leverage its name as workspace ID\n",
"\t\t\t\tid = basename(this.configuration.backupPath);\n"
],
"file_path": "src/vs/workbench/electron-sandbox/shared.desktop.main.ts",
"type": "replace",
"edit_start_line_idx": 319
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken } from 'vs/base/common/cancellation';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { isArray } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { IChannel, IServerChannel } from 'vs/base/parts/ipc/common/ipc';
import { ILogService } from 'vs/platform/log/common/log';
import { IManualSyncTask, IResourcePreview, ISyncResourceHandle, ISyncResourcePreview, ISyncTask, IUserDataManifest, IUserDataSyncService, SyncResource, SyncStatus, UserDataSyncError } from 'vs/platform/userDataSync/common/userDataSync';
type ManualSyncTaskEvent<T> = { manualSyncTaskId: string, data: T };
export class UserDataSyncChannel implements IServerChannel {
private readonly manualSyncTasks = new Map<string, { manualSyncTask: IManualSyncTask, disposables: DisposableStore }>();
private readonly onManualSynchronizeResources = new Emitter<ManualSyncTaskEvent<[SyncResource, URI[]][]>>();
constructor(private readonly service: IUserDataSyncService, private readonly logService: ILogService) { }
listen(_: unknown, event: string): Event<any> {
switch (event) {
// sync
case 'onDidChangeStatus': return this.service.onDidChangeStatus;
case 'onDidChangeConflicts': return this.service.onDidChangeConflicts;
case 'onDidChangeLocal': return this.service.onDidChangeLocal;
case 'onDidChangeLastSyncTime': return this.service.onDidChangeLastSyncTime;
case 'onSyncErrors': return this.service.onSyncErrors;
case 'onDidResetLocal': return this.service.onDidResetLocal;
case 'onDidResetRemote': return this.service.onDidResetRemote;
// manual sync
case 'manualSync/onSynchronizeResources': return this.onManualSynchronizeResources.event;
}
throw new Error(`Event not found: ${event}`);
}
async call(context: any, command: string, args?: any): Promise<any> {
try {
const result = await this._call(context, command, args);
return result;
} catch (e) {
this.logService.error(e);
throw e;
}
}
private async _call(context: any, command: string, args?: any): Promise<any> {
switch (command) {
// sync
case '_getInitialData': return Promise.resolve([this.service.status, this.service.conflicts, this.service.lastSyncTime]);
case 'replace': return this.service.replace(URI.revive(args[0]));
case 'reset': return this.service.reset();
case 'resetRemote': return this.service.resetRemote();
case 'resetLocal': return this.service.resetLocal();
case 'hasPreviouslySynced': return this.service.hasPreviouslySynced();
case 'hasLocalData': return this.service.hasLocalData();
case 'accept': return this.service.accept(args[0], URI.revive(args[1]), args[2], args[3]);
case 'resolveContent': return this.service.resolveContent(URI.revive(args[0]));
case 'getLocalSyncResourceHandles': return this.service.getLocalSyncResourceHandles(args[0]);
case 'getRemoteSyncResourceHandles': return this.service.getRemoteSyncResourceHandles(args[0]);
case 'getAssociatedResources': return this.service.getAssociatedResources(args[0], { created: args[1].created, uri: URI.revive(args[1].uri) });
case 'getMachineId': return this.service.getMachineId(args[0], { created: args[1].created, uri: URI.revive(args[1].uri) });
case 'createManualSyncTask': return this.createManualSyncTask();
}
// manual sync
if (command.startsWith('manualSync/')) {
const manualSyncTaskCommand = command.substring('manualSync/'.length);
const manualSyncTaskId = args[0];
const manualSyncTask = this.getManualSyncTask(manualSyncTaskId);
args = (<Array<any>>args).slice(1);
switch (manualSyncTaskCommand) {
case 'preview': return manualSyncTask.preview();
case 'accept': return manualSyncTask.accept(URI.revive(args[0]), args[1]);
case 'merge': return manualSyncTask.merge(URI.revive(args[0]));
case 'discard': return manualSyncTask.discard(URI.revive(args[0]));
case 'discardConflicts': return manualSyncTask.discardConflicts();
case 'apply': return manualSyncTask.apply();
case 'pull': return manualSyncTask.pull();
case 'push': return manualSyncTask.push();
case 'stop': return manualSyncTask.stop();
case '_getStatus': return manualSyncTask.status;
case 'dispose': return this.disposeManualSyncTask(manualSyncTask);
}
}
throw new Error('Invalid call');
}
private getManualSyncTask(manualSyncTaskId: string): IManualSyncTask {
const value = this.manualSyncTasks.get(this.createKey(manualSyncTaskId));
if (!value) {
throw new Error(`Manual sync taks not found: ${manualSyncTaskId}`);
}
return value.manualSyncTask;
}
private async createManualSyncTask(): Promise<{ id: string, manifest: IUserDataManifest | null, status: SyncStatus }> {
const disposables = new DisposableStore();
const manualSyncTask = disposables.add(await this.service.createManualSyncTask());
disposables.add(manualSyncTask.onSynchronizeResources(synchronizeResources => this.onManualSynchronizeResources.fire({ manualSyncTaskId: manualSyncTask.id, data: synchronizeResources })));
this.manualSyncTasks.set(this.createKey(manualSyncTask.id), { manualSyncTask, disposables });
return { id: manualSyncTask.id, manifest: manualSyncTask.manifest, status: manualSyncTask.status };
}
private disposeManualSyncTask(manualSyncTask: IManualSyncTask): void {
manualSyncTask.dispose();
const key = this.createKey(manualSyncTask.id);
this.manualSyncTasks.get(key)?.disposables.dispose();
this.manualSyncTasks.delete(key);
}
private createKey(manualSyncTaskId: string): string { return `manualSyncTask-${manualSyncTaskId}`; }
}
export class UserDataSyncChannelClient extends Disposable implements IUserDataSyncService {
declare readonly _serviceBrand: undefined;
private readonly channel: IChannel;
private _status: SyncStatus = SyncStatus.Uninitialized;
get status(): SyncStatus { return this._status; }
private _onDidChangeStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>());
readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangeStatus.event;
get onDidChangeLocal(): Event<SyncResource> { return this.channel.listen<SyncResource>('onDidChangeLocal'); }
private _conflicts: [SyncResource, IResourcePreview[]][] = [];
get conflicts(): [SyncResource, IResourcePreview[]][] { return this._conflicts; }
private _onDidChangeConflicts: Emitter<[SyncResource, IResourcePreview[]][]> = this._register(new Emitter<[SyncResource, IResourcePreview[]][]>());
readonly onDidChangeConflicts: Event<[SyncResource, IResourcePreview[]][]> = this._onDidChangeConflicts.event;
private _lastSyncTime: number | undefined = undefined;
get lastSyncTime(): number | undefined { return this._lastSyncTime; }
private _onDidChangeLastSyncTime: Emitter<number> = this._register(new Emitter<number>());
readonly onDidChangeLastSyncTime: Event<number> = this._onDidChangeLastSyncTime.event;
private _onSyncErrors: Emitter<[SyncResource, UserDataSyncError][]> = this._register(new Emitter<[SyncResource, UserDataSyncError][]>());
readonly onSyncErrors: Event<[SyncResource, UserDataSyncError][]> = this._onSyncErrors.event;
get onDidResetLocal(): Event<void> { return this.channel.listen<void>('onDidResetLocal'); }
get onDidResetRemote(): Event<void> { return this.channel.listen<void>('onDidResetRemote'); }
constructor(userDataSyncChannel: IChannel) {
super();
this.channel = {
call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
return userDataSyncChannel.call(command, arg, cancellationToken)
.then(null, error => { throw UserDataSyncError.toUserDataSyncError(error); });
},
listen<T>(event: string, arg?: any): Event<T> {
return userDataSyncChannel.listen(event, arg);
}
};
this.channel.call<[SyncStatus, [SyncResource, IResourcePreview[]][], number | undefined]>('_getInitialData').then(([status, conflicts, lastSyncTime]) => {
this.updateStatus(status);
this.updateConflicts(conflicts);
if (lastSyncTime) {
this.updateLastSyncTime(lastSyncTime);
}
this._register(this.channel.listen<SyncStatus>('onDidChangeStatus')(status => this.updateStatus(status)));
this._register(this.channel.listen<number>('onDidChangeLastSyncTime')(lastSyncTime => this.updateLastSyncTime(lastSyncTime)));
});
this._register(this.channel.listen<[SyncResource, IResourcePreview[]][]>('onDidChangeConflicts')(conflicts => this.updateConflicts(conflicts)));
this._register(this.channel.listen<[SyncResource, Error][]>('onSyncErrors')(errors => this._onSyncErrors.fire(errors.map(([source, error]) => ([source, UserDataSyncError.toUserDataSyncError(error)])))));
}
createSyncTask(): Promise<ISyncTask> {
throw new Error('not supported');
}
async createManualSyncTask(): Promise<IManualSyncTask> {
const { id, manifest, status } = await this.channel.call<{ id: string, manifest: IUserDataManifest | null, status: SyncStatus }>('createManualSyncTask');
const that = this;
const manualSyncTaskChannelClient = new ManualSyncTaskChannelClient(id, manifest, status, {
async call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
return that.channel.call<T>(`manualSync/${command}`, [id, ...(isArray(arg) ? arg : [arg])], cancellationToken);
},
listen<T>(event: string, arg?: any): Event<T> {
return Event.map(
Event.filter(that.channel.listen<{ manualSyncTaskId: string, data: T }>(`manualSync/${event}`, arg), e => !manualSyncTaskChannelClient.isDiposed() && e.manualSyncTaskId === id),
e => e.data);
}
});
return manualSyncTaskChannelClient;
}
replace(uri: URI): Promise<void> {
return this.channel.call('replace', [uri]);
}
reset(): Promise<void> {
return this.channel.call('reset');
}
resetRemote(): Promise<void> {
return this.channel.call('resetRemote');
}
resetLocal(): Promise<void> {
return this.channel.call('resetLocal');
}
hasPreviouslySynced(): Promise<boolean> {
return this.channel.call('hasPreviouslySynced');
}
hasLocalData(): Promise<boolean> {
return this.channel.call('hasLocalData');
}
accept(syncResource: SyncResource, resource: URI, content: string | null, apply: boolean): Promise<void> {
return this.channel.call('accept', [syncResource, resource, content, apply]);
}
resolveContent(resource: URI): Promise<string | null> {
return this.channel.call('resolveContent', [resource]);
}
async getLocalSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> {
const handles = await this.channel.call<ISyncResourceHandle[]>('getLocalSyncResourceHandles', [resource]);
return handles.map(({ created, uri }) => ({ created, uri: URI.revive(uri) }));
}
async getRemoteSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> {
const handles = await this.channel.call<ISyncResourceHandle[]>('getRemoteSyncResourceHandles', [resource]);
return handles.map(({ created, uri }) => ({ created, uri: URI.revive(uri) }));
}
async getAssociatedResources(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<{ resource: URI, comparableResource: URI }[]> {
const result = await this.channel.call<{ resource: URI, comparableResource: URI }[]>('getAssociatedResources', [resource, syncResourceHandle]);
return result.map(({ resource, comparableResource }) => ({ resource: URI.revive(resource), comparableResource: URI.revive(comparableResource) }));
}
async getMachineId(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<string | undefined> {
return this.channel.call<string | undefined>('getMachineId', [resource, syncResourceHandle]);
}
private async updateStatus(status: SyncStatus): Promise<void> {
this._status = status;
this._onDidChangeStatus.fire(status);
}
private async updateConflicts(conflicts: [SyncResource, IResourcePreview[]][]): Promise<void> {
// Revive URIs
this._conflicts = conflicts.map(([syncResource, conflicts]) =>
([
syncResource,
conflicts.map(r =>
({
...r,
localResource: URI.revive(r.localResource),
remoteResource: URI.revive(r.remoteResource),
previewResource: URI.revive(r.previewResource),
}))
]));
this._onDidChangeConflicts.fire(this._conflicts);
}
private updateLastSyncTime(lastSyncTime: number): void {
if (this._lastSyncTime !== lastSyncTime) {
this._lastSyncTime = lastSyncTime;
this._onDidChangeLastSyncTime.fire(lastSyncTime);
}
}
}
class ManualSyncTaskChannelClient extends Disposable implements IManualSyncTask {
private readonly channel: IChannel;
get onSynchronizeResources(): Event<[SyncResource, URI[]][]> { return this.channel.listen<[SyncResource, URI[]][]>('onSynchronizeResources'); }
private _status: SyncStatus;
get status(): SyncStatus { return this._status; }
constructor(
readonly id: string,
readonly manifest: IUserDataManifest | null,
status: SyncStatus,
manualSyncTaskChannel: IChannel
) {
super();
this._status = status;
const that = this;
this.channel = {
async call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
try {
const result = await manualSyncTaskChannel.call<T>(command, arg, cancellationToken);
if (!that.isDiposed()) {
that._status = await manualSyncTaskChannel.call<SyncStatus>('_getStatus');
}
return result;
} catch (error) {
throw UserDataSyncError.toUserDataSyncError(error);
}
},
listen<T>(event: string, arg?: any): Event<T> {
return manualSyncTaskChannel.listen(event, arg);
}
};
}
async preview(): Promise<[SyncResource, ISyncResourcePreview][]> {
const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('preview');
return this.deserializePreviews(previews);
}
async accept(resource: URI, content?: string | null): Promise<[SyncResource, ISyncResourcePreview][]> {
const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('accept', [resource, content]);
return this.deserializePreviews(previews);
}
async merge(resource?: URI): Promise<[SyncResource, ISyncResourcePreview][]> {
const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('merge', [resource]);
return this.deserializePreviews(previews);
}
async discard(resource: URI): Promise<[SyncResource, ISyncResourcePreview][]> {
const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('discard', [resource]);
return this.deserializePreviews(previews);
}
async discardConflicts(): Promise<[SyncResource, ISyncResourcePreview][]> {
const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('discardConflicts');
return this.deserializePreviews(previews);
}
async apply(): Promise<[SyncResource, ISyncResourcePreview][]> {
const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('apply');
return this.deserializePreviews(previews);
}
pull(): Promise<void> {
return this.channel.call('pull');
}
push(): Promise<void> {
return this.channel.call('push');
}
stop(): Promise<void> {
return this.channel.call('stop');
}
private _disposed = false;
isDiposed() { return this._disposed; }
override dispose(): void {
this._disposed = true;
this.channel.call('dispose');
}
private deserializePreviews(previews: [SyncResource, ISyncResourcePreview][]): [SyncResource, ISyncResourcePreview][] {
return previews.map(([syncResource, preview]) =>
([
syncResource,
{
isLastSyncFromCurrentMachine: preview.isLastSyncFromCurrentMachine,
resourcePreviews: preview.resourcePreviews.map(r => ({
...r,
localResource: URI.revive(r.localResource),
remoteResource: URI.revive(r.remoteResource),
previewResource: URI.revive(r.previewResource),
acceptedResource: URI.revive(r.acceptedResource),
}))
}
]));
}
}
|
src/vs/platform/userDataSync/common/userDataSyncServiceIpc.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.9606646299362183,
0.07304640114307404,
0.00016310893988702446,
0.00017315965669695288,
0.25091245770454407
] |
{
"id": 5,
"code_window": [
"\t\t\t} else if (environmentService.isExtensionDevelopment) {\n",
"\t\t\t\tid = 'ext-dev'; // extension development window never stores backups and is a singleton\n",
"\t\t\t} else {\n",
"\t\t\t\tthrow new Error('Unexpected window configuration without backupPath');\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// fallback to a reserved identifier when in extension development where backups are not stored\n",
"\t\t\t\tid = 'ext-dev';\n"
],
"file_path": "src/vs/workbench/electron-sandbox/shared.desktop.main.ts",
"type": "replace",
"edit_start_line_idx": 321
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import product from 'vs/platform/product/common/product';
import { zoomLevelToZoomFactor } from 'vs/platform/windows/common/windows';
import { Workbench } from 'vs/workbench/browser/workbench';
import { NativeWindow } from 'vs/workbench/electron-sandbox/window';
import { setZoomLevel, setZoomFactor, setFullscreen } from 'vs/base/browser/browser';
import { domContentLoaded } from 'vs/base/browser/dom';
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
import { INativeWorkbenchConfiguration, INativeWorkbenchEnvironmentService, NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier, IWorkspaceInitializationPayload, reviveIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { ILoggerService, ILogService } from 'vs/platform/log/common/log';
import { NativeStorageService } from 'vs/platform/storage/electron-sandbox/storageService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { Disposable } from 'vs/base/common/lifecycle';
import { IMainProcessService, ISharedProcessService } from 'vs/platform/ipc/electron-sandbox/services';
import { SharedProcessService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessService';
import { RemoteAuthorityResolverService } from 'vs/platform/remote/electron-sandbox/remoteAuthorityResolverService';
import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { RemoteAgentService } from 'vs/workbench/services/remote/electron-sandbox/remoteAgentServiceImpl';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { FileService } from 'vs/platform/files/common/fileService';
import { IFileService } from 'vs/platform/files/common/files';
import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel';
import { ConfigurationCache } from 'vs/workbench/services/configuration/electron-sandbox/configurationCache';
import { ISignService } from 'vs/platform/sign/common/sign';
import { basename } from 'vs/base/common/path';
import { IProductService } from 'vs/platform/product/common/productService';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { NativeHostService } from 'vs/platform/native/electron-sandbox/nativeHostService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService';
import { KeyboardLayoutService } from 'vs/workbench/services/keybinding/electron-sandbox/nativeKeyboardLayout';
import { IKeyboardLayoutService } from 'vs/platform/keyboardLayout/common/keyboardLayout';
import { ElectronIPCMainProcessService } from 'vs/platform/ipc/electron-sandbox/mainProcessService';
import { LoggerChannelClient, LogLevelChannelClient } from 'vs/platform/log/common/logIpc';
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { NativeLogService } from 'vs/workbench/services/log/electron-sandbox/logService';
import { WorkspaceTrustEnablementService, WorkspaceTrustManagementService } from 'vs/workbench/services/workspaces/common/workspaceTrust';
import { IWorkspaceTrustEnablementService, IWorkspaceTrustManagementService } from 'vs/platform/workspace/common/workspaceTrust';
import { registerWindowDriver } from 'vs/platform/driver/electron-sandbox/driver';
import { safeStringify } from 'vs/base/common/objects';
import { ISharedProcessWorkerWorkbenchService, SharedProcessWorkerWorkbenchService } from 'vs/workbench/services/sharedProcess/electron-sandbox/sharedProcessWorkerWorkbenchService';
import { isMacintosh } from 'vs/base/common/platform';
export abstract class SharedDesktopMain extends Disposable {
constructor(
protected readonly configuration: INativeWorkbenchConfiguration
) {
super();
this.init();
}
private init(): void {
// Massage configuration file URIs
this.reviveUris();
// Browser config
const zoomLevel = this.configuration.zoomLevel || 0;
setZoomFactor(zoomLevelToZoomFactor(zoomLevel));
setZoomLevel(zoomLevel, true /* isTrusted */);
setFullscreen(!!this.configuration.fullscreen);
}
private reviveUris() {
// Workspace
const workspace = reviveIdentifier(this.configuration.workspace);
if (isWorkspaceIdentifier(workspace) || isSingleFolderWorkspaceIdentifier(workspace)) {
this.configuration.workspace = workspace;
}
// Files
const filesToWait = this.configuration.filesToWait;
const filesToWaitPaths = filesToWait?.paths;
[filesToWaitPaths, this.configuration.filesToOpenOrCreate, this.configuration.filesToDiff].forEach(paths => {
if (Array.isArray(paths)) {
paths.forEach(path => {
if (path.fileUri) {
path.fileUri = URI.revive(path.fileUri);
}
});
}
});
if (filesToWait) {
filesToWait.waitMarkerFileUri = URI.revive(filesToWait.waitMarkerFileUri);
}
}
async open(): Promise<void> {
// Init services and wait for DOM to be ready in parallel
const [services] = await Promise.all([this.initServices(), domContentLoaded()]);
// Create Workbench
const workbench = new Workbench(document.body, { extraClasses: this.getExtraClasses() }, services.serviceCollection, services.logService);
// Listeners
this.registerListeners(workbench, services.storageService);
// Startup
const instantiationService = workbench.startup();
// Window
this._register(instantiationService.createInstance(NativeWindow));
// Logging
services.logService.trace('workbench configuration', safeStringify(this.configuration));
// Driver
if (this.configuration.driver) {
instantiationService.invokeFunction(async accessor => this._register(await registerWindowDriver(accessor, this.configuration.windowId)));
}
}
private getExtraClasses(): string[] {
if (isMacintosh) {
if (this.configuration.os.release > '20.0.0') {
return ['macos-bigsur-or-newer'];
}
}
return [];
}
private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
// Workbench Lifecycle
this._register(workbench.onWillShutdown(event => event.join(storageService.close(), 'join.closeStorage')));
this._register(workbench.onDidShutdown(() => this.dispose()));
}
protected abstract registerFileSystemProviders(
mainProcessService: IMainProcessService,
sharedProcessWorkerWorkbenchService: ISharedProcessWorkerWorkbenchService,
fileService: IFileService,
logService: ILogService,
nativeHostService: INativeHostService
): void;
private async initServices(): Promise<{ serviceCollection: ServiceCollection, logService: ILogService, storageService: NativeStorageService }> {
const serviceCollection = new ServiceCollection();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Main Process
const mainProcessService = this._register(new ElectronIPCMainProcessService(this.configuration.windowId));
serviceCollection.set(IMainProcessService, mainProcessService);
// Product
const productService: IProductService = { _serviceBrand: undefined, ...product };
serviceCollection.set(IProductService, productService);
// Environment
const environmentService = new NativeWorkbenchEnvironmentService(this.configuration, productService);
serviceCollection.set(INativeWorkbenchEnvironmentService, environmentService);
// Logger
const logLevelChannelClient = new LogLevelChannelClient(mainProcessService.getChannel('logLevel'));
const loggerService = new LoggerChannelClient(environmentService.configuration.logLevel, logLevelChannelClient.onDidChangeLogLevel, mainProcessService.getChannel('logger'));
serviceCollection.set(ILoggerService, loggerService);
// Log
const logService = this._register(new NativeLogService(`renderer${this.configuration.windowId}`, environmentService.configuration.logLevel, loggerService, logLevelChannelClient, environmentService));
serviceCollection.set(ILogService, logService);
// Shared Process
const sharedProcessService = new SharedProcessService(this.configuration.windowId, logService);
serviceCollection.set(ISharedProcessService, sharedProcessService);
// Shared Process Worker
const sharedProcessWorkerWorkbenchService = new SharedProcessWorkerWorkbenchService(this.configuration.windowId, logService, sharedProcessService);
serviceCollection.set(ISharedProcessWorkerWorkbenchService, sharedProcessWorkerWorkbenchService);
// Remote
const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Sign
const signService = ProxyChannel.toService<ISignService>(mainProcessService.getChannel('sign'));
serviceCollection.set(ISignService, signService);
// Remote Agent
const remoteAgentService = this._register(new RemoteAgentService(environmentService, productService, remoteAuthorityResolverService, signService, logService));
serviceCollection.set(IRemoteAgentService, remoteAgentService);
// Native Host
const nativeHostService = new NativeHostService(this.configuration.windowId, mainProcessService) as INativeHostService;
serviceCollection.set(INativeHostService, nativeHostService);
// Files
const fileService = this._register(new FileService(logService));
serviceCollection.set(IFileService, fileService);
this.registerFileSystemProviders(mainProcessService, sharedProcessWorkerWorkbenchService, fileService, logService, nativeHostService);
// URI Identity
const uriIdentityService = new UriIdentityService(fileService);
serviceCollection.set(IUriIdentityService, uriIdentityService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Remote file system
this._register(RemoteFileSystemProvider.register(remoteAgentService, fileService, logService));
const payload = this.resolveWorkspaceInitializationPayload(environmentService);
const [configurationService, storageService] = await Promise.all([
this.createWorkspaceService(payload, environmentService, fileService, remoteAgentService, uriIdentityService, logService).then(service => {
// Workspace
serviceCollection.set(IWorkspaceContextService, service);
// Configuration
serviceCollection.set(IWorkbenchConfigurationService, service);
return service;
}),
this.createStorageService(payload, environmentService, mainProcessService).then(service => {
// Storage
serviceCollection.set(IStorageService, service);
return service;
}),
this.createKeyboardLayoutService(mainProcessService).then(service => {
// KeyboardLayout
serviceCollection.set(IKeyboardLayoutService, service);
return service;
})
]);
// Workspace Trust Service
const workspaceTrustEnablementService = new WorkspaceTrustEnablementService(configurationService, environmentService);
serviceCollection.set(IWorkspaceTrustEnablementService, workspaceTrustEnablementService);
const workspaceTrustManagementService = new WorkspaceTrustManagementService(configurationService, remoteAuthorityResolverService, storageService, uriIdentityService, environmentService, configurationService, workspaceTrustEnablementService);
serviceCollection.set(IWorkspaceTrustManagementService, workspaceTrustManagementService);
// Update workspace trust so that configuration is updated accordingly
configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted());
this._register(workspaceTrustManagementService.onDidChangeTrust(() => configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted())));
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return { serviceCollection, logService, storageService };
}
private resolveWorkspaceInitializationPayload(environmentService: INativeWorkbenchEnvironmentService): IWorkspaceInitializationPayload {
let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined = this.configuration.workspace;
// Fallback to empty workspace if we have no payload yet.
if (!workspaceInitializationPayload) {
let id: string;
if (this.configuration.backupPath) {
id = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID
} else if (environmentService.isExtensionDevelopment) {
id = 'ext-dev'; // extension development window never stores backups and is a singleton
} else {
throw new Error('Unexpected window configuration without backupPath');
}
workspaceInitializationPayload = { id };
}
return workspaceInitializationPayload;
}
private async createWorkspaceService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, fileService: FileService, remoteAgentService: IRemoteAgentService, uriIdentityService: IUriIdentityService, logService: ILogService): Promise<WorkspaceService> {
const workspaceService = new WorkspaceService({ remoteAuthority: environmentService.remoteAuthority, configurationCache: new ConfigurationCache(URI.file(environmentService.userDataPath), fileService) }, environmentService, fileService, remoteAgentService, uriIdentityService, logService);
try {
await workspaceService.initialize(payload);
return workspaceService;
} catch (error) {
onUnexpectedError(error);
return workspaceService;
}
}
private async createStorageService(payload: IWorkspaceInitializationPayload, environmentService: INativeWorkbenchEnvironmentService, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
const storageService = new NativeStorageService(payload, mainProcessService, environmentService);
try {
await storageService.initialize();
return storageService;
} catch (error) {
onUnexpectedError(error);
return storageService;
}
}
private async createKeyboardLayoutService(mainProcessService: IMainProcessService): Promise<KeyboardLayoutService> {
const keyboardLayoutService = new KeyboardLayoutService(mainProcessService);
try {
await keyboardLayoutService.initialize();
return keyboardLayoutService;
} catch (error) {
onUnexpectedError(error);
return keyboardLayoutService;
}
}
}
|
src/vs/workbench/electron-sandbox/shared.desktop.main.ts
| 1 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.9981347322463989,
0.026910822838544846,
0.0001629315665923059,
0.00017224853218067437,
0.15967142581939697
] |
{
"id": 5,
"code_window": [
"\t\t\t} else if (environmentService.isExtensionDevelopment) {\n",
"\t\t\t\tid = 'ext-dev'; // extension development window never stores backups and is a singleton\n",
"\t\t\t} else {\n",
"\t\t\t\tthrow new Error('Unexpected window configuration without backupPath');\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// fallback to a reserved identifier when in extension development where backups are not stored\n",
"\t\t\t\tid = 'ext-dev';\n"
],
"file_path": "src/vs/workbench/electron-sandbox/shared.desktop.main.ts",
"type": "replace",
"edit_start_line_idx": 321
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { memoize } from './memoize';
const localize = nls.loadMessageBundle();
type LogLevel = 'Trace' | 'Info' | 'Error';
export class Logger {
@memoize
private get output(): vscode.OutputChannel {
return vscode.window.createOutputChannel(localize('channelName', 'TypeScript'));
}
private data2String(data: any): string {
if (data instanceof Error) {
return data.stack || data.message;
}
if (data.success === false && data.message) {
return data.message;
}
return data.toString();
}
public info(message: string, data?: any): void {
this.logLevel('Info', message, data);
}
public error(message: string, data?: any): void {
// See https://github.com/microsoft/TypeScript/issues/10496
if (data && data.message === 'No content available.') {
return;
}
this.logLevel('Error', message, data);
}
public logLevel(level: LogLevel, message: string, data?: any): void {
this.output.appendLine(`[${level} - ${this.now()}] ${message}`);
if (data) {
this.output.appendLine(this.data2String(data));
}
}
private now(): string {
const now = new Date();
return padLeft(now.getUTCHours() + '', 2, '0')
+ ':' + padLeft(now.getMinutes() + '', 2, '0')
+ ':' + padLeft(now.getUTCSeconds() + '', 2, '0') + '.' + now.getMilliseconds();
}
}
function padLeft(s: string, n: number, pad = ' ') {
return pad.repeat(Math.max(0, n - s.length)) + s;
}
|
extensions/typescript-language-features/src/utils/logger.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.0005794946337118745,
0.0002596131234895438,
0.00016940654313657433,
0.00017569647752679884,
0.00014647220086771995
] |
{
"id": 5,
"code_window": [
"\t\t\t} else if (environmentService.isExtensionDevelopment) {\n",
"\t\t\t\tid = 'ext-dev'; // extension development window never stores backups and is a singleton\n",
"\t\t\t} else {\n",
"\t\t\t\tthrow new Error('Unexpected window configuration without backupPath');\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// fallback to a reserved identifier when in extension development where backups are not stored\n",
"\t\t\t\tid = 'ext-dev';\n"
],
"file_path": "src/vs/workbench/electron-sandbox/shared.desktop.main.ts",
"type": "replace",
"edit_start_line_idx": 321
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event, EventMultiplexer } from 'vs/base/common/event';
import {
ILocalExtension, IGalleryExtension, IExtensionIdentifier, IReportedExtension, IGalleryMetadata, IExtensionGalleryService, InstallOptions, UninstallOptions, InstallVSIXOptions, InstallExtensionResult, TargetPlatform, ExtensionManagementError, ExtensionManagementErrorCode
} from 'vs/platform/extensionManagement/common/extensionManagement';
import { DidUninstallExtensionOnServerEvent, IExtensionManagementServer, IExtensionManagementServerService, InstallExtensionOnServerEvent, IWorkbenchExtensionManagementService, UninstallExtensionOnServerEvent } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
import { ExtensionType, isLanguagePackExtension, IExtensionManifest, getWorkspaceSupportTypeMessage } from 'vs/platform/extensions/common/extensions';
import { URI } from 'vs/base/common/uri';
import { Disposable } from 'vs/base/common/lifecycle';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { CancellationToken } from 'vs/base/common/cancellation';
import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { localize } from 'vs/nls';
import { IProductService } from 'vs/platform/product/common/productService';
import { Schemas } from 'vs/base/common/network';
import { IDownloadService } from 'vs/platform/download/common/download';
import { flatten } from 'vs/base/common/arrays';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import Severity from 'vs/base/common/severity';
import { canceled } from 'vs/base/common/errors';
import { IUserDataAutoSyncEnablementService, IUserDataSyncResourceEnablementService, SyncResource } from 'vs/platform/userDataSync/common/userDataSync';
import { Promises } from 'vs/base/common/async';
import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';
import { IExtensionManifestPropertiesService } from 'vs/workbench/services/extensions/common/extensionManifestPropertiesService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ICommandService } from 'vs/platform/commands/common/commands';
export class ExtensionManagementService extends Disposable implements IWorkbenchExtensionManagementService {
declare readonly _serviceBrand: undefined;
readonly onInstallExtension: Event<InstallExtensionOnServerEvent>;
readonly onDidInstallExtensions: Event<readonly InstallExtensionResult[]>;
readonly onUninstallExtension: Event<UninstallExtensionOnServerEvent>;
readonly onDidUninstallExtension: Event<DidUninstallExtensionOnServerEvent>;
protected readonly servers: IExtensionManagementServer[] = [];
constructor(
@IExtensionManagementServerService protected readonly extensionManagementServerService: IExtensionManagementServerService,
@IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService,
@IConfigurationService protected readonly configurationService: IConfigurationService,
@IProductService protected readonly productService: IProductService,
@IDownloadService protected readonly downloadService: IDownloadService,
@IUserDataAutoSyncEnablementService private readonly userDataAutoSyncEnablementService: IUserDataAutoSyncEnablementService,
@IUserDataSyncResourceEnablementService private readonly userDataSyncResourceEnablementService: IUserDataSyncResourceEnablementService,
@IDialogService private readonly dialogService: IDialogService,
@IWorkspaceTrustRequestService private readonly workspaceTrustRequestService: IWorkspaceTrustRequestService,
@IExtensionManifestPropertiesService private readonly extensionManifestPropertiesService: IExtensionManifestPropertiesService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
if (this.extensionManagementServerService.localExtensionManagementServer) {
this.servers.push(this.extensionManagementServerService.localExtensionManagementServer);
}
if (this.extensionManagementServerService.remoteExtensionManagementServer) {
this.servers.push(this.extensionManagementServerService.remoteExtensionManagementServer);
}
if (this.extensionManagementServerService.webExtensionManagementServer) {
this.servers.push(this.extensionManagementServerService.webExtensionManagementServer);
}
this.onInstallExtension = this._register(this.servers.reduce((emitter: EventMultiplexer<InstallExtensionOnServerEvent>, server) => { emitter.add(Event.map(server.extensionManagementService.onInstallExtension, e => ({ ...e, server }))); return emitter; }, new EventMultiplexer<InstallExtensionOnServerEvent>())).event;
this.onDidInstallExtensions = this._register(this.servers.reduce((emitter: EventMultiplexer<readonly InstallExtensionResult[]>, server) => { emitter.add(server.extensionManagementService.onDidInstallExtensions); return emitter; }, new EventMultiplexer<readonly InstallExtensionResult[]>())).event;
this.onUninstallExtension = this._register(this.servers.reduce((emitter: EventMultiplexer<UninstallExtensionOnServerEvent>, server) => { emitter.add(Event.map(server.extensionManagementService.onUninstallExtension, e => ({ ...e, server }))); return emitter; }, new EventMultiplexer<UninstallExtensionOnServerEvent>())).event;
this.onDidUninstallExtension = this._register(this.servers.reduce((emitter: EventMultiplexer<DidUninstallExtensionOnServerEvent>, server) => { emitter.add(Event.map(server.extensionManagementService.onDidUninstallExtension, e => ({ ...e, server }))); return emitter; }, new EventMultiplexer<DidUninstallExtensionOnServerEvent>())).event;
}
async getInstalled(type?: ExtensionType, donotIgnoreInvalidExtensions?: boolean): Promise<ILocalExtension[]> {
const result = await Promise.all(this.servers.map(({ extensionManagementService }) => extensionManagementService.getInstalled(type, donotIgnoreInvalidExtensions)));
return flatten(result);
}
async uninstall(extension: ILocalExtension, options?: UninstallOptions): Promise<void> {
const server = this.getServer(extension);
if (!server) {
return Promise.reject(`Invalid location ${extension.location.toString()}`);
}
if (this.servers.length > 1) {
if (isLanguagePackExtension(extension.manifest)) {
return this.uninstallEverywhere(extension);
}
return this.uninstallInServer(extension, server, options);
}
return server.extensionManagementService.uninstall(extension);
}
private async uninstallEverywhere(extension: ILocalExtension): Promise<void> {
const server = this.getServer(extension);
if (!server) {
return Promise.reject(`Invalid location ${extension.location.toString()}`);
}
const promise = server.extensionManagementService.uninstall(extension);
const otherServers: IExtensionManagementServer[] = this.servers.filter(s => s !== server);
if (otherServers.length) {
for (const otherServer of otherServers) {
const installed = await otherServer.extensionManagementService.getInstalled();
extension = installed.filter(i => !i.isBuiltin && areSameExtensions(i.identifier, extension.identifier))[0];
if (extension) {
await otherServer.extensionManagementService.uninstall(extension);
}
}
}
return promise;
}
private async uninstallInServer(extension: ILocalExtension, server: IExtensionManagementServer, options?: UninstallOptions): Promise<void> {
if (server === this.extensionManagementServerService.localExtensionManagementServer) {
const installedExtensions = await this.extensionManagementServerService.remoteExtensionManagementServer!.extensionManagementService.getInstalled(ExtensionType.User);
const dependentNonUIExtensions = installedExtensions.filter(i => !this.extensionManifestPropertiesService.prefersExecuteOnUI(i.manifest)
&& i.manifest.extensionDependencies && i.manifest.extensionDependencies.some(id => areSameExtensions({ id }, extension.identifier)));
if (dependentNonUIExtensions.length) {
return Promise.reject(new Error(this.getDependentsErrorMessage(extension, dependentNonUIExtensions)));
}
}
return server.extensionManagementService.uninstall(extension, options);
}
private getDependentsErrorMessage(extension: ILocalExtension, dependents: ILocalExtension[]): string {
if (dependents.length === 1) {
return localize('singleDependentError', "Cannot uninstall extension '{0}'. Extension '{1}' depends on this.",
extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name);
}
if (dependents.length === 2) {
return localize('twoDependentsError', "Cannot uninstall extension '{0}'. Extensions '{1}' and '{2}' depend on this.",
extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
}
return localize('multipleDependentsError', "Cannot uninstall extension '{0}'. Extensions '{1}', '{2}' and others depend on this.",
extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
}
async reinstallFromGallery(extension: ILocalExtension): Promise<void> {
const server = this.getServer(extension);
if (server) {
await this.checkForWorkspaceTrust(extension.manifest);
return server.extensionManagementService.reinstallFromGallery(extension);
}
return Promise.reject(`Invalid location ${extension.location.toString()}`);
}
updateMetadata(extension: ILocalExtension, metadata: IGalleryMetadata): Promise<ILocalExtension> {
const server = this.getServer(extension);
if (server) {
return server.extensionManagementService.updateMetadata(extension, metadata);
}
return Promise.reject(`Invalid location ${extension.location.toString()}`);
}
updateExtensionScope(extension: ILocalExtension, isMachineScoped: boolean): Promise<ILocalExtension> {
const server = this.getServer(extension);
if (server) {
return server.extensionManagementService.updateExtensionScope(extension, isMachineScoped);
}
return Promise.reject(`Invalid location ${extension.location.toString()}`);
}
zip(extension: ILocalExtension): Promise<URI> {
const server = this.getServer(extension);
if (server) {
return server.extensionManagementService.zip(extension);
}
return Promise.reject(`Invalid location ${extension.location.toString()}`);
}
unzip(zipLocation: URI): Promise<IExtensionIdentifier> {
return Promises.settled(this.servers
// Filter out web server
.filter(server => server !== this.extensionManagementServerService.webExtensionManagementServer)
.map(({ extensionManagementService }) => extensionManagementService.unzip(zipLocation))).then(([extensionIdentifier]) => extensionIdentifier);
}
async install(vsix: URI, options?: InstallVSIXOptions): Promise<ILocalExtension> {
if (this.extensionManagementServerService.localExtensionManagementServer && this.extensionManagementServerService.remoteExtensionManagementServer) {
const manifest = await this.getManifest(vsix);
if (isLanguagePackExtension(manifest)) {
// Install on both servers
const [local] = await Promises.settled([this.extensionManagementServerService.localExtensionManagementServer, this.extensionManagementServerService.remoteExtensionManagementServer].map(server => this.installVSIX(vsix, server, options)));
return local;
}
if (this.extensionManifestPropertiesService.prefersExecuteOnUI(manifest)) {
// Install only on local server
return this.installVSIX(vsix, this.extensionManagementServerService.localExtensionManagementServer, options);
}
// Install only on remote server
return this.installVSIX(vsix, this.extensionManagementServerService.remoteExtensionManagementServer, options);
}
if (this.extensionManagementServerService.localExtensionManagementServer) {
return this.installVSIX(vsix, this.extensionManagementServerService.localExtensionManagementServer, options);
}
if (this.extensionManagementServerService.remoteExtensionManagementServer) {
return this.installVSIX(vsix, this.extensionManagementServerService.remoteExtensionManagementServer, options);
}
return Promise.reject('No Servers to Install');
}
async installWebExtension(location: URI): Promise<ILocalExtension> {
if (!this.extensionManagementServerService.webExtensionManagementServer) {
throw new Error('Web extension management server is not found');
}
return this.extensionManagementServerService.webExtensionManagementServer.extensionManagementService.install(location);
}
protected async installVSIX(vsix: URI, server: IExtensionManagementServer, options: InstallVSIXOptions | undefined): Promise<ILocalExtension> {
const manifest = await this.getManifest(vsix);
if (manifest) {
await this.checkForWorkspaceTrust(manifest);
return server.extensionManagementService.install(vsix, options);
}
return Promise.reject('Unable to get the extension manifest.');
}
getManifest(vsix: URI): Promise<IExtensionManifest> {
if (vsix.scheme === Schemas.file && this.extensionManagementServerService.localExtensionManagementServer) {
return this.extensionManagementServerService.localExtensionManagementServer.extensionManagementService.getManifest(vsix);
}
if (vsix.scheme === Schemas.vscodeRemote && this.extensionManagementServerService.remoteExtensionManagementServer) {
return this.extensionManagementServerService.remoteExtensionManagementServer.extensionManagementService.getManifest(vsix);
}
return Promise.reject('No Servers');
}
async canInstall(gallery: IGalleryExtension): Promise<boolean> {
if (this.extensionManagementServerService.localExtensionManagementServer
&& await this.extensionManagementServerService.localExtensionManagementServer.extensionManagementService.canInstall(gallery)) {
return true;
}
const manifest = await this.extensionGalleryService.getManifest(gallery, CancellationToken.None);
if (!manifest) {
return false;
}
if (this.extensionManagementServerService.remoteExtensionManagementServer
&& await this.extensionManagementServerService.remoteExtensionManagementServer.extensionManagementService.canInstall(gallery)
&& this.extensionManifestPropertiesService.canExecuteOnWorkspace(manifest)) {
return true;
}
if (this.extensionManagementServerService.webExtensionManagementServer
&& await this.extensionManagementServerService.webExtensionManagementServer.extensionManagementService.canInstall(gallery)
&& this.extensionManifestPropertiesService.canExecuteOnWeb(manifest)) {
return true;
}
return false;
}
async updateFromGallery(gallery: IGalleryExtension, extension: ILocalExtension, installOptions?: InstallOptions): Promise<ILocalExtension> {
const server = this.getServer(extension);
if (!server) {
return Promise.reject(`Invalid location ${extension.location.toString()}`);
}
const servers: IExtensionManagementServer[] = [];
// Update Language pack on local and remote servers
if (isLanguagePackExtension(extension.manifest)) {
servers.push(...this.servers.filter(server => server !== this.extensionManagementServerService.webExtensionManagementServer));
} else {
servers.push(server);
}
return Promises.settled(servers.map(server => server.extensionManagementService.installFromGallery(gallery, installOptions))).then(([local]) => local);
}
async installExtensions(extensions: IGalleryExtension[], installOptions?: InstallOptions): Promise<ILocalExtension[]> {
if (!installOptions) {
const isMachineScoped = await this.hasToFlagExtensionsMachineScoped(extensions);
installOptions = { isMachineScoped, isBuiltin: false };
}
return Promises.settled(extensions.map(extension => this.installFromGallery(extension, installOptions)));
}
async installFromGallery(gallery: IGalleryExtension, installOptions?: InstallOptions): Promise<ILocalExtension> {
const manifest = await this.extensionGalleryService.getManifest(gallery, CancellationToken.None);
if (!manifest) {
return Promise.reject(localize('Manifest is not found', "Installing Extension {0} failed: Manifest is not found.", gallery.displayName || gallery.name));
}
const servers: IExtensionManagementServer[] = [];
// Install Language pack on local and remote servers
if (isLanguagePackExtension(manifest)) {
servers.push(...this.servers.filter(server => server !== this.extensionManagementServerService.webExtensionManagementServer));
} else {
const server = this.getExtensionManagementServerToInstall(manifest);
if (server) {
servers.push(server);
}
}
if (servers.length) {
if (!installOptions) {
const isMachineScoped = await this.hasToFlagExtensionsMachineScoped([gallery]);
installOptions = { isMachineScoped, isBuiltin: false };
}
if (!installOptions.isMachineScoped && this.isExtensionsSyncEnabled()) {
if (this.extensionManagementServerService.localExtensionManagementServer && !servers.includes(this.extensionManagementServerService.localExtensionManagementServer) && (await this.extensionManagementServerService.localExtensionManagementServer.extensionManagementService.canInstall(gallery))) {
servers.push(this.extensionManagementServerService.localExtensionManagementServer);
}
}
await this.checkForWorkspaceTrust(manifest);
if (!installOptions.donotIncludePackAndDependencies) {
await this.checkInstallingExtensionOnWeb(gallery, manifest);
}
return Promises.settled(servers.map(server => server.extensionManagementService.installFromGallery(gallery, installOptions))).then(([local]) => local);
}
const error = new Error(localize('cannot be installed', "Cannot install the '{0}' extension because it is not available in this setup.", gallery.displayName || gallery.name));
error.name = ExtensionManagementErrorCode.Unsupported;
return Promise.reject(error);
}
getExtensionManagementServerToInstall(manifest: IExtensionManifest): IExtensionManagementServer | null {
// Only local server
if (this.servers.length === 1 && this.extensionManagementServerService.localExtensionManagementServer) {
return this.extensionManagementServerService.localExtensionManagementServer;
}
const extensionKind = this.extensionManifestPropertiesService.getExtensionKind(manifest);
for (const kind of extensionKind) {
if (kind === 'ui' && this.extensionManagementServerService.localExtensionManagementServer) {
return this.extensionManagementServerService.localExtensionManagementServer;
}
if (kind === 'workspace' && this.extensionManagementServerService.remoteExtensionManagementServer) {
return this.extensionManagementServerService.remoteExtensionManagementServer;
}
if (kind === 'web' && this.extensionManagementServerService.webExtensionManagementServer) {
return this.extensionManagementServerService.webExtensionManagementServer;
}
}
// Local server can accept any extension. So return local server if not compatible server found.
return this.extensionManagementServerService.localExtensionManagementServer;
}
private isExtensionsSyncEnabled(): boolean {
return this.userDataAutoSyncEnablementService.isEnabled() && this.userDataSyncResourceEnablementService.isResourceEnabled(SyncResource.Extensions);
}
private async hasToFlagExtensionsMachineScoped(extensions: IGalleryExtension[]): Promise<boolean> {
if (this.isExtensionsSyncEnabled()) {
const result = await this.dialogService.show(
Severity.Info,
extensions.length === 1 ? localize('install extension', "Install Extension") : localize('install extensions', "Install Extensions"),
[
localize('install', "Install"),
localize('install and do no sync', "Install (Do not sync)"),
localize('cancel', "Cancel"),
],
{
cancelId: 2,
detail: extensions.length === 1
? localize('install single extension', "Would you like to install and synchronize '{0}' extension across your devices?", extensions[0].displayName)
: localize('install multiple extensions', "Would you like to install and synchronize extensions across your devices?")
}
);
switch (result.choice) {
case 0:
return false;
case 1:
return true;
}
throw canceled();
}
return false;
}
getExtensionsReport(): Promise<IReportedExtension[]> {
if (this.extensionManagementServerService.localExtensionManagementServer) {
return this.extensionManagementServerService.localExtensionManagementServer.extensionManagementService.getExtensionsReport();
}
if (this.extensionManagementServerService.remoteExtensionManagementServer) {
return this.extensionManagementServerService.remoteExtensionManagementServer.extensionManagementService.getExtensionsReport();
}
return Promise.resolve([]);
}
private getServer(extension: ILocalExtension): IExtensionManagementServer | null {
return this.extensionManagementServerService.getExtensionManagementServer(extension);
}
protected async checkForWorkspaceTrust(manifest: IExtensionManifest): Promise<void> {
if (this.extensionManifestPropertiesService.getExtensionUntrustedWorkspaceSupportType(manifest) === false) {
const trustState = await this.workspaceTrustRequestService.requestWorkspaceTrust({
message: localize('extensionInstallWorkspaceTrustMessage', "Enabling this extension requires a trusted workspace."),
buttons: [
{ label: localize('extensionInstallWorkspaceTrustButton', "Trust Workspace & Install"), type: 'ContinueWithTrust' },
{ label: localize('extensionInstallWorkspaceTrustContinueButton', "Install"), type: 'ContinueWithoutTrust' },
{ label: localize('extensionInstallWorkspaceTrustManageButton', "Learn More"), type: 'Manage' }
]
});
if (trustState === undefined) {
throw canceled();
}
}
}
private async checkInstallingExtensionOnWeb(extension: IGalleryExtension, manifest: IExtensionManifest): Promise<void> {
if (this.servers.length !== 1 || this.servers[0] !== this.extensionManagementServerService.webExtensionManagementServer) {
return;
}
const nonWebExtensions = [];
if (manifest.extensionPack?.length) {
const extensions = await this.extensionGalleryService.getExtensions(manifest.extensionPack.map(id => ({ id })), CancellationToken.None);
for (const extension of extensions) {
if (!(await this.servers[0].extensionManagementService.canInstall(extension))) {
nonWebExtensions.push(extension);
}
}
if (nonWebExtensions.length && nonWebExtensions.length === extensions.length) {
throw new ExtensionManagementError('Not supported in Web', ExtensionManagementErrorCode.Unsupported);
}
}
const productName = localize('VS Code for Web', "{0} for the Web", this.productService.nameLong);
const virtualWorkspaceSupport = this.extensionManifestPropertiesService.getExtensionVirtualWorkspaceSupportType(manifest);
const virtualWorkspaceSupportReason = getWorkspaceSupportTypeMessage(manifest.capabilities?.virtualWorkspaces);
const hasLimitedSupport = virtualWorkspaceSupport === 'limited' || !!virtualWorkspaceSupportReason;
if (!nonWebExtensions.length && !hasLimitedSupport) {
return;
}
const limitedSupportMessage = localize('limited support', "'{0}' has limited functionality in {1}.", extension.displayName || extension.identifier.id, productName);
let message: string, buttons: string[], detail: string | undefined;
if (nonWebExtensions.length && hasLimitedSupport) {
message = limitedSupportMessage;
detail = `${virtualWorkspaceSupportReason ? `${virtualWorkspaceSupportReason}\n` : ''}${localize('non web extensions detail', "Contains extensions which are not supported.")}`;
buttons = [localize('install anyways', "Install Anyway"), localize('showExtensions', "Show Extensions"), localize('cancel', "Cancel")];
}
else if (hasLimitedSupport) {
message = limitedSupportMessage;
detail = virtualWorkspaceSupportReason || undefined;
buttons = [localize('install anyways', "Install Anyway"), localize('cancel', "Cancel")];
}
else {
message = localize('non web extensions', "'{0}' contains extensions which are not supported in {1}.", extension.displayName || extension.identifier.id, productName);
buttons = [localize('install anyways', "Install Anyway"), localize('showExtensions', "Show Extensions"), localize('cancel', "Cancel")];
}
const { choice } = await this.dialogService.show(Severity.Info, message, buttons, { cancelId: buttons.length - 1, detail });
if (choice === 0) {
return;
}
if (choice === buttons.length - 2) {
// Unfortunately ICommandService cannot be used directly due to cyclic dependencies
this.instantiationService.invokeFunction(accessor => accessor.get(ICommandService).executeCommand('extension.open', extension.identifier.id, 'extensionPack'));
}
throw canceled();
}
registerParticipant() { throw new Error('Not Supported'); }
getTargetPlatform(): Promise<TargetPlatform> { throw new Error('Not Supported'); }
}
|
src/vs/workbench/services/extensionManagement/common/extensionManagementService.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.0003727039438672364,
0.0001795803545974195,
0.0001641809067223221,
0.00016850262181833386,
0.000035219534765928984
] |
{
"id": 5,
"code_window": [
"\t\t\t} else if (environmentService.isExtensionDevelopment) {\n",
"\t\t\t\tid = 'ext-dev'; // extension development window never stores backups and is a singleton\n",
"\t\t\t} else {\n",
"\t\t\t\tthrow new Error('Unexpected window configuration without backupPath');\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t// fallback to a reserved identifier when in extension development where backups are not stored\n",
"\t\t\t\tid = 'ext-dev';\n"
],
"file_path": "src/vs/workbench/electron-sandbox/shared.desktop.main.ts",
"type": "replace",
"edit_start_line_idx": 321
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import * as network from 'vs/base/common/network';
import * as paths from 'vs/base/common/path';
import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge';
import { ResourceLabels, IResourceLabel } from 'vs/workbench/browser/labels';
import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel';
import { IMarker, MarkerSeverity } from 'vs/platform/markers/common/markers';
import { ResourceMarkers, Marker, RelatedInformation, MarkerElement } from 'vs/workbench/contrib/markers/browser/markersModel';
import Messages from 'vs/workbench/contrib/markers/browser/messages';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { attachBadgeStyler } from 'vs/platform/theme/common/styler';
import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';
import { IDisposable, dispose, Disposable, toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { QuickFixAction, QuickFixActionViewItem } from 'vs/workbench/contrib/markers/browser/markersViewActions';
import { ILabelService } from 'vs/platform/label/common/label';
import { dirname, basename, isEqual } from 'vs/base/common/resources';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { ITreeFilter, TreeVisibility, TreeFilterResult, ITreeRenderer, ITreeNode, ITreeDragAndDrop, ITreeDragOverReaction } from 'vs/base/browser/ui/tree/tree';
import { FilterOptions } from 'vs/workbench/contrib/markers/browser/markersFilterOptions';
import { IMatch } from 'vs/base/common/filters';
import { Event, Emitter } from 'vs/base/common/event';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { isUndefinedOrNull } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { Action, IAction } from 'vs/base/common/actions';
import { localize } from 'vs/nls';
import { IDragAndDropData } from 'vs/base/browser/dnd';
import { ElementsDragAndDropData } from 'vs/base/browser/ui/list/listView';
import { fillEditorsDragData } from 'vs/workbench/browser/dnd';
import { CancelablePromise, createCancelablePromise, Delayer } from 'vs/base/common/async';
import { IModelService } from 'vs/editor/common/services/modelService';
import { Range } from 'vs/editor/common/core/range';
import { getCodeActions, CodeActionSet } from 'vs/editor/contrib/codeAction/codeAction';
import { CodeActionKind } from 'vs/editor/contrib/codeAction/types';
import { ITextModel } from 'vs/editor/common/model';
import { IEditorService, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { applyCodeAction } from 'vs/editor/contrib/codeAction/codeActionCommands';
import { SeverityIcon } from 'vs/platform/severityIcon/common/severityIcon';
import { CodeActionTriggerType } from 'vs/editor/common/modes';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IFileService } from 'vs/platform/files/common/files';
import { Progress } from 'vs/platform/progress/common/progress';
import { ActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems';
import { Codicon } from 'vs/base/common/codicons';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import { Link } from 'vs/platform/opener/browser/link';
interface IResourceMarkersTemplateData {
resourceLabel: IResourceLabel;
count: CountBadge;
styler: IDisposable;
}
interface IMarkerTemplateData {
markerWidget: MarkerWidget;
}
interface IRelatedInformationTemplateData {
resourceLabel: HighlightedLabel;
lnCol: HTMLElement;
description: HighlightedLabel;
}
export class MarkersTreeAccessibilityProvider implements IListAccessibilityProvider<MarkerElement> {
constructor(@ILabelService private readonly labelService: ILabelService) { }
getWidgetAriaLabel(): string {
return localize('problemsView', "Problems View");
}
public getAriaLabel(element: MarkerElement): string | null {
if (element instanceof ResourceMarkers) {
const path = this.labelService.getUriLabel(element.resource, { relative: true }) || element.resource.fsPath;
return Messages.MARKERS_TREE_ARIA_LABEL_RESOURCE(element.markers.length, element.name, paths.dirname(path));
}
if (element instanceof Marker) {
return Messages.MARKERS_TREE_ARIA_LABEL_MARKER(element);
}
if (element instanceof RelatedInformation) {
return Messages.MARKERS_TREE_ARIA_LABEL_RELATED_INFORMATION(element.raw);
}
return null;
}
}
const enum TemplateId {
ResourceMarkers = 'rm',
Marker = 'm',
RelatedInformation = 'ri'
}
export class VirtualDelegate implements IListVirtualDelegate<MarkerElement> {
static LINE_HEIGHT: number = 22;
constructor(private readonly markersViewState: MarkersViewModel) { }
getHeight(element: MarkerElement): number {
if (element instanceof Marker) {
const viewModel = this.markersViewState.getViewModel(element);
const noOfLines = !viewModel || viewModel.multiline ? element.lines.length : 1;
return noOfLines * VirtualDelegate.LINE_HEIGHT;
}
return VirtualDelegate.LINE_HEIGHT;
}
getTemplateId(element: MarkerElement): string {
if (element instanceof ResourceMarkers) {
return TemplateId.ResourceMarkers;
} else if (element instanceof Marker) {
return TemplateId.Marker;
} else {
return TemplateId.RelatedInformation;
}
}
}
const enum FilterDataType {
ResourceMarkers,
Marker,
RelatedInformation
}
interface ResourceMarkersFilterData {
type: FilterDataType.ResourceMarkers;
uriMatches: IMatch[];
}
interface MarkerFilterData {
type: FilterDataType.Marker;
lineMatches: IMatch[][];
sourceMatches: IMatch[];
codeMatches: IMatch[];
}
interface RelatedInformationFilterData {
type: FilterDataType.RelatedInformation;
uriMatches: IMatch[];
messageMatches: IMatch[];
}
export type FilterData = ResourceMarkersFilterData | MarkerFilterData | RelatedInformationFilterData;
export class ResourceMarkersRenderer implements ITreeRenderer<ResourceMarkers, ResourceMarkersFilterData, IResourceMarkersTemplateData> {
private renderedNodes = new Map<ITreeNode<ResourceMarkers, ResourceMarkersFilterData>, IResourceMarkersTemplateData>();
private readonly disposables = new DisposableStore();
constructor(
private labels: ResourceLabels,
onDidChangeRenderNodeCount: Event<ITreeNode<ResourceMarkers, ResourceMarkersFilterData>>,
@IThemeService private readonly themeService: IThemeService,
@ILabelService private readonly labelService: ILabelService,
@IFileService private readonly fileService: IFileService
) {
onDidChangeRenderNodeCount(this.onDidChangeRenderNodeCount, this, this.disposables);
}
templateId = TemplateId.ResourceMarkers;
renderTemplate(container: HTMLElement): IResourceMarkersTemplateData {
const data = <IResourceMarkersTemplateData>Object.create(null);
const resourceLabelContainer = dom.append(container, dom.$('.resource-label-container'));
data.resourceLabel = this.labels.create(resourceLabelContainer, { supportHighlights: true });
const badgeWrapper = dom.append(container, dom.$('.count-badge-wrapper'));
data.count = new CountBadge(badgeWrapper);
data.styler = attachBadgeStyler(data.count, this.themeService);
return data;
}
renderElement(node: ITreeNode<ResourceMarkers, ResourceMarkersFilterData>, _: number, templateData: IResourceMarkersTemplateData): void {
const resourceMarkers = node.element;
const uriMatches = node.filterData && node.filterData.uriMatches || [];
if (this.fileService.hasProvider(resourceMarkers.resource) || resourceMarkers.resource.scheme === network.Schemas.untitled) {
templateData.resourceLabel.setFile(resourceMarkers.resource, { matches: uriMatches });
} else {
templateData.resourceLabel.setResource({ name: resourceMarkers.name, description: this.labelService.getUriLabel(dirname(resourceMarkers.resource), { relative: true }), resource: resourceMarkers.resource }, { matches: uriMatches });
}
this.updateCount(node, templateData);
this.renderedNodes.set(node, templateData);
}
disposeElement(node: ITreeNode<ResourceMarkers, ResourceMarkersFilterData>): void {
this.renderedNodes.delete(node);
}
disposeTemplate(templateData: IResourceMarkersTemplateData): void {
templateData.resourceLabel.dispose();
templateData.styler.dispose();
}
private onDidChangeRenderNodeCount(node: ITreeNode<ResourceMarkers, ResourceMarkersFilterData>): void {
const templateData = this.renderedNodes.get(node);
if (!templateData) {
return;
}
this.updateCount(node, templateData);
}
private updateCount(node: ITreeNode<ResourceMarkers, ResourceMarkersFilterData>, templateData: IResourceMarkersTemplateData): void {
templateData.count.setCount(node.children.reduce((r, n) => r + (n.visible ? 1 : 0), 0));
}
dispose(): void {
this.disposables.dispose();
}
}
export class FileResourceMarkersRenderer extends ResourceMarkersRenderer {
}
export class MarkerRenderer implements ITreeRenderer<Marker, MarkerFilterData, IMarkerTemplateData> {
constructor(
private readonly markersViewState: MarkersViewModel,
@IInstantiationService protected instantiationService: IInstantiationService,
@IOpenerService protected openerService: IOpenerService,
) { }
templateId = TemplateId.Marker;
renderTemplate(container: HTMLElement): IMarkerTemplateData {
const data: IMarkerTemplateData = Object.create(null);
data.markerWidget = new MarkerWidget(container, this.markersViewState, this.openerService, this.instantiationService);
return data;
}
renderElement(node: ITreeNode<Marker, MarkerFilterData>, _: number, templateData: IMarkerTemplateData): void {
templateData.markerWidget.render(node.element, node.filterData);
}
disposeTemplate(templateData: IMarkerTemplateData): void {
templateData.markerWidget.dispose();
}
}
const expandedIcon = registerIcon('markers-view-multi-line-expanded', Codicon.chevronUp, localize('expandedIcon', 'Icon indicating that multiple lines are shown in the markers view.'));
const collapsedIcon = registerIcon('markers-view-multi-line-collapsed', Codicon.chevronDown, localize('collapsedIcon', 'Icon indicating that multiple lines are collapsed in the markers view.'));
const toggleMultilineAction = 'problems.action.toggleMultiline';
class ToggleMultilineActionViewItem extends ActionViewItem {
override render(container: HTMLElement): void {
super.render(container);
this.updateExpandedAttribute();
}
override updateClass(): void {
super.updateClass();
this.updateExpandedAttribute();
}
private updateExpandedAttribute(): void {
if (this.element) {
this.element.setAttribute('aria-expanded', `${this._action.class === ThemeIcon.asClassName(expandedIcon)}`);
}
}
}
class MarkerWidget extends Disposable {
private readonly actionBar: ActionBar;
private readonly icon: HTMLElement;
private readonly multilineActionbar: ActionBar;
private readonly messageAndDetailsContainer: HTMLElement;
private readonly disposables = this._register(new DisposableStore());
constructor(
private parent: HTMLElement,
private readonly markersViewModel: MarkersViewModel,
private readonly _openerService: IOpenerService,
_instantiationService: IInstantiationService
) {
super();
this.actionBar = this._register(new ActionBar(dom.append(parent, dom.$('.actions')), {
actionViewItemProvider: (action: IAction) => action.id === QuickFixAction.ID ? _instantiationService.createInstance(QuickFixActionViewItem, <QuickFixAction>action) : undefined
}));
this.icon = dom.append(parent, dom.$(''));
this.multilineActionbar = this._register(new ActionBar(dom.append(parent, dom.$('.multiline-actions')), {
actionViewItemProvider: (action) => {
if (action.id === toggleMultilineAction) {
return new ToggleMultilineActionViewItem(undefined, action, { icon: true });
}
return undefined;
}
}));
this.messageAndDetailsContainer = dom.append(parent, dom.$('.marker-message-details-container'));
}
render(element: Marker, filterData: MarkerFilterData | undefined): void {
this.actionBar.clear();
this.multilineActionbar.clear();
this.disposables.clear();
dom.clearNode(this.messageAndDetailsContainer);
this.icon.className = `marker-icon codicon ${SeverityIcon.className(MarkerSeverity.toSeverity(element.marker.severity))}`;
this.renderQuickfixActionbar(element);
this.renderMultilineActionbar(element);
this.renderMessageAndDetails(element, filterData);
this.disposables.add(dom.addDisposableListener(this.parent, dom.EventType.MOUSE_OVER, () => this.markersViewModel.onMarkerMouseHover(element)));
this.disposables.add(dom.addDisposableListener(this.parent, dom.EventType.MOUSE_LEAVE, () => this.markersViewModel.onMarkerMouseLeave(element)));
}
private renderQuickfixActionbar(marker: Marker): void {
const viewModel = this.markersViewModel.getViewModel(marker);
if (viewModel) {
const quickFixAction = viewModel.quickFixAction;
this.actionBar.push([quickFixAction], { icon: true, label: false });
this.icon.classList.toggle('quickFix', quickFixAction.enabled);
quickFixAction.onDidChange(({ enabled }) => {
if (!isUndefinedOrNull(enabled)) {
this.icon.classList.toggle('quickFix', enabled);
}
}, this, this.disposables);
quickFixAction.onShowQuickFixes(() => {
const quickFixActionViewItem = <QuickFixActionViewItem>this.actionBar.viewItems[0];
if (quickFixActionViewItem) {
quickFixActionViewItem.showQuickFixes();
}
}, this, this.disposables);
}
}
private renderMultilineActionbar(marker: Marker): void {
const viewModel = this.markersViewModel.getViewModel(marker);
const multiline = viewModel && viewModel.multiline;
const action = new Action(toggleMultilineAction);
action.enabled = !!viewModel && marker.lines.length > 1;
action.tooltip = multiline ? localize('single line', "Show message in single line") : localize('multi line', "Show message in multiple lines");
action.class = ThemeIcon.asClassName(multiline ? expandedIcon : collapsedIcon);
action.run = () => { if (viewModel) { viewModel.multiline = !viewModel.multiline; } return Promise.resolve(); };
this.multilineActionbar.push([action], { icon: true, label: false });
}
private renderMessageAndDetails(element: Marker, filterData: MarkerFilterData | undefined) {
const { marker, lines } = element;
const viewState = this.markersViewModel.getViewModel(element);
const multiline = !viewState || viewState.multiline;
const lineMatches = filterData && filterData.lineMatches || [];
let lastLineElement: HTMLElement | undefined = undefined;
this.messageAndDetailsContainer.title = element.marker.message;
for (let index = 0; index < (multiline ? lines.length : 1); index++) {
lastLineElement = dom.append(this.messageAndDetailsContainer, dom.$('.marker-message-line'));
const messageElement = dom.append(lastLineElement, dom.$('.marker-message'));
const highlightedLabel = new HighlightedLabel(messageElement);
highlightedLabel.set(lines[index].length > 1000 ? `${lines[index].substring(0, 1000)}...` : lines[index], lineMatches[index]);
if (lines[index] === '') {
lastLineElement.style.height = `${VirtualDelegate.LINE_HEIGHT}px`;
}
}
this.renderDetails(marker, filterData, lastLineElement || dom.append(this.messageAndDetailsContainer, dom.$('.marker-message-line')));
}
private renderDetails(marker: IMarker, filterData: MarkerFilterData | undefined, parent: HTMLElement): void {
parent.classList.add('details-container');
if (marker.source || marker.code) {
const source = new HighlightedLabel(dom.append(parent, dom.$('.marker-source')));
const sourceMatches = filterData && filterData.sourceMatches || [];
source.set(marker.source, sourceMatches);
if (marker.code) {
if (typeof marker.code === 'string') {
const code = new HighlightedLabel(dom.append(parent, dom.$('.marker-code')));
const codeMatches = filterData && filterData.codeMatches || [];
code.set(marker.code, codeMatches);
} else {
// TODO@sandeep: these widgets should be disposed
const container = dom.$('.marker-code');
const code = new HighlightedLabel(container);
new Link(parent, { href: marker.code.target.toString(), label: container, title: marker.code.target.toString() }, undefined, this._openerService);
const codeMatches = filterData && filterData.codeMatches || [];
code.set(marker.code.value, codeMatches);
}
}
}
const lnCol = dom.append(parent, dom.$('span.marker-line'));
lnCol.textContent = Messages.MARKERS_PANEL_AT_LINE_COL_NUMBER(marker.startLineNumber, marker.startColumn);
}
}
export class RelatedInformationRenderer implements ITreeRenderer<RelatedInformation, RelatedInformationFilterData, IRelatedInformationTemplateData> {
constructor(
@ILabelService private readonly labelService: ILabelService
) { }
templateId = TemplateId.RelatedInformation;
renderTemplate(container: HTMLElement): IRelatedInformationTemplateData {
const data: IRelatedInformationTemplateData = Object.create(null);
dom.append(container, dom.$('.actions'));
dom.append(container, dom.$('.icon'));
data.resourceLabel = new HighlightedLabel(dom.append(container, dom.$('.related-info-resource')));
data.lnCol = dom.append(container, dom.$('span.marker-line'));
const separator = dom.append(container, dom.$('span.related-info-resource-separator'));
separator.textContent = ':';
separator.style.paddingRight = '4px';
data.description = new HighlightedLabel(dom.append(container, dom.$('.marker-description')));
return data;
}
renderElement(node: ITreeNode<RelatedInformation, RelatedInformationFilterData>, _: number, templateData: IRelatedInformationTemplateData): void {
const relatedInformation = node.element.raw;
const uriMatches = node.filterData && node.filterData.uriMatches || [];
const messageMatches = node.filterData && node.filterData.messageMatches || [];
templateData.resourceLabel.set(basename(relatedInformation.resource), uriMatches);
templateData.resourceLabel.element.title = this.labelService.getUriLabel(relatedInformation.resource, { relative: true });
templateData.lnCol.textContent = Messages.MARKERS_PANEL_AT_LINE_COL_NUMBER(relatedInformation.startLineNumber, relatedInformation.startColumn);
templateData.description.set(relatedInformation.message, messageMatches);
templateData.description.element.title = relatedInformation.message;
}
disposeTemplate(templateData: IRelatedInformationTemplateData): void {
// noop
}
}
export class Filter implements ITreeFilter<MarkerElement, FilterData> {
constructor(public options: FilterOptions) { }
filter(element: MarkerElement, parentVisibility: TreeVisibility): TreeFilterResult<FilterData> {
if (element instanceof ResourceMarkers) {
return this.filterResourceMarkers(element);
} else if (element instanceof Marker) {
return this.filterMarker(element, parentVisibility);
} else {
return this.filterRelatedInformation(element, parentVisibility);
}
}
private filterResourceMarkers(resourceMarkers: ResourceMarkers): TreeFilterResult<FilterData> {
if (resourceMarkers.resource.scheme === network.Schemas.walkThrough || resourceMarkers.resource.scheme === network.Schemas.walkThroughSnippet) {
return false;
}
// Filter resource by pattern first (globs)
// Excludes pattern
if (this.options.excludesMatcher.matches(resourceMarkers.resource)) {
return false;
}
// Includes pattern
if (this.options.includesMatcher.matches(resourceMarkers.resource)) {
return true;
}
// Fiter by text. Do not apply negated filters on resources instead use exclude patterns
if (this.options.textFilter.text && !this.options.textFilter.negate) {
const uriMatches = FilterOptions._filter(this.options.textFilter.text, basename(resourceMarkers.resource));
if (uriMatches) {
return { visibility: true, data: { type: FilterDataType.ResourceMarkers, uriMatches: uriMatches || [] } };
}
}
return TreeVisibility.Recurse;
}
private filterMarker(marker: Marker, parentVisibility: TreeVisibility): TreeFilterResult<FilterData> {
const matchesSeverity = this.options.showErrors && MarkerSeverity.Error === marker.marker.severity ||
this.options.showWarnings && MarkerSeverity.Warning === marker.marker.severity ||
this.options.showInfos && MarkerSeverity.Info === marker.marker.severity;
if (!matchesSeverity) {
return false;
}
if (!this.options.textFilter.text) {
return true;
}
const lineMatches: IMatch[][] = [];
for (const line of marker.lines) {
const lineMatch = FilterOptions._messageFilter(this.options.textFilter.text, line);
lineMatches.push(lineMatch || []);
}
const sourceMatches = marker.marker.source ? FilterOptions._filter(this.options.textFilter.text, marker.marker.source) : undefined;
const codeMatches = marker.marker.code ? FilterOptions._filter(this.options.textFilter.text, typeof marker.marker.code === 'string' ? marker.marker.code : marker.marker.code.value) : undefined;
const matched = sourceMatches || codeMatches || lineMatches.some(lineMatch => lineMatch.length > 0);
// Matched and not negated
if (matched && !this.options.textFilter.negate) {
return { visibility: true, data: { type: FilterDataType.Marker, lineMatches, sourceMatches: sourceMatches || [], codeMatches: codeMatches || [] } };
}
// Matched and negated - exclude it only if parent visibility is not set
if (matched && this.options.textFilter.negate && parentVisibility === TreeVisibility.Recurse) {
return false;
}
// Not matched and negated - include it only if parent visibility is not set
if (!matched && this.options.textFilter.negate && parentVisibility === TreeVisibility.Recurse) {
return true;
}
return parentVisibility;
}
private filterRelatedInformation(relatedInformation: RelatedInformation, parentVisibility: TreeVisibility): TreeFilterResult<FilterData> {
if (!this.options.textFilter.text) {
return true;
}
const uriMatches = FilterOptions._filter(this.options.textFilter.text, basename(relatedInformation.raw.resource));
const messageMatches = FilterOptions._messageFilter(this.options.textFilter.text, paths.basename(relatedInformation.raw.message));
const matched = uriMatches || messageMatches;
// Matched and not negated
if (matched && !this.options.textFilter.negate) {
return { visibility: true, data: { type: FilterDataType.RelatedInformation, uriMatches: uriMatches || [], messageMatches: messageMatches || [] } };
}
// Matched and negated - exclude it only if parent visibility is not set
if (matched && this.options.textFilter.negate && parentVisibility === TreeVisibility.Recurse) {
return false;
}
// Not matched and negated - include it only if parent visibility is not set
if (!matched && this.options.textFilter.negate && parentVisibility === TreeVisibility.Recurse) {
return true;
}
return parentVisibility;
}
}
export class MarkerViewModel extends Disposable {
private readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
private modelPromise: CancelablePromise<ITextModel> | null = null;
private codeActionsPromise: CancelablePromise<CodeActionSet> | null = null;
constructor(
private readonly marker: Marker,
@IModelService private modelService: IModelService,
@IInstantiationService private instantiationService: IInstantiationService,
@IEditorService private readonly editorService: IEditorService
) {
super();
this._register(toDisposable(() => {
if (this.modelPromise) {
this.modelPromise.cancel();
}
if (this.codeActionsPromise) {
this.codeActionsPromise.cancel();
}
}));
}
private _multiline: boolean = true;
get multiline(): boolean {
return this._multiline;
}
set multiline(value: boolean) {
if (this._multiline !== value) {
this._multiline = value;
this._onDidChange.fire();
}
}
private _quickFixAction: QuickFixAction | null = null;
get quickFixAction(): QuickFixAction {
if (!this._quickFixAction) {
this._quickFixAction = this._register(this.instantiationService.createInstance(QuickFixAction, this.marker));
}
return this._quickFixAction;
}
showLightBulb(): void {
this.setQuickFixes(true);
}
showQuickfixes(): void {
this.setQuickFixes(false).then(() => this.quickFixAction.run());
}
async getQuickFixes(waitForModel: boolean): Promise<IAction[]> {
const codeActions = await this.getCodeActions(waitForModel);
return codeActions ? this.toActions(codeActions) : [];
}
private async setQuickFixes(waitForModel: boolean): Promise<void> {
const codeActions = await this.getCodeActions(waitForModel);
this.quickFixAction.quickFixes = codeActions ? this.toActions(codeActions) : [];
this.quickFixAction.autoFixable(!!codeActions && codeActions.hasAutoFix);
}
private getCodeActions(waitForModel: boolean): Promise<CodeActionSet | null> {
if (this.codeActionsPromise !== null) {
return this.codeActionsPromise;
}
return this.getModel(waitForModel)
.then<CodeActionSet | null>(model => {
if (model) {
if (!this.codeActionsPromise) {
this.codeActionsPromise = createCancelablePromise(cancellationToken => {
return getCodeActions(model, new Range(this.marker.range.startLineNumber, this.marker.range.startColumn, this.marker.range.endLineNumber, this.marker.range.endColumn), {
type: CodeActionTriggerType.Invoke, filter: { include: CodeActionKind.QuickFix }
}, Progress.None, cancellationToken).then(actions => {
return this._register(actions);
});
});
}
return this.codeActionsPromise;
}
return null;
});
}
private toActions(codeActions: CodeActionSet): IAction[] {
return codeActions.validActions.map(item => new Action(
item.action.command ? item.action.command.id : item.action.title,
item.action.title,
undefined,
true,
() => {
return this.openFileAtMarker(this.marker)
.then(() => this.instantiationService.invokeFunction(applyCodeAction, item));
}));
}
private openFileAtMarker(element: Marker): Promise<void> {
const { resource, selection } = { resource: element.resource, selection: element.range };
return this.editorService.openEditor({
resource,
options: {
selection,
preserveFocus: true,
pinned: false,
revealIfVisible: true
},
}, ACTIVE_GROUP).then(() => undefined);
}
private getModel(waitForModel: boolean): Promise<ITextModel | null> {
const model = this.modelService.getModel(this.marker.resource);
if (model) {
return Promise.resolve(model);
}
if (waitForModel) {
if (!this.modelPromise) {
this.modelPromise = createCancelablePromise(cancellationToken => {
return new Promise((c) => {
this._register(this.modelService.onModelAdded(model => {
if (isEqual(model.uri, this.marker.resource)) {
c(model);
}
}));
});
});
}
return this.modelPromise;
}
return Promise.resolve(null);
}
}
export class MarkersViewModel extends Disposable {
private readonly _onDidChange: Emitter<Marker | undefined> = this._register(new Emitter<Marker | undefined>());
readonly onDidChange: Event<Marker | undefined> = this._onDidChange.event;
private readonly markersViewStates: Map<string, { viewModel: MarkerViewModel, disposables: IDisposable[] }> = new Map<string, { viewModel: MarkerViewModel, disposables: IDisposable[] }>();
private readonly markersPerResource: Map<string, Marker[]> = new Map<string, Marker[]>();
private bulkUpdate: boolean = false;
private hoveredMarker: Marker | null = null;
private hoverDelayer: Delayer<void> = new Delayer<void>(300);
constructor(
multiline: boolean = true,
@IInstantiationService private instantiationService: IInstantiationService
) {
super();
this._multiline = multiline;
}
add(marker: Marker): void {
if (!this.markersViewStates.has(marker.id)) {
const viewModel = this.instantiationService.createInstance(MarkerViewModel, marker);
const disposables: IDisposable[] = [viewModel];
viewModel.multiline = this.multiline;
viewModel.onDidChange(() => {
if (!this.bulkUpdate) {
this._onDidChange.fire(marker);
}
}, this, disposables);
this.markersViewStates.set(marker.id, { viewModel, disposables });
const markers = this.markersPerResource.get(marker.resource.toString()) || [];
markers.push(marker);
this.markersPerResource.set(marker.resource.toString(), markers);
}
}
remove(resource: URI): void {
const markers = this.markersPerResource.get(resource.toString()) || [];
for (const marker of markers) {
const value = this.markersViewStates.get(marker.id);
if (value) {
dispose(value.disposables);
}
this.markersViewStates.delete(marker.id);
if (this.hoveredMarker === marker) {
this.hoveredMarker = null;
}
}
this.markersPerResource.delete(resource.toString());
}
getViewModel(marker: Marker): MarkerViewModel | null {
const value = this.markersViewStates.get(marker.id);
return value ? value.viewModel : null;
}
onMarkerMouseHover(marker: Marker): void {
this.hoveredMarker = marker;
this.hoverDelayer.trigger(() => {
if (this.hoveredMarker) {
const model = this.getViewModel(this.hoveredMarker);
if (model) {
model.showLightBulb();
}
}
});
}
onMarkerMouseLeave(marker: Marker): void {
if (this.hoveredMarker === marker) {
this.hoveredMarker = null;
}
}
private _multiline: boolean = true;
get multiline(): boolean {
return this._multiline;
}
set multiline(value: boolean) {
let changed = false;
if (this._multiline !== value) {
this._multiline = value;
changed = true;
}
this.bulkUpdate = true;
this.markersViewStates.forEach(({ viewModel }) => {
if (viewModel.multiline !== value) {
viewModel.multiline = value;
changed = true;
}
});
this.bulkUpdate = false;
if (changed) {
this._onDidChange.fire(undefined);
}
}
override dispose(): void {
this.markersViewStates.forEach(({ disposables }) => dispose(disposables));
this.markersViewStates.clear();
this.markersPerResource.clear();
super.dispose();
}
}
export class ResourceDragAndDrop implements ITreeDragAndDrop<MarkerElement> {
constructor(
private instantiationService: IInstantiationService
) { }
onDragOver(data: IDragAndDropData, targetElement: MarkerElement, targetIndex: number, originalEvent: DragEvent): boolean | ITreeDragOverReaction {
return false;
}
getDragURI(element: MarkerElement): string | null {
if (element instanceof ResourceMarkers) {
return element.resource.toString();
}
return null;
}
getDragLabel?(elements: MarkerElement[]): string | undefined {
if (elements.length > 1) {
return String(elements.length);
}
const element = elements[0];
return element instanceof ResourceMarkers ? basename(element.resource) : undefined;
}
onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void {
const elements = (data as ElementsDragAndDropData<MarkerElement>).elements;
const resources = elements
.filter(e => e instanceof ResourceMarkers)
.map(resourceMarker => (resourceMarker as ResourceMarkers).resource);
if (resources.length) {
// Apply some datatransfer types to allow for dragging the element outside of the application
this.instantiationService.invokeFunction(accessor => fillEditorsDragData(accessor, resources, originalEvent));
}
}
drop(data: IDragAndDropData, targetElement: MarkerElement, targetIndex: number, originalEvent: DragEvent): void {
}
}
|
src/vs/workbench/contrib/markers/browser/markersTreeViewer.ts
| 0 |
https://github.com/microsoft/vscode/commit/4bb7826d02e0b873d180f00c68643bb0bf26966a
|
[
0.0003344742872286588,
0.0001750168448779732,
0.00016426407091785222,
0.00017248124640900642,
0.000019034705474041402
] |
{
"id": 0,
"code_window": [
"\n",
"/// <reference types=\"node\" />\n",
"\n",
"import { Duplex, DuplexOptions } from \"stream\";\n",
"\n",
"declare namespace ListStream {\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"interface ListStreamMethod {\n",
" (callback?: (err: Error, data: any[]) => void): ListStream;\n",
" (options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 9
}
|
// Type definitions for list-stream 1.0
// Project: https://github.com/rvagg/list-stream
// Definitions by: IanStorm <https://github.com/IanStorm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Duplex, DuplexOptions } from "stream";
declare namespace ListStream {
}
declare class ListStream extends Duplex {
constructor(callback?: (err: Error, data: any[]) => void);
constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void);
static obj(callback?: (err: Error, data: any[]) => void): ListStream;
static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;
append(chunk: any): void;
duplicate(): ListStream;
end(): void;
get(index: number): any;
length: number;
}
export = ListStream;
|
types/list-stream/index.d.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.9984337687492371,
0.9966877102851868,
0.9941099286079407,
0.9975194334983826,
0.0018605950754135847
] |
{
"id": 0,
"code_window": [
"\n",
"/// <reference types=\"node\" />\n",
"\n",
"import { Duplex, DuplexOptions } from \"stream\";\n",
"\n",
"declare namespace ListStream {\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"interface ListStreamMethod {\n",
" (callback?: (err: Error, data: any[]) => void): ListStream;\n",
" (options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 9
}
|
// Date picker tests from http://amsul.ca/pickadate.js/date/
$('.datepicker').pickadate();
// Change the month and weekday labels
$('.datepicker').pickadate({
weekdaysShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
showMonthsShort: true
});
// Change button text or hide a button completely
$('.datepicker').pickadate({
today: '',
clear: 'Clear selection',
close: 'Cancel'
});
// Change the title attributes of several elements within the picker
$('.datepicker').pickadate({
labelMonthNext: 'Go to the next month',
labelMonthPrev: 'Go to the previous month',
labelMonthSelect: 'Pick a month from the dropdown',
labelYearSelect: 'Pick a year from the dropdown',
selectMonths: true,
selectYears: true
});
// Extend the default picker options for all instances.
$.extend($.fn.pickadate.defaults, {
monthsFull: ['Janvier', 'FΓ©vrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'AoΓ»t', 'Septembre', 'Octobre', 'Novembre', 'DΓ©cembre'],
weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
today: 'aujourd\'hui',
clear: 'effacer',
formatSubmit: 'yyyy/mm/dd'
});
// Or, pass the months and weekdays as an array for each invocation.
$('.datepicker').pickadate({
monthsFull: ['Janvier', 'FΓ©vrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'AoΓ»t', 'Septembre', 'Octobre', 'Novembre', 'DΓ©cembre'],
weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
today: 'aujourd\'hui',
clear: 'effacer',
formatSubmit: 'yyyy/mm/dd'
});
// Display a human-friendly format and use an alternate one to submit to the server
$('.datepicker').pickadate({
// Escape any "rule" characters with an exclamation mark (!).
format: 'You selecte!d: dddd, dd mmm, yyyy',
formatSubmit: 'yyyy/mm/dd',
hiddenPrefix: 'prefix__',
hiddenSuffix: '__suffix'
});
// Send the hidden value only
$('.datepicker').pickadate({
formatSubmit: 'yyyy/mm/dd',
hiddenName: true
});
// Editable input
$('.datepicker').pickadate({
editable: true
});
// Display select menus to pick the month and year
$('.datepicker').pickadate({
selectYears: true,
selectMonths: true
});
// Specify the number of years to show in the dropdown using an
// even integer - half before and half after the year in focus:
$('.datepicker').pickadate({
// `true` defaults to 10.
selectYears: 4
});
// The first day of the week can be set to either Sunday or Monday.
// Anything truth-y sets it as Monday and anything false-y as Sunday.
$('.datepicker').pickadate({
firstDay: 1
});
// Date Limits
// Using JavaScript dates
$('.datepicker').pickadate({
min: new Date(2013, 3, 20),
max: new Date(2013, 7, 14)
});
// Using arrays formatted as [YEAR,MONTH,DATE]
$('.datepicker').pickadate({
min: [2013, 3, 20],
max: [2013, 7, 14]
});
// Using integers or a boolean
$('.datepicker').pickadate({
// An integer (positive/negative) sets it relative to today.
min: -15,
// `true` sets it to today. `false` removes any limits.
max: true
});
// Disable dates
// Using JavaScript dates
$('.datepicker').pickadate({
disable: [
new Date(2013, 3, 13),
new Date(2013, 3, 29)
]
});
// Using arrays formatted as [YEAR,MONTH,DATE]
$('.datepicker').pickadate({
disable: [
[2015, 3, 3],
[2015, 3, 12],
[2015, 3, 20]
]
});
// Using integers as days of the week (1 to 7)
$('.datepicker').pickadate({
disable: [
1, 4, 7
]
});
// Using objects as a range of dates
$('.datepicker').pickadate({
disable: [
{ from: [2016, 2, 14], to: [2016, 2, 27] }
]
});
// Enable only a specific or arbitrary set of dates by setting true as the first item in the collection
$('.datepicker').pickadate({
disable: [
true,
1, 4, 7,
[2013, 3, 3],
[2013, 3, 12],
[2013, 3, 20],
new Date(2015, 3, 13),
new Date(2015, 3, 29)
]
});
// Enable dates that fall within a range of disabled dates by adding
// the inverted parameter to the item within the collection
$('.datepicker').pickadate({
disable: [
5,
[2015, 10, 21, 'inverted'],
{ from: [2016, 3, 15], to: [2016, 3, 25] },
[2016, 3, 20, 'inverted'],
{ from: [2016, 3, 17], to: [2016, 3, 18], inverted: true }
]
});
// Specify where to insert the root element by passing any valid CSS selector to the container option
$('.datepicker').pickadate({
container: '#root-picker-outlet'
});
// Specify where to insert the hidden element by passing any valid CSS selector to the containerHidden option
$('.datepicker').pickadate({
containerHidden: '#hidden-input-outlet'
});
// Close on a user action
$('.datepicker').pickadate({
closeOnSelect: false,
closeOnClear: false
});
// Fire off events as the user interacts with the picker
$('.datepicker').pickadate({
onStart: function () {
console.log('Hello there :)')
},
onRender: function () {
console.log('Whoa.. rendered anew')
},
onOpen: function () {
console.log('Opened up')
},
onClose: function () {
console.log('Closed now')
},
onStop: function () {
console.log('See ya.')
},
onSet: function (context) {
console.log('Just set stuff:', context)
}
});
// Time picker tests from http://amsul.ca/pickadate.js/time/
$('.timepicker').pickatime();
// Extend the default picker options for all instances.
$.extend($.fn.pickatime.defaults, {
clear: 'Effacer'
});
// Or, pass the months and weekdays as an array for each invocation.
$('.timepicker').pickatime({
clear: 'Effacer'
});
// Change the text or hide the button completely by passing a false-y value
$('.timepicker').pickatime({
clear: ''
});
// Display a human-friendly label and input format and use an alternate one to submit
$('.timepicker').pickatime({
// Escape any "rule" characters with an exclamation mark (!).
format: 'T!ime selected: h:i a',
formatLabel: '<b>h</b>:i <!i>a</!i>',
formatSubmit: 'HH:i',
hiddenPrefix: 'prefix__',
hiddenSuffix: '__suffix'
});
// The formatLabel option is unique. It can contain HTML and it can also
// be a function if you want to create the label during run-time:
$('.timepicker').pickatime({
formatLabel: function (time) {
var hours = (time.pick - this.get('now').pick) / 60,
label = hours < 0 ? ' !hours to now' : hours > 0 ? ' !hours from now' : 'now'
return 'h:i a <sm!all>' + (hours ? Math.abs(hours) : '') + label + '</sm!all>'
}
});
// Send the hidden value only
$('.timepicker').pickatime({
formatSubmit: 'HH:i',
hiddenName: true
});
// Editable input
$('.timepicker').pickatime({
editable: true
});
// Choose the minutes interval between each time in the list
$('.timepicker').pickatime({
interval: 150
});
// Time Limits
// Using JavaScript dates
$('.timepicker').pickatime({
min: new Date(2015, 3, 20, 7),
max: new Date(2015, 7, 14, 18, 30)
});
// Using arrays formatted as [HOUR,MINUTE]
$('.timepicker').pickatime({
min: [7, 30],
max: [14, 0]
});
// Using integers or a boolean
$('.timepicker').pickatime({
// An integer (positive/negative) sets it as intervals relative from now.
min: -5,
// `true` sets it to now. `false` removes any limits.
max: true
});
// Disable Times
// Using JavaScript dates
$('.timepicker').pickatime({
disable: [
new Date(2016, 3, 20, 4, 30),
new Date(2016, 3, 20, 9)
]
});
// Using arrays formatted as [HOUR,MINUTE]
$('.timepicker').pickatime({
disable: [
[0, 30],
[2, 0],
[8, 30],
[9, 0]
]
});
// Using integers as hours (0 to 23)
$('.timepicker').pickatime({
disable: [
3, 5, 7
]
});
// Using objects as a range of times
$('.timepicker').pickatime({
disable: [
{ from: [2, 0], to: [5, 30] }
]
});
// Enable only a specific or arbitrary set of times by setting true as the first item in the collection
$('.timepicker').pickatime({
disable: [
true,
3, 5, 7,
[0, 30],
[2, 0],
[8, 30],
[9, 0]
]
});
// Enable times that fall within a range of disabled times by adding
// the inverted parameter to the item within the collection
$('.timepicker').pickatime({
disable: [
1,
[1, 30, 'inverted'],
{ from: [4, 30], to: [10, 30] },
[6, 30, 'inverted'],
{ from: [8, 0], to: [9, 0], inverted: true }
]
});
// Specify where to insert the root element by passing any valid CSS selector to the container option
$('.timepicker').pickatime({
container: '#root-picker-outlet'
});
// Specify where to insert the hidden element by passing any valid CSS selector to the containerHidden option
$('.timepicker').pickatime({
containerHidden: '#hidden-input-outlet'
});
// Close on a user action
$('.timepicker').pickatime({
closeOnSelect: false,
closeOnClear: false
});
// Fire off events as the user interacts with the picker
$('.timepicker').pickatime({
onStart: function () {
console.log('Hello there :)')
},
onRender: function () {
console.log('Whoa.. rendered anew')
},
onOpen: function () {
console.log('Opened up')
},
onClose: function () {
console.log('Closed now')
},
onStop: function () {
console.log('See ya.')
},
onSet: function (context) {
console.log('Just set stuff:', context)
}
});
// API tests from http://amsul.ca/pickadate.js/api/
var $input = $('.datepicker').pickadate();
// Use the picker object directly.
var picker = $input.pickadate('picker');
picker.$node;
picker.$root;
picker._hidden;
// Or pass through the elementβs plugin data.
$input.pickadate('open');
$input.pickadate('close');
$input.pickadate('close');
$input.pickadate('start');
$input.pickadate('stop');
$input.pickadate('render');
$input.pickadate('get');
$input.pickadate('set', 'highlight', 1429970887654);
$input.pickadate('on', 'open', function () { });
$input.pickadate('on', 'close', function () { });
$input.pickadate('off', 'open', 'close');
$input.pickadate('trigger', 'open');
$input.pickadate('$node');
$input.pickadate('$root');
$input.pickadate('_hidden');
picker.open().clear().close();
picker.open();
picker.close();
picker.close(true);
picker.open(false);
$(document).on('click', function () {
picker.close();
});
picker.start();
picker.stop();
picker.render();
picker.render(true);
picker.clear();
picker.get(); // Short for `picker.get('value')`
picker.get('select');
picker.get('select', 'yyyy/mm/dd');
picker.get('highlight');
picker.get('highlight', 'yyyy/mm/dd');
picker.get('view');
picker.get('view', 'yyyy/mm/dd');
picker.get('min');
picker.get('min', 'yyyy/mm/dd');
picker.get('max');
picker.get('max', 'yyyy/mm/dd');
picker.get('open');
picker.get('start');
picker.get('id');
picker.get('enable');
picker.get('disable');
// Set multiple at once
picker.set({
select: new Date(2015, 3, 20),
highlight: [2015, 3, 20],
min: -4
});
// Muted callbacks
// One at a time
picker.set('disable', 'flip', { muted: true });
// Multiple at once
picker.set({
select: [1988, 7, 14],
view: new Date(1988, 7, 14),
max: 4
}, { muted: true });
// Clear the value in the pickerβs input element.
picker.set('clear');
// Set select for a date item object
// Using arrays formatted as [YEAR,MONTH,DATE].
picker.set('select', [2013, 3, 20]);
// Using JavaScript Date objects.
picker.set('select', new Date(2013, 3, 20));
// Using positive integers as UNIX timestamps.
picker.set('select', 1365961912346);
// Using a string along with the parsing format (defaults to `format` option).
picker.set('select', '2016-04-20', { format: 'yyyy-mm-dd' });
// Set select for a time item object
// Using arrays formatted as [HOUR,MINUTE].
picker.set('select', [3, 0]);
// Using JavaScript Date objects.
picker.set('select', new Date(2015, 3, 20, 10, 30));
// Using positive integers as minutes.
picker.set('select', 540);
// Using a string along with the parsing format (defaults to `format` option).
picker.set('select', '04-30', { format: 'hh-i' });
// Set highlight for a date item object
// Using arrays formatted as [YEAR,MONTH,DATE].
picker.set('highlight', [2013, 3, 20]);
// Using JavaScript Date objects.
picker.set('highlight', new Date(2015, 3, 30));
// Using positive integers as UNIX timestamps.
picker.set('highlight', 1365961912346);
// Using a string along with the parsing format (defaults to `format` option).
picker.set('highlight', '2016-04-20', { format: 'yyyy-mm-dd' });
// Set highlight for a time item object
// Using arrays formatted as [HOUR,MINUTE].
picker.set('highlight', [15, 30]);
// Using JavaScript Date objects.
picker.set('highlight', new Date(2015, 3, 20, 10, 30));
// Using positive integers as minutes.
picker.set('highlight', 1080);
// Using a string along with the parsing format (defaults to `format` option).
picker.set('highlight', '04-30', { format: 'hh-i' });
// Set view for a date item object
// Using arrays formatted as [YEAR,MONTH,DATE].
picker.set('view', [2000, 3, 20]);
// Using JavaScript Date objects.
picker.set('view', new Date(1988, 7, 14));
// Using positive integers as UNIX timestamps.
picker.set('view', 1587355200000);
// Using a string along with the parsing format (defaults to `format` option).
picker.set('view', '2016-04-20', { format: 'yyyy-mm-dd' });
// Set view for a time item object
// Using arrays formatted as [HOUR,MINUTE].
picker.set('view', [15, 30]);
// Using JavaScript Date objects.
picker.set('view', new Date(2015, 3, 20, 10, 30));
// Using positive integers as minutes.
picker.set('view', 1080);
// Using a string along with the parsing format (defaults to `format` option).
picker.set('view', '04-30', { format: 'hh-i' });
// Limit the min date
// Using arrays formatted as [YEAR,MONTH,DATE].
picker.set('min', [2013, 3, 20]);
// Using JavaScript Date objects.
picker.set('min', new Date(2015, 7, 14));
// Using formatted strings.
picker.set('min', '8 January, 2016');
// Using integers as days relative to today.
picker.set('min', -4);
// Using `true` for "today".
picker.set('min', true);
// Using `false` to remove.
picker.set('min', false);
// Limit the min time
// Using arrays formatted as [HOUR,MINUTE].
picker.set('min', [15, 30]);
// Using JavaScript Date objects.
picker.set('min', new Date(2015, 3, 20, 10, 30));
// Using formatted strings.
picker.set('min', '4:30 PM');
// Using integers as intervals relative from now.
picker.set('min', -4);
// Using `true` for "now".
picker.set('min', true);
// Using `false` to remove.
picker.set('min', false);
// Limit the max date
// Using arrays formatted as [YEAR,MONTH,DATE].
picker.set('max', [2013, 3, 20]);
// Using JavaScript Date objects.
picker.set('max', new Date(2015, 7, 14));
// Using formatted strings.
picker.set('max', '20 April, 2016');
// Using integers as days relative to today.
picker.set('max', 4);
// Using `true` for "today".
picker.set('max', true);
// Using `false` to remove.
picker.set('max', false);
// Limit the max time
// Using arrays formatted as [HOUR,MINUTE].
picker.set('max', [15, 30]);
// Using JavaScript Date objects.
picker.set('max', new Date(2015, 3, 20, 10, 30));
// Using formatted strings.
picker.set('max', '11:30 AM');
// Using integers as intervals relative from now.
picker.set('max', 4);
// Using `true` for "now".
picker.set('max', true);
// Using `false` to remove.
picker.set('max', false);
// Disable/enable specific dates
picker.set('disable', [
// Using a collection of arrays formatted as [YEAR,MONTH,DATE]
[2016, 9, 3], [2016, 9, 9], [2016, 9, 20],
// Using JavaScript Date objects
new Date(2015, 9, 13), new Date(2015, 9, 24)
]);
picker.set('enable', [
[2016, 9, 9],
[2016, 9, 13],
new Date(2015, 9, 20)
]);
// Disable/enable ranges of dates
picker.set('disable', [
1, 4, 7, // Using integers as the days of the week (1 to 7)
// Using a range object with a "from" and "to" property
{ from: [2016, 2, 14], to: [2016, 2, 27] }
]);
picker.set('enable', [
4,
{ from: [2016, 2, 24], to: [2016, 2, 27] }
]);
// "Flip" the enabled and disabled dates:
picker.set('disable', 'flip');
picker.set('enable', 'flip');
// Disable all the dates
picker.set('disable', true);
picker.set('enable', false);
// Enable all the dates
picker.set('enable', true);
picker.set('disable', false);
// Disable/enable specific times
picker.set('disable', [
// Using a collection of arrays formatted as [HOUR,MINUTES]
[2, 30], [4, 30], [9, 0],
// Using JavaScript Date objects
new Date(2015, 9, 13, 6), new Date(2015, 9, 13, 12, 30)
]);
picker.set('enable', [
[4, 30], [6, 0],
new Date(2015, 9, 13, 9)
]);
// Disable/enable ranges of times
picker.set('disable', [
1, 4, 7, // Using integers as hours of the day (from 0 to 23)
// Using a range object with a βfromβ and βtoβ property
{ from: [10, 30], to: [18, 0] }
]);
picker.set('enable', [
4,
{ from: [14, 0], to: [16, 30] }
]);
// "Flip" the enabled and disabled times:
picker.set('disable', 'flip');
picker.set('enable', 'flip');
// Disable all the times
picker.set('disable', true);
picker.set('enable', true);
// Enable all the times
picker.set('enable', true);
picker.set('disable', false);
// Enable an element within a disabled range
picker.set('disable', [
// Disable all Mondays, except November 15th, 2015.
1, [2015, 10, 15, 'inverted'],
// Disable all dates from March 2nd, 2016 to March 28th, 2016
// except for March 10th and all between March 14th and March 23rd.
{ from: [2016, 2, 2], to: [2016, 2, 28] },
[2016, 2, 10, 'inverted'],
{ from: [2016, 2, 14], to: [2016, 2, 23], inverted: true }
]);
picker.set('disable', [
// Disable all times from 1:00 AM to 1:59 AM, except 1:30 AM.
1, [1, 30, 'inverted'],
// Disable all times from 3:00 AM to 6:00 PM except
// for 4:30 AM and all between 7:30 AM and 11:30 AM.
{ from: [3, 0], to: [18, 0] },
[4, 30, 'inverted'],
{ from: [7, 30], to: [11, 30], inverted: true }
]);
// For the time picker only, you can change the interval between each time display
// using integers representing the interval length in minutes.
picker.set('interval', 15);
picker.set('interval', 20);
picker.set('interval', 120);
picker.on({
open: function () {
console.log('Opened up!')
},
close: function () {
console.log('Closed now')
},
render: function () {
console.log('Just rendered anew')
},
stop: function () {
console.log('See ya')
},
set: function (thingSet) {
console.log('Set stuff:', thingSet)
}
});
$('.datepicker').pickadate({
onOpen: function () {
console.log('Opened up!')
},
onClose: function () {
console.log('Closed now')
},
onRender: function () {
console.log('Just rendered anew')
},
onStart: function () {
console.log('Hello there :)')
},
onStop: function () {
console.log('See ya')
},
onSet: function (thingSet) {
console.log('Set stuff:', thingSet)
}
});
picker.on('open', function () {
console.log('Even when Iβm opened, Iβm not logged..');
});
picker.off('open');
// Trigger an eventβs callbacks that have been queued up
picker.on('open', function () {
console.log('This logs without opening!');
});
picker.trigger('open');
// Optionally, you can also pass some data to the method being triggered
picker.on('open', function (data) {
console.log('This logs without opening with this data:', data);
});
picker.trigger('open', { some: 'value' });
|
types/pickadate/pickadate-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00017958498210646212,
0.0001744733890518546,
0.00016523174417670816,
0.00017453503096476197,
0.000002524099727452267
] |
{
"id": 0,
"code_window": [
"\n",
"/// <reference types=\"node\" />\n",
"\n",
"import { Duplex, DuplexOptions } from \"stream\";\n",
"\n",
"declare namespace ListStream {\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"interface ListStreamMethod {\n",
" (callback?: (err: Error, data: any[]) => void): ListStream;\n",
" (options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 9
}
|
import { KeySet } from '../ojkeyset';
import { DataProvider } from '../ojdataprovider';
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojLegend<K, D> extends dvtBaseComponent<ojLegendSettableProperties<K, D>> {
as: string;
data: DataProvider<K, D> | null;
drilling: 'on' | 'off';
expanded: KeySet<K> | null;
halign: 'center' | 'end' | 'start';
hiddenCategories: string[];
hideAndShowBehavior: 'on' | 'off';
highlightedCategories: string[];
hoverBehavior: 'dim' | 'none';
hoverBehaviorDelay: number;
orientation: 'horizontal' | 'vertical';
scrolling: 'off' | 'asNeeded';
symbolHeight: number;
symbolWidth: number;
textStyle?: object;
valign: 'middle' | 'bottom' | 'top';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
onAsChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["as"]>) => any) | null;
onDataChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["data"]>) => any) | null;
onDrillingChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["drilling"]>) => any) | null;
onExpandedChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["expanded"]>) => any) | null;
onHalignChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["halign"]>) => any) | null;
onHiddenCategoriesChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["hiddenCategories"]>) => any) | null;
onHideAndShowBehaviorChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["hideAndShowBehavior"]>) => any) | null;
onHighlightedCategoriesChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["highlightedCategories"]>) => any) | null;
onHoverBehaviorChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["hoverBehavior"]>) => any) | null;
onHoverBehaviorDelayChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["hoverBehaviorDelay"]>) => any) | null;
onOrientationChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["orientation"]>) => any) | null;
onScrollingChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["scrolling"]>) => any) | null;
onSymbolHeightChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["symbolHeight"]>) => any) | null;
onSymbolWidthChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["symbolWidth"]>) => any) | null;
onTextStyleChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["textStyle"]>) => any) | null;
onValignChanged: ((event: JetElementCustomEvent<ojLegend<K, D>["valign"]>) => any) | null;
onOjDrill: ((event: ojLegend.ojDrill) => any) | null;
addEventListener<T extends keyof ojLegendEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojLegendEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojLegendSettableProperties<K, D>>(property: T): ojLegend<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojLegendSettableProperties<K, D>>(property: T, value: ojLegendSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojLegendSettableProperties<K, D>>): void;
setProperties(properties: ojLegendSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojLegend.NodeContext | null;
getItem(subIdPath: any[]): ojLegend.ItemContext | null;
getPreferredSize(): ojLegend.PreferredSize | null;
getSection(subIdPath: any[]): ojLegend.SectionContext | null;
}
export namespace ojLegend {
interface ojDrill extends CustomEvent<{
id: any;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type ItemContext = {
text: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
itemIndex: number;
sectionIndexPath: number[];
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type PreferredSize = {
width: number;
height: number;
};
// tslint:disable-next-line interface-over-type-literal
type SectionContext = {
title: string;
sections: object[];
items: object[];
getSection: {
title: string;
sections: string;
items: boolean;
};
getItems: {
text: string;
};
};
}
export interface ojLegendEventMap<K, D> extends dvtBaseComponentEventMap<ojLegendSettableProperties<K, D>> {
'ojDrill': ojLegend.ojDrill;
'asChanged': JetElementCustomEvent<ojLegend<K, D>["as"]>;
'dataChanged': JetElementCustomEvent<ojLegend<K, D>["data"]>;
'drillingChanged': JetElementCustomEvent<ojLegend<K, D>["drilling"]>;
'expandedChanged': JetElementCustomEvent<ojLegend<K, D>["expanded"]>;
'halignChanged': JetElementCustomEvent<ojLegend<K, D>["halign"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojLegend<K, D>["hiddenCategories"]>;
'hideAndShowBehaviorChanged': JetElementCustomEvent<ojLegend<K, D>["hideAndShowBehavior"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojLegend<K, D>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojLegend<K, D>["hoverBehavior"]>;
'hoverBehaviorDelayChanged': JetElementCustomEvent<ojLegend<K, D>["hoverBehaviorDelay"]>;
'orientationChanged': JetElementCustomEvent<ojLegend<K, D>["orientation"]>;
'scrollingChanged': JetElementCustomEvent<ojLegend<K, D>["scrolling"]>;
'symbolHeightChanged': JetElementCustomEvent<ojLegend<K, D>["symbolHeight"]>;
'symbolWidthChanged': JetElementCustomEvent<ojLegend<K, D>["symbolWidth"]>;
'textStyleChanged': JetElementCustomEvent<ojLegend<K, D>["textStyle"]>;
'valignChanged': JetElementCustomEvent<ojLegend<K, D>["valign"]>;
}
export interface ojLegendSettableProperties<K, D> extends dvtBaseComponentSettableProperties {
as: string;
data: DataProvider<K, D> | null;
drilling: 'on' | 'off';
expanded: KeySet<K> | null;
halign: 'center' | 'end' | 'start';
hiddenCategories: string[];
hideAndShowBehavior: 'on' | 'off';
highlightedCategories: string[];
hoverBehavior: 'dim' | 'none';
hoverBehaviorDelay: number;
orientation: 'horizontal' | 'vertical';
scrolling: 'off' | 'asNeeded';
symbolHeight: number;
symbolWidth: number;
textStyle?: object;
valign: 'middle' | 'bottom' | 'top';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
}
export interface ojLegendSettablePropertiesLenient<K, D> extends Partial<ojLegendSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojLegendItem extends JetElement<ojLegendItemSettableProperties> {
borderColor?: string;
categories?: string[];
categoryVisibility?: 'hidden' | 'visible';
color?: string;
drilling?: 'on' | 'off' | 'inherit';
lineStyle?: 'dotted' | 'dashed' | 'solid';
lineWidth?: number;
markerColor?: string;
markerShape: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
markerSvgClassName?: string;
markerSvgStyle?: object;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shortDesc?: string;
source?: string;
svgClassName?: string;
svgStyle?: object;
symbolType?: 'line' | 'lineWithMarker' | 'image' | 'marker';
text: string;
onBorderColorChanged: ((event: JetElementCustomEvent<ojLegendItem["borderColor"]>) => any) | null;
onCategoriesChanged: ((event: JetElementCustomEvent<ojLegendItem["categories"]>) => any) | null;
onCategoryVisibilityChanged: ((event: JetElementCustomEvent<ojLegendItem["categoryVisibility"]>) => any) | null;
onColorChanged: ((event: JetElementCustomEvent<ojLegendItem["color"]>) => any) | null;
onDrillingChanged: ((event: JetElementCustomEvent<ojLegendItem["drilling"]>) => any) | null;
onLineStyleChanged: ((event: JetElementCustomEvent<ojLegendItem["lineStyle"]>) => any) | null;
onLineWidthChanged: ((event: JetElementCustomEvent<ojLegendItem["lineWidth"]>) => any) | null;
onMarkerColorChanged: ((event: JetElementCustomEvent<ojLegendItem["markerColor"]>) => any) | null;
onMarkerShapeChanged: ((event: JetElementCustomEvent<ojLegendItem["markerShape"]>) => any) | null;
onMarkerSvgClassNameChanged: ((event: JetElementCustomEvent<ojLegendItem["markerSvgClassName"]>) => any) | null;
onMarkerSvgStyleChanged: ((event: JetElementCustomEvent<ojLegendItem["markerSvgStyle"]>) => any) | null;
onPatternChanged: ((event: JetElementCustomEvent<ojLegendItem["pattern"]>) => any) | null;
onShortDescChanged: ((event: JetElementCustomEvent<ojLegendItem["shortDesc"]>) => any) | null;
onSourceChanged: ((event: JetElementCustomEvent<ojLegendItem["source"]>) => any) | null;
onSvgClassNameChanged: ((event: JetElementCustomEvent<ojLegendItem["svgClassName"]>) => any) | null;
onSvgStyleChanged: ((event: JetElementCustomEvent<ojLegendItem["svgStyle"]>) => any) | null;
onSymbolTypeChanged: ((event: JetElementCustomEvent<ojLegendItem["symbolType"]>) => any) | null;
onTextChanged: ((event: JetElementCustomEvent<ojLegendItem["text"]>) => any) | null;
addEventListener<T extends keyof ojLegendItemEventMap>(type: T, listener: (this: HTMLElement, ev: ojLegendItemEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojLegendItemSettableProperties>(property: T): ojLegendItem[T];
getProperty(property: string): any;
setProperty<T extends keyof ojLegendItemSettableProperties>(property: T, value: ojLegendItemSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojLegendItemSettableProperties>): void;
setProperties(properties: ojLegendItemSettablePropertiesLenient): void;
}
export interface ojLegendItemEventMap extends HTMLElementEventMap {
'borderColorChanged': JetElementCustomEvent<ojLegendItem["borderColor"]>;
'categoriesChanged': JetElementCustomEvent<ojLegendItem["categories"]>;
'categoryVisibilityChanged': JetElementCustomEvent<ojLegendItem["categoryVisibility"]>;
'colorChanged': JetElementCustomEvent<ojLegendItem["color"]>;
'drillingChanged': JetElementCustomEvent<ojLegendItem["drilling"]>;
'lineStyleChanged': JetElementCustomEvent<ojLegendItem["lineStyle"]>;
'lineWidthChanged': JetElementCustomEvent<ojLegendItem["lineWidth"]>;
'markerColorChanged': JetElementCustomEvent<ojLegendItem["markerColor"]>;
'markerShapeChanged': JetElementCustomEvent<ojLegendItem["markerShape"]>;
'markerSvgClassNameChanged': JetElementCustomEvent<ojLegendItem["markerSvgClassName"]>;
'markerSvgStyleChanged': JetElementCustomEvent<ojLegendItem["markerSvgStyle"]>;
'patternChanged': JetElementCustomEvent<ojLegendItem["pattern"]>;
'shortDescChanged': JetElementCustomEvent<ojLegendItem["shortDesc"]>;
'sourceChanged': JetElementCustomEvent<ojLegendItem["source"]>;
'svgClassNameChanged': JetElementCustomEvent<ojLegendItem["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojLegendItem["svgStyle"]>;
'symbolTypeChanged': JetElementCustomEvent<ojLegendItem["symbolType"]>;
'textChanged': JetElementCustomEvent<ojLegendItem["text"]>;
}
export interface ojLegendItemSettableProperties extends JetSettableProperties {
borderColor?: string;
categories?: string[];
categoryVisibility?: 'hidden' | 'visible';
color?: string;
drilling?: 'on' | 'off' | 'inherit';
lineStyle?: 'dotted' | 'dashed' | 'solid';
lineWidth?: number;
markerColor?: string;
markerShape: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
markerSvgClassName?: string;
markerSvgStyle?: object;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
shortDesc?: string;
source?: string;
svgClassName?: string;
svgStyle?: object;
symbolType?: 'line' | 'lineWithMarker' | 'image' | 'marker';
text: string;
}
export interface ojLegendItemSettablePropertiesLenient extends Partial<ojLegendItemSettableProperties> {
[key: string]: any;
}
export interface ojLegendSection extends JetElement<ojLegendSectionSettableProperties> {
collapsible?: 'on' | 'off';
text?: string;
textHalign?: 'center' | 'end' | 'start';
textStyle?: object;
onCollapsibleChanged: ((event: JetElementCustomEvent<ojLegendSection["collapsible"]>) => any) | null;
onTextChanged: ((event: JetElementCustomEvent<ojLegendSection["text"]>) => any) | null;
onTextHalignChanged: ((event: JetElementCustomEvent<ojLegendSection["textHalign"]>) => any) | null;
onTextStyleChanged: ((event: JetElementCustomEvent<ojLegendSection["textStyle"]>) => any) | null;
addEventListener<T extends keyof ojLegendSectionEventMap>(type: T, listener: (this: HTMLElement, ev: ojLegendSectionEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojLegendSectionSettableProperties>(property: T): ojLegendSection[T];
getProperty(property: string): any;
setProperty<T extends keyof ojLegendSectionSettableProperties>(property: T, value: ojLegendSectionSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojLegendSectionSettableProperties>): void;
setProperties(properties: ojLegendSectionSettablePropertiesLenient): void;
}
export interface ojLegendSectionEventMap extends HTMLElementEventMap {
'collapsibleChanged': JetElementCustomEvent<ojLegendSection["collapsible"]>;
'textChanged': JetElementCustomEvent<ojLegendSection["text"]>;
'textHalignChanged': JetElementCustomEvent<ojLegendSection["textHalign"]>;
'textStyleChanged': JetElementCustomEvent<ojLegendSection["textStyle"]>;
}
export interface ojLegendSectionSettableProperties extends JetSettableProperties {
collapsible?: 'on' | 'off';
text?: string;
textHalign?: 'center' | 'end' | 'start';
textStyle?: object;
}
export interface ojLegendSectionSettablePropertiesLenient extends Partial<ojLegendSectionSettableProperties> {
[key: string]: any;
}
|
types/oracle__oraclejet/ojlegend/index.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.0001886461250251159,
0.00017395215400028974,
0.00016629116726107895,
0.0001740459119901061,
0.000004589729542203713
] |
{
"id": 0,
"code_window": [
"\n",
"/// <reference types=\"node\" />\n",
"\n",
"import { Duplex, DuplexOptions } from \"stream\";\n",
"\n",
"declare namespace ListStream {\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"interface ListStreamMethod {\n",
" (callback?: (err: Error, data: any[]) => void): ListStream;\n",
" (options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 9
}
|
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"simplebar-tests.ts",
"test/module-tests.ts"
]
}
|
types/simplebar/tsconfig.json
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00017323777137789875,
0.00017050742462743074,
0.0001688946213107556,
0.0001693899102974683,
0.000001941199343491462
] |
{
"id": 1,
"code_window": [
"}\n",
"\n",
"declare class ListStream extends Duplex {\n",
" constructor(callback?: (err: Error, data: any[]) => void);\n",
" constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void);\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"interface ListStreamConstructor extends ListStreamMethod {\n",
" new(callback?: (err: Error, data: any[]) => void): ListStream;\n",
" new(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 12
}
|
// Type definitions for list-stream 1.0
// Project: https://github.com/rvagg/list-stream
// Definitions by: IanStorm <https://github.com/IanStorm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Duplex, DuplexOptions } from "stream";
declare namespace ListStream {
}
declare class ListStream extends Duplex {
constructor(callback?: (err: Error, data: any[]) => void);
constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void);
static obj(callback?: (err: Error, data: any[]) => void): ListStream;
static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;
append(chunk: any): void;
duplicate(): ListStream;
end(): void;
get(index: number): any;
length: number;
}
export = ListStream;
|
types/list-stream/index.d.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.9989081621170044,
0.99454665184021,
0.9861684441566467,
0.9985633492469788,
0.005925959907472134
] |
{
"id": 1,
"code_window": [
"}\n",
"\n",
"declare class ListStream extends Duplex {\n",
" constructor(callback?: (err: Error, data: any[]) => void);\n",
" constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void);\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"interface ListStreamConstructor extends ListStreamMethod {\n",
" new(callback?: (err: Error, data: any[]) => void): ListStream;\n",
" new(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 12
}
|
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class FaBellSlash extends React.Component<IconBaseProps> { }
export = FaBellSlash;
|
types/react-icons/lib/fa/bell-slash.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00016859294555615634,
0.00016859294555615634,
0.00016859294555615634,
0.00016859294555615634,
0
] |
{
"id": 1,
"code_window": [
"}\n",
"\n",
"declare class ListStream extends Duplex {\n",
" constructor(callback?: (err: Error, data: any[]) => void);\n",
" constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void);\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"interface ListStreamConstructor extends ListStreamMethod {\n",
" new(callback?: (err: Error, data: any[]) => void): ListStream;\n",
" new(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 12
}
|
// Type definitions for methods 1.1
// Project: https://github.com/jshttp/methods
// Definitions by: Carlos Precioso <https://github.com/cprecioso>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare const methods: string[];
export = methods;
|
types/methods/index.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00016566194244660437,
0.00016566194244660437,
0.00016566194244660437,
0.00016566194244660437,
0
] |
{
"id": 1,
"code_window": [
"}\n",
"\n",
"declare class ListStream extends Duplex {\n",
" constructor(callback?: (err: Error, data: any[]) => void);\n",
" constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void);\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"interface ListStreamConstructor extends ListStreamMethod {\n",
" new(callback?: (err: Error, data: any[]) => void): ListStream;\n",
" new(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 12
}
|
import * as React from 'react';
import NotificationSystem = require('react-notification-system');
class MyComponent extends React.Component {
private notificationSystem: NotificationSystem.System = null;
private notification: NotificationSystem.Notification = {
title: 'Notification title',
message: 'Notification message',
level: 'success',
action: {
label: "Button inside this notification",
callback: () => {
this.notificationSystem.removeNotification(this.notification);
}
}
};
private addNotification() {
this.notification = this.notificationSystem.addNotification(this.notification);
}
componentDidMount() {
this.addNotification();
}
render() {
const style: NotificationSystem.Style = {
NotificationItem: { // Override the notification item
DefaultStyle: { // Applied to every notification, regardless of the notification level
margin: '10px 5px 2px 1px'
},
success: { // Applied only to the success notification item
color: 'red'
}
}
};
const attributes: NotificationSystem.Attributes = {
style: {
...style,
Containers: {
DefaultStyle: {
margin: '10px 5px 2px 1px'
}
},
Title: {
success: {
color: 'green'
}
}
}
};
const ref = (instance: NotificationSystem.System) => {
this.notificationSystem = instance
}
return (
<NotificationSystem style={style} ref={ref}/>
)
}
}
|
types/react-notification-system/react-notification-system-tests.tsx
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.0001743756583891809,
0.00017228756041731685,
0.00016826242790557444,
0.00017267344810534269,
0.0000019074157080467558
] |
{
"id": 2,
"code_window": [
"\n",
" static obj(callback?: (err: Error, data: any[]) => void): ListStream;\n",
" static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" obj: ListStreamMethod;\n",
"}\n",
"\n",
"declare let ListStream: ListStreamConstructor;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 16
}
|
import * as ListStream from "list-stream";
let chunk: any = "chunk";
let listStream: ListStream;
let num = 1;
listStream = new ListStream((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = ListStream.obj((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream.append(chunk);
listStream = listStream.duplicate();
listStream.end();
chunk = listStream.get(num);
num = listStream.length;
|
types/list-stream/list-stream-tests.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.9980940222740173,
0.25596803426742554,
0.00022456275473814458,
0.012776743620634079,
0.4285420775413513
] |
{
"id": 2,
"code_window": [
"\n",
" static obj(callback?: (err: Error, data: any[]) => void): ListStream;\n",
" static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" obj: ListStreamMethod;\n",
"}\n",
"\n",
"declare let ListStream: ListStreamConstructor;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 16
}
|
// Type definitions for argv
// Project: https://www.npmjs.com/package/argv
// Definitions by: Hookclaw <https://github.com/hookclaw>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// argv module
type args = {
targets: string[],
options: { [key: string]: any }
};
type helpOption = {
name: string,
type: string,
short?: string,
description?: string,
example?: string
};
type module = {
mod: string,
description: string,
options: { [key: string]: helpOption }
};
type typeFunction = (value: any, ...arglist: any[]) => any;
type argv = {
// Runs the arguments parser
run: (argv?: string[]) => args,
// Adding options to definitions list
option: (mod: helpOption | helpOption[]) => argv,
// Creating module
mod: (object: module | module[]) => argv,
// Creates custom type function
type: (name: string | { [key: string]: typeFunction }, callback?: typeFunction) => any,
// Setting version number, and auto setting version option
version: (v: string) => argv,
// Description setup
info: (mod: string, description?: module) => argv,
// Cleans out current options
clear: () => argv,
// Prints out the help doc
help: (mod?: string) => argv
};
declare const argv: argv;
export = argv;
|
types/argv/index.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.0002882179105654359,
0.00020809221314266324,
0.00016754359239712358,
0.00017204636242240667,
0.00005355650864657946
] |
{
"id": 2,
"code_window": [
"\n",
" static obj(callback?: (err: Error, data: any[]) => void): ListStream;\n",
" static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" obj: ListStreamMethod;\n",
"}\n",
"\n",
"declare let ListStream: ListStreamConstructor;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 16
}
|
// Type definitions for OpenFin API 17.0
// Project: https://openfin.co/
// Definitions by: Chris Barker <https://github.com/chrisbarker>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// based on v6.49.17.14
// see https://openfin.co/support/technical-faq/#what-do-the-numbers-in-the-runtime-version-mean
/**
* JavaScript API
* The JavaScript API allows you to create an HTML/JavaScript application that has access to the native windowing environment,
* can communicate with other applications and has access to sandboxed system-level features.
*
* API Ready
* When using the OpenFin API, it is important to ensure that it has been fully loaded before making any API calls. To verify
* that the API is in fact ready, be sure to make any API calls either from within the fin.desktop.main() method or explicitly
* after it has returned. This avoids the situation of trying to access methods that are not yet fully injected.
*
* Overview
* When running within the OpenFin Runtime your web applications have access to the "fin" namespace and all the modules within the API
* without the need to include additional source files. You can treat the "fin" namespace as you would the "window", "navigator" or "document" objects.
*/
declare namespace fin {
const desktop: OpenFinDesktop;
interface OpenFinDesktop {
main(f: () => any): void;
Application: OpenFinApplicationStatic;
ExternalApp: OpenFinExternalApplicationStatic;
InterApplicationBus: OpenFinInterApplicationBus;
Notification: OpenFinNotificationStatic;
System: OpenFinSystem;
Window: OpenFinWindowStatic;
}
interface OpenFinApplicationStatic {
/**
* Creates a new Application.
* An object representing an application. Allows the developer to create, execute, show/close an application as well as listen to application events.
*/
new (
options: ApplicationOptions,
callback?: (successObj: { httpResponseCode: number }) => void,
errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinApplication;
/**
* Returns an Application object that represents an existing application.
*/
getCurrent(): OpenFinApplication;
/**
* Returns an Application object that represents an existing application.
*/
wrap(uuid: string): OpenFinApplication;
}
/**
* Application
* An object representing an application.Allows the developer to create, execute, show / close an application as well as listen to application events.
*/
interface OpenFinApplication {
/**
* Returns an instance of the main Window of the application
*/
getWindow(): OpenFinWindow;
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinApplicationEventType,
listener: (event: ApplicationBaseEvent
| TrayIconClickedEvent
| WindowEvent
| WindowAlertRequestedEvent
| WindowAuthRequested
| WindowNavigationRejectedEvent
| WindowEndLoadEvent) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Closes the application and any child windows created by the application.
*/
close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of wrapped fin.desktop.Windows for each of the application's child windows.
*/
getChildWindows(callback?: (children: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of active window groups for all of the application's windows. Each group is represented as an array of wrapped fin.desktop.Windows.
*/
getGroups(callback?: (groups: OpenFinWindow[][]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the JSON manifest that was used to create the application. Invokes the error callback if the application was not created from a manifest.
*/
getManifest(callback?: (manifest: any) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves UUID of the application that launches this application. Invokes the error callback if the application was created from a manifest.
*/
getParentUuid(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves current configuration of application's shortcuts.
*/
getShortcuts(callback?: (config: ShortCutConfig) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves information about the application.
*/
getInfo(callback?: (info: LaunchInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Determines if the application is currently running.
*/
isRunning(callback?: (running: boolean) => void, errorCallback?: (reason: string) => void): void;
/**
* Passes in custom data that will be relayed to the RVM
*/
registerCustomData(data: any, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinApplicationEventType,
previouslyRegisteredListener: (event: ApplicationBaseEvent
| TrayIconClickedEvent
| WindowEvent
| WindowAlertRequestedEvent
| WindowAuthRequested
| WindowNavigationRejectedEvent
| WindowEndLoadEvent) => any,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Removes the application's icon from the tray.
*/
removeTrayIcon(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Restarts the application.
*/
restart(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Runs the application. When the application is created, run must be called.
*/
run(callback?: (successObj: SuccessObj) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void;
/**
* Tells the rvm to relaunch the main application once upon a complete shutdown
*/
scheduleRestart(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sets new shortcut configuration for current application.
* Application has to be launched with a manifest and has to have shortcut configuration (icon url, name, etc.) in its manifest to
* be able to change shortcut states.
*/
setShortcuts(config: ShortCutConfig, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Adds a customizable icon in the system tray and notifies the application when clicked.
*/
setTrayIcon(iconUrl: string, listener: (clickInfo: TrayIconClickedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Closes the application by terminating its process.
*/
terminate(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Waits for a hanging application. This method can be called in response to an application "not-responding" to allow the application
* to continue and to generate another "not-responding" message after a certain period of time.
*/
wait(callback?: () => void, errorCallback?: (reason: string) => void): void;
}
interface ShortCutConfig {
/**
* application has a shortcut on the desktop
*/
desktop?: boolean;
/**
* application has no shortcut in the start menu
*/
startMenu?: boolean;
/**
* application will be launched on system startup
*/
systemStartup?: boolean;
}
interface SuccessObj {
httpResponseCode: number;
}
interface NetworkErrorInfo extends ErrorInfo {
networkErrorCode: number;
}
interface ErrorInfo {
stack: string;
message: string;
}
interface ApplicationOptions {
/**
* The name of the application.
*/
name?: string;
/**
* The url to the application.
*/
url?: string;
/**
* The UUID of the application, unique within the set of all other applications running in the OpenFin Runtime. name and uuid must match.
*/
uuid?: string;
/**
* Enable Flash at the application level. Default: false.
*/
plugins?: boolean;
/**
* The options of the main window of the application.
*/
mainWindowOptions?: WindowOptions;
}
interface WindowOptions {
/**
* Enable keyboard shortcuts for devtools and zoom. Default: false for both.
*/
accelerator?: {
devtools?: boolean,
zoom?: boolean,
reload?: boolean,
reloadIgnoreCache?: boolean,
};
/**
* A flag to always position the window at the top of the window stack. Default: false.
* Updatable
*/
alwaysOnTop?: boolean;
/**
* A flag to automatically show the Window when it is created. Default: false.
*/
autoShow?: boolean;
/**
* A flag to show the context menu when right-clicking on a window. Gives access to the Developer Console for the Window. Default: true
* Updatable
*/
contextMenu?: boolean;
/**
* This defines and applies rounded corners for a frameless window. Default for both width and height: 0.
* Updatable
*/
cornerRounding?: {
width?: number;
height?: number;
};
/**
* A field that the user can attach serializable data to to be ferried around with the window options. Default: ''.
*/
customData?: any;
/**
* Specifies that the window will be positioned in the center of the primary monitor when loaded for the first time on a machine.
* When the window corresponding to that id is loaded again, the position from before the window was closed is used.
* This option overrides defaultLeft and defaultTop. Default: false.
*/
defaultCentered?: boolean;
/**
* The default height of the window. Specifies the height of the window when loaded for the first time on a machine.
* When the window corresponding to that id is loaded again, the height is taken to be the last height of the window before it was closed. Default: 500.
*/
defaultHeight?: number;
/**
* The default left position of the window. Specifies the position of the left of the window when loaded for the first time on a machine.
* When the window corresponding to that id is loaded again, the value of left is taken to be the last value before the window was closed. Default: 100.
*/
defaultWidth?: number;
/**
* The default top position of the window. Specifies the position of the top of the window when loaded for the first time on a machine.
* When the window corresponding to that id is loaded again, the value of top is taken to be the last value before the window was closed. Default: 100.
*/
defaultTop?: number;
/**
* The default width of the window. Specifies the width of the window when loaded for the first time on a machine.
* When the window corresponding to that id is loaded again, the width is taken to be the last width of the window before it was closed. Default: 800.
*/
defaultLeft?: number;
/**
* A flag to show the frame. Default: true.
* Updatable
*/
frame?: boolean;
/**
* A flag to allow a window to be hidden when the close button is clicked.Default: false.
* Updatable
*/
hideOnClose?: boolean;
/**
* A URL for the icon to be shown in the window title bar and the taskbar.Default: The parent application's applicationIcon.
* Updatable
*/
icon?: string;
/**
* The maximum height of a window.Will default to the OS defined value if set to - 1. Default: -1.
* Updatable
*/
maxHeight?: number;
/**
* A flag that lets the window be maximized.Default: true.
* Updatable
*/
maximizable?: boolean;
/**
* The maximum width of a window.Will default to the OS defined value if set to - 1. Default: -1.
* Updatable
*/
maxWidth?: number;
/**
* The minimum height of a window.Default: 0.
* Updatable
*/
minHeight?: number;
/**
* A flag that lets the window be minimized.Default: true.
*/
minimizable?: boolean;
/**
* The minimum width of a window.Default: 0.
*/
minWidth?: number;
/**
* The name for the window which must be unique within the context of the invoking Application.
*/
name?: string;
/**
* A flag that specifies how transparent the window will be.This value is clamped between 0.0 and 1.0.Default: 1.0.
* Updatable
*/
opacity?: number;
/**
* A flag to drop to allow the user to resize the window.Default: true.
* Updatable
*/
resizable?: boolean;
/**
* Defines a region in pixels that will respond to user mouse interaction for resizing a frameless window.
* Updatable
*/
resizeRegion?: {
/**
* The size in pixels (Default: 2),
*/
size?: number;
/**
* The size in pixels of an additional
* square resizable region located at the
* bottom right corner of a
* frameless window. (Default: 4)
*/
bottomRightCorner?: number;
};
/**
* A flag to show the Window's icon in the taskbar. Default: true.
*/
showTaskbarIcon?: boolean;
/**
* A flag to cache the location of the window or not. Default: true.
*/
saveWindowState?: boolean;
/**
* Specify a taskbar group for the window. Default: app's uuid.
*/
taskbarIconGroup?: string;
/**
* A string that sets the window to be "minimized", "maximized", or "normal" on creation. Default: "normal".
*/
state?: string;
/**
* The URL of the window. Default: "about:blank".
*/
url?: string;
/**
* When set to false, the window will render before the "load" event is fired on the content's window.
* Caution, when false you will see an initial empty white window. Default: true.
*/
waitForPageLoad?: boolean;
}
/**
* Clipboard
* Clipboard API allows reading and writting to the clipboard in multiple formats.
*/
interface OpenFinClipboard {
/**
* Reads available formats for the clipboard type
*/
availableFormats(type: string | null, callback?: (formats: string[]) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Reads available formats for the clipboard type
*/
readHtml(type: string | null, callback?: (html: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Read the content of the clipboard as Rtf
*/
readRtf(type: string | null, callback?: (rtf: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Read the content of the clipboard as plain text
*/
readText(type: string | null, callback?: (text: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard
*/
write(data: any, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard as Html
*/
writeHtml(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard as Rtf
*/
writeRtf(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Writes data into the clipboard as plain text
*/
writeText(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
}
interface OpenFinExternalApplicationStatic {
/**
* Returns an External Application object that represents an existing external application.
*/
wrap(uuid: string): OpenFinExternalApplication;
}
/**
* ExternalApplication
* An object representing an application. Allows the developer to create, execute, show and close an application, as well as listen to application events.
*/
interface OpenFinExternalApplication {
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinExternalApplicationEventType,
listener: () => void,
callback?: () => void,
errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinExternalApplicationEventType,
listener: () => void,
callback?: () => void,
errorCallback?: (reason: string, error: ErrorInfo) => void): void;
}
/**
* InterApplicationBus
* A messaging bus that allows for pub/sub messaging between different applications.
*/
interface OpenFinInterApplicationBus {
/**
* Adds a listener that gets called when applications subscribe to the current application's messages.
*/
addSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void;
/**
* Adds a listener that gets called when applications unsubscribe to the current application's messages.
*/
addUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void;
/**
* Removes a previously registered subscribe listener.
*/
removeSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void;
/**
* Removes a previously registered unsubscribe listener.
*/
removeUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void;
/**
* Publishes a message to all applications running on OpenFin Runtime that are subscribed to the specified topic.
*/
publish(topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sends a message to a specific application on a specific topic.
*/
send(destinationUuid: string, name: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void;
send(destinationUuid: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Subscribes to messages from the specified application on the specified topic. If the subscription is for a uuid, [name],
* topic combination that has already been published to upon subscription you will receive the last 20 missed messages in the order they were published.
*/
subscribe(
senderUuid: string,
name: string,
topic: string,
listener: (message: any, uuid: string, name: string) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
subscribe(
senderUuid: string,
topic: string,
listener: (message: any, uuid: string, name: string) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Unsubscribes to messages from the specified application on the specified topic.
*/
unsubscribe(
senderUuid: string,
name: string,
topic: string,
listener: (message: any, uuid: string, name: string) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
unsubscribe(
senderUuid: string,
topic: string,
listener: (message: any, uuid: string, name: string) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
}
interface OpenFinNotificationStatic {
/**
* ctor
*/
new (options: NotificationOptions, callback?: () => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinNotification;
/**
* Gets an instance of the current notification. For use within a notification window to close the window or send a message back to its parent application.
*/
getCurrent(): OpenFinNotification;
}
/**
* Notification
* Notification represents a window on OpenFin Runtime which is shown briefly to the user on the bottom-right corner of the primary monitor.
* A notification is typically used to alert the user of some important event which requires his or her attention.
* Notifications are a child or your application that are controlled by the runtime.
*/
interface OpenFinNotification {
/**
* Closes the notification.
*/
close(callback?: () => void): void;
/**
* Sends a message to the notification.
*/
sendMessage(message: any, callback?: () => void): void;
/**
* Sends a message from the notification to the application that created the notification. The message is handled by the notification's onMessage callback.
*/
sendMessageToApplication(message: any, callback?: () => void): void;
}
interface NotificationOptions {
/**
* A boolean that will force dismissal even if the mouse is hovering over the notification
*/
ignoreMouseOver?: boolean;
/**
* A message of any primitive or composite-primitive type to be passed to the notification upon creation.
*/
message?: any;
/**
* The timeout for displaying a notification.Can be in milliseconds or "never".
*/
duration?: number | "never";
/**
* The url of the notification
*/
url?: string;
/**
* A function that is called when a notification is clicked.
*/
onClick?(callback: () => void): void;
/**
* Invoked when the notification is closed via .close() method on the created notification instance
* or the by the notification itself via fin.desktop.Notification.getCurrent().close().
* NOTE: this is not invoked when the notification is dismissed via a swipe. For the swipe dismissal callback see onDismiss
*/
onClose?(callback: () => void): void;
/**
* Invoked when a the notification is dismissed by swiping it off the screen to the right. NOTE: this is no fired on a programmatic close.
*/
onDismiss?(callback: () => void): void;
/**
* A function that is called when an error occurs.The reason for the error is passed as an argument.
*/
onError?(errorCallback: (reason: string, errorObj: NetworkErrorInfo) => void): void;
/**
* The onMessage function will respond to messages sent from notification.sendMessageToApplication.
* The function is passed the message, which can be of any primitive or composite-primitive type.
*/
onMessage?(callback: (message: any) => void): void;
/**
* A function that is called when a notification is shown.
*/
onShow?(callback: (successObj: SuccessObj) => void): void;
}
/**
* System
* An object representing the core of OpenFin Runtime.
* Allows the developer to perform system-level actions, such as accessing logs, viewing processes, clearing the cache and exiting the runtime.
*/
interface OpenFinSystem {
Clipboard: OpenFinClipboard;
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinSystemEventType,
listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Clears cached data containing window state/positions,
* application resource files (images, HTML, JavaScript files), cookies, and items stored in the Local Storage.
*/
clearCache(options: CacheOptions, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Clears all cached data when OpenFin Runtime exits.
*/
deleteCacheOnExit(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Downloads the given application asset
*/
downloadAsset(
assetObj: AppAssetInfo,
progressListener?: (progress: { downloadedBytes: number, totalBytes: number }) => void,
callback?: (successObj: { path: string }) => void,
errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void;
/**
* Exits the Runtime.
*/
exit(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of data for all applications.
*/
getAllApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of data for all external applications.
*/
getAllExternalApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of data (name, ids, bounds) for all application windows.
*/
getAllWindows(callback?: (windowInfoList: WindowDetails[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the command line argument string that started OpenFin Runtime.
*/
getCommandLineArguments(callback?: (args: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the configuration object that started the OpenFin Runtime.
*/
getDeviceId(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets the value of a given environment variable on the computer on which the runtime is installed.
*/
getEnvironmentVariable(envVar: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves system information.
*/
getHostSpecs(callback?: (info: HostSpecInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the contents of the log with the specified filename.
*/
getLog(logFileName: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array containing information for each log file.
*/
getLogList(callback?: (logInfoList: LogInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an object that contains data about the about the monitor setup of the computer that the runtime is running on.
*/
getMonitorInfo(callback?: (monitorInfo: MonitorInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns the mouse in virtual screen coordinates (left, top).
*/
getMousePosition(callback?: (mousePosition: VirtualScreenCoordinates) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array of all of the runtime processes that are currently running.
* Each element in the array is an object containing the uuid and the name of the application to which the process belongs.
*/
getProcessList(callback?: (processInfoList: ProcessInfo[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves the Proxy settings.
*/
getProxySettings(callback?: (proxy: ProxyInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns information about the running RVM in an object.
*/
getRvmInfo(callback?: (rvmInfo: RvmInfo) => void, errorCallback?: (reason: string) => void): void;
/**
* Returns the version of the runtime. The version contains the major, minor, build and revision numbers.
*/
getVersion(callback?: (version: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Runs an executable or batch file.
*/
launchExternalProcess(options: ExternalProcessLaunchInfo, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void;
/**
* Writes the passed message into both the log file and the console.
*/
log(level: "debug" | "info" | "warn" | "error", message: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Monitors a running process.
*/
monitorExternalProcess(options: ExternalProcessInfo, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void;
/**
* Opens the passed URL in the default web browser.
*/
openUrlWithBrowser(url: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* This function call will register a unique id and produce a token. The token can be used to broker an external connection.
*/
registerExternalConnection(
uuid: string,
callback?: (detail: {
/**
* this will be unique each time
*/
token: string;
/**
* "remote-connection-uuid"
*/
uuid: string;
}) => void,
errorCallback?: (reason: string) => void): void;
/**
* Removes the process entry for the passed UUID obtained from a prior call of fin.desktop.System.launchExternalProcess().
*/
releaseExternalProcess(processUuid: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinSystemEventType,
listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void,
callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Shows the Chrome Developer Tools for the specified window.
*/
showDeveloperTools(uuid: string, name: string, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Attempt to close an external process. The process will be terminated if it has not closed after the elapsed timeout in milliseconds.
*/
terminateExternalProcess(
processUuid: string,
timeout: number,
killTree: boolean,
callback?: (info: { result: "clean" | "terminated" | "failed" }) => void,
errorCallback?: (reason: string) => void): void;
terminateExternalProcess(
processUuid: string,
timeout: number,
callback?: (info: { result: "clean" | "terminated" | "failed" }) => void,
errorCallback?: (reason: string) => void): void;
/**
* Update the OpenFin Runtime Proxy settings.
*/
updateProxySettings(type: string, address: string, port: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
}
interface CacheOptions {
cache?: boolean;
cookies?: boolean;
localStorage?: boolean;
appcache?: boolean;
userData?: boolean;
}
interface AppAssetInfo {
src?: string;
alias?: string;
version?: string;
target?: string;
args?: string;
}
interface ApplicationInfo {
/**
* true when the application is running.
*/
isRunning?: boolean;
/**
* uuid of the application.
*/
uuid?: string;
/**
* uuid of the application that launches this application.
*/
parentUuid?: string;
}
interface WindowDetails {
uuid?: string;
mainWindow?: WindowInfo;
childWindows?: WindowInfo[];
}
interface WindowInfo {
/**
* name of the child window
*/
name?: string;
/**
* top-most coordinate of the child window
*/
top?: number;
/**
* right-most coordinate of the child window
*/
right?: number;
/**
* bottom-most coordinate of the child window
*/
bottom?: number;
/**
* left-most coordinate of the child window
*/
left?: number;
}
interface HostSpecInfo {
/**
* "x86" for 32-bit or "x86_64" for 64-bit
*/
arch: string;
/**
* Same payload as Node's os.cpus()
*/
cpus: NodeCpuInfo[];
gpu: {
/**
* Graphics card name
*/
name: string;
};
/**
* Same payload as Node's os.totalmem()
*/
memory: number;
/**
* OS name and version/edition
*/
name: string;
}
interface NodeCpuInfo {
model: string;
/**
* in MHz
*/
speed: number;
times: {
/**
* The number of milliseconds the CPU has spent in user mode.
*/
user: number;
/**
* The number of milliseconds the CPU has spent in nice mode.
*/
nice: number;
/**
* The number of milliseconds the CPU has spent in sys mode.
*/
sys: number;
/**
* The number of milliseconds the CPU has spent in idle mode.
*/
idle: number;
/**
* The number of milliseconds the CPU has spent in irq mode.
*/
irq: number;
};
}
interface LogInfo {
/**
* the filename of the log
*/
name?: string;
/**
* the size of the log in bytes
*/
size?: number;
/**
* the unix time at which the log was created "Thu Jan 08 2015 14:40:30 GMT-0500 (Eastern Standard Time)"
*/
date?: string;
}
interface ProcessInfo {
/**
* the percentage of total CPU usage
*/
cpuUsage?: number;
/**
* the application name
*/
name?: string;
/**
* the current nonpaged pool usage in bytes
*/
nonPagedPoolUsage?: number;
/**
* the number of page faults
*/
pageFaultCount?: number;
/**
* the current paged pool usage in bytes
*/
pagedPoolUsage?: number;
/**
* the total amount of memory in bytes that the memory manager has committed
*/
pagefileUsage?: number;
/**
* the peak nonpaged pool usage in bytes
*/
peakNonPagedPoolUsage?: number;
/**
* the peak paged pool usage in bytes
*/
peakPagedPoolUsage?: number;
/**
* the peak value in bytes of pagefileUsage during the lifetime of this process
*/
peakPagefileUsage?: number;
/**
* the peak working set size in bytes
*/
peakWorkingSetSize?: number;
/**
* the native process identifier
*/
processId?: number;
/**
* the application UUID
*/
uuid?: string;
/**
* the current working set size (both shared and private data) in bytes
*/
workingSetSize?: number;
}
interface ProxyInfo {
/**
* the configured Proxy Address
*/
proxyAddress?: string;
/**
* the configured Proxy port
*/
proxyPort?: number;
/**
* Proxy Type
*/
type?: string;
}
interface RvmInfo {
version?: string;
"start-time"?: string;
}
interface ExternalProcessLaunchInfo {
path?: string;
/**
* Additionally note that the executable found in the zip file specified in appAssets
* will default to the one mentioned by appAssets.target
* If the the path below refers to a specific path it will override this default
*/
alias?: string;
/**
* When using alias; if no arguments are passed then the arguments (if any)
* are taken from the 'app.json' file, from the 'args' parameter
* of the 'appAssets' Object with the relevant 'alias'.
* If 'arguments' is passed as a parameter it takes precedence
* over any 'args' set in the 'app.json'.
*/
arguments?: string;
listener?(result: {
/**
* "Exited" Or "released" on a call to releaseExternalProcess
*/
topic?: string;
/**
* The mapped UUID which identifies the launched process
*/
uuid?: string;
/*
* Process exit code
*/
exitCode?: number;
}): void;
certificate?: CertificationInfo;
}
interface CertificationInfo {
/**
* A hex string with or without spaces
*/
serial?: string;
/**
* An internally tokenized and comma delimited string allowing partial or full checks of the subject fields
*/
subject?: string;
/**
* A hex string with or without spaces
*/
publickey?: string;
/**
* A hex string with or without spaces
*/
thumbprint?: string;
/**
* A boolean indicating that the certificate is trusted and not revoked
*/
trusted?: boolean;
}
interface ExternalProcessInfo {
pid?: number;
listener?(result: {
/**
* "Exited" Or "released" on a call to releaseExternalProcess
*/
topic?: string;
/**
* The mapped UUID which identifies the launched process
*/
uuid?: string;
/*
* Process exit code
*/
exitCode?: number;
}): void;
}
interface OpenFinWindowStatic {
/**
* Class: Window
*
* new Window(options, callbackopt, errorCallbackopt)
*
* Creates a new OpenFin Window
*
* A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize,
* maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually.
* The new window appears in the same process as the parent window.
* @param options - The options of the window
* @param [callback] - Called if the window creation was successful
* @param [callback.successObj] - httpResponseCode
*/
new (
options: WindowOptions,
callback?: (successObj: { httpResponseCode: number }) => void,
errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinWindow;
/**
* Returns an instance of the current window.
* @returns Current window
*/
getCurrent(): OpenFinWindow;
/**
* Returns a Window object that wraps an existing window.
*/
wrap(appUuid: string, windowName: string): OpenFinWindow;
}
/**
* Window
* A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize,
* maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually.
* The new window appears in the same process as the parent window.
*/
interface OpenFinWindow {
/**
* Name of window
*/
name: string;
/**
* Returns the native JavaScript "window" object for the window. This method can only be used by the parent application or the window itself,
* otherwise it will return undefined. The same Single-Origin-Policy (SOP) rules apply for child windows created by window.open(url) in that the
* contents of the window object are only accessible if the URL has the same origin as the invoking window. See example below.
* Also, will not work with fin.desktop.Window objects created with fin.desktop.Window.wrap().
* @returns Native window
*/
getNativeWindow(): Window;
/**
* Gets the parent application.
* @returns Parent application
*/
getParentApplication(): OpenFinApplication;
/**
* Gets the parent window.
*/
getParentWindow(): OpenFinWindow;
/**
* Registers an event listener on the specified event.
*/
addEventListener(
type: OpenFinWindowEventType,
listener: (event: WindowBaseEvent
| WindowAuthRequestedEvent
| WindowBoundsEvent
| WindowExternalProcessStartedEvent
| WindowExternalProcessExited
| WindowGroupChangedEvent
| WindowHiddenEvent
| Window_NavigationRejectedEvent) => void,
callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Performs the specified window transitions
*/
animate(transitions: AnimationTransition, options: AnimationOptions, callback?: (event: any) => void, errorCallback?: (reason: string) => void): void;
/**
* Provides credentials to authentication requests
*/
authenticate(userName: string, password: string, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void;
/**
* Removes focus from the window.
*/
blur(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Brings the window to the front of the OpenFin window stack.
*/
bringToFront(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Closes the window.
* @param Close will be prevented from closing when force is false and 'close-requested' has been subscribed to for application's main window.
*/
close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Prevents a user from changing a window's size/position when using the window's frame.
* 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation.
* 'disabled-frame-bounds-changed' is generated after a user move/size operation.
* The events provide the bounds that would have been applied if the frame was enabled.
* 'frame-disabled' is generated when an enabled frame becomes disabled.
*/
disableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Re-enables user changes to a window's size/position when using the window's frame.
* 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation.
* 'disabled-frame-bounds-changed' is generated after a user move/size operation.
* The events provide the bounds that would have been applied if the frame was enabled.
* 'frame-enabled' is generated when a disabled frame has becomes enabled.
*/
enableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Flashes the window's frame and taskbar icon until the window is activated.
*/
flash(options?: any, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Gives focus to the window.
*/
focus(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Gets the current bounds (top, left, width, height) of the window.
*/
getBounds(callback?: (bounds: WindowBounds) => void, errorCallback?: (reason: string) => void): void;
/**
* Retrieves an array containing wrapped fin.desktop.Windows that are grouped with this window. If a window is not in a group an empty array is returned.
* Please note that calling window is included in the result array.
*/
getGroup(callback?: (group: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets the current settings of the window.
*/
getOptions(callback?: (options: WindowOptions) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets a base64 encoded PNG snapshot of the window.
*/
getSnapshot(callback?: (base64Snapshot: string) => void, errorCallback?: (reason: string) => void): void;
/**
* Gets the current state ("minimized", "maximized", or "restored") of the window.
*/
getState(callback?: (state: "minimized" | "maximized" | "restored") => void, errorCallback?: (reason: string) => void): void;
/**
* Returns the zoom level of the window.
*/
getZoomLevel(callback?: (level: number) => void, errorCallback?: (reason: string) => void): void;
/**
* Hides the window.
*/
hide(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Determines if the window is currently showing.
*/
isShowing(callback?: (showing: boolean) => void, errorCallback?: (reason: string) => void): void;
/**
* Joins the same window group as the specified window.
*/
joinGroup(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Leaves the current window group so that the window can be move independently of those in the group.
*/
leaveGroup(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Maximizes the window.
*/
maximize(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Merges the instance's window group with the same window group as the specified window
*/
mergeGroups(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Minimizes the window.
*/
minimize(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Moves the window by a specified amount.
*/
moveBy(deltaLeft: number, deltaTop: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Moves the window to a specified location.
*/
moveTo(left: number, top: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Removes a previously registered event listener from the specified event.
*/
removeEventListener(
type: OpenFinWindowEventType,
listener: (event: WindowBaseEvent
| WindowAuthRequestedEvent
| WindowBoundsEvent
| WindowExternalProcessStartedEvent
| WindowExternalProcessExited
| WindowGroupChangedEvent
| WindowHiddenEvent
| Window_NavigationRejectedEvent) => void,
callback?: () => void,
errorCallback?: (reason: string) => void): void;
/**
* Resizes the window by a specified amount.
*/
resizeBy(deltaWidth: number, deltaHeight: number, anchor: OpenFinAnchor, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Resizes the window by a specified amount.
*/
resizeTo(width: number, height: number, anchor: OpenFinAnchor, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Restores the window to its normal state (i.e., unminimized, unmaximized).
*/
restore(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Will bring the window to the front of the entire stack and give it focus.
*/
setAsForeground(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sets the window's size and position
*/
setBounds(left: number, top: number, width: number, height: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Sets the zoom level of the window.
*/
setZoomLevel(level: number, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Shows the window if it is hidden.
* @param Show will be prevented from closing when force is false and 'show-requested' has been subscribed to for application's main window.
*/
show(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Shows the window if it is hidden at the specified location. If the toggle parameter is set to true, the window will alternate between showing and hiding.
*/
showAt(left: number, top: number, force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Stops the taskbar icon from flashing.
*/
stopFlashing(callback?: () => void, errorCallback?: (reason: string) => void): void;
/**
* Updates the window using the passed options
*/
updateOptions(options: WindowOptions, callback?: () => void, errorCallback?: (reason: string) => void): void;
}
interface ApplicationBaseEvent {
topic: string;
type: OpenFinApplicationEventType;
uuid: string;
}
interface TrayIconClickedEvent extends ApplicationBaseEvent {
button: number; // 0 for left, 1 for middle, 2 for right
monitorInfo: MonitorInfo;
x: number; // the cursor x coordinate
y: number; // the cursor y coordinate
}
interface WindowEvent extends ApplicationBaseEvent {
name: string;
}
interface WindowAlertRequestedEvent extends WindowEvent {
message: string;
url: string;
}
interface WindowAuthRequested extends WindowEvent {
authInfo: {
host: string;
isProxy: boolean;
port: number;
realm: string;
scheme: string;
};
}
interface WindowNavigationRejectedEvent extends WindowEvent {
sourceName: string;
url: string;
}
interface WindowEndLoadEvent extends WindowEvent {
documentName: string;
isMain: boolean;
}
interface MonitorInfoChangedEvent extends MonitorInfo {
topic: "system";
type: "monitor-info-changed";
}
interface MonitorInfo {
nonPrimaryMonitors: MonitorInfoDetail[];
primaryMonitor: MonitorInfoDetail;
reason: string;
taskbar: {
edge: "left" | "right" | "top" | "bottom",
rect: MontiorCoordinates
};
topic: "system";
type: "monitor-info-changed";
virtualScreen: MontiorCoordinates;
}
interface MonitorInfoDetail {
availableRect: MontiorCoordinates;
deviceId: string;
displayDeviceActive: boolean;
monitorRect: MontiorCoordinates;
name: string;
}
interface MontiorCoordinates {
bottom: number;
left: number;
right: number;
top: number;
}
interface VirtualScreenCoordinates {
left: number;
top: number;
}
interface SystemBaseEvent {
topic: string;
type: OpenFinSystemEventType;
uuid: string;
}
interface DesktopIconClickedEvent {
mouse: {
/**
* the left virtual screen coordinate of the mouse
*/
left: number,
/**
* the top virtual screen coordinate of the mouse
*/
top: number
};
/**
* the number of milliseconds that have elapsed since the system was started,
*/
tickCount: number;
topic: "system";
type: "desktop-icon-clicked";
}
interface IdleStateChangedEvent {
/**
* How long in milliseconds since the user has been idle.
*/
elapsedTime: number;
/**
* true when the user is idle,false when the user has returned;
*/
isIdle: boolean;
topic: "system";
type: "idle-state-changed";
}
interface WindowBaseEvent {
/**
* the name of the window
*/
name: string;
/**
* always window
*/
topic: "window";
/**
* window event type
*/
type: OpenFinWindowEventType;
/**
* the UUID of the application the window belongs to
*/
uuid: string;
}
interface WindowAuthRequestedEvent extends WindowBaseEvent {
authInfo: {
host: string;
isProxy: boolean;
port: number;
realm: string;
scheme: string;
};
}
interface WindowBoundsEvent extends WindowBaseEvent {
/**
* describes what kind of change occurred.
* 0 means a change in position.
* 1 means a change in size.
* 2 means a change in position and size.
*/
changeType: number;
/**
* true when pending changes have been applied to the window.
*/
deferred: boolean;
/**
* the new height of the window.
*/
height: number;
/**
* the left-most coordinate of the window.
*/
left: number;
/**
* the top-most coordinate of the window.
*/
top: number;
type: "bounds-changed" | "bounds-changing" | "disabled-frame-bounds-changed" | "disabled-frame-bounds-changing";
/**
* the new width of the window.
*/
width: number;
}
interface WindowExternalProcessStartedEvent extends WindowBaseEvent {
/**
* the process handle uuid
*/
processUuid: string;
type: "external-process-started";
}
interface WindowExternalProcessExited extends WindowBaseEvent {
/**
* the process exit code
*/
exitCode: number;
/**
* the process handle uuid
*/
processUuid: string;
type: "external-process-exited";
}
interface WindowGroupChangedEvent extends WindowBaseEvent {
/**
* Which group array the window that the event listener was registered on is included in:
* 'source' The window is included in sourceGroup.
* 'target' The window is included in targetGroup.
* 'nothing' The window is not included in sourceGroup nor targetGroup.
*/
memberOf: "source" | "target" | "nothing";
/**
* The reason this event was triggered.
* 'leave' A window has left the group due to a leave or merge with group.
* 'join' A window has joined the group.
* 'merge' Two groups have been merged together.
* 'disband' There are no other windows in the group.
*/
reason: "leave" | "join" | "merge" | "disband";
/**
* All the windows in the group the sourceWindow originated from.
*/
sourceGroup: WindowOfGroupInfo[];
/**
* The UUID of the application the sourceWindow belongs to The source window is the window in which (merge/join/leave)group(s) was called.
*/
sourceWindowAppUuid: string;
/**
* the name of the sourcewindow.The source window is the window in which(merge / join / leave) group(s) was called.
*/
sourceWindowName: string;
/**
* All the windows in the group the targetWindow orginated from
*/
targetGroup: WindowOfGroupInfo[];
/**
* The UUID of the application the targetWindow belongs to. The target window is the window that was passed into (merge/join) group(s).
*/
targetWindowAppUuid: string;
/**
* The name of the targetWindow. The target window is the window that was passed into (merge/join) group(s).
*/
targetWindowName: string;
type: "group-changed";
}
interface WindowOfGroupInfo {
/**
* The UUID of the application this window entry belongs to.
*/
appUuid: string;
/**
* The name of this window entry.
*/
windowName: string;
}
interface WindowHiddenEvent extends WindowBaseEvent {
/**
* What action prompted the close.
* The reasons are: "hide", "hide-on-close"
*/
reason: "hide" | "hide-on-close";
type: "hidden";
}
interface Window_NavigationRejectedEvent {
name: string;
/**
* source of navigation window name
*/
sourceName: string;
topic: "navigation-rejected";
/**
* Url that was not reached "http://blocked-content.url"
*/
url: string;
/**
* the UUID of the application the window belongs to.
*/
uuid: string;
}
interface AnimationTransition {
opacity?: {
/**
* This value is clamped from 0.0 to 1.0
*/
opacity?: number;
/**
* The total time in milliseconds this transition should take.
*/
duration?: number;
/**
* Treat 'opacity' as absolute or as a delta. Defaults to false.
*/
relative?: boolean;
};
position?: {
/**
* Defaults to the window's current left position in virtual screen coordinates.
*/
left?: number;
/**
* Defaults to the window's current top position in virtual screen coordinates.
*/
top?: number;
/**
* The total time in milliseconds this transition should take.
*/
duration?: number;
/**
* Treat 'left' and 'top' as absolute or as deltas. Defaults to false.
*/
relative?: boolean;
};
size?: {
/**
* Optional if height is present. Defaults to the window's current width.
*/
width?: number;
/**
* Optional if width is present. Defaults to the window's current height.
*/
height?: number;
/**
* The total time in milliseconds this transition should take.
*/
duration?: number;
/**
* Treat 'width' and 'height' as absolute or as deltas. Defaults to false.
*/
relative?: boolean;
};
}
interface AnimationOptions {
/**
* This option interrupts the current animation. When false it pushes this animation onto the end of the animation queue.
*/
interrupt?: boolean;
/**
* Transition effect. Defaults to 'ease-in-out'.
*/
tween?: OpenFinTweenType;
}
interface WindowBounds {
/**
* the height of the window.
*/
height?: number;
/**
* left-most coordinate of the window.
*/
left?: number;
/**
* top-most coordinate of the window.
*/
top?: number;
/**
* the width of the window.
*/
width?: number;
}
interface SessionChangedEvent {
/**
* the action that triggered this event:
*/
reason: "lock"
| "unlock"
| "remote-connect"
| "remote-disconnect"
| "unknown";
topic: "system";
type: "session-changed";
}
interface LaunchInfo {
launchMode: "fin-protocol"
| "fins-protocol"
| "shortcut"
| "command-line"
| "adapter"
| "other"
| string;
}
type OpenFinTweenType = "linear"
| "ease-in"
| "ease-out"
| "ease-in-out"
| "ease-in-quad"
| "ease-out-quad"
| "ease-in-out-quad"
| "ease-in-cubic"
| "ease-out-cubic"
| "ease-in-out-cubic"
| "ease-out-bounce"
| "ease-in-back"
| "ease-out-back"
| "ease-in-out-back"
| "ease-in-elastic"
| "ease-out-elastic"
| "ease-in-out-elastic";
type OpenFinApplicationEventType = "closed"
| "connected"
| "crashed"
| "initialized"
| "manifest-changed"
| "not-responding"
| "out-of-memory"
| "responding"
| "run-requested"
| "started"
| "tray-icon-clicked"
| "window-alert-requested"
| "window-auth-requested"
| "window-closed"
| "window-created"
| "window-end-load"
| "window-navigation-rejected"
| "window-show-requested"
| "window-start-load";
type OpenFinExternalApplicationEventType = "connected"
| "disconnected";
type OpenFinSystemEventType = "application-closed"
| "application-crashed"
| "application-created"
| "application-started"
| "desktop-icon-clicked"
| "idle-state-changed"
| "monitor-info-changed"
| "session-changed";
type OpenFinWindowEventType = "auth-requested"
| "blurred"
| "bounds-changed"
| "bounds-changing"
| "close-requested"
| "closed"
| "disabled-frame-bounds-changed"
| "disabled-frame-bounds-changing"
| "embedded"
| "external-process-exited"
| "external-process-started"
| "focused"
| "frame-disabled"
| "frame-enabled"
| "group-changed"
| "hidden"
| "initialized"
| "maximized"
| "minimized"
| "navigation-rejected"
| "restored"
| "show-requested"
| "shown";
type OpenFinAnchor = "top-left"
| "top-right"
| "bottom-left"
| "bottom-right";
}
|
types/openfin/v17/index.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.0008596010156907141,
0.00019881904881913215,
0.00016287316975649446,
0.00017160247080028057,
0.00008265536598628387
] |
{
"id": 2,
"code_window": [
"\n",
" static obj(callback?: (err: Error, data: any[]) => void): ListStream;\n",
" static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" obj: ListStreamMethod;\n",
"}\n",
"\n",
"declare let ListStream: ListStreamConstructor;\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "replace",
"edit_start_line_idx": 16
}
|
import umd = require("umd");
var res1: string = umd("name1", "return 123");
var res2: string = umd("name2", "return 'abc'", { commonJS: true });
var res3: string = umd.prelude("pre1", false);
var res4: string = umd.postlude("post1", true);
var res5: string = umd.prelude("pre2");
var res6: string = umd.postlude("post2");
|
types/umd/umd-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.0001779426820576191,
0.00017662362370174378,
0.00017530456534586847,
0.00017662362370174378,
0.0000013190583558753133
] |
{
"id": 3,
"code_window": [
"\n",
" append(chunk: any): void;\n",
" duplicate(): ListStream;\n",
" end(): void;\n",
" get(index: number): any;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface ListStream extends Duplex {\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "add",
"edit_start_line_idx": 19
}
|
import * as ListStream from "list-stream";
let chunk: any = "chunk";
let listStream: ListStream;
let num = 1;
listStream = new ListStream((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = ListStream.obj((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream.append(chunk);
listStream = listStream.duplicate();
listStream.end();
chunk = listStream.get(num);
num = listStream.length;
|
types/list-stream/list-stream-tests.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.9931929707527161,
0.29095104336738586,
0.0024282443337142467,
0.08409149944782257,
0.4107525944709778
] |
{
"id": 3,
"code_window": [
"\n",
" append(chunk: any): void;\n",
" duplicate(): ListStream;\n",
" end(): void;\n",
" get(index: number): any;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface ListStream extends Duplex {\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "add",
"edit_start_line_idx": 19
}
|
import * as assert from 'assert';
assert(true, "it's working");
assert.ok(true, "inner functions work as well");
assert.throws(() => {});
assert.throws(() => {}, () => {}, "works wonderfully");
assert['fail'](true, true, "works like a charm");
|
types/assert/assert-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.0001747350033838302,
0.00017446567653678358,
0.00017419634968973696,
0.00017446567653678358,
2.693268470466137e-7
] |
{
"id": 3,
"code_window": [
"\n",
" append(chunk: any): void;\n",
" duplicate(): ListStream;\n",
" end(): void;\n",
" get(index: number): any;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface ListStream extends Duplex {\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "add",
"edit_start_line_idx": 19
}
|
{ "extends": "dtslint/dt.json" }
|
types/flush-write-stream/tslint.json
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00017196216504089534,
0.00017196216504089534,
0.00017196216504089534,
0.00017196216504089534,
0
] |
{
"id": 3,
"code_window": [
"\n",
" append(chunk: any): void;\n",
" duplicate(): ListStream;\n",
" end(): void;\n",
" get(index: number): any;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface ListStream extends Duplex {\n"
],
"file_path": "types/list-stream/index.d.ts",
"type": "add",
"edit_start_line_idx": 19
}
|
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"zenscroll-tests.ts"
]
}
|
types/zenscroll/tsconfig.json
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00017006363486871123,
0.00016953505109995604,
0.0001685125898802653,
0.00017002892855089158,
7.231280960695585e-7
] |
{
"id": 4,
"code_window": [
"let chunk: any = \"chunk\";\n",
"let listStream: ListStream;\n",
"let num = 1;\n",
"\n",
"listStream = new ListStream((err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"listStream = ListStream((err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n",
"listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n"
],
"file_path": "types/list-stream/list-stream-tests.ts",
"type": "add",
"edit_start_line_idx": 6
}
|
import * as ListStream from "list-stream";
let chunk: any = "chunk";
let listStream: ListStream;
let num = 1;
listStream = new ListStream((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = ListStream.obj((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream.append(chunk);
listStream = listStream.duplicate();
listStream.end();
chunk = listStream.get(num);
num = listStream.length;
|
types/list-stream/list-stream-tests.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.9986335635185242,
0.9978001117706299,
0.9973031282424927,
0.9976319074630737,
0.0005407340358942747
] |
{
"id": 4,
"code_window": [
"let chunk: any = \"chunk\";\n",
"let listStream: ListStream;\n",
"let num = 1;\n",
"\n",
"listStream = new ListStream((err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"listStream = ListStream((err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n",
"listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n"
],
"file_path": "types/list-stream/list-stream-tests.ts",
"type": "add",
"edit_start_line_idx": 6
}
|
import {
PlayerData,
PlayerDataBinder
} from "chromecast-caf-receiver/cast.framework.ui";
import {
ReadyEvent,
ApplicationData
} from "chromecast-caf-receiver/cast.framework.system";
import {
RequestEvent,
Event,
BreaksEvent
} from "chromecast-caf-receiver/cast.framework.events";
import {
QueueBase,
TextTracksManager,
QueueManager,
PlayerManager
} from "chromecast-caf-receiver/cast.framework";
import {
BreakSeekData,
BreakClipLoadInterceptorContext,
BreakManager
} from "chromecast-caf-receiver/cast.framework.breaks";
import {
Break,
BreakClip,
LoadRequestData,
Track,
MediaMetadata
} from "chromecast-caf-receiver/cast.framework.messages";
const breaksEvent = new BreaksEvent('BREAK_STARTED');
breaksEvent.breakId = 'some-break-id';
breaksEvent.breakClipId = 'some-break-clip-id';
const track = new Track(1, "TEXT");
const breakClip = new BreakClip("id");
const adBreak = new Break("id", ["id"], 1);
const rEvent = new RequestEvent("BITRATE_CHANGED", { requestId: 2 });
const pManager = new PlayerManager();
pManager.addEventListener("STALLED", () => { });
const ttManager = new TextTracksManager();
const qManager = new QueueManager();
const qBase = new QueueBase();
const items = qBase.fetchItems(1, 3, 4);
const breakSeekData = new BreakSeekData(0, 100, []);
const breakClipLoadContext = new BreakClipLoadInterceptorContext(adBreak);
const breakManager: BreakManager = {
getBreakById: () => adBreak,
getBreakClipById: () => breakClip,
getBreakClips: () => [breakClip],
getBreaks: () => [adBreak],
getPlayWatchedBreak: () => true,
setBreakClipLoadInterceptor: () => { },
setBreakSeekInterceptor: () => { },
setPlayWatchedBreak: () => { },
setVastTrackingInterceptor: () => { }
};
const lrd: LoadRequestData = {
requestId: 1,
activeTrackIds: [1, 2],
media: {
tracks: [],
textTrackStyle: {},
streamType: "BUFFERED",
metadata: { metadataType: "GENERIC" },
hlsSegmentFormat: "AAC",
contentId: "id",
contentType: "type",
breakClips: [breakClip],
breaks: [adBreak]
},
queueData: {}
};
const appData: ApplicationData = {
id: () => "id",
launchingSenderId: () => "launch-id",
name: () => "name",
namespaces: () => ["namespace"],
sessionId: () => 1
};
const readyEvent = new ReadyEvent(appData);
const data = readyEvent.data;
const pData: PlayerData = {
breakPercentagePositions: [1],
contentType: "video",
currentBreakClipNumber: 2,
currentTime: 1234,
displayStatus: true,
duration: 222,
isBreakSkippable: false,
isLive: true,
isPlayingBreak: false,
isSeeking: true,
metadata: new MediaMetadata("GENERIC"),
nextSubtitle: "sub",
nextThumbnailUrl: "url",
nextTitle: "title",
numberBreakClips: 3,
preloadingNext: false,
state: "paused",
thumbnailUrl: "url",
title: "title",
whenSkippable: 321
};
const binder = new PlayerDataBinder(pData);
binder.addEventListener("ANY_CHANGE", e => { });
|
types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.0001761925668688491,
0.0001715432881610468,
0.0001667758187977597,
0.0001716085971565917,
0.000002937773388111964
] |
{
"id": 4,
"code_window": [
"let chunk: any = \"chunk\";\n",
"let listStream: ListStream;\n",
"let num = 1;\n",
"\n",
"listStream = new ListStream((err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"listStream = ListStream((err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n",
"listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n"
],
"file_path": "types/list-stream/list-stream-tests.ts",
"type": "add",
"edit_start_line_idx": 6
}
|
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class FaExpand extends React.Component<IconBaseProps> { }
export = FaExpand;
|
types/react-icons/lib/fa/expand.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00017621928418520838,
0.00017621928418520838,
0.00017621928418520838,
0.00017621928418520838,
0
] |
{
"id": 4,
"code_window": [
"let chunk: any = \"chunk\";\n",
"let listStream: ListStream;\n",
"let num = 1;\n",
"\n",
"listStream = new ListStream((err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"listStream = ListStream((err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n",
"listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => {\n",
" if (err) { throw err; }\n",
" console.log(data.length);\n",
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n"
],
"file_path": "types/list-stream/list-stream-tests.ts",
"type": "add",
"edit_start_line_idx": 6
}
|
import GoogleMapReact, { BootstrapURLKeys, MapOptions } from 'google-map-react';
import * as React from 'react';
const center = { lat: 0, lng: 0 };
const key: BootstrapURLKeys = { key: 'my-google-maps-key' };
const client: BootstrapURLKeys = { client: 'my-client-identifier', v: '3.28' , language: 'en' };
const options: MapOptions = {
zoomControl: false,
gestureHandling: 'cooperative',
styles: [
{
featureType: "administrative",
elementType: "all",
stylers: [ {saturation: "-100"} ]
},
{
featureType: "administrative.neighborhood",
stylers: [ {visibility: "off" } ]
},
{
elementType: "labels.text.stroke",
stylers: [ {color: "#242f3e"} ]
},
{
stylers: [ {color: "#fcfffd"} ]
}
],
};
<GoogleMapReact center={center} zoom={3} bootstrapURLKeys={client} options={options} />;
|
types/google-map-react/google-map-react-tests.tsx
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00017615007527638227,
0.00017416344780940562,
0.000172294516232796,
0.00017410461441613734,
0.0000016170507706192438
] |
{
"id": 5,
"code_window": [
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n",
"\n",
"listStream.append(chunk);\n",
"\n",
"listStream = listStream.duplicate();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"listStream = ListStream.obj();\n",
"listStream.write({ key: \"value\" });\n",
"\n"
],
"file_path": "types/list-stream/list-stream-tests.ts",
"type": "add",
"edit_start_line_idx": 28
}
|
// Type definitions for list-stream 1.0
// Project: https://github.com/rvagg/list-stream
// Definitions by: IanStorm <https://github.com/IanStorm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Duplex, DuplexOptions } from "stream";
declare namespace ListStream {
}
declare class ListStream extends Duplex {
constructor(callback?: (err: Error, data: any[]) => void);
constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void);
static obj(callback?: (err: Error, data: any[]) => void): ListStream;
static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;
append(chunk: any): void;
duplicate(): ListStream;
end(): void;
get(index: number): any;
length: number;
}
export = ListStream;
|
types/list-stream/index.d.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.006841324269771576,
0.005368128418922424,
0.003694971324875951,
0.0055680894292891026,
0.0012922519817948341
] |
{
"id": 5,
"code_window": [
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n",
"\n",
"listStream.append(chunk);\n",
"\n",
"listStream = listStream.duplicate();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"listStream = ListStream.obj();\n",
"listStream.write({ key: \"value\" });\n",
"\n"
],
"file_path": "types/list-stream/list-stream-tests.ts",
"type": "add",
"edit_start_line_idx": 28
}
|
import MarkdownIt = require("markdown-it");
import anchor = require("markdown-it-anchor");
const md = new MarkdownIt();
md.use(anchor, {
level: 1,
// slugify: string => string,
permalink: false,
// renderPermalink: (slug, opts, state, permalink) => {},
permalinkClass: 'header-anchor',
permalinkSymbol: 'ΒΆ',
permalinkBefore: false
});
const src = `# First header
Lorem ipsum.
## Next section!
This is totaly awesome.`;
md.render(src);
|
types/markdown-it-anchor/markdown-it-anchor-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00017524106078781188,
0.0001714482787065208,
0.00016914958541747183,
0.00016995420446619391,
0.0000027019402750738664
] |
{
"id": 5,
"code_window": [
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n",
"\n",
"listStream.append(chunk);\n",
"\n",
"listStream = listStream.duplicate();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"listStream = ListStream.obj();\n",
"listStream.write({ key: \"value\" });\n",
"\n"
],
"file_path": "types/list-stream/list-stream-tests.ts",
"type": "add",
"edit_start_line_idx": 28
}
|
Session.setTemp('a', 'a');
Session.setPersistent('a', 'a');
Session.setAuth('a', 'a');
Session.setDefaultTemp('a', 'a');
Session.setDefaultPersistent('a', 'a');
Session.setDefaultAuth('a', 'a');
Session.makeTemp('a');
Session.makePersistent('a');
Session.makeAuth('a');
Session.clear();
Session.clear('a');
Session.clearTemp();
Session.clearPersistent();
Session.clearAuth();
|
types/meteor-persistent-session/meteor-persistent-session-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00017270851822104305,
0.00017207511700689793,
0.00017144170124083757,
0.00017207511700689793,
6.334084901027381e-7
] |
{
"id": 5,
"code_window": [
" for (const date of data) {\n",
" console.log(date);\n",
" }\n",
"});\n",
"\n",
"listStream.append(chunk);\n",
"\n",
"listStream = listStream.duplicate();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"listStream = ListStream.obj();\n",
"listStream.write({ key: \"value\" });\n",
"\n"
],
"file_path": "types/list-stream/list-stream-tests.ts",
"type": "add",
"edit_start_line_idx": 28
}
|
{ "extends": "dtslint/dt.json" }
|
types/png.js/tslint.json
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f6a44f54c73a0b255e7b36a1953824e518165996
|
[
0.00017903342086356133,
0.00017903342086356133,
0.00017903342086356133,
0.00017903342086356133,
0
] |
{
"id": 0,
"code_window": [
"import { Component, FunctionComponent } from 'react';\n",
"import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons';\n",
"import { StoryFnReactReturnType } from './types';\n",
"\n",
"// Base types\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" Args as DefaultArgs,\n",
" ArgTypes,\n",
" Parameters,\n",
" DecoratorFunction,\n",
" StoryContext,\n",
"} from '@storybook/addons';\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 1
}
|
import { Component, FunctionComponent } from 'react';
import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons';
import { StoryFnReactReturnType } from './types';
// Base types
interface Annotations<ArgsType, StoryFnReturnType> {
args?: ArgsType;
argTypes?: ArgTypes;
parameters?: Parameters;
decorators?: DecoratorFunction<StoryFnReturnType>[];
}
interface BaseMeta<ComponentType> {
title: string;
component?: ComponentType;
subcomponents?: Record<string, ComponentType>;
}
interface BaseStory<ArgsType, StoryFnReturnType> {
(args: ArgsType, context: StoryContext): StoryFnReturnType;
}
// Re-export generic types
export { Args, ArgTypes, Parameters, StoryContext };
// React specific types
type ReactComponent = Component | FunctionComponent<any>;
type ReactReturnType = StoryFnReactReturnType;
export type Decorator = DecoratorFunction<ReactReturnType>;
export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> &
Annotations<ArgsType, ReactReturnType>;
export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> &
Annotations<ArgsType, ReactReturnType>;
|
app/react/src/client/preview/csf.ts
| 1 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.9583663940429688,
0.25284966826438904,
0.003298047697171569,
0.024867109954357147,
0.4075324833393097
] |
{
"id": 0,
"code_window": [
"import { Component, FunctionComponent } from 'react';\n",
"import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons';\n",
"import { StoryFnReactReturnType } from './types';\n",
"\n",
"// Base types\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" Args as DefaultArgs,\n",
" ArgTypes,\n",
" Parameters,\n",
" DecoratorFunction,\n",
" StoryContext,\n",
"} from '@storybook/addons';\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 1
}
|
import { Meteor } from 'meteor/meteor';
Meteor.startup(() => {
// code to run on server at startup
});
|
lib/cli/test/fixtures/meteor/server/main.js
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.0001743577013257891,
0.0001743577013257891,
0.0001743577013257891,
0.0001743577013257891,
0
] |
{
"id": 0,
"code_window": [
"import { Component, FunctionComponent } from 'react';\n",
"import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons';\n",
"import { StoryFnReactReturnType } from './types';\n",
"\n",
"// Base types\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" Args as DefaultArgs,\n",
" ArgTypes,\n",
" Parameters,\n",
" DecoratorFunction,\n",
" StoryContext,\n",
"} from '@storybook/addons';\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 1
}
|
import mergeConfigs from './merge-webpack-config';
const config = {
devtool: 'source-maps',
entry: {
bundle: 'index.js',
},
output: {
filename: '[name].js',
},
module: {
rules: ['r1', 'r2'],
},
plugins: ['p1', 'p2'],
resolve: {
enforceModuleExtension: true,
extensions: ['.js', '.json'],
alias: {
A1: 'src/B1',
A2: 'src/B2',
},
},
optimization: {
splitChunks: {
chunks: 'all',
},
runtimeChunk: true,
},
};
describe('mergeConfigs', () => {
it('merges two full configs in one', () => {
const customConfig = {
profile: true,
entry: {
bundle: 'should_not_be_merged.js',
},
output: {
filename: 'should_not_be_merged.js',
},
module: {
noParse: /jquery|lodash/,
rules: ['r3', 'r4'],
},
plugins: ['p3', 'p4'],
resolve: {
enforceExtension: false,
extensions: ['.ts', '.tsx'],
alias: {
A3: 'src/B3',
A4: 'src/B4',
},
},
optimization: {
minimizer: ['banana'],
},
};
const result = mergeConfigs(config, customConfig);
expect(result).toMatchSnapshot();
});
it('merges partial custom config', () => {
const customConfig = {
plugins: ['p3'],
resolve: {
extensions: ['.ts', '.tsx'],
},
};
const result = mergeConfigs(config, customConfig);
expect(result).toMatchSnapshot();
});
it('merges successfully if custom config is empty', () => {
const customConfig = {};
const result = mergeConfigs(config, customConfig);
expect(result).toMatchSnapshot();
});
});
|
lib/core/src/server/utils/merge-webpack-config.test.js
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.0001773405383573845,
0.00017385043611284345,
0.00017029145965352654,
0.0001737398561090231,
0.0000020131049041083315
] |
{
"id": 0,
"code_window": [
"import { Component, FunctionComponent } from 'react';\n",
"import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons';\n",
"import { StoryFnReactReturnType } from './types';\n",
"\n",
"// Base types\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" Args as DefaultArgs,\n",
" ArgTypes,\n",
" Parameters,\n",
" DecoratorFunction,\n",
" StoryContext,\n",
"} from '@storybook/addons';\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 1
}
|
/* eslint-disable */
import React from 'react';
import Button from './Button';
import { storiesOf } from '@storybook/react';
storiesOf('Button', module)
.add('with story parameters', () => <Button label="The Button" />, {
header: false,
inline: true,
})
.add('foo', () => <Button label="Foo" />, {
bar: 1,
});
|
lib/codemod/src/transforms/__testfixtures__/storiesof-to-csf/story-parameters.input.js
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.00017268511874135584,
0.00016998345381580293,
0.00016728178889025003,
0.00016998345381580293,
0.0000027016649255529046
] |
{
"id": 1,
"code_window": [
"import { StoryFnReactReturnType } from './types';\n",
"\n",
"// Base types\n",
"interface Annotations<ArgsType, StoryFnReturnType> {\n",
" args?: ArgsType;\n",
" argTypes?: ArgTypes;\n",
" parameters?: Parameters;\n",
" decorators?: DecoratorFunction<StoryFnReturnType>[];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface Annotations<Args, StoryFnReturnType> {\n",
" args?: Partial<Args>;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 5
}
|
import { Component, FunctionComponent } from 'react';
import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons';
import { StoryFnReactReturnType } from './types';
// Base types
interface Annotations<ArgsType, StoryFnReturnType> {
args?: ArgsType;
argTypes?: ArgTypes;
parameters?: Parameters;
decorators?: DecoratorFunction<StoryFnReturnType>[];
}
interface BaseMeta<ComponentType> {
title: string;
component?: ComponentType;
subcomponents?: Record<string, ComponentType>;
}
interface BaseStory<ArgsType, StoryFnReturnType> {
(args: ArgsType, context: StoryContext): StoryFnReturnType;
}
// Re-export generic types
export { Args, ArgTypes, Parameters, StoryContext };
// React specific types
type ReactComponent = Component | FunctionComponent<any>;
type ReactReturnType = StoryFnReactReturnType;
export type Decorator = DecoratorFunction<ReactReturnType>;
export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> &
Annotations<ArgsType, ReactReturnType>;
export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> &
Annotations<ArgsType, ReactReturnType>;
|
app/react/src/client/preview/csf.ts
| 1 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.9976381063461304,
0.9899474382400513,
0.9700515270233154,
0.9960500001907349,
0.011506106704473495
] |
{
"id": 1,
"code_window": [
"import { StoryFnReactReturnType } from './types';\n",
"\n",
"// Base types\n",
"interface Annotations<ArgsType, StoryFnReturnType> {\n",
" args?: ArgsType;\n",
" argTypes?: ArgTypes;\n",
" parameters?: Parameters;\n",
" decorators?: DecoratorFunction<StoryFnReturnType>[];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface Annotations<Args, StoryFnReturnType> {\n",
" args?: Partial<Args>;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 5
}
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`presets-add-preset transforms correctly using "basic.input.js" data 1`] = `"module.exports = ['foo', 'test'];"`;
|
lib/postinstall/src/__testfixtures__/presets-add-preset/basic.output.snapshot
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.00017376634059473872,
0.00017376634059473872,
0.00017376634059473872,
0.00017376634059473872,
0
] |
{
"id": 1,
"code_window": [
"import { StoryFnReactReturnType } from './types';\n",
"\n",
"// Base types\n",
"interface Annotations<ArgsType, StoryFnReturnType> {\n",
" args?: ArgsType;\n",
" argTypes?: ArgTypes;\n",
" parameters?: Parameters;\n",
" decorators?: DecoratorFunction<StoryFnReturnType>[];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface Annotations<Args, StoryFnReturnType> {\n",
" args?: Partial<Args>;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 5
}
|
DOTENV_DEVELOPMENT_DISPLAY_WARNING=true
|
examples/official-storybook/.env.development
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.00017126409511547536,
0.00017126409511547536,
0.00017126409511547536,
0.00017126409511547536,
0
] |
{
"id": 1,
"code_window": [
"import { StoryFnReactReturnType } from './types';\n",
"\n",
"// Base types\n",
"interface Annotations<ArgsType, StoryFnReturnType> {\n",
" args?: ArgsType;\n",
" argTypes?: ArgTypes;\n",
" parameters?: Parameters;\n",
" decorators?: DecoratorFunction<StoryFnReturnType>[];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface Annotations<Args, StoryFnReturnType> {\n",
" args?: Partial<Args>;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 5
}
|
---
id: 'guide-html'
title: 'Storybook for HTML'
---
## Automatic setup
You may have tried to use our quick start guide to setup your project for Storybook.
If it failed because it couldn't detect you're using html, you could try forcing it to use html:
```sh
npx -p @storybook/cli sb init --type html
```
## Manual setup
If you want to set up Storybook manually for your html project, this is the guide for you.
## Step 1: Add dependencies
### Init npm if necessary
If you don't have `package.json` in your project, you'll need to init it first:
```sh
npm init
```
### Add @storybook/html
Add `@storybook/html` to your project. To do that, run:
```sh
npm install @storybook/html --save-dev
```
### Add @babel/core and babel-loader
Make sure that you have `@babel/core`, and `babel-loader` in your dependencies as well because we list these as a peer dependencies:
```sh
npm install babel-loader @babel/core --save-dev
```
## Step 2: Add npm scripts
Then add the following scripts to your `package.json` in order to start the storybook later in this guide:
```json
{
"scripts": {
"storybook": "start-storybook",
"build-storybook": "build-storybook"
}
}
```
## Step 3: Create the main file
For a basic Storybook configuration, the only thing you need to do is tell Storybook where to find stories.
To do that, create a file at `.storybook/main.js` with the following content:
```js
module.exports = {
stories: ['../src/**/*.stories.@(ts|js)'],
};
```
That will load all the stories underneath your `../src` directory that match the pattern `*.stories.@(ts|js)`. We recommend co-locating your stories with your source files, but you can place them wherever you choose.
## Step 4: Write your stories
Now create a `../src/index.stories.js` file, and write your first story like this:
```js
export default { title: 'Button' };
export const withText = () => '<button class="btn">Hello World</button>';
export const withEmoji = () => {
const button = document.createElement('button');
button.innerText = 'π π π π―';
return button;
};
```
Each story is a single state of your component. In the above case, there are two stories for the demo button component:
```plaintext
Button
βββ With Text
βββ With Emoji
```
## Finally: Run your Storybook
Now everything is ready. Run your storybook with:
```sh
npm run storybook
```
Storybook should start, on a random open port in dev-mode.
Now you can develop your components and write stories and see the changes in Storybook immediately since it uses Webpack's hot module reloading.
|
docs/src/pages/guides/guide-html/index.md
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.000176419664057903,
0.0001706044567981735,
0.00016615074127912521,
0.0001701053261058405,
0.000002795336058625253
] |
{
"id": 2,
"code_window": [
" subcomponents?: Record<string, ComponentType>;\n",
"}\n",
"\n",
"interface BaseStory<ArgsType, StoryFnReturnType> {\n",
" (args: ArgsType, context: StoryContext): StoryFnReturnType;\n",
"}\n",
"\n",
"// Re-export generic types\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface BaseStory<Args, StoryFnReturnType> {\n",
" (args: Args, context: StoryContext): StoryFnReturnType;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 18
}
|
import { Component, FunctionComponent } from 'react';
import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons';
import { StoryFnReactReturnType } from './types';
// Base types
interface Annotations<ArgsType, StoryFnReturnType> {
args?: ArgsType;
argTypes?: ArgTypes;
parameters?: Parameters;
decorators?: DecoratorFunction<StoryFnReturnType>[];
}
interface BaseMeta<ComponentType> {
title: string;
component?: ComponentType;
subcomponents?: Record<string, ComponentType>;
}
interface BaseStory<ArgsType, StoryFnReturnType> {
(args: ArgsType, context: StoryContext): StoryFnReturnType;
}
// Re-export generic types
export { Args, ArgTypes, Parameters, StoryContext };
// React specific types
type ReactComponent = Component | FunctionComponent<any>;
type ReactReturnType = StoryFnReactReturnType;
export type Decorator = DecoratorFunction<ReactReturnType>;
export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> &
Annotations<ArgsType, ReactReturnType>;
export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> &
Annotations<ArgsType, ReactReturnType>;
|
app/react/src/client/preview/csf.ts
| 1 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.9969377517700195,
0.9012409448623657,
0.6223260760307312,
0.9928499460220337,
0.16106058657169342
] |
{
"id": 2,
"code_window": [
" subcomponents?: Record<string, ComponentType>;\n",
"}\n",
"\n",
"interface BaseStory<ArgsType, StoryFnReturnType> {\n",
" (args: ArgsType, context: StoryContext): StoryFnReturnType;\n",
"}\n",
"\n",
"// Re-export generic types\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface BaseStory<Args, StoryFnReturnType> {\n",
" (args: Args, context: StoryContext): StoryFnReturnType;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 18
}
|
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
|
lib/cli/test/fixtures/sfc_vue/config/index.js
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.0001762300089467317,
0.0001722171436995268,
0.00016718196275178343,
0.0001727282942738384,
0.000003318025846965611
] |
{
"id": 2,
"code_window": [
" subcomponents?: Record<string, ComponentType>;\n",
"}\n",
"\n",
"interface BaseStory<ArgsType, StoryFnReturnType> {\n",
" (args: ArgsType, context: StoryContext): StoryFnReturnType;\n",
"}\n",
"\n",
"// Re-export generic types\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface BaseStory<Args, StoryFnReturnType> {\n",
" (args: Args, context: StoryContext): StoryFnReturnType;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 18
}
|
import dedent from 'ts-dedent';
import { formatter } from './formatter';
test('handles empty string', () => {
const input = '';
const result = formatter(input);
expect(result).toBe(input);
});
test('handles single line', () => {
const input = 'console.log("hello world")';
const result = formatter(input);
expect(result).toBe(input);
});
test('does not transform correct code', () => {
const input = dedent`
console.log("hello");
console.log("world");
`;
const result = formatter(input);
expect(result).toBe(input);
});
test('does transform incorrect code', () => {
const input = `
console.log("hello");
console.log("world");
`;
const result = formatter(input);
expect(result).toBe(`console.log("hello");
console.log("world");`);
});
test('more indentations - skip first line', () => {
const input = `
test('handles empty string', () => {
const input = '';
const result = formatter(input);
expect(result).toBe(input);
});
`;
const result = formatter(input);
expect(result).toBe(`test('handles empty string', () => {
const input = '';
const result = formatter(input);
expect(result).toBe(input);
});`);
});
test('more indentations - code on first line', () => {
const input = `// some comment
test('handles empty string', () => {
const input = '';
const result = formatter(input);
expect(result).toBe(input);
});
`;
const result = formatter(input);
expect(result).toBe(`// some comment
test('handles empty string', () => {
const input = '';
const result = formatter(input);
expect(result).toBe(input);
});`);
});
test('removes whitespace in empty line completely', () => {
const input = `
console.log("hello");
console.log("world");
`;
const result = formatter(input);
expect(result).toBe(`console.log("hello");
console.log("world");`);
});
|
lib/components/src/syntaxhighlighter/formatter.test.js
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.00018051874940283597,
0.000177742462255992,
0.00017280290194321424,
0.00017835770267993212,
0.000002264931026729755
] |
{
"id": 2,
"code_window": [
" subcomponents?: Record<string, ComponentType>;\n",
"}\n",
"\n",
"interface BaseStory<ArgsType, StoryFnReturnType> {\n",
" (args: ArgsType, context: StoryContext): StoryFnReturnType;\n",
"}\n",
"\n",
"// Re-export generic types\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface BaseStory<Args, StoryFnReturnType> {\n",
" (args: Args, context: StoryContext): StoryFnReturnType;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 18
}
|
import React, { Component } from 'react';
import { polyfill } from 'react-lifecycles-compat';
import { logger } from '@storybook/client-logger';
function log(name) {
logger.info(`LifecycleLogger: ${name}`);
}
// A component that logs its lifecycle so we can check that things happen
// the right number of times (i.e. we are using React properly)
class LifecycleLogger extends Component {
constructor() {
super();
log('constructor');
this.state = {};
}
componentDidMount() {
log('componentDidMount');
}
// deepscan-disable-next-line
getSnapshotBeforeUpdate() {
// deepscan-disable-next-line
log('getSnapshotBeforeUpdate');
}
componentDidUpdate() {
log('componentDidUpdate');
}
componentDidCatch() {
log('componentDidCatch');
}
componentWillUnmount() {
log('componentWillUnmount');
}
render() {
log('render');
return <div>Lifecycle methods are logged to the console</div>;
}
}
LifecycleLogger.getDerivedStateFromProps = () => {
log('getDerivedStateFromProps');
return null;
};
polyfill(LifecycleLogger);
export default LifecycleLogger;
|
examples/cra-kitchen-sink/src/components/LifecycleLogger.js
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.00020477188809309155,
0.00018340046517550945,
0.0001672033395152539,
0.0001764219778124243,
0.000014753813957213424
] |
{
"id": 3,
"code_window": [
"}\n",
"\n",
"// Re-export generic types\n",
"export { Args, ArgTypes, Parameters, StoryContext };\n",
"\n",
"// React specific types\n",
"type ReactComponent = Component | FunctionComponent<any>;\n",
"type ReactReturnType = StoryFnReactReturnType;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export { DefaultArgs as Args, ArgTypes, Parameters, StoryContext };\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 23
}
|
import { Component, FunctionComponent } from 'react';
import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons';
import { StoryFnReactReturnType } from './types';
// Base types
interface Annotations<ArgsType, StoryFnReturnType> {
args?: ArgsType;
argTypes?: ArgTypes;
parameters?: Parameters;
decorators?: DecoratorFunction<StoryFnReturnType>[];
}
interface BaseMeta<ComponentType> {
title: string;
component?: ComponentType;
subcomponents?: Record<string, ComponentType>;
}
interface BaseStory<ArgsType, StoryFnReturnType> {
(args: ArgsType, context: StoryContext): StoryFnReturnType;
}
// Re-export generic types
export { Args, ArgTypes, Parameters, StoryContext };
// React specific types
type ReactComponent = Component | FunctionComponent<any>;
type ReactReturnType = StoryFnReactReturnType;
export type Decorator = DecoratorFunction<ReactReturnType>;
export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> &
Annotations<ArgsType, ReactReturnType>;
export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> &
Annotations<ArgsType, ReactReturnType>;
|
app/react/src/client/preview/csf.ts
| 1 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.9984661340713501,
0.3036392331123352,
0.003940081223845482,
0.10607534646987915,
0.4096682369709015
] |
{
"id": 3,
"code_window": [
"}\n",
"\n",
"// Re-export generic types\n",
"export { Args, ArgTypes, Parameters, StoryContext };\n",
"\n",
"// React specific types\n",
"type ReactComponent = Component | FunctionComponent<any>;\n",
"type ReactReturnType = StoryFnReactReturnType;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export { DefaultArgs as Args, ArgTypes, Parameters, StoryContext };\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 23
}
|
import { color, typography } from '../base';
import { ThemeVars } from '../types';
const theme: ThemeVars = {
base: 'dark',
// Storybook-specific color palette
colorPrimary: '#FF4785', // coral
colorSecondary: '#1EA7FD', // ocean
// UI
appBg: '#2f2f2f',
appContentBg: '#333',
appBorderColor: 'rgba(255,255,255,.1)',
appBorderRadius: 4,
// Fonts
fontBase: typography.fonts.base,
fontCode: typography.fonts.mono,
// Text colors
textColor: color.lightest,
textInverseColor: color.darkest,
// Toolbar default and active colors
barTextColor: '#999999',
barSelectedColor: color.secondary,
barBg: color.darkest,
// Form colors
inputBg: '#3f3f3f',
inputBorder: 'rgba(0,0,0,.3)',
inputTextColor: color.lightest,
inputBorderRadius: 4,
};
export default theme;
|
lib/theming/src/themes/dark.ts
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.00017826755356509238,
0.00017335376469418406,
0.0001693372760200873,
0.00017290512914769351,
0.000003470512638159562
] |
{
"id": 3,
"code_window": [
"}\n",
"\n",
"// Re-export generic types\n",
"export { Args, ArgTypes, Parameters, StoryContext };\n",
"\n",
"// React specific types\n",
"type ReactComponent = Component | FunctionComponent<any>;\n",
"type ReactReturnType = StoryFnReactReturnType;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export { DefaultArgs as Args, ArgTypes, Parameters, StoryContext };\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 23
}
|
import React, { useState } from 'react';
import { useArgs } from '@storybook/client-api';
// eslint-disable-next-line react/prop-types
const ArgUpdater = ({ args, updateArgs, resetArgs }) => {
const [argsInput, updateArgsInput] = useState(JSON.stringify(args));
return (
<div>
<h3>Hooks args:</h3>
<pre>{JSON.stringify(args)}</pre>
<form
onSubmit={(e) => {
e.preventDefault();
updateArgs(JSON.parse(argsInput));
}}
>
<textarea value={argsInput} onChange={(e) => updateArgsInput(e.target.value)} />
<br />
<button type="submit">Change</button>
<button type="button" onClick={() => resetArgs()}>
Reset all
</button>
</form>
</div>
);
};
export default {
title: 'Core/Args',
decorators: [
(story) => {
const [args, updateArgs, resetArgs] = useArgs();
return (
<>
{story()}
<ArgUpdater args={args} updateArgs={updateArgs} resetArgs={resetArgs} />
</>
);
},
],
};
const Template = (args) => {
return (
<div>
<h3>Input args:</h3>
<pre>{JSON.stringify(args)}</pre>
</div>
);
};
export const PassedToStory = Template.bind({});
PassedToStory.argTypes = { name: { defaultValue: 'initial', control: 'text' } };
export const OtherValues = Template.bind({});
OtherValues.argTypes = { name: { control: 'text' } };
export const DifferentSet = Template.bind({});
DifferentSet.args = {
foo: 'bar',
bar: 2,
};
|
examples/official-storybook/stories/core/args.stories.js
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.00315129105001688,
0.000598689541220665,
0.0001661396527197212,
0.0001735194819048047,
0.001042113988660276
] |
{
"id": 3,
"code_window": [
"}\n",
"\n",
"// Re-export generic types\n",
"export { Args, ArgTypes, Parameters, StoryContext };\n",
"\n",
"// React specific types\n",
"type ReactComponent = Component | FunctionComponent<any>;\n",
"type ReactReturnType = StoryFnReactReturnType;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export { DefaultArgs as Args, ArgTypes, Parameters, StoryContext };\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 23
}
|
# Storybook Viewport Addon
Storybook Viewport Addon allows your stories to be displayed in different sizes and layouts in [Storybook](https://storybook.js.org). This helps build responsive components inside of Storybook.
[Framework Support](https://github.com/storybookjs/storybook/blob/master/ADDONS_SUPPORT.md)

## Installation
Install the following npm module:
```sh
npm i --save-dev @storybook/addon-viewport
```
or with yarn:
```sh
yarn add -D @storybook/addon-viewport
```
within `.storybook/main.js`:
```js
module.exports = {
addons: ['@storybook/addon-viewport'],
};
```
You should now be able to see the viewport addon icon in the the toolbar at the top of the screen.
## Configuration
The viewport addon is configured by story parameters with the `viewport` key. To configure globally, import `addParameters` from your app layer in your `preview.js` file.
```js
import { addParameters } from '@storybook/client-api';
addParameters({
viewport: {
viewports: newViewports, // newViewports would be an ViewportMap. (see below for examples)
defaultViewport: 'someDefault',
},
});
```
Options can take a object with the following keys:
### defaultViewport : String
---
Setting this property to, let say `iphone6`, will make `iPhone 6` the default device/viewport for all stories. Default is `'responsive'` which fills 100% of the preview area.
### disable : Boolean
---
Disable viewport addon per component, story or global.
### viewports : Object
---
A key-value pair of viewport's key and properties (see `Viewport` definition below) for all viewports to be displayed. Default is [`MINIMAL_VIEWPORTS`](src/defaults.ts)
#### Viewport Model
```js
{
/**
* name to display in the dropdown
* @type {String}
*/
name: 'Responsive',
/**
* Inline styles to be applied to the story (iframe).
* styles is an object whose key is the camelCased version of the style name, and whose
* value is the styleβs value, usually a string
* @type {Object}
*/
styles: {
width: '100%',
height: '100%',
},
/**
* type of the device (e.g. desktop, mobile, or tablet)
* @type {String}
*/
type: 'desktop',
}
```
## Configuring per component or story
Parameters can be configured for a whole set of stories or a single story via the standard parameter API:
```js
export default {
title: 'Stories',
parameters: {
viewport: {
viewports: INITIAL_VIEWPORTS,
defaultViewport: 'iphone6'
},
};
};
export const myStory = () => <div />;
myStory.parameters = {
viewport: {
defaultViewport: 'iphonex'
},
};
```
## Examples
### Use Detailed Set of Devices
The default viewports being used is [`MINIMAL_VIEWPORTS`](src/defaults.ts). If you'd like to use a more granular list of devices, you can use [`INITIAL_VIEWPORTS`](src/defaults.ts) like so in your `.storybook/preview.js` file.
```js
import { addParameters } from '@storybook/client-api';
import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';
addParameters({
viewport: {
viewports: INITIAL_VIEWPORTS,
},
});
```
### Use Custom Set of Devices
This will replace all previous devices with `Kindle Fire 2` and `Kindle Fire HD` by calling `addParameters` with the two devices as `viewports` in `.storybook/preview.js` file.
```js
import { addParameters } from '@storybook/client-api';
const customViewports = {
kindleFire2: {
name: 'Kindle Fire 2',
styles: {
width: '600px',
height: '963px',
},
},
kindleFireHD: {
name: 'Kindle Fire HD',
styles: {
width: '533px',
height: '801px',
},
},
};
addParameters({
viewport: { viewports: customViewports },
});
```
### Add New Device
This will add both `Kindle Fire 2` and `Kindle Fire HD` to the list of devices. This is achieved by making use of the exported [`INITIAL_VIEWPORTS`](src/defaults.ts) or [`MINIMAL_VIEWPORTS`](src/defaults.ts) property, by merging it with the new viewports and pass the result as `viewports` to `configureViewport` function
```js
import { addParameters } from '@storybook/react';
import {
INITIAL_VIEWPORTS,
// or MINIMAL_VIEWPORTS,
} from '@storybook/addon-viewport';
const customViewports = {
kindleFire2: {
name: 'Kindle Fire 2',
styles: {
width: '600px',
height: '963px',
},
},
kindleFireHD: {
name: 'Kindle Fire HD',
styles: {
width: '533px',
height: '801px',
},
},
};
addParameters({
viewport: {
viewports: {
...INITIAL_VIEWPORTS,
// or ...MINIMAL_VIEWPORTS,
...customViewports,
},
},
});
```
|
addons/viewport/README.md
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.0015298023354262114,
0.0002491739287506789,
0.00016176806821022183,
0.00017400957585778087,
0.00028932446730323136
] |
{
"id": 4,
"code_window": [
"type ReactComponent = Component | FunctionComponent<any>;\n",
"type ReactReturnType = StoryFnReactReturnType;\n",
"\n",
"export type Decorator = DecoratorFunction<ReactReturnType>;\n",
"\n",
"export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> &\n",
" Annotations<ArgsType, ReactReturnType>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"export type Meta<Args = DefaultArgs> = BaseMeta<ReactComponent> &\n",
" Annotations<Args, ReactReturnType>;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 31
}
|
import { Component, FunctionComponent } from 'react';
import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons';
import { StoryFnReactReturnType } from './types';
// Base types
interface Annotations<ArgsType, StoryFnReturnType> {
args?: ArgsType;
argTypes?: ArgTypes;
parameters?: Parameters;
decorators?: DecoratorFunction<StoryFnReturnType>[];
}
interface BaseMeta<ComponentType> {
title: string;
component?: ComponentType;
subcomponents?: Record<string, ComponentType>;
}
interface BaseStory<ArgsType, StoryFnReturnType> {
(args: ArgsType, context: StoryContext): StoryFnReturnType;
}
// Re-export generic types
export { Args, ArgTypes, Parameters, StoryContext };
// React specific types
type ReactComponent = Component | FunctionComponent<any>;
type ReactReturnType = StoryFnReactReturnType;
export type Decorator = DecoratorFunction<ReactReturnType>;
export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> &
Annotations<ArgsType, ReactReturnType>;
export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> &
Annotations<ArgsType, ReactReturnType>;
|
app/react/src/client/preview/csf.ts
| 1 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.998245120048523,
0.5007330179214478,
0.002060539089143276,
0.5013132095336914,
0.49686500430107117
] |
{
"id": 4,
"code_window": [
"type ReactComponent = Component | FunctionComponent<any>;\n",
"type ReactReturnType = StoryFnReactReturnType;\n",
"\n",
"export type Decorator = DecoratorFunction<ReactReturnType>;\n",
"\n",
"export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> &\n",
" Annotations<ArgsType, ReactReturnType>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"export type Meta<Args = DefaultArgs> = BaseMeta<ReactComponent> &\n",
" Annotations<Args, ReactReturnType>;\n"
],
"file_path": "app/react/src/client/preview/csf.ts",
"type": "replace",
"edit_start_line_idx": 31
}
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Storyshots Another Button with some emoji 1`] = `
<button
onClick={[Function]}
style={
Object {
"backgroundColor": "#FFFFFF",
"border": "1px solid #eee",
"borderRadius": 3,
"cursor": "pointer",
"fontSize": 15,
"margin": 10,
"padding": "3px 10px",
}
}
type="button"
>
<span
aria-label="so cool"
role="img"
>
π π π π―
</span>
</button>
`;
|
addons/storyshots/storyshots-core/stories/directly_required/__snapshots__/index@Another-_-Button@with-_-some-_-emoji.boo
| 0 |
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
|
[
0.00017474216292612255,
0.00017162114090751857,
0.00016624234558548778,
0.0001738788851071149,
0.000003819669473159593
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.