type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
MethodDeclaration | // note: don’t claim .astro files with resolveId() — it prevents Vite from transpiling the final JS (import.meta.globEager, etc.)
async resolveId(id, from) {
// If resolving from an astro subresource such as a hoisted script,
// we need to resolve relative paths ourselves.
if (from) {
const parsedFrom = parseAstroRequest(from);
if (parsedFrom.query.astro && isRelativePath(id) && parsedFrom.query.type === 'script') {
const filename = normalizeFilename(parsedFrom.filename);
const resolvedURL = new URL(id, `file://${filename}`);
const resolved = resolvedURL.pathname;
if (isBrowserPath(resolved)) {
return relativeToRoot(resolved + resolvedURL.search);
}
return slash(fileURLToPath(resolvedURL)) + resolvedURL.search;
}
}
// serve sub-part requests (*?astro) as virtual modules
const { query } = parseAstroRequest(id);
if (query.astro) {
// Convert /src/pages/index.astro?astro&type=style to /Users/name/
// Because this needs to be the id for the Vite CSS plugin to property resolve
// relative @imports.
if (query.type === 'style' && isBrowserPath(id)) {
return relativeToRoot(id);
}
return id;
}
} | natemoo-re/astro | packages/astro/src/vite-plugin-astro/index.ts | TypeScript |
MethodDeclaration |
async load(this: PluginContext, id, opts) {
const parsedId = parseAstroRequest(id);
const query = parsedId.query;
if (!id.endsWith('.astro') && !query.astro) {
return null;
}
const filename = normalizeFilename(parsedId.filename);
const fileUrl = new URL(`file://${filename}`);
let source = await fs.promises.readFile(fileUrl, 'utf-8');
const isPage = fileUrl.pathname.startsWith(resolvePages(config).pathname);
if (isPage && config._ctx.scripts.some((s) => s.stage === 'page')) {
source += `\n<script src="${PAGE_SCRIPT_ID}" />`;
}
const compileProps = {
config,
filename,
moduleId: id,
source,
ssr: Boolean(opts?.ssr),
viteTransform,
};
if (query.astro) {
if (query.type === 'style') {
if (typeof query.index === 'undefined') {
throw new Error(`Requests for Astro CSS must include an index.`);
}
const transformResult = await cachedCompilation(compileProps);
// Track any CSS dependencies so that HMR is triggered when they change.
await trackCSSDependencies.call(this, {
viteDevServer,
id,
filename,
deps: transformResult.rawCSSDeps,
});
const csses = transformResult.css;
const code = csses[query.index];
return {
code,
};
} else if (query.type === 'script') {
if (typeof query.index === 'undefined') {
throw new Error(`Requests for hoisted scripts must include an index`);
}
// HMR hoisted script only exists to make them appear in the module graph.
if (opts?.ssr) {
return {
code: `/* client hoisted script, empty in SSR: ${id} */`,
};
}
const transformResult = await cachedCompilation(compileProps);
const scripts = transformResult.scripts;
const hoistedScript = scripts[query.index];
if (!hoistedScript) {
throw new Error(`No hoisted script at index ${query.index}`);
}
if (hoistedScript.type === 'external') {
const src = hoistedScript.src!;
if (src.startsWith('/') && !isBrowserPath(src)) {
const publicDir = config.publicDir.pathname.replace(/\/$/, '').split('/').pop() + '/';
throw new Error(
`\n\n<script src="${src}"> references an asset in the "${publicDir}" directory. Please add the "is:inline" directive to keep this asset from being bundled.\n\nFile: ${filename}`
);
}
}
return {
code:
hoistedScript.type === 'inline'
? hoistedScript.code!
: `import "${hoistedScript.src!}";`,
};
}
}
try {
const transformResult = await cachedCompilation(compileProps);
const { fileId: file, fileUrl: url } = getFileInfo(id, config);
// Compile all TypeScript to JavaScript.
// Also, catches invalid JS/TS in the compiled output before returning.
const { code, map } = await esbuild.transform(transformResult.code, {
loader: 'ts',
sourcemap: 'external',
sourcefile: id,
// Pass relevant Vite options, if needed:
define: config.vite?.define,
});
let SUFFIX = '';
SUFFIX += `\nconst $$file = ${JSON.stringify(file)};\nconst $$url = ${JSON.stringify(
url
)};export { $$file as file, $$url as url };\n`;
// Add HMR handling in dev mode.
if (!resolvedConfig.isProduction) {
// HACK: extract dependencies from metadata until compiler static extraction handles them
const metadata = transformResult.code.split('$$createMetadata(')[1].split('});\n')[0];
const pattern = /specifier:\s*'([^']*)'/g;
const deps = new Set();
let match;
while ((match = pattern.exec(metadata)?.[1])) {
deps.add(match);
}
let i = 0;
while (i < transformResult.scripts.length) {
deps.add(`${id}?astro&type=script&index=${i}`);
SUFFIX += `import "${id}?astro&type=script&index=${i}";`;
i++;
}
SUFFIX += `\nif (import.meta.hot) {
import.meta.hot.accept(mod => mod);
}`;
}
// Add handling to inject scripts into each page JS bundle, if needed.
if (isPage) {
SUFFIX += `\nimport "${PAGE_SSR_SCRIPT_ID}";`;
}
return {
code: `${code}${SUFFIX}`,
map,
};
} catch (err: any) {
// Verify frontmatter: a common reason that this plugin fails is that
// the user provided invalid JS/TS in the component frontmatter.
// If the frontmatter is invalid, the `err` object may be a compiler
// panic or some other vague/confusing compiled error message.
//
// Before throwing, it is better to verify the frontmatter here, and
// let esbuild throw a more specific exception if the code is invalid.
// If frontmatter is valid or cannot be parsed, then continue.
const scannedFrontmatter = FRONTMATTER_PARSE_REGEXP.exec(source);
if (scannedFrontmatter) {
try {
await esbuild.transform(scannedFrontmatter[1], {
loader: 'ts',
sourcemap: false,
sourcefile: id,
});
} catch (frontmatterErr: any) {
// Improve the error by replacing the phrase "unexpected end of file"
// with "unexpected end of frontmatter" in the esbuild error message.
if (frontmatterErr && frontmatterErr.message) {
frontmatterErr.message = frontmatterErr.message.replace(
'end of file',
'end of frontmatter'
);
}
throw frontmatterErr;
}
}
// improve compiler errors
if (err.stack.includes('wasm-function')) {
const search = new URLSearchParams({
labels: 'compiler',
title: '🐛 BUG: `@astrojs/compiler` panic',
template: '---01-bug-report.yml',
'bug-description': `\`@astrojs/compiler\` encountered an unrecoverable error when compiling the following file.
**${id.replace(fileURLToPath(config.root), '')}**
\`\`\`astro
${source}
\`\`\``,
});
err.url = `https://github.com/withastro/astro/issues/new?${search.toString()}`;
err.message = `Error: Uh oh, the Astro compiler encountered an unrecoverable error!
Please open
a GitHub issue using the link below:
${err.url}`;
if (logging.level !== 'debug') {
// TODO: remove stack replacement when compiler throws better errors
err.stack = ` at ${id}`;
}
}
throw err;
}
} | natemoo-re/astro | packages/astro/src/vite-plugin-astro/index.ts | TypeScript |
MethodDeclaration |
async handleHotUpdate(context) {
if (context.server.config.isProduction) return;
return handleHotUpdate.call(this, context, config, logging);
} | natemoo-re/astro | packages/astro/src/vite-plugin-astro/index.ts | TypeScript |
ClassDeclaration |
@Component({
selector: 'app-task',
template: `
<div class="list-item {{ task?.state }}">
<label class="checkbox">
<input
type="checkbox"
[defaultChecked]="task?.state === 'TASK_ARCHIVED'"
disabled="true"
name="checked"
/>
<span class="checkbox-custom" (click)="onArchive(task.id)"></span>
</label>
<div class="title">
<input
type="text"
[value]="task?.title"
readonly="true"
placeholder="Input title"
/>
</div>
<div class="actions">
<a *ngIf="task?.state !== 'TASK_ARCHIVED'" (click)="onPin(task.id)">
<span class="icon-star"></span>
</a>
</div>
</div>
`,
})
export class TaskComponent {
@Input() task: Task;
// tslint:disable-next-line: no-output-on-prefix
@Output()
onPinTask = new EventEmitter<Event>();
// tslint:disable-next-line: no-output-on-prefix
@Output()
onArchiveTask = new EventEmitter<Event>();
/**
* Component method to trigger the onPin event
* @param id string
*/
onPin(id: any) {
this.onPinTask.emit(id);
}
/**
* Component method to trigger the onArchive event
* @param id string
*/
onArchive(id: any) {
this.onArchiveTask.emit(id);
}
} | ser14joker/storybook-angular-example | src/app/components/task.component.ts | TypeScript |
MethodDeclaration | /**
* Component method to trigger the onPin event
* @param id string
*/
onPin(id: any) {
this.onPinTask.emit(id);
} | ser14joker/storybook-angular-example | src/app/components/task.component.ts | TypeScript |
MethodDeclaration | /**
* Component method to trigger the onArchive event
* @param id string
*/
onArchive(id: any) {
this.onArchiveTask.emit(id);
} | ser14joker/storybook-angular-example | src/app/components/task.component.ts | TypeScript |
FunctionDeclaration |
function titleFromFile(c :Config, file :string, name :string) :string {
let title = name
if (title == "index") {
let parent = Path.dir(file)
if (parent == c.srcdirAbs) {
return "Home"
} else {
title = Path.base(parent)
}
}
// "foo-bar.baz" -> "Foo bar baz"
return title[0].toUpperCase() + title.substr(1).replace(/[_\-\.]+/g, " ")
} | rsms/wgen | src/page.ts | TypeScript |
FunctionDeclaration | // The most minimal structured page is 8 bytes:
//---\n
//---\n
function hasMoreToRead(s :ReadState) :bool {
return s.buf.length >= HEADER_READ_SIZE && s.buf.length % HEADER_READ_SIZE == 0
} | rsms/wgen | src/page.ts | TypeScript |
FunctionDeclaration |
function fread(fd :number, buf :Buffer, offs :int) :Promise<int> {
// dlog(`fread len=${buf.length - offs} from fd=${fd} into buf[${offs}]`)
return fs.read(fd, buf, offs, buf.length - offs, null).then(r => r.bytesRead)
} | rsms/wgen | src/page.ts | TypeScript |
FunctionDeclaration |
function freadSync(fd :number, buf :Buffer, offs :int, len :int) :int {
// dlog(`freadSync len=${buf.length - offs} from fd=${fd} into buf[${offs}]`)
return fs.readSync(fd, buf, offs, len, null)
} | rsms/wgen | src/page.ts | TypeScript |
FunctionDeclaration |
async function readHeader(c :Config, fd :number, file :string) :Promise<ReadState> {
let buf = Buffer.allocUnsafe(HEADER_READ_SIZE)
let len = await fread(fd, buf, 0)
let nread = HEADER_READ_SIZE
let fm :FrontMatter|null = null
let fmend = -1
if (len > 7) { // The most minimal magic page is 8 bytes
let i = 0 // index in buf
// find start of front matter
let fmstart = 0
while (i < len) {
let c = buf[i++]
if (c != 0x2D) { // -
if (c == 0x0A) {
// ---\n
fmstart = i
}
break
}
}
if (fmstart) {
// find end of front matter
let index = i
while (1) {
index-- // to include "\n"
let count = 0
while (index < len) {
let c = buf[index]
if (fmend != -1) {
if (c == 0x0A && count >= 3) {
// found end; <LF> c{n,} <LF>
// ^
index++
break
} else if (c == 0x2D) { // -
count++
} else {
fmend = -1
}
} else if (c == 0x0A) {
// probably start
fmend = index
}
index++
}
// Note: In case the header is larger than HEADER_READ_SIZE we may get a false positive
// here, indicating there's no header end, but in fact it is beyond what we read.
if (fmend == -1 && len == nread) {
buf = bufexpand(buf, HEADER_READ_SIZE)
len += freadSync(fd, buf, len, HEADER_READ_SIZE)
nread += HEADER_READ_SIZE
index = i // reset index
} else {
break
}
}
if (fmend != -1) {
try {
fm = parseFrontMatter(buf.subarray(fmstart, fmend).toString("utf8"))
fmend = index // end of the last "\n---\n" <
} catch (err) {
console.error(
`${c.relpath(file)}: Failed to parse header: ${err.message||err}; ` +
`Treating this page as a verbatim file.`
)
}
} else if (len > HEADER_READ_SIZE) {
// in this case we read until the end of the file but found no ending \n---\n
c.log(
`suspicious: %q seems to have front matter ("---" at the beginning)` +
` but no ending "\\n---\\n" was found. Treating this page as a verbatim file.`,
()=>c.relpath(file)
)
}
}
}
return {
fd,
buf: buf.subarray(0, len),
fm,
fmEndOffs: fmend,
}
} | rsms/wgen | src/page.ts | TypeScript |
ArrowFunction |
r => r.bytesRead | rsms/wgen | src/page.ts | TypeScript |
ArrowFunction |
()=>c.relpath(file) | rsms/wgen | src/page.ts | TypeScript |
ClassDeclaration |
export default class Page {
// internal
_s :ReadState
parent :Page|null = null
children :Page[] = []
constructor(
public title :string,
public sfile :string, // source filename (absolute path)
public sext :string, // source file extension, e.g. ".md"
public ofile :string, // output filename (relative path)
public url :string, // inter-site URL, e.g /foo/bar.html
public meta :FrontMatter|null, // null if there is no front matter
_s :ReadState,
) {
this._s = _s
}
toString() :string {
return `Page(${this.title})`
}
// NOTE: Any properties in Page objects are visible within templates.
// For this reason, helper functions like readAll are not part of the prototype.
// readAll reads the complete page source
//
static readAll(p :Page) :Buffer {
let buf = p._s.buf
let hasMore = buf.length >= HEADER_READ_SIZE && buf.length % HEADER_READ_SIZE == 0
if (p._s.fmEndOffs != -1) {
// trim way front matter
buf = buf.subarray(p._s.fmEndOffs)
}
let fd = p._s.fd
if (hasMore) {
// read rest
while (1) {
let z = buf.length
buf = bufexpand(buf, REST_READ_SIZE) // grow buffer
let bytesRead = freadSync(fd, buf, z, REST_READ_SIZE)
if (bytesRead < REST_READ_SIZE) {
buf = buf.subarray(0, z + bytesRead)
break
}
}
}
fs.close(fd)
delete p._s
return buf
}
static async read(c :Config, file :string, sext :string) :Promise<Page> {
// dlog(`Page.read ${file}`)
let fd = fs.openSync(file, "r")
try {
let _s = await readHeader(c, fd, file)
let fm = _s.fm ; _s.fm = null
let file_noext = file.substr(0, file.length - sext.length) // a/b.md -> a/b
let name = Path.base(file_noext) // a/b -> b
// figure out ofile and url
let url = c.baseUrl
let ofile = ""
if (name == "index") {
ofile = Path.join(Path.dir(c.relpath(file_noext)), "index.html")
url += c.relpath(Path.dir(file)) + "/"
} else {
ofile = c.relpath(file_noext) + ".html"
url += name + ".html"
}
return new Page(
(fm && fm.title) || titleFromFile(c, file, name),
file,
sext,
ofile,
url,
fm,
_s,
)
} catch (err) {
fs.closeSync(fd)
throw err
}
}
} | rsms/wgen | src/page.ts | TypeScript |
InterfaceDeclaration |
interface ReadState {
fd :number // source file read FD. -1 when invalid
buf :Buffer
fm :FrontMatter|null
fmEndOffs :number // offset in buf where front matter ends, -1 if no front matter
} | rsms/wgen | src/page.ts | TypeScript |
MethodDeclaration |
toString() :string {
return `Page(${this.title})`
} | rsms/wgen | src/page.ts | TypeScript |
MethodDeclaration | // NOTE: Any properties in Page objects are visible within templates.
// For this reason, helper functions like readAll are not part of the prototype.
// readAll reads the complete page source
//
static readAll(p :Page) :Buffer {
let buf = p._s.buf
let hasMore = buf.length >= HEADER_READ_SIZE && buf.length % HEADER_READ_SIZE == 0
if (p._s.fmEndOffs != -1) {
// trim way front matter
buf = buf.subarray(p._s.fmEndOffs)
}
let fd = p._s.fd
if (hasMore) {
// read rest
while (1) {
let z = buf.length
buf = bufexpand(buf, REST_READ_SIZE) // grow buffer
let bytesRead = freadSync(fd, buf, z, REST_READ_SIZE)
if (bytesRead < REST_READ_SIZE) {
buf = buf.subarray(0, z + bytesRead)
break
}
}
}
fs.close(fd)
delete p._s
return buf
} | rsms/wgen | src/page.ts | TypeScript |
MethodDeclaration |
static async read(c :Config, file :string, sext :string) :Promise<Page> {
// dlog(`Page.read ${file}`)
let fd = fs.openSync(file, "r")
try {
let _s = await readHeader(c, fd, file)
let fm = _s.fm ; _s.fm = null
let file_noext = file.substr(0, file.length - sext.length) // a/b.md -> a/b
let name = Path.base(file_noext) // a/b -> b
// figure out ofile and url
let url = c.baseUrl
let ofile = ""
if (name == "index") {
ofile = Path.join(Path.dir(c.relpath(file_noext)), "index.html")
url += c.relpath(Path.dir(file)) + "/"
} else {
ofile = c.relpath(file_noext) + ".html"
url += name + ".html"
}
return new Page(
(fm && fm.title) || titleFromFile(c, file, name),
file,
sext,
ofile,
url,
fm,
_s,
)
} catch (err) {
fs.closeSync(fd)
throw err
}
} | rsms/wgen | src/page.ts | TypeScript |
ArrowFunction |
() => {
let service: MoedaService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MoedaService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
} | Brunocs1991/Udemy_Angula_13 | projet-final/src/app/conversor/services/moeda.service.spec.ts | TypeScript |
ArrowFunction |
() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MoedaService);
} | Brunocs1991/Udemy_Angula_13 | projet-final/src/app/conversor/services/moeda.service.spec.ts | TypeScript |
ArrowFunction |
(theme: Theme) =>
createStyles({
root: {
display: "flex",
},
drawer: {
[theme.breakpoints.up("sm")]: {
width: drawerWidth,
flexShrink: 0,
},
},
onlyMobile: {
[theme.breakpoints.up("md")]: {
display: "none",
},
},
appBar: {
background: "white",
[theme.breakpoints.up("sm")]: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
},
},
menuButton: {
color: theme.palette.primary.main,
marginRight: theme.spacing(2),
[theme.breakpoints.up("sm")]: {
display: "none",
},
},
// necessary for content to be below app bar
toolbar: {
...theme.mixins.toolbar,
height: 64,
},
drawerPaper: {
width: drawerWidth,
},
topleft: {
color: "#666666",
fontSize: "xx-large",
display: "flex",
"justify-content": "center",
"align-items": "center",
height: 64,
},
content: {
flexGrow: 1,
paddingLeft: 12,
display: "flex",
flexDirection: "column",
height: "100vh",
},
}) | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
(async () => {
if (photos.length === 0) setAutocompleteOptions([]);
else setAutocompleteOptions((await getPhotoLabels(photos.map((photo) => photo.id))).data);
})();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async () => {
if (photos.length === 0) setAutocompleteOptions([]);
else setAutocompleteOptions((await getPhotoLabels(photos.map((photo) => photo.id))).data);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(photo) => photo.id | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
upload(acceptedFiles, fileRejections);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async () => {
setShowLoadingBar(true);
const resp = await getPhotosInAlbum(id, searchTerm);
if (resp.status === 200) {
setPhotos(resp.data);
setShowLoadingBar(false);
} else {
window.alert(await resp.data);
}
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async () => {
const resp = await getAlbums("");
if (resp.status === 200) {
setAlbums(resp.data);
} else {
window.alert(await resp.data);
}
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
fetchPhotos();
fetchAlbums();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async (albumIds: string[]) => {
topBarButtonFunctions.unselect();
await addPhotosToAlbums(selected, albumIds, enqueueSnackbar, closeSnackbar);
await props.refresh();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async (labels: any) => {
topBarButtonFunctions.unselect();
await addLabel(selected, labels);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async (pid: string) => {
setPhotos(photos.filter((p) => p.id !== pid));
await deletePhotos([pid], enqueueSnackbar, closeSnackbar);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(p) => p.id !== pid | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async (pid: string) => {
setPhotos(photos.filter((p) => p.id !== pid));
await removePhotosFromAlbum([pid], id, enqueueSnackbar, closeSnackbar);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async (files: File[], fileRejections: FileRejection[]) => {
if (!files) return;
const formData = new FormData();
files.forEach((file) => {
if (file.size > maxSize) {
fileRejections.push({ file, errors: [{ message: `File is bigger than ${maxSize / (1024 * 1024 * 1024)} GB`, code: "file-too-large" }] });
} else {
formData.append("file", file);
}
});
const snackbar = UploadErrorSnackbar.createInstance(enqueueSnackbar, closeSnackbar);
snackbar?.begin(fileRejections);
if (formData.getAll("file").length === 0) return;
const data = await addPhotos(formData, enqueueSnackbar, closeSnackbar, albums);
await addPhotosToAlbums(data, [id], enqueueSnackbar, closeSnackbar);
await fetchPhotos();
await props.refresh();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(file) => {
if (file.size > maxSize) {
fileRejections.push({ file, errors: [{ message: `File is bigger than ${maxSize / (1024 * 1024 * 1024)} GB`, code: "file-too-large" }] });
} else {
formData.append("file", file);
}
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(photoId: string) => () => {
if (anySelected()) {
clickHandler(photoId)();
} else {
history.push(`/albums/open/${id}/view/${photoId}`);
}
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
if (anySelected()) {
clickHandler(photoId)();
} else {
history.push(`/albums/open/${id}/view/${photoId}`);
}
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(id: string) => () => {
let copy = selected.slice();
if (copy.includes(id)) copy = copy.filter((v) => v !== id);
else copy.push(id);
setSelected(copy);
if (copy.length === 0) {
setSelectable(false);
}
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
let copy = selected.slice();
if (copy.includes(id)) copy = copy.filter((v) => v !== id);
else copy.push(id);
setSelected(copy);
if (copy.length === 0) {
setSelectable(false);
}
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(v) => v !== id | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(): boolean => {
return selected.length !== 0 || selectable;
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async (id: string) => {
await deletePhoto(id);
// await fetchPhotos();
await props.refresh();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async (id: string) => {
await removePhoto(id);
setPhotos(photos.filter((p) => p.id !== id));
// await fetchPhotos();
await props.refresh();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(p) => p.id !== id | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(id: string) => {
setSelected([id]);
setAlbumDialogOpen(true);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async (photoID: string) => {
await setCover(id, photoID);
await props.refresh();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async (id: string) => {
await download(
photos.filter((photo) => id === photo.id),
enqueueSnackbar,
closeSnackbar
);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(photo) => id === photo.id | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async () => {
await setCover(id, selected[0]);
topBarButtonFunctions.unselect();
await props.refresh();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async () => {
topBarButtonFunctions.unselect();
await deletePhotos(selected, enqueueSnackbar, closeSnackbar);
setPhotos(photos.filter((p) => !selected.includes(p.id)));
await props.refresh();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(p) => !selected.includes(p.id) | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async () => {
topBarButtonFunctions.unselect();
await removePhotosFromAlbum(selected, id, enqueueSnackbar, closeSnackbar);
setPhotos(photos.filter((p) => !selected.includes(p.id)));
await props.refresh();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
setSelected([]);
setSelectable(false);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
openM();
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
//Nav to settings page
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
setSelectable(!selectable);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
setAlbumDialogOpen(true);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
setLabelDialogOpen(true);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async () => {
topBarButtonFunctions.unselect();
download(
photos.filter((photo) => selected.includes(photo.id)),
enqueueSnackbar,
closeSnackbar
);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(photo) => selected.includes(photo.id) | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(s: string) => async () => {
setSearchTerm(s);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
async () => {
setSearchTerm(s);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
() => {
setShowSearchBar(!showSearchBar);
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(id: string, buttonFunctions: any) => {
return <TopRightBar id={id} buttonFunctions={buttonFunctions} />;
} | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ArrowFunction |
(album: AlbumT) => album.id.toString() === id | lezli01/ImageStore | frontend/src/Components/AlbumPage/AlbumPhotoPage/AlbumPhotoPage.tsx | TypeScript |
ClassDeclaration |
export class AppStartupBase implements Contracts.IAppStartup {
public constructor(public appEvents: Contracts.IAppEvents[]) {
}
@Log()
public async configuration(): Promise<void> {
for (let appEvent of this.appEvents) {
await appEvent.onAppStartup();
}
}
} | Jaguel/bit-framework | src/TypeScriptClient/Bit.TSClient.Core/Implementations/appStartupBase.ts | TypeScript |
MethodDeclaration |
@Log()
public async configuration(): Promise<void> {
for (let appEvent of this.appEvents) {
await appEvent.onAppStartup();
}
} | Jaguel/bit-framework | src/TypeScriptClient/Bit.TSClient.Core/Implementations/appStartupBase.ts | TypeScript |
FunctionDeclaration |
function maybeSerializeListItem(
item: ListItem | ListItemBuilder | Divider,
index: number,
path: SerializePath
): ListItem | Divider {
if (item instanceof ListItemBuilder) {
return item.serialize({path, index})
}
const listItem = item as ListItem
if (listItem && listItem.type === 'divider') {
return item as Divider
}
if (!listItem || listItem.type !== 'listItem') {
const gotWhat = (listItem && listItem.type) || getArgType(listItem)
const helpText = gotWhat === 'array' ? ' - did you forget to spread (...moreItems)?' : ''
throw new SerializeError(
`List items must be of type "listItem", got "${gotWhat}"${helpText}`,
path,
index
).withHelpUrl(HELP_URL.INVALID_LIST_ITEM)
}
return item
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
FunctionDeclaration |
function isPromise<T>(thing: any): thing is Promise<T> {
return thing && typeof thing.then === 'function'
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
FunctionDeclaration |
export function isList(list: Collection): list is List {
return list.type === 'list'
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
(thing: ListItem) => {
if (thing instanceof ListBuilder) {
return 'ListBuilder'
}
if (isPromise<ListItem>(thing)) {
return 'Promise'
}
return Array.isArray(thing) ? 'array' : typeof thing
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
(item: ListItem | Divider): item is ListItem => {
return item.type === 'listItem'
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
(intentName: string, params, context) => {
const pane = context.pane as List
const items = pane.items || []
return (
items
.filter(isDocumentListItem)
.some(item => item.schemaType.name === params.type && item._id === params.id) ||
shallowIntentChecker(intentName, params, context)
)
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
item => item.schemaType.name === params.type && item._id === params.id | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
(itemId: string, options: ChildResolverOptions) => {
const parentItem = options.parent as List
const items = parentItem.items.filter(isListItem)
const target = (items.find(item => item.id === itemId) || {child: undefined}).child
if (!target || typeof target !== 'function') {
return target
}
return typeof target === 'function' ? target(itemId, options) : target
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
item => item.id === itemId | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
(item, index) => maybeSerializeListItem(item, index, path) | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
(val, i) => find(serializedItems, {id: val.id}, i + 1) | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
item => item.id | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ClassDeclaration |
export class ListBuilder extends GenericListBuilder<BuildableList, ListBuilder> {
protected spec: BuildableList
constructor(spec?: ListInput) {
super()
this.spec = spec ? spec : {}
this.initialValueTemplatesSpecified = Boolean(spec && spec.initialValueTemplates)
}
items(items: (ListItemBuilder | ListItem | Divider)[]): ListBuilder {
return this.clone({items})
}
getItems() {
return this.spec.items
}
serialize(options: SerializeOptions = {path: []}): List {
const id = this.spec.id
if (typeof id !== 'string' || !id) {
throw new SerializeError(
'`id` is required for lists',
options.path,
options.index
).withHelpUrl(HELP_URL.ID_REQUIRED)
}
const items = typeof this.spec.items === 'undefined' ? [] : this.spec.items
if (!Array.isArray(items)) {
throw new SerializeError(
'`items` must be an array of items',
options.path,
options.index
).withHelpUrl(HELP_URL.LIST_ITEMS_MUST_BE_ARRAY)
}
const path = (options.path || []).concat(id)
const serializedItems = items.map((item, index) => maybeSerializeListItem(item, index, path))
const dupes = serializedItems.filter((val, i) => find(serializedItems, {id: val.id}, i + 1))
if (dupes.length > 0) {
const dupeIds = dupes.map(item => item.id).slice(0, 5)
const dupeDesc = dupes.length > 5 ? `${dupeIds.join(', ')}...` : dupeIds.join(', ')
throw new SerializeError(
`List items with same ID found (${dupeDesc})`,
options.path,
options.index
).withHelpUrl(HELP_URL.LIST_ITEM_IDS_MUST_BE_UNIQUE)
}
return {
...super.serialize(options),
type: 'list',
canHandleIntent: this.spec.canHandleIntent || defaultCanHandleIntent,
child: this.spec.child || resolveChildForItem,
items: serializedItems
}
}
clone(withSpec?: BuildableList) {
const builder = new ListBuilder()
builder.spec = {...this.spec, ...(withSpec || {})}
return builder
}
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
InterfaceDeclaration |
export interface List extends GenericList {
items: (ListItem | Divider)[]
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
InterfaceDeclaration |
export interface ListInput extends GenericListInput {
items?: (ListItem | ListItemBuilder | Divider)[]
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
InterfaceDeclaration |
export interface BuildableList extends BuildableGenericList {
items?: (ListItem | ListItemBuilder | Divider)[]
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
MethodDeclaration |
items(items: (ListItemBuilder | ListItem | Divider)[]): ListBuilder {
return this.clone({items})
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
MethodDeclaration |
getItems() {
return this.spec.items
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
MethodDeclaration |
serialize(options: SerializeOptions = {path: []}): List {
const id = this.spec.id
if (typeof id !== 'string' || !id) {
throw new SerializeError(
'`id` is required for lists',
options.path,
options.index
).withHelpUrl(HELP_URL.ID_REQUIRED)
}
const items = typeof this.spec.items === 'undefined' ? [] : this.spec.items
if (!Array.isArray(items)) {
throw new SerializeError(
'`items` must be an array of items',
options.path,
options.index
).withHelpUrl(HELP_URL.LIST_ITEMS_MUST_BE_ARRAY)
}
const path = (options.path || []).concat(id)
const serializedItems = items.map((item, index) => maybeSerializeListItem(item, index, path))
const dupes = serializedItems.filter((val, i) => find(serializedItems, {id: val.id}, i + 1))
if (dupes.length > 0) {
const dupeIds = dupes.map(item => item.id).slice(0, 5)
const dupeDesc = dupes.length > 5 ? `${dupeIds.join(', ')}...` : dupeIds.join(', ')
throw new SerializeError(
`List items with same ID found (${dupeDesc})`,
options.path,
options.index
).withHelpUrl(HELP_URL.LIST_ITEM_IDS_MUST_BE_UNIQUE)
}
return {
...super.serialize(options),
type: 'list',
canHandleIntent: this.spec.canHandleIntent || defaultCanHandleIntent,
child: this.spec.child || resolveChildForItem,
items: serializedItems
}
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
MethodDeclaration |
clone(withSpec?: BuildableList) {
const builder = new ListBuilder()
builder.spec = {...this.spec, ...(withSpec || {})}
return builder
} | AjDigitalDesign/portfoliov1 | studio/node_modules/@sanity/structure/src/List.ts | TypeScript |
ArrowFunction |
() => {
utils.logger(logGroup, 'ready');
this.sendEvent();
} | Wikia/ad-engine | src/ad-services/nativo/index.ts | TypeScript |
ClassDeclaration |
class Nativo {
call(): Promise<void> {
if (!this.isEnabled()) {
utils.logger(logGroup, 'disabled');
return Promise.resolve();
}
return utils.scriptLoader
.loadScript(libraryUrl, 'text/javascript', true, null, {}, { ntvSetNoAutoStart: '' })
.then(() => {
utils.logger(logGroup, 'ready');
this.sendEvent();
});
}
start(): void {
this.displayTestAd();
}
private sendEvent(): void {
communicationService.dispatch(nativoLoadedEvent({ isLoaded: true }));
}
private isEnabled(): boolean {
return context.get('services.nativo.enabled') && context.get('wiki.opts.enableNativeAds');
}
private displayTestAd(): void {
if (utils.queryString.get('native_ads_test') !== '1') {
return;
}
const nativeAdIncontentPlaceholder = document.getElementById('ntv-ad');
nativeAdIncontentPlaceholder.innerHTML = `<div class="ntv-wrapper">
<img
src="https://placekitten.com/100/100"
alt="mr. mittens"
class="ntv-img"
/>
<div class="ntv-content">
<p class="ntv-ad-label">AD · best buy</p>
<p class="ntv-ad-title">Buy Opla: Very good Astra 1.0 TDI</p>
<p class="ntv-ad-offer">Available from komis for $213.7</p>
<button class="ntv-ad-button">buy now</button>
</div>
</div>`;
}
} | Wikia/ad-engine | src/ad-services/nativo/index.ts | TypeScript |
MethodDeclaration |
call(): Promise<void> {
if (!this.isEnabled()) {
utils.logger(logGroup, 'disabled');
return Promise.resolve();
}
return utils.scriptLoader
.loadScript(libraryUrl, 'text/javascript', true, null, {}, { ntvSetNoAutoStart: '' })
.then(() => {
utils.logger(logGroup, 'ready');
this.sendEvent();
});
} | Wikia/ad-engine | src/ad-services/nativo/index.ts | TypeScript |
MethodDeclaration |
start(): void {
this.displayTestAd();
} | Wikia/ad-engine | src/ad-services/nativo/index.ts | TypeScript |
MethodDeclaration |
private sendEvent(): void {
communicationService.dispatch(nativoLoadedEvent({ isLoaded: true }));
} | Wikia/ad-engine | src/ad-services/nativo/index.ts | TypeScript |
MethodDeclaration |
private isEnabled(): boolean {
return context.get('services.nativo.enabled') && context.get('wiki.opts.enableNativeAds');
} | Wikia/ad-engine | src/ad-services/nativo/index.ts | TypeScript |
MethodDeclaration |
private displayTestAd(): void {
if (utils.queryString.get('native_ads_test') !== '1') {
return;
}
const nativeAdIncontentPlaceholder = document.getElementById('ntv-ad');
nativeAdIncontentPlaceholder.innerHTML = `<div class="ntv-wrapper">
<img
src="https://placekitten.com/100/100"
alt="mr. mittens"
class="ntv-img"
/>
<div class="ntv-content">
<p class="ntv-ad-label">AD · best buy</p>
<p class="ntv-ad-title">Buy Opla: Very good Astra 1.0 TDI</p>
<p class="ntv-ad-offer">Available from komis for $213.7</p>
<button class="ntv-ad-button">buy now</button>
</div>
</div>`;
} | Wikia/ad-engine | src/ad-services/nativo/index.ts | TypeScript |
FunctionDeclaration |
export async function on_get_plots(daemon: TDaemon, callback: (e: GetMessageType<chia_harvester_service, get_plots_command, TGetPlotsBroadCast>) => unknown){
await daemon.subscribe(wallet_ui_service);
const messageListener = (e: WsMessage) => {
if(e.origin === chia_harvester_service && e.command === get_plots_command){
callback(e);
}
};
return daemon.addMessageListener(chia_harvester_service, messageListener);
} | 1Megu/chia-agent | src/api/ws/harvester/index.ts | TypeScript |
FunctionDeclaration |
export async function on_message_from_harvester(daemon: TDaemon, callback: (e: GetMessageType<chia_harvester_service, chia_harvester_commands, TChiaHarvesterBroadcast>) => unknown){
await daemon.subscribe(wallet_ui_service);
const messageListener = (e: WsMessage) => {
if(e.origin === chia_harvester_service){
callback(e);
}
};
return daemon.addMessageListener(chia_harvester_service, messageListener);
} | 1Megu/chia-agent | src/api/ws/harvester/index.ts | TypeScript |
ArrowFunction |
(e: WsMessage) => {
if(e.origin === chia_harvester_service && e.command === get_plots_command){
callback(e);
}
} | 1Megu/chia-agent | src/api/ws/harvester/index.ts | TypeScript |
ArrowFunction |
(e: WsMessage) => {
if(e.origin === chia_harvester_service){
callback(e);
}
} | 1Megu/chia-agent | src/api/ws/harvester/index.ts | TypeScript |
TypeAliasDeclaration |
export type chia_harvester_service = typeof chia_harvester_service; | 1Megu/chia-agent | src/api/ws/harvester/index.ts | TypeScript |
TypeAliasDeclaration |
export type get_plots_command = typeof get_plots_command; | 1Megu/chia-agent | src/api/ws/harvester/index.ts | TypeScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.