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": 7,
"code_window": [
" const selectedOrg = useSelectedOrganization()\n",
"\n",
" const { data: integrations } = useOrgIntegrationsQuery({\n",
" orgSlug: selectedOrg?.slug,\n",
" })\n",
" const githubIntegration = integrations?.find(\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isBranch = project?.parent_project_ref !== undefined\n",
" const projectRef =\n",
" project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined\n",
"\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "add",
"edit_start_line_idx": 26
} | <svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M4.55762 4.87402L9.07535 15.2056L10.2522 10.6476L15.0002 9.46582L4.55762 4.87402Z" fill="#92CEAC" stroke="#299764" stroke-miterlimit="10" stroke-linejoin="bevel"/>
<path d="M1.36621 1.63246L3.49715 3.82855" stroke="#299764" stroke-miterlimit="10"/>
<line x1="5.3623" y1="1.33521" x2="5.3623" y2="3.68408" stroke="#299764" stroke-miterlimit="10"/>
<line x1="3.41797" y1="5.55371" x2="1.05225" y2="5.55371" stroke="#299764" stroke-miterlimit="10"/>
</svg>
| apps/docs/public/img/icons/menu/realtime-light.svg | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017107052553910762,
0.00017107052553910762,
0.00017107052553910762,
0.00017107052553910762,
0
]
|
{
"id": 7,
"code_window": [
" const selectedOrg = useSelectedOrganization()\n",
"\n",
" const { data: integrations } = useOrgIntegrationsQuery({\n",
" orgSlug: selectedOrg?.slug,\n",
" })\n",
" const githubIntegration = integrations?.find(\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isBranch = project?.parent_project_ref !== undefined\n",
" const projectRef =\n",
" project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined\n",
"\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "add",
"edit_start_line_idx": 26
} | export { default as IconXSquare } from './IconXSquare' | packages/ui/src/components/Icon/icons/IconXSquare/index.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017639478028286248,
0.00017639478028286248,
0.00017639478028286248,
0.00017639478028286248,
0
]
|
{
"id": 8,
"code_window": [
" integration.organization.slug === selectedOrg?.slug\n",
" )\n",
" const githubConnection = githubIntegration?.connections.find(\n",
" (connection) => connection.supabase_project_ref === ref\n",
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n",
" const {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" (connection) => connection.supabase_project_ref === projectRef\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "replace",
"edit_start_line_idx": 35
} | import { isError, partition } from 'lodash'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useState } from 'react'
import {
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
Alert_Shadcn_,
Button,
IconAlertTriangle,
IconGitBranch,
IconSearch,
Input,
Modal,
} from 'ui'
import { useParams } from 'common'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
import AlertError from 'components/ui/AlertError'
import ConfirmationModal from 'components/ui/ConfirmationModal'
import TextConfirmModal from 'components/ui/Modals/TextConfirmModal'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useBranchDeleteMutation } from 'data/branches/branch-delete-mutation'
import { useBranchesDisableMutation } from 'data/branches/branches-disable-mutation'
import { Branch, useBranchesQuery } from 'data/branches/branches-query'
import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'
import { useSelectedOrganization, useSelectedProject, useStore } from 'hooks'
import { useAppUiStateSnapshot } from 'state/app'
import { MainBranchPanel } from './BranchPanels'
import CreateBranchSidePanel from './CreateBranchSidePanel'
import PreviewBranches from './PreviewBranches'
import PullRequests from './PullRequests'
const BranchManagement = () => {
const { ui } = useStore()
const router = useRouter()
const { ref } = useParams()
const projectDetails = useSelectedProject()
const selectedOrg = useSelectedOrganization()
const hasAccessToBranching =
selectedOrg?.opt_in_tags?.includes('PREVIEW_BRANCHES_OPT_IN') ?? false
const isBranch = projectDetails?.parent_project_ref !== undefined
const hasBranchEnabled = projectDetails?.is_branch_enabled
const projectRef =
projectDetails !== undefined ? (isBranch ? projectDetails.parent_project_ref : ref) : undefined
const snap = useAppUiStateSnapshot()
const [showCreateBranch, setShowCreateBranch] = useState(false)
const [showDisableBranching, setShowDisableBranching] = useState(false)
const [selectedBranchToDelete, setSelectedBranchToDelete] = useState<Branch>()
const {
data: integrations,
error: integrationsError,
isLoading: isLoadingIntegrations,
isError: isErrorIntegrations,
isSuccess: isSuccessIntegrations,
} = useOrgIntegrationsQuery({ orgSlug: selectedOrg?.slug })
const githubConnections = integrations
?.filter((integration) => integration.integration.name === 'GitHub')
.flatMap((integration) => integration.connections)
const githubConnection = githubConnections?.find(
(connection) => connection.supabase_project_ref === ref
)
const { data: branches } = useBranchesQuery({ projectRef })
const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)
const { mutate: deleteBranch, isLoading: isDeleting } = useBranchDeleteMutation({
onSuccess: () => {
if (selectedBranchToDelete?.project_ref === ref) {
ui.setNotification({
category: 'success',
message:
'Successfully deleted branch. You are now currently on the main branch of your project.',
})
router.push(`/project/${projectRef}/branches`)
} else {
ui.setNotification({ category: 'success', message: 'Successfully deleted branch' })
}
setSelectedBranchToDelete(undefined)
},
})
const { mutate: disableBranching, isLoading: isDisabling } = useBranchesDisableMutation({
onSuccess: () => {
ui.setNotification({
category: 'success',
message: 'Successfully disabled branching for project',
})
setShowDisableBranching(false)
},
})
const generateCreatePullRequestURL = (branch?: string) => {
if (githubConnection === undefined) return 'https://github.com'
return branch !== undefined
? `https://github.com/${githubConnection.metadata.name}/compare/${mainBranch?.git_branch}...${branch}`
: `https://github.com/${githubConnection.metadata.name}/compare`
}
const onConfirmDeleteBranch = () => {
if (selectedBranchToDelete == undefined) return console.error('No branch selected')
if (projectRef == undefined) return console.error('Project ref is required')
deleteBranch({ id: selectedBranchToDelete?.id, projectRef })
}
const onConfirmDisableBranching = () => {
if (projectRef == undefined) return console.error('Project ref is required')
if (!previewBranches) return console.error('No branches available')
disableBranching({ projectRef, branchIds: previewBranches?.map((branch) => branch.id) })
}
if (!hasBranchEnabled) {
// [Joshen] Some empty state here
return (
<ProductEmptyState title="Database Branching">
<p className="text-sm text-light">
{hasAccessToBranching
? 'Create preview branches to experiment changes to your database schema in a safe, non-destructible environment.'
: "Register for early access and you'll be contacted by email when your organization is enrolled in database branching."}
</p>
{hasAccessToBranching ? (
<div className="!mt-4">
<Button
icon={<IconGitBranch strokeWidth={1.5} />}
onClick={() => snap.setShowEnableBranchingModal(true)}
>
Enable branching
</Button>
</div>
) : (
<div className="flex items-center space-x-2 !mt-4">
<Link passHref href={'/'}>
<a rel="noreferrer" target="_blank">
<Button>Join waitlist</Button>
</a>
</Link>
<Link passHref href={'/'}>
<a rel="noreferrer" target="_blank">
<Button type="default">View the docs</Button>
</a>
</Link>
</div>
)}
</ProductEmptyState>
)
}
return (
<>
<ScaffoldContainer>
<ScaffoldSection>
<div className="col-span-12">
<h3 className="text-xl mb-8">Branch Manager</h3>
<div className="mb-6 flex items-center justify-between">
<div className="flex items-center space-x-2">
<Input placeholder="Search branch" size="small" icon={<IconSearch />} />
</div>
<Button onClick={() => setShowCreateBranch(true)}>Create preview branch</Button>
</div>
<div className="">
{isLoadingIntegrations && <GenericSkeletonLoader />}
{isErrorIntegrations && (
<AlertError
error={integrationsError}
subject="Failed to retrieve GitHub integration connection"
/>
)}
{isSuccessIntegrations && (
<>
<MainBranchPanel
repo={githubConnection?.metadata.name}
branch={mainBranch}
onSelectDisableBranching={() => setShowDisableBranching(true)}
/>
<PullRequests
previewBranches={previewBranches}
generateCreatePullRequestURL={generateCreatePullRequestURL}
onSelectDeleteBranch={setSelectedBranchToDelete}
/>
<PreviewBranches
generateCreatePullRequestURL={generateCreatePullRequestURL}
onSelectCreateBranch={() => setShowCreateBranch(true)}
onSelectDeleteBranch={setSelectedBranchToDelete}
/>
</>
)}
</div>
</div>
</ScaffoldSection>
</ScaffoldContainer>
<TextConfirmModal
size="medium"
visible={selectedBranchToDelete !== undefined}
onCancel={() => setSelectedBranchToDelete(undefined)}
onConfirm={() => onConfirmDeleteBranch()}
loading={isDeleting}
title="Delete branch"
confirmLabel="Delete branch"
confirmPlaceholder="Type in name of branch"
confirmString={selectedBranchToDelete?.name ?? ''}
text={`This will delete your database preview branch "${selectedBranchToDelete?.name}"`}
alert="You cannot recover this branch once it is deleted!"
/>
<ConfirmationModal
danger
size="medium"
loading={isDisabling}
visible={showDisableBranching}
header="Confirm disable branching for project"
buttonLabel="Confirm disable branching"
buttonLoadingLabel="Disabling branching..."
onSelectConfirm={() => onConfirmDisableBranching()}
onSelectCancel={() => setShowDisableBranching(false)}
>
<Modal.Content>
<div className="py-6">
<Alert_Shadcn_ variant="warning">
<IconAlertTriangle strokeWidth={2} />
<AlertTitle_Shadcn_>This action cannot be undone</AlertTitle_Shadcn_>
<AlertDescription_Shadcn_>
All database preview branches will be removed upon disabling branching. You may
still re-enable branching again thereafter, but your existing preview branches will
not be restored.
</AlertDescription_Shadcn_>
</Alert_Shadcn_>
<ul className="mt-4 space-y-5">
<li className="flex gap-3">
<div>
<strong className="text-sm">Before you disable branching, consider:</strong>
<ul className="space-y-2 mt-2 text-sm text-light">
<li className="list-disc ml-6">
Your project no longer requires database previews.
</li>
<li className="list-disc ml-6">
None of your database previews are currently being used in any app.
</li>
</ul>
</div>
</li>
</ul>
</div>
</Modal.Content>
</ConfirmationModal>
<CreateBranchSidePanel
visible={showCreateBranch}
onClose={() => setShowCreateBranch(false)}
/>
</>
)
}
export default BranchManagement
| studio/components/interfaces/BranchManagement/BranchManagement.tsx | 1 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.9990361928939819,
0.1218072921037674,
0.00016777699056547135,
0.00017516054504085332,
0.3145352602005005
]
|
{
"id": 8,
"code_window": [
" integration.organization.slug === selectedOrg?.slug\n",
" )\n",
" const githubConnection = githubIntegration?.connections.find(\n",
" (connection) => connection.supabase_project_ref === ref\n",
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n",
" const {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" (connection) => connection.supabase_project_ref === projectRef\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "replace",
"edit_start_line_idx": 35
} | export { default as IconList } from './IconList' | packages/ui/src/components/Icon/icons/IconList/index.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017732667038217187,
0.00017732667038217187,
0.00017732667038217187,
0.00017732667038217187,
0
]
|
{
"id": 8,
"code_window": [
" integration.organization.slug === selectedOrg?.slug\n",
" )\n",
" const githubConnection = githubIntegration?.connections.find(\n",
" (connection) => connection.supabase_project_ref === ref\n",
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n",
" const {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" (connection) => connection.supabase_project_ref === projectRef\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "replace",
"edit_start_line_idx": 35
} | .info {
}
@media (min-width: 768px) {
.info {
/* display: grid;
grid-template-columns: 1fr 2fr;
gap: calc(var(--space-4x) * var(--size));
font-size: calc(1em * var(--size)); */
padding: 0;
margin-bottom: calc(32px * var(--size));
margin-left: calc(160px * var(--size));
}
}
@media (max-width: 768px) {
.info {
flex-direction: column;
align-items: center;
}
}
.logo {
/* margin-bottom: var(--space-6x); */
/* max-width: 96px; */
font-size: 18px;
}
/* @media (min-width: 768px) {
.logo {
margin-bottom: 0;
font-size: calc(16px * var(--size));
}
} */
.date {
/* text-transform: uppercase; */
/* font-size: calc(18px * var(--size)); */
color: var(--lw-secondary-color);
}
.date-golden {
color: var(--gold-primary);
}
@media (min-width: 768px) {
.date {
margin-bottom: 0;
line-height: 1.15;
/* font-size: calc(20px * var(--size)); */
}
}
.created-by {
display: flex;
align-items: center;
color: var(--accents-4);
}
@media (min-width: 768px) {
.created-by {
margin-right: var(--space-4x);
}
}
.created-by-text {
white-space: nowrap;
margin-right: var(--space);
}
/* .created-by-logo {
height: calc(16px * var(--size));
display: inline-flex;
} */
.url {
color: var(--lw-secondary-color);
}
.url-golden {
color: var(--gold-primary);
}
| apps/www/components/LaunchWeek/7/Ticket/ticket-info.module.css | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00018116622231900692,
0.00017891889729071409,
0.00017563534493092448,
0.0001792790717445314,
0.0000017160523384518456
]
|
{
"id": 8,
"code_window": [
" integration.organization.slug === selectedOrg?.slug\n",
" )\n",
" const githubConnection = githubIntegration?.connections.find(\n",
" (connection) => connection.supabase_project_ref === ref\n",
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n",
" const {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" (connection) => connection.supabase_project_ref === projectRef\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "replace",
"edit_start_line_idx": 35
} | import type { PostgresColumn } from '@supabase/postgres-meta'
export interface Notification {
category: 'info' | 'error' | 'success' | 'loading'
message: string // Readable message for users to understand
description?: string
id?: string
error?: any // Optional: Any other errors that needs to be logged out in the console
progress?: number // Optional: For loading messages to show a progress bar (Out of 100)
duration?: number // Optional: How long to show the message for (ms)
metadata?: NotificationMetadata
}
interface NotificationMetadata {
[key: string]: any
}
export interface ChartIntervals {
key: 'minutely' | 'hourly' | 'daily' | '5min' | '15min' | '1hr' | '1day' | '7day'
label: string
startValue: number
startUnit: 'minute' | 'hour' | 'day'
format?: 'MMM D, h:mm:ssa' | 'MMM D, h:mma' | 'MMM D, ha' | 'MMM D'
}
export interface VaultSecret {
id: string
name: string
description: string
secret: string
decryptedSecret?: string
key_id: string
created_at: string
updated_at: string
}
export interface SchemaView {
id: number
name: string
schema: string
is_updatable: boolean
comment?: string
columns: PostgresColumn[]
}
| studio/types/ui.ts | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017870664305519313,
0.00017356235184706748,
0.00016812130343168974,
0.00017562646826263517,
0.000004143679234402953
]
|
{
"id": 9,
"code_window": [
" data: branches,\n",
" error: branchesError,\n",
" isLoading: isLoadingBranches,\n",
" isError: isErrorBranches,\n",
" isSuccess: isSuccessBranches,\n",
" } = useBranchesQuery({ projectRef: ref })\n",
" const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)\n",
"\n",
" const { data: allPullRequests } = useGithubPullRequestsQuery({\n",
" organizationIntegrationId: githubIntegration?.id,\n",
" repoOwner,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" } = useBranchesQuery({ projectRef })\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "replace",
"edit_start_line_idx": 45
} | import { Button, IconExternalLink, IconGitBranch } from 'ui'
import { Branch, useBranchesQuery } from 'data/branches/branches-query'
import { BranchContainer, BranchHeader, BranchPanel } from './BranchPanels'
import { useParams } from 'common'
import { useGithubPullRequestsQuery } from 'data/integrations/integrations-github-pull-requests-query'
import { partition } from 'lodash'
import { useSelectedOrganization } from 'hooks'
import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import AlertError from 'components/ui/AlertError'
interface PreviewBranchesProps {
generateCreatePullRequestURL: (branch?: string) => string
onSelectCreateBranch: () => void
onSelectDeleteBranch: (branch: Branch) => void
}
const PreviewBranches = ({
generateCreatePullRequestURL,
onSelectCreateBranch,
onSelectDeleteBranch,
}: PreviewBranchesProps) => {
const { ref } = useParams()
const selectedOrg = useSelectedOrganization()
const { data: integrations } = useOrgIntegrationsQuery({
orgSlug: selectedOrg?.slug,
})
const githubIntegration = integrations?.find(
(integration) =>
integration.integration.name === 'GitHub' &&
integration.organization.slug === selectedOrg?.slug
)
const githubConnection = githubIntegration?.connections.find(
(connection) => connection.supabase_project_ref === ref
)
const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []
const {
data: branches,
error: branchesError,
isLoading: isLoadingBranches,
isError: isErrorBranches,
isSuccess: isSuccessBranches,
} = useBranchesQuery({ projectRef: ref })
const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)
const { data: allPullRequests } = useGithubPullRequestsQuery({
organizationIntegrationId: githubIntegration?.id,
repoOwner,
repoName,
target: mainBranch?.git_branch,
})
const previewBranchesNotInPR = previewBranches.filter(
(branch) => !allPullRequests?.find((pr) => pr.branch === branch.git_branch)
)
return (
<>
{previewBranches.length > 0 && previewBranchesNotInPR.length > 0 && (
<BranchHeader markdown={previewBranches.length > 0 ? `#### Preview branches` : undefined} />
)}
{isLoadingBranches && (
<BranchContainer>
<div className="w-full">
<GenericSkeletonLoader />
</div>
</BranchContainer>
)}
{isErrorBranches && (
<BranchContainer>
<div className="w-full">
<AlertError error={branchesError} subject="Failed to retrieve GitHub branches" />
</div>
</BranchContainer>
)}
{isSuccessBranches && (
<>
{previewBranches.length === 0 ? (
<BranchContainer>
<div className="flex items-center flex-col justify-center w-full py-8">
<p>No database preview branches</p>
<p className="text-scale-1000">Database preview branches will be shown here</p>
<div className="w-[500px] border rounded-md mt-4">
<div className="px-5 py-3 bg-surface-100 flex items-center justify-between">
<div className="flex items-center space-x-4">
<IconGitBranch strokeWidth={2} className="text-scale-1100" />
<div>
<p>Create a preview branch</p>
<p className="text-scale-1000">Start developing in preview</p>
</div>
</div>
<Button type="default" onClick={() => onSelectCreateBranch()}>
Create preview branch
</Button>
</div>
<div className="px-5 py-3 border-t flex items-center justify-between">
<div>
<p>Not sure what to do?</p>
<p className="text-scale-1000">Browse our documentation</p>
</div>
<Button type="default" iconRight={<IconExternalLink />}>
Docs
</Button>
</div>
</div>
</div>
</BranchContainer>
) : (
previewBranchesNotInPR.map((branch) => (
<BranchPanel
key={branch.id}
branch={branch}
generateCreatePullRequestURL={generateCreatePullRequestURL}
onSelectDelete={() => onSelectDeleteBranch(branch)}
/>
))
)}
</>
)}
</>
)
}
export default PreviewBranches
| studio/components/interfaces/BranchManagement/PreviewBranches.tsx | 1 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.9989866614341736,
0.366771399974823,
0.0001676452229730785,
0.022931870073080063,
0.4703136086463928
]
|
{
"id": 9,
"code_window": [
" data: branches,\n",
" error: branchesError,\n",
" isLoading: isLoadingBranches,\n",
" isError: isErrorBranches,\n",
" isSuccess: isSuccessBranches,\n",
" } = useBranchesQuery({ projectRef: ref })\n",
" const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)\n",
"\n",
" const { data: allPullRequests } = useGithubPullRequestsQuery({\n",
" organizationIntegrationId: githubIntegration?.id,\n",
" repoOwner,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" } = useBranchesQuery({ projectRef })\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "replace",
"edit_start_line_idx": 45
} | import { PermissionAction } from '@supabase/shared-types/out/constants'
import { observer } from 'mobx-react-lite'
import { useEffect } from 'react'
import { Form, Input } from 'ui'
import { boolean, number, object, string } from 'yup'
import {
FormActions,
FormHeader,
FormPanel,
FormSection,
FormSectionContent,
} from 'components/ui/Forms'
import { useCheckPermissions, useSelectedProject, useStore } from 'hooks'
const SiteUrl = observer(() => {
const { authConfig, ui } = useStore()
const { isLoaded } = authConfig
const formId = 'auth-config-general-form'
const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')
const INITIAL_VALUES = {
DISABLE_SIGNUP: !authConfig.config.DISABLE_SIGNUP,
JWT_EXP: authConfig.config.JWT_EXP,
SITE_URL: authConfig.config.SITE_URL,
REFRESH_TOKEN_ROTATION_ENABLED: authConfig.config.REFRESH_TOKEN_ROTATION_ENABLED || false,
SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: authConfig.config.SECURITY_REFRESH_TOKEN_REUSE_INTERVAL,
SECURITY_CAPTCHA_ENABLED: authConfig.config.SECURITY_CAPTCHA_ENABLED || false,
SECURITY_CAPTCHA_PROVIDER: authConfig.config.SECURITY_CAPTCHA_PROVIDER || 'hcaptcha',
SECURITY_CAPTCHA_SECRET: authConfig.config.SECURITY_CAPTCHA_SECRET || '',
}
const schema = object({
DISABLE_SIGNUP: boolean().required(),
SITE_URL: string().required('Must have a Site URL'),
JWT_EXP: number()
.max(604800, 'Must be less than 604800')
.required('Must have a JWT expiry value'),
REFRESH_TOKEN_ROTATION_ENABLED: boolean().required(),
SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: number()
.min(0, 'Must be a value more than 0')
.required('Must have a Reuse Interval value'),
SECURITY_CAPTCHA_ENABLED: boolean().required(),
SECURITY_CAPTCHA_SECRET: string().when('SECURITY_CAPTCHA_ENABLED', {
is: true,
then: string().required('Must have a Captcha secret'),
}),
})
const onSubmit = async (values: any, { setSubmitting, resetForm }: any) => {
const payload = { ...values }
payload.DISABLE_SIGNUP = !values.DISABLE_SIGNUP
setSubmitting(true)
const { error } = await authConfig.update(payload)
if (!error) {
ui.setNotification({
category: 'success',
message: `Successfully updated settings`,
})
resetForm({ values: values, initialValues: values })
} else {
ui.setNotification({
category: 'error',
message: `Failed to update settings`,
})
}
setSubmitting(false)
}
return (
<Form id={formId} initialValues={INITIAL_VALUES} onSubmit={onSubmit} validationSchema={schema}>
{({ isSubmitting, handleReset, resetForm, values, initialValues }: any) => {
const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
// Form is reset once remote data is loaded in store
useEffect(() => {
resetForm({ values: INITIAL_VALUES, initialValues: INITIAL_VALUES })
}, [authConfig.isLoaded])
return (
<>
<FormHeader
title="Site URL"
description="Configure the url of your site. This is used for password reset emails and other links."
/>
<FormPanel
disabled={true}
footer={
<div className="flex py-4 px-8">
<FormActions
form={formId}
isSubmitting={isSubmitting}
hasChanges={hasChanges}
handleReset={handleReset}
disabled={!canUpdateConfig}
helper={
!canUpdateConfig
? 'You need additional permissions to update authentication settings'
: undefined
}
/>
</div>
}
>
<FormSection>
<FormSectionContent loading={!isLoaded}>
<Input
id="SITE_URL"
size="small"
label="Site URL"
descriptionText="The base URL of your website. Used as an allow-list for redirects and for constructing URLs used in emails."
disabled={!canUpdateConfig}
/>
</FormSectionContent>
</FormSection>
</FormPanel>
</>
)
}}
</Form>
)
})
export default SiteUrl
| studio/components/interfaces/Auth/SiteUrl/SiteUrl.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017552134522702545,
0.0001694596285233274,
0.00016177084762603045,
0.00016986105765681714,
0.0000032868383641471155
]
|
{
"id": 9,
"code_window": [
" data: branches,\n",
" error: branchesError,\n",
" isLoading: isLoadingBranches,\n",
" isError: isErrorBranches,\n",
" isSuccess: isSuccessBranches,\n",
" } = useBranchesQuery({ projectRef: ref })\n",
" const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)\n",
"\n",
" const { data: allPullRequests } = useGithubPullRequestsQuery({\n",
" organizationIntegrationId: githubIntegration?.id,\n",
" repoOwner,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" } = useBranchesQuery({ projectRef })\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "replace",
"edit_start_line_idx": 45
} | // DO NOT EDIT
// this file is generated by /internals/populate-icons script
import * as React from 'react'
// @ts-ignore
import { FolderPlus } from 'react-feather'
import IconBase from './../../IconBase'
function IconFolderPlus(props: any) {
return <IconBase icon={FolderPlus} {...props} />
}
export default IconFolderPlus
| packages/ui/src/components/Icon/icons/IconFolderPlus/IconFolderPlus.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.0001777441066224128,
0.00017659056175034493,
0.00017543701687827706,
0.00017659056175034493,
0.0000011535448720678687
]
|
{
"id": 9,
"code_window": [
" data: branches,\n",
" error: branchesError,\n",
" isLoading: isLoadingBranches,\n",
" isError: isErrorBranches,\n",
" isSuccess: isSuccessBranches,\n",
" } = useBranchesQuery({ projectRef: ref })\n",
" const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)\n",
"\n",
" const { data: allPullRequests } = useGithubPullRequestsQuery({\n",
" organizationIntegrationId: githubIntegration?.id,\n",
" repoOwner,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" } = useBranchesQuery({ projectRef })\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PreviewBranches.tsx",
"type": "replace",
"edit_start_line_idx": 45
} | import SubscriptionV2 from 'components/interfaces/BillingV2/Subscription/Subscription'
import { SettingsLayout } from 'components/layouts'
import { useSelectedOrganization } from 'hooks'
import { NextPageWithLayout } from 'types'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
const ProjectBilling: NextPageWithLayout = () => {
const organization = useSelectedOrganization()
const isOrgBilling = !!organization?.subscription_id
const router = useRouter()
useEffect(() => {
if (isOrgBilling) {
const { ref, panel } = router.query
let redirectUri = `/org/${organization.slug}/billing`
switch (panel) {
case 'subscriptionPlan':
redirectUri = `/org/${organization.slug}/billing?panel=subscriptionPlan`
break
case 'costControl':
redirectUri = `/org/${organization.slug}/billing?panel=costControl`
break
case 'computeInstance':
redirectUri = `/project/${ref}/settings/addons?panel=computeInstance`
break
case 'pitr':
redirectUri = `/project/${ref}/settings/addons?panel=pitr`
break
case 'customDomain':
redirectUri = `/project/${ref}/settings/addons?panel=customDomain`
break
}
router.push(redirectUri)
}
}, [router, organization?.slug, isOrgBilling])
// No need to bother rendering, we'll redirect anyway
if (isOrgBilling) {
return null
}
return <SubscriptionV2 />
}
ProjectBilling.getLayout = (page) => (
<SettingsLayout title="Billing and Usage">{page}</SettingsLayout>
)
export default ProjectBilling
| studio/pages/project/[ref]/settings/billing/subscription.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.0021439355332404375,
0.0007061606738716364,
0.00016488406981807202,
0.00043357795220799744,
0.0006795934168621898
]
|
{
"id": 10,
"code_window": [
"\n",
"import { useParams } from 'common'\n",
"import { Branch, useBranchesQuery } from 'data/branches/branches-query'\n",
"import { useGithubPullRequestsQuery } from 'data/integrations/integrations-github-pull-requests-query'\n",
"import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'\n",
"import { useSelectedOrganization } from 'hooks'\n",
"import { BranchContainer, BranchHeader, PullRequestPanel } from './BranchPanels'\n",
"import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'\n",
"import AlertError from 'components/ui/AlertError'\n",
"\n",
"interface PullRequestsProps {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { useSelectedOrganization, useSelectedProject } from 'hooks'\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 7
} | import Link from 'next/link'
import { Button, IconExternalLink, IconGitBranch } from 'ui'
import { useParams } from 'common'
import { Branch, useBranchesQuery } from 'data/branches/branches-query'
import { useGithubPullRequestsQuery } from 'data/integrations/integrations-github-pull-requests-query'
import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'
import { useSelectedOrganization } from 'hooks'
import { BranchContainer, BranchHeader, PullRequestPanel } from './BranchPanels'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import AlertError from 'components/ui/AlertError'
interface PullRequestsProps {
previewBranches: Branch[]
generateCreatePullRequestURL: (branch?: string) => string
onSelectDeleteBranch: (branch: Branch) => void
}
const PullRequests = ({
previewBranches,
generateCreatePullRequestURL,
onSelectDeleteBranch,
}: PullRequestsProps) => {
const { ref } = useParams()
const selectedOrg = useSelectedOrganization()
const pullRequestUrl = generateCreatePullRequestURL()
const { data: integrations, isLoading: isLoadingIntegrations } = useOrgIntegrationsQuery({
orgSlug: selectedOrg?.slug,
})
const githubIntegration = integrations?.find(
(integration) =>
integration.integration.name === 'GitHub' &&
integration.organization.slug === selectedOrg?.slug
)
const githubConnection = githubIntegration?.connections?.find(
(connection) => connection.supabase_project_ref === ref
)
const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []
const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef: ref })
const mainBranch = branches?.find((branch) => branch.is_default)
const {
data: allPullRequests,
error: pullRequestsError,
isLoading: isLoadingPullRequests,
isError: isErrorPullRequests,
isSuccess: isSuccessPullRequests,
} = useGithubPullRequestsQuery({
organizationIntegrationId: githubIntegration?.id,
repoOwner,
repoName,
target: mainBranch?.git_branch,
})
const pullRequests = allPullRequests?.filter((pr) =>
branches?.some((branch) => branch.git_branch === pr.branch)
)
const showEmptyState = previewBranches.length === 0 || (pullRequests || []).length === 0
return (
<>
<BranchHeader
markdown={!showEmptyState ? `#### Preview branches in pull requests` : undefined}
/>
{(isLoadingBranches || isLoadingPullRequests || isLoadingIntegrations) && (
<BranchContainer>
<div className="w-full">
<GenericSkeletonLoader />
</div>
</BranchContainer>
)}
{isErrorPullRequests && (
<BranchContainer>
<div className="w-full">
<AlertError
error={pullRequestsError}
subject="Failed to retrieve GitHub pull requests"
/>
</div>
</BranchContainer>
)}
{isSuccessPullRequests && (
<>
{showEmptyState ? (
<BranchContainer>
<div className="flex items-center flex-col justify-center w-full py-8">
<p>No pull requests made yet for this repository</p>
<p className="text-scale-1000">
Only pull requests with the ./migration directory changes will show here.
</p>
{previewBranches.length > 0 && (
<div className="w-96 border rounded-md mt-4">
<div className="px-5 py-3 bg-surface-100 flex items-center justify-between">
<div className="flex items-center space-x-4">
<IconGitBranch strokeWidth={2} className="text-scale-1100" />
<p>Create a pull request</p>
</div>
<Link passHref href={pullRequestUrl}>
<a target="_blank" rel="noreferrer">
<Button type="default" iconRight={<IconExternalLink />}>
Github
</Button>
</a>
</Link>
</div>
<div className="px-5 py-3 border-t flex items-center justify-between">
<div>
<p>Not sure what to do?</p>
<p className="text-scale-1000">Browse our documentation</p>
</div>
<Button type="default" iconRight={<IconExternalLink />}>
Docs
</Button>
</div>
</div>
)}
</div>
</BranchContainer>
) : (
pullRequests?.map((pr) => {
const branch = branches?.find((branch) => branch.git_branch === pr.branch)
return (
<PullRequestPanel
key={pr.id}
pr={pr}
onSelectDelete={() => {
if (branch !== undefined) onSelectDeleteBranch(branch)
}}
/>
)
})
)}
</>
)}
</>
)
}
export default PullRequests
| studio/components/interfaces/BranchManagement/PullRequests.tsx | 1 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.9894571900367737,
0.12915602326393127,
0.00016876455629244447,
0.0017500625690445304,
0.32200887799263
]
|
{
"id": 10,
"code_window": [
"\n",
"import { useParams } from 'common'\n",
"import { Branch, useBranchesQuery } from 'data/branches/branches-query'\n",
"import { useGithubPullRequestsQuery } from 'data/integrations/integrations-github-pull-requests-query'\n",
"import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'\n",
"import { useSelectedOrganization } from 'hooks'\n",
"import { BranchContainer, BranchHeader, PullRequestPanel } from './BranchPanels'\n",
"import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'\n",
"import AlertError from 'components/ui/AlertError'\n",
"\n",
"interface PullRequestsProps {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { useSelectedOrganization, useSelectedProject } from 'hooks'\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 7
} |
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="14.2222in" height="14.2222in" version="1.1" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
viewBox="0 0 14222 14222"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<style type="text/css">
<![CDATA[
.fil0 {fill:#1977F3;fill-rule:nonzero}
.fil1 {fill:#FEFEFE;fill-rule:nonzero}
]]>
</style>
</defs>
<g id="Layer_x0020_1">
<metadata id="CorelCorpID_0Corel-Layer"/>
<path class="fil0" d="M14222 7111c0,-3927 -3184,-7111 -7111,-7111 -3927,0 -7111,3184 -7111,7111 0,3549 2600,6491 6000,7025l0 -4969 -1806 0 0 -2056 1806 0 0 -1567c0,-1782 1062,-2767 2686,-2767 778,0 1592,139 1592,139l0 1750 -897 0c-883,0 -1159,548 -1159,1111l0 1334 1972 0 -315 2056 -1657 0 0 4969c3400,-533 6000,-3475 6000,-7025z"/>
<path class="fil1" d="M9879 9167l315 -2056 -1972 0 0 -1334c0,-562 275,-1111 1159,-1111l897 0 0 -1750c0,0 -814,-139 -1592,-139 -1624,0 -2686,984 -2686,2767l0 1567 -1806 0 0 2056 1806 0 0 4969c362,57 733,86 1111,86 378,0 749,-30 1111,-86l0 -4969 1657 0z"/>
</g>
</svg>
| apps/www/public/images/product/auth/facebook-icon.svg | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.0001734051911626011,
0.00016880979819688946,
0.0001642144052311778,
0.00016880979819688946,
0.000004595392965711653
]
|
{
"id": 10,
"code_window": [
"\n",
"import { useParams } from 'common'\n",
"import { Branch, useBranchesQuery } from 'data/branches/branches-query'\n",
"import { useGithubPullRequestsQuery } from 'data/integrations/integrations-github-pull-requests-query'\n",
"import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'\n",
"import { useSelectedOrganization } from 'hooks'\n",
"import { BranchContainer, BranchHeader, PullRequestPanel } from './BranchPanels'\n",
"import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'\n",
"import AlertError from 'components/ui/AlertError'\n",
"\n",
"interface PullRequestsProps {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { useSelectedOrganization, useSelectedProject } from 'hooks'\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 7
} |
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>'Postgres | Supabase Blog</title>
<link>https://supabase.com/blog</link>
<description>Latest Postgres news from Egor Romanov at Supabase</description>
<language>en</language>
<lastBuildDate>Wed, 02 Aug 2023 22:00:00 GMT</lastBuildDate>
<atom:link href="https://supabase.com/planetpg-egor_romanov-rss.xml" rel="self" type="application/rss+xml"/>
<item>
<guid>https://supabase.com/blog/fewer-dimensions-are-better-pgvector</guid>
<title>pgvector: Fewer dimensions are better</title>
<link>https://supabase.com/blog/fewer-dimensions-are-better-pgvector</link>
<description>Increase performance in pgvector by using embedding vectors with fewer dimensions</description>
<pubDate>Wed, 02 Aug 2023 22:00:00 GMT</pubDate>
</item>
<item>
<guid>https://supabase.com/blog/pgvector-performance</guid>
<title>pgvector 0.4.0 performance</title>
<link>https://supabase.com/blog/pgvector-performance</link>
<description>There's been lot of talk about pgvector performance lately, so we took some datasets and pushed pgvector to the limits to find out its strengths and limitations.</description>
<pubDate>Wed, 12 Jul 2023 22:00:00 GMT</pubDate>
</item>
</channel>
</rss>
| apps/www/public/planetpg-egor_romanov-rss.xml | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017649555229581892,
0.0001727341441437602,
0.00016700749984011054,
0.0001746993511915207,
0.000004115202955290442
]
|
{
"id": 10,
"code_window": [
"\n",
"import { useParams } from 'common'\n",
"import { Branch, useBranchesQuery } from 'data/branches/branches-query'\n",
"import { useGithubPullRequestsQuery } from 'data/integrations/integrations-github-pull-requests-query'\n",
"import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'\n",
"import { useSelectedOrganization } from 'hooks'\n",
"import { BranchContainer, BranchHeader, PullRequestPanel } from './BranchPanels'\n",
"import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'\n",
"import AlertError from 'components/ui/AlertError'\n",
"\n",
"interface PullRequestsProps {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { useSelectedOrganization, useSelectedProject } from 'hooks'\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 7
} | export { default as IconSmartphone } from './IconSmartphone' | packages/ui/src/components/Icon/icons/IconSmartphone/index.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.0001725376641843468,
0.0001725376641843468,
0.0001725376641843468,
0.0001725376641843468,
0
]
|
{
"id": 11,
"code_window": [
" onSelectDeleteBranch,\n",
"}: PullRequestsProps) => {\n",
" const { ref } = useParams()\n",
" const selectedOrg = useSelectedOrganization()\n",
" const pullRequestUrl = generateCreatePullRequestURL()\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const project = useSelectedProject()\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "add",
"edit_start_line_idx": 24
} | import { Button, IconExternalLink, IconGitBranch } from 'ui'
import { Branch, useBranchesQuery } from 'data/branches/branches-query'
import { BranchContainer, BranchHeader, BranchPanel } from './BranchPanels'
import { useParams } from 'common'
import { useGithubPullRequestsQuery } from 'data/integrations/integrations-github-pull-requests-query'
import { partition } from 'lodash'
import { useSelectedOrganization } from 'hooks'
import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import AlertError from 'components/ui/AlertError'
interface PreviewBranchesProps {
generateCreatePullRequestURL: (branch?: string) => string
onSelectCreateBranch: () => void
onSelectDeleteBranch: (branch: Branch) => void
}
const PreviewBranches = ({
generateCreatePullRequestURL,
onSelectCreateBranch,
onSelectDeleteBranch,
}: PreviewBranchesProps) => {
const { ref } = useParams()
const selectedOrg = useSelectedOrganization()
const { data: integrations } = useOrgIntegrationsQuery({
orgSlug: selectedOrg?.slug,
})
const githubIntegration = integrations?.find(
(integration) =>
integration.integration.name === 'GitHub' &&
integration.organization.slug === selectedOrg?.slug
)
const githubConnection = githubIntegration?.connections.find(
(connection) => connection.supabase_project_ref === ref
)
const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []
const {
data: branches,
error: branchesError,
isLoading: isLoadingBranches,
isError: isErrorBranches,
isSuccess: isSuccessBranches,
} = useBranchesQuery({ projectRef: ref })
const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)
const { data: allPullRequests } = useGithubPullRequestsQuery({
organizationIntegrationId: githubIntegration?.id,
repoOwner,
repoName,
target: mainBranch?.git_branch,
})
const previewBranchesNotInPR = previewBranches.filter(
(branch) => !allPullRequests?.find((pr) => pr.branch === branch.git_branch)
)
return (
<>
{previewBranches.length > 0 && previewBranchesNotInPR.length > 0 && (
<BranchHeader markdown={previewBranches.length > 0 ? `#### Preview branches` : undefined} />
)}
{isLoadingBranches && (
<BranchContainer>
<div className="w-full">
<GenericSkeletonLoader />
</div>
</BranchContainer>
)}
{isErrorBranches && (
<BranchContainer>
<div className="w-full">
<AlertError error={branchesError} subject="Failed to retrieve GitHub branches" />
</div>
</BranchContainer>
)}
{isSuccessBranches && (
<>
{previewBranches.length === 0 ? (
<BranchContainer>
<div className="flex items-center flex-col justify-center w-full py-8">
<p>No database preview branches</p>
<p className="text-scale-1000">Database preview branches will be shown here</p>
<div className="w-[500px] border rounded-md mt-4">
<div className="px-5 py-3 bg-surface-100 flex items-center justify-between">
<div className="flex items-center space-x-4">
<IconGitBranch strokeWidth={2} className="text-scale-1100" />
<div>
<p>Create a preview branch</p>
<p className="text-scale-1000">Start developing in preview</p>
</div>
</div>
<Button type="default" onClick={() => onSelectCreateBranch()}>
Create preview branch
</Button>
</div>
<div className="px-5 py-3 border-t flex items-center justify-between">
<div>
<p>Not sure what to do?</p>
<p className="text-scale-1000">Browse our documentation</p>
</div>
<Button type="default" iconRight={<IconExternalLink />}>
Docs
</Button>
</div>
</div>
</div>
</BranchContainer>
) : (
previewBranchesNotInPR.map((branch) => (
<BranchPanel
key={branch.id}
branch={branch}
generateCreatePullRequestURL={generateCreatePullRequestURL}
onSelectDelete={() => onSelectDeleteBranch(branch)}
/>
))
)}
</>
)}
</>
)
}
export default PreviewBranches
| studio/components/interfaces/BranchManagement/PreviewBranches.tsx | 1 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.9989224672317505,
0.2482093721628189,
0.000165961857419461,
0.0011801058426499367,
0.3965136408805847
]
|
{
"id": 11,
"code_window": [
" onSelectDeleteBranch,\n",
"}: PullRequestsProps) => {\n",
" const { ref } = useParams()\n",
" const selectedOrg = useSelectedOrganization()\n",
" const pullRequestUrl = generateCreatePullRequestURL()\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const project = useSelectedProject()\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "add",
"edit_start_line_idx": 24
} | import fs from 'fs'
import yaml from 'js-yaml'
import cliCommonSections from '../../../../spec/common-cli-sections.json' assert { type: 'json' }
import { flattenSections } from '../helpers.mjs'
const flatCLISections = flattenSections(cliCommonSections)
const cliSpec = yaml.load(fs.readFileSync(`../../spec/cli_v1_commands.yaml`, 'utf8'))
export function generateCLIPages() {
let cliPages = []
cliSpec.commands.map((section) => {
const slug = flatCLISections.find((item) => item.id === section.id)?.slug
if (slug) cliPages.push(`reference/cli/${slug}`)
})
return cliPages
}
| apps/docs/internals/files/cli.mjs | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017585017485544086,
0.00017125607701018453,
0.00016666199371684343,
0.00017125607701018453,
0.000004594090569298714
]
|
{
"id": 11,
"code_window": [
" onSelectDeleteBranch,\n",
"}: PullRequestsProps) => {\n",
" const { ref } = useParams()\n",
" const selectedOrg = useSelectedOrganization()\n",
" const pullRequestUrl = generateCreatePullRequestURL()\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const project = useSelectedProject()\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "add",
"edit_start_line_idx": 24
} | import React from 'react'
import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
import { LogsLayout } from 'components/layouts'
import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'
import { NextPageWithLayout } from 'types'
export const LogPage: NextPageWithLayout = () => {
const router = useRouter()
const { ref } = router.query
return (
<LogsPreviewer
projectRef={ref as string}
condensedLayout={true}
// @ts-ignore
tableName={'edge_logs'}
queryType={'api'}
/>
)
}
LogPage.getLayout = (page) => <LogsLayout title="Database">{page}</LogsLayout>
export default observer(LogPage)
| studio/pages/project/[ref]/logs/edge-logs.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.2979719340801239,
0.10056066513061523,
0.0001733777462504804,
0.0035366711672395468,
0.13959760963916779
]
|
{
"id": 11,
"code_window": [
" onSelectDeleteBranch,\n",
"}: PullRequestsProps) => {\n",
" const { ref } = useParams()\n",
" const selectedOrg = useSelectedOrganization()\n",
" const pullRequestUrl = generateCreatePullRequestURL()\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const project = useSelectedProject()\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "add",
"edit_start_line_idx": 24
} | .sbui-toast-container {
@apply max-w-xs w-full shadow-lg rounded-md pointer-events-auto overflow-hidden py-4 px-2;
@apply border border-solid;
@apply bg-white border-gray-300;
@apply dark:bg-dark-700 dark:border-gray-400;
}
.sbui-toast-container--sm {
@apply max-w-sm;
}
.sbui-toast-container--md {
@apply max-w-md;
}
.sbui-toast-container.sbui-toast-container--success {
@apply border border-solid border-green-500;
}
.sbui-toast-container.sbui-toast-container--error {
@apply border border-solid border-red-500;
}
.sbui-toast-container > div {
@apply flex items-start;
}
.sbui-toast-icon-container {
@apply flex-shrink-0 text-sm;
}
.sbui-toast-details {
@apply ml-3 w-0 flex flex-1 justify-between;
}
.sbui-toast-details--actions-bottom {
@apply flex-col;
}
.sbui-toast-details--actions-bottom .sbui-toast-details__actions {
@apply mt-4;
}
.sbui-toast-details__content {
@apply flex flex-col;
}
.sbui-toast-message {
@apply m-0 text-sm font-medium text-gray-900;
}
.sbui-toast-description {
@apply m-0 mt-1 text-sm font-normal text-gray-500;
}
.sbui-toast-details__actions {
@apply flex space-x-4;
}
.sbui-toast-close-container {
@apply ml-4 flex-shrink-0 flex;
}
.sbui-toast-close-button {
@apply bg-transparent rounded-md inline-flex text-gray-400 hover:text-gray-500 focus:outline-none cursor-pointer border-0;
}
.sbui-toast-container--success .sbui-toast-icon-container {
@apply text-green-500;
}
.sbui-toast-container--error .sbui-toast-icon-container {
@apply text-red-500;
}
.sbui-alert--anim--spin {
@apply stroke-current;
animation-name: spin;
animation-duration: 1500ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
/* transform: rotate(3deg); */
/* transform: rotate(0.3rad);/ */
/* transform: rotate(3grad); */
/* transform: rotate(.03turn); */
transform-origin: center center;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
div[data-radix-portal]:not(.portal--toast) {
/*
override z-index to be lower than radix value of 2147483647
except for the toast portal
*/
z-index: 2147483646 !important;
}
| packages/ui/src/components/Toast/Toast.module.css | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.0001759897277224809,
0.00017429812578484416,
0.0001721695443848148,
0.00017455882334616035,
0.0000012336159898040933
]
|
{
"id": 12,
"code_window": [
" const selectedOrg = useSelectedOrganization()\n",
" const pullRequestUrl = generateCreatePullRequestURL()\n",
"\n",
" const { data: integrations, isLoading: isLoadingIntegrations } = useOrgIntegrationsQuery({\n",
" orgSlug: selectedOrg?.slug,\n",
" })\n",
" const githubIntegration = integrations?.find(\n",
" (integration) =>\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isBranch = project?.parent_project_ref !== undefined\n",
" const projectRef =\n",
" project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined\n",
"\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "add",
"edit_start_line_idx": 27
} | import { isError, partition } from 'lodash'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useState } from 'react'
import {
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
Alert_Shadcn_,
Button,
IconAlertTriangle,
IconGitBranch,
IconSearch,
Input,
Modal,
} from 'ui'
import { useParams } from 'common'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
import AlertError from 'components/ui/AlertError'
import ConfirmationModal from 'components/ui/ConfirmationModal'
import TextConfirmModal from 'components/ui/Modals/TextConfirmModal'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useBranchDeleteMutation } from 'data/branches/branch-delete-mutation'
import { useBranchesDisableMutation } from 'data/branches/branches-disable-mutation'
import { Branch, useBranchesQuery } from 'data/branches/branches-query'
import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'
import { useSelectedOrganization, useSelectedProject, useStore } from 'hooks'
import { useAppUiStateSnapshot } from 'state/app'
import { MainBranchPanel } from './BranchPanels'
import CreateBranchSidePanel from './CreateBranchSidePanel'
import PreviewBranches from './PreviewBranches'
import PullRequests from './PullRequests'
const BranchManagement = () => {
const { ui } = useStore()
const router = useRouter()
const { ref } = useParams()
const projectDetails = useSelectedProject()
const selectedOrg = useSelectedOrganization()
const hasAccessToBranching =
selectedOrg?.opt_in_tags?.includes('PREVIEW_BRANCHES_OPT_IN') ?? false
const isBranch = projectDetails?.parent_project_ref !== undefined
const hasBranchEnabled = projectDetails?.is_branch_enabled
const projectRef =
projectDetails !== undefined ? (isBranch ? projectDetails.parent_project_ref : ref) : undefined
const snap = useAppUiStateSnapshot()
const [showCreateBranch, setShowCreateBranch] = useState(false)
const [showDisableBranching, setShowDisableBranching] = useState(false)
const [selectedBranchToDelete, setSelectedBranchToDelete] = useState<Branch>()
const {
data: integrations,
error: integrationsError,
isLoading: isLoadingIntegrations,
isError: isErrorIntegrations,
isSuccess: isSuccessIntegrations,
} = useOrgIntegrationsQuery({ orgSlug: selectedOrg?.slug })
const githubConnections = integrations
?.filter((integration) => integration.integration.name === 'GitHub')
.flatMap((integration) => integration.connections)
const githubConnection = githubConnections?.find(
(connection) => connection.supabase_project_ref === ref
)
const { data: branches } = useBranchesQuery({ projectRef })
const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)
const { mutate: deleteBranch, isLoading: isDeleting } = useBranchDeleteMutation({
onSuccess: () => {
if (selectedBranchToDelete?.project_ref === ref) {
ui.setNotification({
category: 'success',
message:
'Successfully deleted branch. You are now currently on the main branch of your project.',
})
router.push(`/project/${projectRef}/branches`)
} else {
ui.setNotification({ category: 'success', message: 'Successfully deleted branch' })
}
setSelectedBranchToDelete(undefined)
},
})
const { mutate: disableBranching, isLoading: isDisabling } = useBranchesDisableMutation({
onSuccess: () => {
ui.setNotification({
category: 'success',
message: 'Successfully disabled branching for project',
})
setShowDisableBranching(false)
},
})
const generateCreatePullRequestURL = (branch?: string) => {
if (githubConnection === undefined) return 'https://github.com'
return branch !== undefined
? `https://github.com/${githubConnection.metadata.name}/compare/${mainBranch?.git_branch}...${branch}`
: `https://github.com/${githubConnection.metadata.name}/compare`
}
const onConfirmDeleteBranch = () => {
if (selectedBranchToDelete == undefined) return console.error('No branch selected')
if (projectRef == undefined) return console.error('Project ref is required')
deleteBranch({ id: selectedBranchToDelete?.id, projectRef })
}
const onConfirmDisableBranching = () => {
if (projectRef == undefined) return console.error('Project ref is required')
if (!previewBranches) return console.error('No branches available')
disableBranching({ projectRef, branchIds: previewBranches?.map((branch) => branch.id) })
}
if (!hasBranchEnabled) {
// [Joshen] Some empty state here
return (
<ProductEmptyState title="Database Branching">
<p className="text-sm text-light">
{hasAccessToBranching
? 'Create preview branches to experiment changes to your database schema in a safe, non-destructible environment.'
: "Register for early access and you'll be contacted by email when your organization is enrolled in database branching."}
</p>
{hasAccessToBranching ? (
<div className="!mt-4">
<Button
icon={<IconGitBranch strokeWidth={1.5} />}
onClick={() => snap.setShowEnableBranchingModal(true)}
>
Enable branching
</Button>
</div>
) : (
<div className="flex items-center space-x-2 !mt-4">
<Link passHref href={'/'}>
<a rel="noreferrer" target="_blank">
<Button>Join waitlist</Button>
</a>
</Link>
<Link passHref href={'/'}>
<a rel="noreferrer" target="_blank">
<Button type="default">View the docs</Button>
</a>
</Link>
</div>
)}
</ProductEmptyState>
)
}
return (
<>
<ScaffoldContainer>
<ScaffoldSection>
<div className="col-span-12">
<h3 className="text-xl mb-8">Branch Manager</h3>
<div className="mb-6 flex items-center justify-between">
<div className="flex items-center space-x-2">
<Input placeholder="Search branch" size="small" icon={<IconSearch />} />
</div>
<Button onClick={() => setShowCreateBranch(true)}>Create preview branch</Button>
</div>
<div className="">
{isLoadingIntegrations && <GenericSkeletonLoader />}
{isErrorIntegrations && (
<AlertError
error={integrationsError}
subject="Failed to retrieve GitHub integration connection"
/>
)}
{isSuccessIntegrations && (
<>
<MainBranchPanel
repo={githubConnection?.metadata.name}
branch={mainBranch}
onSelectDisableBranching={() => setShowDisableBranching(true)}
/>
<PullRequests
previewBranches={previewBranches}
generateCreatePullRequestURL={generateCreatePullRequestURL}
onSelectDeleteBranch={setSelectedBranchToDelete}
/>
<PreviewBranches
generateCreatePullRequestURL={generateCreatePullRequestURL}
onSelectCreateBranch={() => setShowCreateBranch(true)}
onSelectDeleteBranch={setSelectedBranchToDelete}
/>
</>
)}
</div>
</div>
</ScaffoldSection>
</ScaffoldContainer>
<TextConfirmModal
size="medium"
visible={selectedBranchToDelete !== undefined}
onCancel={() => setSelectedBranchToDelete(undefined)}
onConfirm={() => onConfirmDeleteBranch()}
loading={isDeleting}
title="Delete branch"
confirmLabel="Delete branch"
confirmPlaceholder="Type in name of branch"
confirmString={selectedBranchToDelete?.name ?? ''}
text={`This will delete your database preview branch "${selectedBranchToDelete?.name}"`}
alert="You cannot recover this branch once it is deleted!"
/>
<ConfirmationModal
danger
size="medium"
loading={isDisabling}
visible={showDisableBranching}
header="Confirm disable branching for project"
buttonLabel="Confirm disable branching"
buttonLoadingLabel="Disabling branching..."
onSelectConfirm={() => onConfirmDisableBranching()}
onSelectCancel={() => setShowDisableBranching(false)}
>
<Modal.Content>
<div className="py-6">
<Alert_Shadcn_ variant="warning">
<IconAlertTriangle strokeWidth={2} />
<AlertTitle_Shadcn_>This action cannot be undone</AlertTitle_Shadcn_>
<AlertDescription_Shadcn_>
All database preview branches will be removed upon disabling branching. You may
still re-enable branching again thereafter, but your existing preview branches will
not be restored.
</AlertDescription_Shadcn_>
</Alert_Shadcn_>
<ul className="mt-4 space-y-5">
<li className="flex gap-3">
<div>
<strong className="text-sm">Before you disable branching, consider:</strong>
<ul className="space-y-2 mt-2 text-sm text-light">
<li className="list-disc ml-6">
Your project no longer requires database previews.
</li>
<li className="list-disc ml-6">
None of your database previews are currently being used in any app.
</li>
</ul>
</div>
</li>
</ul>
</div>
</Modal.Content>
</ConfirmationModal>
<CreateBranchSidePanel
visible={showCreateBranch}
onClose={() => setShowCreateBranch(false)}
/>
</>
)
}
export default BranchManagement
| studio/components/interfaces/BranchManagement/BranchManagement.tsx | 1 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.9949573874473572,
0.14580866694450378,
0.0001682050060480833,
0.00017541108536534011,
0.34719789028167725
]
|
{
"id": 12,
"code_window": [
" const selectedOrg = useSelectedOrganization()\n",
" const pullRequestUrl = generateCreatePullRequestURL()\n",
"\n",
" const { data: integrations, isLoading: isLoadingIntegrations } = useOrgIntegrationsQuery({\n",
" orgSlug: selectedOrg?.slug,\n",
" })\n",
" const githubIntegration = integrations?.find(\n",
" (integration) =>\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isBranch = project?.parent_project_ref !== undefined\n",
" const projectRef =\n",
" project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined\n",
"\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "add",
"edit_start_line_idx": 27
} | <svg width="1000" height="1000" viewBox="0 0 1000 1000" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M467.253 0.269139C465.103 0.464613 458.26 1.14878 452.102 1.63747C310.068 14.4411 177.028 91.0671 92.7664 208.841C45.8456 274.325 15.8358 348.605 4.49658 427.284C0.488759 454.748 0 462.86 0 500.098C0 537.336 0.488759 545.448 4.49658 572.912C31.6716 760.666 165.298 918.414 346.53 976.861C378.983 987.319 413.196 994.453 452.102 998.754C467.253 1000.42 532.747 1000.42 547.898 998.754C615.054 991.326 671.945 974.71 728.055 946.073C736.657 941.675 738.319 940.502 737.146 939.525C736.364 938.939 699.707 889.777 655.718 830.352L575.758 722.353L475.562 574.085C420.43 492.572 375.073 425.915 374.682 425.915C374.291 425.818 373.9 491.693 373.705 572.13C373.412 712.97 373.314 718.639 371.554 721.962C369.013 726.751 367.058 728.706 362.952 730.856C359.824 732.42 357.087 732.713 342.327 732.713H325.415L320.919 729.878C317.986 728.021 315.836 725.578 314.37 722.744L312.317 718.345L312.512 522.382L312.805 326.321L315.836 322.509C317.4 320.457 320.723 317.818 323.069 316.547C327.077 314.592 328.641 314.397 345.552 314.397C365.494 314.397 368.817 315.179 373.998 320.848C375.464 322.411 429.717 404.12 494.624 502.541C559.531 600.963 648.289 735.352 691.887 801.324L771.065 921.248L775.073 918.609C810.557 895.543 848.094 862.703 877.81 828.495C941.056 755.877 981.818 667.326 995.503 572.912C999.511 545.448 1000 537.336 1000 500.098C1000 462.86 999.511 454.748 995.503 427.284C968.328 239.53 834.702 81.7821 653.47 23.3352C621.505 12.975 587.488 5.84016 549.365 1.53972C539.98 0.562345 475.367 -0.51276 467.253 0.269139ZM671.945 302.668C676.637 305.014 680.45 309.51 681.818 314.201C682.6 316.743 682.796 371.085 682.6 493.549L682.307 669.281L651.32 621.781L620.235 574.281V446.538C620.235 363.95 620.626 317.525 621.212 315.277C622.776 309.803 626.197 305.503 630.89 302.962C634.897 300.909 636.364 300.714 651.711 300.714C666.178 300.714 668.719 300.909 671.945 302.668Z" fill="white"/>
</svg>
| studio/public/img/icons/nextjs-dark-icon.svg | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.0002859469677787274,
0.0002859469677787274,
0.0002859469677787274,
0.0002859469677787274,
0
]
|
{
"id": 12,
"code_window": [
" const selectedOrg = useSelectedOrganization()\n",
" const pullRequestUrl = generateCreatePullRequestURL()\n",
"\n",
" const { data: integrations, isLoading: isLoadingIntegrations } = useOrgIntegrationsQuery({\n",
" orgSlug: selectedOrg?.slug,\n",
" })\n",
" const githubIntegration = integrations?.find(\n",
" (integration) =>\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isBranch = project?.parent_project_ref !== undefined\n",
" const projectRef =\n",
" project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined\n",
"\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "add",
"edit_start_line_idx": 27
} | # Supabase
.branches
.temp
| examples/todo-list/nextjs-todo-list/supabase/.gitignore | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017510542238596827,
0.00017510542238596827,
0.00017510542238596827,
0.00017510542238596827,
0
]
|
{
"id": 12,
"code_window": [
" const selectedOrg = useSelectedOrganization()\n",
" const pullRequestUrl = generateCreatePullRequestURL()\n",
"\n",
" const { data: integrations, isLoading: isLoadingIntegrations } = useOrgIntegrationsQuery({\n",
" orgSlug: selectedOrg?.slug,\n",
" })\n",
" const githubIntegration = integrations?.find(\n",
" (integration) =>\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isBranch = project?.parent_project_ref !== undefined\n",
" const projectRef =\n",
" project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined\n",
"\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "add",
"edit_start_line_idx": 27
} | .sbui-popover__content {
@apply bg-scale-200 p-0;
@apply border;
@apply rounded;
@apply shadow;
border-style: solid;
border-width: 1px;
}
/* @keyframes fadeIn {
from {
transform: scale(0.95);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
@keyframes fadeOut {
from {
transform: scale(1);
opacity: 1;
}
to {
transform: scale(0.95);
opacity: 0;
}
} */
/* .sbui-popover__content {
transform-origin: var(--radix-popover-menu-content-transform-origin);
}
.sbui-popover__content[data-state='open'] {
animation: fadeIn 50ms ease-out;
}
.sbui-popover__content[data-state='closed'] {
animation: fadeOut 50ms ease-in;
} */
/* .sbui-popover__trigger {
@apply border-none bg-transparent p-0 focus:ring-0;
} */
.sbui-popover__arrow {
@apply fill-current text-scale-200;
@apply border-0 border-t;
border-style: solid;
}
.sbui-popover__close {
@apply absolute top-1 right-0;
@apply bg-transparent cursor-pointer border-none;
@apply text-gray-300;
@apply hover:text-gray-400;
@apply dark:text-dark-400;
@apply dark:hover:text-dark-300;
}
| packages/ui/src/components/Popover/Popover.module.css | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017923719133250415,
0.00017674709670245647,
0.0001689474593149498,
0.0001780136371962726,
0.0000033273829558311263
]
|
{
"id": 13,
"code_window": [
" integration.integration.name === 'GitHub' &&\n",
" integration.organization.slug === selectedOrg?.slug\n",
" )\n",
"\n",
" const githubConnection = githubIntegration?.connections?.find(\n",
" (connection) => connection.supabase_project_ref === ref\n",
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" (connection) => connection.supabase_project_ref === projectRef\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 37
} | import { Button, IconExternalLink, IconGitBranch } from 'ui'
import { Branch, useBranchesQuery } from 'data/branches/branches-query'
import { BranchContainer, BranchHeader, BranchPanel } from './BranchPanels'
import { useParams } from 'common'
import { useGithubPullRequestsQuery } from 'data/integrations/integrations-github-pull-requests-query'
import { partition } from 'lodash'
import { useSelectedOrganization } from 'hooks'
import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import AlertError from 'components/ui/AlertError'
interface PreviewBranchesProps {
generateCreatePullRequestURL: (branch?: string) => string
onSelectCreateBranch: () => void
onSelectDeleteBranch: (branch: Branch) => void
}
const PreviewBranches = ({
generateCreatePullRequestURL,
onSelectCreateBranch,
onSelectDeleteBranch,
}: PreviewBranchesProps) => {
const { ref } = useParams()
const selectedOrg = useSelectedOrganization()
const { data: integrations } = useOrgIntegrationsQuery({
orgSlug: selectedOrg?.slug,
})
const githubIntegration = integrations?.find(
(integration) =>
integration.integration.name === 'GitHub' &&
integration.organization.slug === selectedOrg?.slug
)
const githubConnection = githubIntegration?.connections.find(
(connection) => connection.supabase_project_ref === ref
)
const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []
const {
data: branches,
error: branchesError,
isLoading: isLoadingBranches,
isError: isErrorBranches,
isSuccess: isSuccessBranches,
} = useBranchesQuery({ projectRef: ref })
const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)
const { data: allPullRequests } = useGithubPullRequestsQuery({
organizationIntegrationId: githubIntegration?.id,
repoOwner,
repoName,
target: mainBranch?.git_branch,
})
const previewBranchesNotInPR = previewBranches.filter(
(branch) => !allPullRequests?.find((pr) => pr.branch === branch.git_branch)
)
return (
<>
{previewBranches.length > 0 && previewBranchesNotInPR.length > 0 && (
<BranchHeader markdown={previewBranches.length > 0 ? `#### Preview branches` : undefined} />
)}
{isLoadingBranches && (
<BranchContainer>
<div className="w-full">
<GenericSkeletonLoader />
</div>
</BranchContainer>
)}
{isErrorBranches && (
<BranchContainer>
<div className="w-full">
<AlertError error={branchesError} subject="Failed to retrieve GitHub branches" />
</div>
</BranchContainer>
)}
{isSuccessBranches && (
<>
{previewBranches.length === 0 ? (
<BranchContainer>
<div className="flex items-center flex-col justify-center w-full py-8">
<p>No database preview branches</p>
<p className="text-scale-1000">Database preview branches will be shown here</p>
<div className="w-[500px] border rounded-md mt-4">
<div className="px-5 py-3 bg-surface-100 flex items-center justify-between">
<div className="flex items-center space-x-4">
<IconGitBranch strokeWidth={2} className="text-scale-1100" />
<div>
<p>Create a preview branch</p>
<p className="text-scale-1000">Start developing in preview</p>
</div>
</div>
<Button type="default" onClick={() => onSelectCreateBranch()}>
Create preview branch
</Button>
</div>
<div className="px-5 py-3 border-t flex items-center justify-between">
<div>
<p>Not sure what to do?</p>
<p className="text-scale-1000">Browse our documentation</p>
</div>
<Button type="default" iconRight={<IconExternalLink />}>
Docs
</Button>
</div>
</div>
</div>
</BranchContainer>
) : (
previewBranchesNotInPR.map((branch) => (
<BranchPanel
key={branch.id}
branch={branch}
generateCreatePullRequestURL={generateCreatePullRequestURL}
onSelectDelete={() => onSelectDeleteBranch(branch)}
/>
))
)}
</>
)}
</>
)
}
export default PreviewBranches
| studio/components/interfaces/BranchManagement/PreviewBranches.tsx | 1 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.9984887838363647,
0.1432582288980484,
0.00016955973114818335,
0.0001754352415446192,
0.3491288721561432
]
|
{
"id": 13,
"code_window": [
" integration.integration.name === 'GitHub' &&\n",
" integration.organization.slug === selectedOrg?.slug\n",
" )\n",
"\n",
" const githubConnection = githubIntegration?.connections?.find(\n",
" (connection) => connection.supabase_project_ref === ref\n",
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" (connection) => connection.supabase_project_ref === projectRef\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 37
} | import { FC } from 'react'
import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useCheckPermissions, useLocalStorage, useStore } from 'hooks'
import { useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
interface Props {
selectedSchema: string
onAddTable: () => void
}
const EmptyState: FC<Props> = ({ selectedSchema, onAddTable }) => {
const { meta } = useStore()
const isProtectedSchema = meta.excludedSchemas.includes(selectedSchema)
const canCreateTables =
useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables') && !isProtectedSchema
const [sort] = useLocalStorage<'alphabetical' | 'grouped-alphabetical'>(
'table-editor-sort',
'alphabetical'
)
const { project } = useProjectContext()
const { data } = useEntityTypesQuery(
{
projectRef: project?.ref,
connectionString: project?.connectionString,
schema: selectedSchema,
sort,
},
{
keepPreviousData: true,
}
)
const totalCount = data?.pages?.[0].data.count ?? 0
return (
<div className="w-full h-full flex items-center justify-center">
{totalCount === 0 ? (
<ProductEmptyState
title="Table Editor"
ctaButtonLabel={canCreateTables ? 'Create a new table' : undefined}
onClickCta={canCreateTables ? onAddTable : undefined}
>
<p className="text-sm text-scale-1100">There are no tables available in this schema.</p>
</ProductEmptyState>
) : (
<div className="flex flex-col items-center space-y-4">
<ProductEmptyState
title="Table Editor"
ctaButtonLabel={canCreateTables ? 'Create a new table' : undefined}
onClickCta={canCreateTables ? onAddTable : undefined}
>
<p className="text-sm text-scale-1100">
Select a table from the navigation panel on the left to view its data
{canCreateTables && ', or create a new one.'}
</p>
</ProductEmptyState>
</div>
)}
</div>
)
}
export default observer(EmptyState)
| studio/components/interfaces/TableGridEditor/EmptyState.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017633473908063024,
0.00017177779227495193,
0.00016479604528285563,
0.0001739160215947777,
0.000004366502253105864
]
|
{
"id": 13,
"code_window": [
" integration.integration.name === 'GitHub' &&\n",
" integration.organization.slug === selectedOrg?.slug\n",
" )\n",
"\n",
" const githubConnection = githubIntegration?.connections?.find(\n",
" (connection) => connection.supabase_project_ref === ref\n",
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" (connection) => connection.supabase_project_ref === projectRef\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 37
} | import { writeToDisk } from './helpers'
import stringify from 'json-stringify-safe'
const fs = require('fs')
const main = (command: string[], options: any) => {
handleInput(command[0], options)
}
// Run everything
const argv = require('minimist')(process.argv.slice(2))
main(argv['_'], argv)
function handleInput(command: string, options: any) {
switch (command) {
case 'dereference':
dereference(options)
break
default:
console.log('Unrecognized command:', command)
break
}
}
interface KV {
[key: string]: any
}
async function dereference({
input,
output,
}: {
input: string
output: string
}) {
console.log('input', input)
const specRaw = fs.readFileSync(input, 'utf8')
const spec = JSON.parse(specRaw)
const kv = chilrenReducer({}, spec)
// console.log('kv', kv)
const dereferenced = dereferenceReducer(spec, kv)
// console.log('dereferenced', dereferenced)
await writeToDisk(output, stringify(dereferenced, null, 2))
// console.log('JSON.stringify(dereferenced)', JSON.stringify(spec))
}
function chilrenReducer(acc: KV, child: any): KV {
if (!!child.children) {
child.children.forEach((x: any) => chilrenReducer(acc, x))
}
const { id }: { id: string } = child
acc[id] = { ...child }
return acc
}
// Recurse through all children, and if the `type.type` == 'reference'
// then it will add a key "dereferecnced" to the object.
function dereferenceReducer(child: any, kv: KV) {
if (!!child.children) {
child.children.forEach((x: any) => dereferenceReducer(x, kv))
}
if (!!child.signatures) {
child.signatures.forEach((x: any) => dereferenceReducer(x, kv))
}
if (!!child.parameters) {
child.parameters.forEach((x: any) => dereferenceReducer(x, kv))
}
if (
!!child.type &&
!!child.type.declaration &&
!!child.type.declaration.children &&
child.type.type === 'reflection'
) {
child.type.declaration.children.forEach((x: any) =>
dereferenceReducer(x, kv)
)
}
const final = { ...child }
if (
// For now I can only dereference parameters
// because anything else is producing an error when saving to file:
// TypeError: Converting circular structure to JSON
final.kindString === 'Parameter' &&
final.type?.type === 'reference' &&
final.type?.id
) {
const dereferenced = kv[final.type.id]
final.type.dereferenced = dereferenced || {}
return final
} else if (
final.kindString === 'Property' &&
final.type?.type === 'reference' &&
final.type?.id
) {
const dereferenced = kv[final.type.id]
final.type.dereferenced = dereferenced || {}
return final
} else if (
final.kindString === 'Type alias' &&
final.type?.type === 'union'
) {
// handles union types that contain nested references
// by replacing the reference in-place
final.type.types = final.type.types.map((item: any) => {
return item.type === 'reference' ? kv[item.id] : item
})
return final
} else {
return final
}
}
| spec/parser/tsdoc.ts | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.0001790223177522421,
0.0001749418443068862,
0.0001710641518002376,
0.00017499217938166112,
0.000002247063093818724
]
|
{
"id": 13,
"code_window": [
" integration.integration.name === 'GitHub' &&\n",
" integration.organization.slug === selectedOrg?.slug\n",
" )\n",
"\n",
" const githubConnection = githubIntegration?.connections?.find(\n",
" (connection) => connection.supabase_project_ref === ref\n",
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" (connection) => connection.supabase_project_ref === projectRef\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 37
} | import { Integration } from 'data/integrations/integrations.types'
import { SupaResponse } from 'types'
import { isResponseOk } from './common/fetch'
async function fetchGitHub<T = any>(url: string, responseJson = true): Promise<SupaResponse<T>> {
const response = await fetch(url)
if (!response.ok) {
return {
error: {
code: response.status,
message: response.statusText,
requestId: '',
},
}
}
try {
return (responseJson ? await response.json() : await response.text()) as T
} catch (error: any) {
return {
error: {
message: error.message,
code: 500,
requestId: '',
},
}
}
}
export type File = {
name: string
download_url: string
}
/**
* Returns the initial migration SQL from a GitHub repo.
* @param externalId An external GitHub URL for example: https://github.com/vercel/next.js/tree/canary/examples/with-supabase
*/
export async function getInitialMigrationSQLFromGitHubRepo(
externalId?: string
): Promise<string | null> {
if (!externalId) return null
const [, , , owner, repo, , branch, ...pathSegments] = externalId?.split('/') ?? []
const path = pathSegments.join('/')
const baseGitHubUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`
const supabaseFolderUrl = `${baseGitHubUrl}/supabase?ref=${branch}`
const supabaseMigrationsPath = `supabase/migrations` // TODO: read this from the `supabase/config.toml` file
const migrationsFolderUrl = `${baseGitHubUrl}/${supabaseMigrationsPath}${
branch ? `?ref=${branch}` : ``
}`
const [supabaseFilesResponse, migrationFilesResponse] = await Promise.all([
fetchGitHub<File[]>(supabaseFolderUrl),
fetchGitHub<File[]>(migrationsFolderUrl),
])
if (!isResponseOk(supabaseFilesResponse)) {
console.warn(`Failed to fetch supabase files from GitHub: ${supabaseFilesResponse.error}`)
return null
}
if (!isResponseOk(migrationFilesResponse)) {
console.warn(`Failed to fetch migration files from GitHub: ${migrationFilesResponse.error}`)
return null
}
const seedFileUrl = supabaseFilesResponse.find((file) => file.name === 'seed.sql')?.download_url
const sortedFiles = migrationFilesResponse.sort((a, b) => {
// sort by name ascending
if (a.name < b.name) return -1
if (a.name > b.name) return 1
return 0
})
const migrationFileDownloadUrlPromises = sortedFiles.map((file) =>
fetchGitHub<string>(file.download_url, false)
)
const [seedFileResponse, ...migrationFileResponses] = await Promise.all([
seedFileUrl ? fetchGitHub<string>(seedFileUrl, false) : Promise.resolve<string>(''),
...migrationFileDownloadUrlPromises,
])
const migrations = migrationFileResponses.filter((response) => isResponseOk(response)).join(';')
const seed = isResponseOk(seedFileResponse) ? seedFileResponse : ''
const migrationsTableSql = /* SQL */ `
create schema if not exists supabase_migrations;
create table if not exists supabase_migrations.schema_migrations (
version text not null primary key,
statements text[],
name text
);
${sortedFiles.map((file, i) => {
const migration = migrationFileResponses[i]
if (!isResponseOk(migration)) return ''
const version = file.name.split('_')[0]
const statements = JSON.stringify(
migration
.split(';')
.map((statement) => statement.trim())
.filter(Boolean)
)
return /* SQL */ `
insert into supabase_migrations.schema_migrations (version, statements, name)
select '${version}', array_agg(jsonb_statements)::text[], '${file.name}'
from jsonb_array_elements_text($statements$${statements}$statements$::jsonb) as jsonb_statements;
`
})}
`
return `${migrations};${migrationsTableSql};${seed}`
}
type VercelIntegration = Extract<Integration, { integration: { name: 'Vercel' } }>
type GitHubIntegration = Extract<Integration, { integration: { name: 'GitHub' } }>
export function getIntegrationConfigurationUrl(integration: Integration) {
if (integration.integration.name === 'Vercel') {
return getVercelConfigurationUrl(integration as VercelIntegration)
}
if (integration.integration.name === 'GitHub') {
return getGitHubConfigurationUrl(integration as GitHubIntegration)
}
return ''
}
export function getVercelConfigurationUrl(integration: VercelIntegration) {
return `https://vercel.com/dashboard/${
integration.metadata?.account.type === 'Team'
? `${integration.metadata?.account.team_slug}/`
: ''
}integrations/${integration.metadata?.configuration_id}`
}
export function getGitHubConfigurationUrl(integration: GitHubIntegration) {
return `https://github.com/${
integration.metadata?.account.type === 'Organization'
? `organizations/${integration.metadata?.account.name}/`
: ''
}settings/installations/${integration.metadata?.installation_id}`
}
| studio/lib/integration-utils.ts | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.9616633057594299,
0.06512745469808578,
0.00016491378482896835,
0.00023371983843389899,
0.2396152913570404
]
|
{
"id": 14,
"code_window": [
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n",
" const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef: ref })\n",
" const mainBranch = branches?.find((branch) => branch.is_default)\n",
"\n",
" const {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef })\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 41
} | import Link from 'next/link'
import { Button, IconExternalLink, IconGitBranch } from 'ui'
import { useParams } from 'common'
import { Branch, useBranchesQuery } from 'data/branches/branches-query'
import { useGithubPullRequestsQuery } from 'data/integrations/integrations-github-pull-requests-query'
import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'
import { useSelectedOrganization } from 'hooks'
import { BranchContainer, BranchHeader, PullRequestPanel } from './BranchPanels'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import AlertError from 'components/ui/AlertError'
interface PullRequestsProps {
previewBranches: Branch[]
generateCreatePullRequestURL: (branch?: string) => string
onSelectDeleteBranch: (branch: Branch) => void
}
const PullRequests = ({
previewBranches,
generateCreatePullRequestURL,
onSelectDeleteBranch,
}: PullRequestsProps) => {
const { ref } = useParams()
const selectedOrg = useSelectedOrganization()
const pullRequestUrl = generateCreatePullRequestURL()
const { data: integrations, isLoading: isLoadingIntegrations } = useOrgIntegrationsQuery({
orgSlug: selectedOrg?.slug,
})
const githubIntegration = integrations?.find(
(integration) =>
integration.integration.name === 'GitHub' &&
integration.organization.slug === selectedOrg?.slug
)
const githubConnection = githubIntegration?.connections?.find(
(connection) => connection.supabase_project_ref === ref
)
const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []
const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef: ref })
const mainBranch = branches?.find((branch) => branch.is_default)
const {
data: allPullRequests,
error: pullRequestsError,
isLoading: isLoadingPullRequests,
isError: isErrorPullRequests,
isSuccess: isSuccessPullRequests,
} = useGithubPullRequestsQuery({
organizationIntegrationId: githubIntegration?.id,
repoOwner,
repoName,
target: mainBranch?.git_branch,
})
const pullRequests = allPullRequests?.filter((pr) =>
branches?.some((branch) => branch.git_branch === pr.branch)
)
const showEmptyState = previewBranches.length === 0 || (pullRequests || []).length === 0
return (
<>
<BranchHeader
markdown={!showEmptyState ? `#### Preview branches in pull requests` : undefined}
/>
{(isLoadingBranches || isLoadingPullRequests || isLoadingIntegrations) && (
<BranchContainer>
<div className="w-full">
<GenericSkeletonLoader />
</div>
</BranchContainer>
)}
{isErrorPullRequests && (
<BranchContainer>
<div className="w-full">
<AlertError
error={pullRequestsError}
subject="Failed to retrieve GitHub pull requests"
/>
</div>
</BranchContainer>
)}
{isSuccessPullRequests && (
<>
{showEmptyState ? (
<BranchContainer>
<div className="flex items-center flex-col justify-center w-full py-8">
<p>No pull requests made yet for this repository</p>
<p className="text-scale-1000">
Only pull requests with the ./migration directory changes will show here.
</p>
{previewBranches.length > 0 && (
<div className="w-96 border rounded-md mt-4">
<div className="px-5 py-3 bg-surface-100 flex items-center justify-between">
<div className="flex items-center space-x-4">
<IconGitBranch strokeWidth={2} className="text-scale-1100" />
<p>Create a pull request</p>
</div>
<Link passHref href={pullRequestUrl}>
<a target="_blank" rel="noreferrer">
<Button type="default" iconRight={<IconExternalLink />}>
Github
</Button>
</a>
</Link>
</div>
<div className="px-5 py-3 border-t flex items-center justify-between">
<div>
<p>Not sure what to do?</p>
<p className="text-scale-1000">Browse our documentation</p>
</div>
<Button type="default" iconRight={<IconExternalLink />}>
Docs
</Button>
</div>
</div>
)}
</div>
</BranchContainer>
) : (
pullRequests?.map((pr) => {
const branch = branches?.find((branch) => branch.git_branch === pr.branch)
return (
<PullRequestPanel
key={pr.id}
pr={pr}
onSelectDelete={() => {
if (branch !== undefined) onSelectDeleteBranch(branch)
}}
/>
)
})
)}
</>
)}
</>
)
}
export default PullRequests
| studio/components/interfaces/BranchManagement/PullRequests.tsx | 1 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.9992291927337646,
0.25846409797668457,
0.0001647343160584569,
0.0002837548090610653,
0.4237072765827179
]
|
{
"id": 14,
"code_window": [
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n",
" const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef: ref })\n",
" const mainBranch = branches?.find((branch) => branch.is_default)\n",
"\n",
" const {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef })\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 41
} | import Layout from '~/layouts/DefaultGuideLayout'
export const meta = {
id: 'troubeshooting',
title: 'Troubleshooting',
description: 'Diagnosing and fixing issues with your hosted Supabase project.',
}
Learn how to diagnose and fix common issues with your Supabase project.
## HTTP API Issues
Symptoms:
- HTTP timeouts
- 5xx response codes
- High response times
### Under-provisioned resources
The most common class of issues that causes HTTP timeouts and 5xx response codes is the under-provisioning of resources for your project. This can cause your project to be unable to service the traffic it is receiving.
Each Supabase project is provisioned with [segregated compute resources](../platform/compute-add-ons). This allows the project to serve unlimited requests, as long as they can be handled using the resources that have been provisioned. Complex queries, or queries that process larger amounts of data, will require higher amounts of resources. As such, the amount of resources that can handle a high volume of simple queries (or queries involving small amounts of data), will likely be unable to handle a similar volume of complex queries.
You can view the resource utilization of your Supabase Project using the [reports in the Dashboard](https://supabase.com/dashboard/project/_/reports/database).
Some common solutions for this issue are:
- [Upgrading](https://supabase.com/dashboard/project/_/settings/billing/subscription) to a [larger compute add-on](../platform/compute-add-ons) in order to serve higher volumes of traffic.
- [Optimizing the queries](../platform/performance#examining-query-performance) being executed.
- [Using fewer Postgres connections](../platform/performance#configuring-clients-to-use-fewer-connections) can reduce the amount of resources needed on the project.
- [Restarting](https://supabase.com/dashboard/project/_/settings/general) the database. This only temporarily solves the issue by terminating any ongoing workloads that might be tying up your compute resources.
If your [Disk IO budget](../platform/compute-add-ons#disk-io) has been drained, you will need to either wait for it to be replenished the next day, or upgrade to a larger compute add-on to increase the budget available to your project.
## Unable to connect to your Supabase Project
Symptom: You're unable to connect to your Postgres database directly, but can open the Project in the [Supabase Dashboard](https://supabase.com/dashboard/project/_/).
### Too many open connections
Errors about too many open connections can be _temporarily_ resolved by [restarting the database](https://supabase.com/dashboard/project/_/settings/general). However, this won't solve the underlying issue for a permanent solution.
- If you're receiving a `No more connections allowed (max_client_conn)` error:
- Configure your applications and services to [use fewer connections](../platform/performance#configuring-clients-to-use-fewer-connections).
- [Upgrade](https://supabase.com/dashboard/project/_/settings/billing/subscription) to a [larger compute add-on](../platform/compute-add-ons) to increase the number of available connections.
- If you're receiving a `sorry, too many clients already` or `remaining connection slots are reserved for non-replication superuser connections` error message in addition to the above suggestions, switch to using the [connection pooler](/docs/guides/database/connecting-to-postgres#connection-pool) instead.
### Connection refused
If you receive a `connection refused` error after a few initial failed connection attempts, your client has likely been temporarily blocked in order to protect the database from brute-force attacks. You can wait 30 minutes before trying again with the correct password, or you can [contact support](https://supabase.com/dashboard/support/new) with your client's IP address to manually unblock you.
If you're also unable to open the project using the [Supabase Dashboard](https://supabase.com/dashboard/project/_/), review the solutions for [under-provisioned projects](#under-provisioned-resources).
export const Page = ({ children }) => <Layout meta={meta} children={children} />
export default Page
| apps/docs/pages/guides/platform/troubleshooting.mdx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017181382281705737,
0.00016662944108247757,
0.00016444506763946265,
0.00016543426318094134,
0.0000025417452889087144
]
|
{
"id": 14,
"code_window": [
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n",
" const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef: ref })\n",
" const mainBranch = branches?.find((branch) => branch.is_default)\n",
"\n",
" const {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef })\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 41
} | import rangeParser from 'parse-numeric-range'
import { useMemo } from 'react'
import CodeBlock, { CodeBlockProps } from './CodeBlock/CodeBlock'
interface ScrollableCodeBlockProps extends CodeBlockProps {
highlightLines: string
children: string
/**
* Shows an application toolbar at the top
*/
showToolbar?: boolean
}
const MAX_HEIGHT = 520
const CODE_LINE_HEIGHT = 22
const TOP_OFFSET = 4
const ScrollableCodeBlock = ({
highlightLines: highlightLinesRange,
children,
showToolbar,
...props
}: ScrollableCodeBlockProps) => {
const highlightLines = useMemo(
() => rangeParser(highlightLinesRange ?? ''),
[highlightLinesRange]
)
const firstLine = Math.min(...highlightLines)
const lastLine = Math.max(...highlightLines)
const firstLinePosition = firstLine * CODE_LINE_HEIGHT
const lastLinePosition = lastLine * CODE_LINE_HEIGHT
const middlePosition = (firstLinePosition + lastLinePosition) / 2
const position = Math.max(middlePosition - MAX_HEIGHT / 2 + TOP_OFFSET, 0)
return (
<div>
{showToolbar && (
<div className="bg-scale-1200 dark:bg-scale-200 border-scale-1200 dark:border-scale-400 flex h-7 w-full items-center gap-1.5 rounded-t-lg border border-b-0 px-4">
<div className="flex items-center gap-1.5">
<div className="bg-scale-1100 dark:bg-scale-400 h-2.5 w-2.5 rounded-full"></div>
<div className="bg-scale-1100 dark:bg-scale-400 h-2.5 w-2.5 rounded-full"></div>
<div className="bg-scale-1100 dark:bg-scale-400 h-2.5 w-2.5 rounded-full"></div>
</div>
</div>
)}
<div
className="border-scale-1100 dark:border-scale-400 overflow-hidden rounded-b-lg border"
style={{ maxHeight: MAX_HEIGHT, transform: 'translateZ(0)' }}
>
<div
className="transition-transform duration-500"
style={{ transform: `translate3d(0, -${position}px, 0)` }}
>
{/* <CodeBlock highlightLines={highlightLinesRange} hideBorder={true} {...props}> */}
<CodeBlock {...props}>{children + '\n'.repeat(100)}</CodeBlock>
</div>
</div>
</div>
)
}
export default ScrollableCodeBlock
| apps/www/components/ScrollableCodeBlock.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.00017483148258179426,
0.0001718954008538276,
0.00016707280883565545,
0.00017277307051699609,
0.0000024081064111669548
]
|
{
"id": 14,
"code_window": [
" )\n",
" const [repoOwner, repoName] = githubConnection?.metadata.name.split('/') || []\n",
"\n",
" const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef: ref })\n",
" const mainBranch = branches?.find((branch) => branch.is_default)\n",
"\n",
" const {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { data: branches, isLoading: isLoadingBranches } = useBranchesQuery({ projectRef })\n"
],
"file_path": "studio/components/interfaces/BranchManagement/PullRequests.tsx",
"type": "replace",
"edit_start_line_idx": 41
} | // DO NOT EDIT
// this file is generated by /internals/populate-icons script
import * as React from 'react'
// @ts-ignore
import { ShieldOff } from 'react-feather'
import IconBase from './../../IconBase'
function IconShieldOff(props: any) {
return <IconBase icon={ShieldOff} {...props} />
}
export default IconShieldOff
| packages/ui/src/components/Icon/icons/IconShieldOff/IconShieldOff.tsx | 0 | https://github.com/supabase/supabase/commit/5d327d0ed0684ae3611a620d4e4e2d98342a4e2e | [
0.0001792204420780763,
0.00017734963330440223,
0.0001754788390826434,
0.00017734963330440223,
0.0000018708014977164567
]
|
{
"id": 0,
"code_window": [
" | 'timer'\n",
" | 'list'\n",
" | 'toolbar';\n",
"\n",
"export interface AccessibilityPropsAndroid {\n",
" /**\n",
" * Indicates to accessibility services whether the user should be notified when this view changes.\n",
" * Works for Android API >= 19 only.\n",
" * See http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion for references.\n",
" * @platform android\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * Specifies the nativeID of the associated label text. When the assistive technology focuses on the component with this props, the text is read aloud.\n",
" * @platform android\n",
" */\n",
" accessibilityLabelledBy?: string | string[] | undefined;\n",
"\n"
],
"file_path": "types/react-native/index.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | /*
The content of index.io.js could be something like
'use strict';
import { AppRegistry } from 'react-native'
import Welcome from './gen/Welcome'
AppRegistry.registerComponent('MopNative', () => Welcome);
For a list of complete Typescript examples: check https://github.com/bgrieder/RNTSExplorer
*/
import * as PropTypes from 'prop-types';
import * as React from 'react';
import {
AccessibilityInfo,
ActionSheetIOS,
AsyncStorage,
Alert,
AppState,
AppStateStatus,
Appearance,
BackHandler,
Button,
ColorValue,
DataSourceAssetCallback,
DatePickerAndroid,
DevSettings,
DeviceEventEmitter,
DeviceEventEmitterStatic,
Dimensions,
DrawerLayoutAndroid,
DrawerSlideEvent,
DynamicColorIOS,
FlatList,
FlatListProps,
GestureResponderEvent,
HostComponent,
I18nManager,
Image,
ImageBackground,
ImageErrorEventData,
ImageLoadEventData,
ImageResizeMode,
ImageResolvedAssetSource,
ImageStyle,
InputAccessoryView,
InteractionManager,
Keyboard,
KeyboardAvoidingView,
LayoutChangeEvent,
Linking,
ListRenderItemInfo,
ListView,
ListViewDataSource,
LogBox,
MaskedViewIOS,
Modal,
NativeEventEmitter,
NativeModule, // Not actually exported, not sure why
NativeModules,
NativeScrollEvent,
NativeSyntheticEvent,
PermissionsAndroid,
Platform,
PlatformColor,
Pressable,
ProgressBarAndroid,
ProgressViewIOS,
PushNotificationIOS,
RefreshControl,
RegisteredStyle,
ScaledSize,
ScrollView,
ScrollViewProps,
SectionList,
SectionListProps,
SectionListRenderItemInfo,
Share,
ShareDismissedAction,
ShareSharedAction,
StatusBar,
StyleProp,
StyleSheet,
Switch,
SwitchIOS,
SwitchChangeEvent,
Systrace,
TabBarIOS,
Text,
TextInput,
TextInputChangeEventData,
TextInputContentSizeChangeEventData,
TextInputEndEditingEventData,
TextInputFocusEventData,
TextInputKeyPressEventData,
TextInputScrollEventData,
TextInputSelectionChangeEventData,
TextInputSubmitEditingEventData,
TextLayoutEventData,
TextProps,
TextStyle,
TimePickerAndroid,
TouchableNativeFeedback,
UIManager,
View,
ViewPagerAndroid,
ViewStyle,
VirtualizedList,
YellowBox,
findNodeHandle,
requireNativeComponent,
useColorScheme,
useWindowDimensions,
SectionListData,
ToastAndroid,
Touchable,
LayoutAnimation,
} from 'react-native';
declare module 'react-native' {
interface NativeTypedModule {
someFunction(): void;
someProperty: string;
}
interface NativeModulesStatic {
NativeTypedModule: NativeTypedModule;
}
}
NativeModules.NativeUntypedModule;
NativeModules.NativeTypedModule.someFunction();
NativeModules.NativeTypedModule.someProperty = '';
function dimensionsListener(dimensions: { window: ScaledSize; screen: ScaledSize }) {
console.log('window dimensions: ', dimensions.window);
console.log('screen dimensions: ', dimensions.screen);
}
function testDimensions() {
const { width, height, scale, fontScale } = Dimensions.get(1 === 1 ? 'window' : 'screen');
Dimensions.addEventListener('change', dimensionsListener);
Dimensions.removeEventListener('change', dimensionsListener);
}
function TextUseWindowDimensions() {
const { width, height, scale, fontScale } = useWindowDimensions();
}
BackHandler.addEventListener('hardwareBackPress', () => true).remove();
BackHandler.addEventListener('hardwareBackPress', () => false).remove();
BackHandler.addEventListener('hardwareBackPress', () => undefined).remove();
BackHandler.addEventListener('hardwareBackPress', () => null).remove();
interface LocalStyles {
container: ViewStyle;
welcome: TextStyle;
instructions: TextStyle;
}
const styles = StyleSheet.create<LocalStyles>({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
//alternative declaration of styles (inline typings)
const stylesAlt = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
StyleSheet.setStyleAttributePreprocessor('fontFamily', (family: string) => family);
const welcomeFontSize = StyleSheet.flatten(styles.welcome).fontSize;
const viewStyle: StyleProp<ViewStyle> = {
backgroundColor: '#F5FCFF',
};
const textStyle: StyleProp<TextStyle> = {
fontSize: 20,
};
const imageStyle: StyleProp<ImageStyle> = {
resizeMode: 'contain',
};
const fontVariantStyle: StyleProp<TextStyle> = {
fontVariant: ['tabular-nums'],
};
const viewProperty = StyleSheet.flatten(viewStyle).backgroundColor;
const textProperty = StyleSheet.flatten(textStyle).fontSize;
const imageProperty = StyleSheet.flatten(imageStyle).resizeMode;
const fontVariantProperty = StyleSheet.flatten(fontVariantStyle).fontVariant;
// correct use of the StyleSheet.flatten
const styleArray: StyleProp<ViewStyle>[] = [];
const flattenStyle = StyleSheet.flatten(styleArray);
const { top } = flattenStyle;
const s = StyleSheet.create({
shouldWork: {
fontWeight: '900', // if we comment this line, errors gone
marginTop: 5, // if this line commented, errors also gone
},
});
const f1: TextStyle = s.shouldWork;
// StyleSheet.compose
// It creates a new style object by composing two existing styles
const composeTextStyle: StyleProp<TextStyle> = {
color: '#000000',
fontSize: 20,
};
const composeImageStyle: StyleProp<ImageStyle> = {
resizeMode: 'contain',
};
// The following use of the compose method is valid
const combinedStyle: StyleProp<TextStyle> = StyleSheet.compose(composeTextStyle, composeTextStyle);
const combinedStyle1: StyleProp<ImageStyle> = StyleSheet.compose(composeImageStyle, composeImageStyle);
const combinedStyle2: StyleProp<TextStyle | ConcatArray<TextStyle>> = StyleSheet.compose(
[composeTextStyle],
[composeTextStyle],
);
const combinedStyle3: StyleProp<TextStyle | null> = StyleSheet.compose(composeTextStyle, null);
const combinedStyle4: StyleProp<TextStyle | ConcatArray<TextStyle> | null> = StyleSheet.compose(
[composeTextStyle],
null,
);
const combinedStyle5: StyleProp<TextStyle> = StyleSheet.compose(
composeTextStyle,
Math.random() < 0.5 ? composeTextStyle : null,
);
const combinedStyle6: StyleProp<TextStyle | null> = StyleSheet.compose(null, null);
// The following use of the compose method is invalid:
// @ts-expect-error
const combinedStyle7 = StyleSheet.compose(composeImageStyle, composeTextStyle);
// @ts-expect-error
const combinedStyle8: StyleProp<ImageStyle> = StyleSheet.compose(composeTextStyle, composeTextStyle);
// @ts-expect-error
const combinedStyle9: StyleProp<ImageStyle> = StyleSheet.compose([composeTextStyle], null);
// @ts-expect-error
const combinedStyle10: StyleProp<ImageStyle> = StyleSheet.compose(Math.random() < 0.5 ? composeTextStyle : null, null);
const testNativeSyntheticEvent = <T extends {}>(e: NativeSyntheticEvent<T>): void => {
e.isDefaultPrevented();
e.preventDefault();
e.isPropagationStopped();
e.stopPropagation();
e.persist();
e.cancelable;
e.bubbles;
e.currentTarget;
e.defaultPrevented;
e.eventPhase;
e.isTrusted;
e.nativeEvent;
e.target;
e.timeStamp;
e.type;
e.nativeEvent;
};
function eventHandler<T extends React.BaseSyntheticEvent>(e: T) {}
function handler(e: GestureResponderEvent) {
eventHandler(e);
}
type ElementProps<C> = C extends React.Component<infer P, any> ? P : never;
class CustomView extends React.Component {
render() {
return <Text style={[StyleSheet.absoluteFill, { ...StyleSheet.absoluteFillObject }]}>Custom View</Text>;
}
}
class Welcome extends React.Component<ElementProps<View> & { color: string }> {
// tslint:disable-next-line:no-object-literal-type-assertion
refs = {} as {
[key: string]: React.ReactInstance;
rootView: View;
customView: CustomView;
};
testNativeMethods() {
const { rootView } = this.refs;
rootView.setNativeProps({});
rootView.measure((x: number, y: number, width: number, height: number) => {});
}
testFindNodeHandle() {
const { rootView, customView } = this.refs;
const nativeComponentHandle = findNodeHandle(rootView);
const customComponentHandle = findNodeHandle(customView);
const fromHandle = findNodeHandle(customComponentHandle);
}
render() {
const { color, ...props } = this.props;
return (
<View {...props} ref="rootView" style={[[styles.container], undefined, null, false]}>
<Text style={styles.welcome}>Welcome to React Native</Text>
<Text style={styles.instructions}>To get started, edit index.ios.js</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
<CustomView ref="customView" />
</View>
);
}
}
export default Welcome;
// TouchableTest
function TouchableTest() {
function basicUsage() {
if (Touchable.TOUCH_TARGET_DEBUG) {
return Touchable.renderDebugView({
color: 'mediumspringgreen',
hitSlop: { bottom: 5, top: 5 },
});
}
}
function defaultHitSlop() {
return Touchable.renderDebugView({
color: 'red',
});
}
}
// TouchableNativeFeedbackTest
export class TouchableNativeFeedbackTest extends React.Component {
onPressButton = (e: GestureResponderEvent) => {
e.persist();
e.isPropagationStopped();
e.isDefaultPrevented();
};
render() {
return (
<>
<TouchableNativeFeedback onPress={this.onPressButton}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.Ripple('red', true)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.Ripple('red', true, 30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground()}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground(30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless()}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless(30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
</>
);
}
}
// PressableTest
export class PressableTest extends React.Component<{}> {
private readonly myRef: React.RefObject<View> = React.createRef();
onPressButton = (e: GestureResponderEvent) => {
e.persist();
e.isPropagationStopped();
e.isDefaultPrevented();
};
render() {
return (
<>
<Pressable ref={this.myRef} onPress={this.onPressButton} style={{ backgroundColor: 'blue' }} unstable_pressDelay={100}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
{/* Style function */}
<Pressable
onPress={this.onPressButton}
style={state => ({
backgroundColor: state.pressed ? 'red' : 'blue',
})}
>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
{/* Children function */}
<Pressable
onPress={this.onPressButton}
style={state => ({
backgroundColor: state.pressed ? 'red' : 'blue',
})}
>
{state =>
state.pressed ? (
<View>
<Text>Pressed</Text>
</View>
) : (
<View>
<Text>Not Pressed</Text>
</View>
)
}
</Pressable>
{/* Android Ripple */}
<Pressable
android_ripple={{
borderless: true,
color: 'green',
radius: 20,
foreground: true,
}}
onPress={this.onPressButton}
style={{ backgroundColor: 'blue' }}
>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
</>
);
}
}
// App State
function appStateListener(state: string) {
console.log('New state: ' + state);
}
function appStateTest() {
console.log('Current state: ' + AppState.currentState);
AppState.addEventListener('change', appStateListener);
AppState.addEventListener('blur', appStateListener);
AppState.addEventListener('focus', appStateListener);
}
let appState: AppStateStatus = 'active';
appState = 'background';
appState = 'inactive';
appState = 'unknown';
appState = 'extension';
const AppStateExample = () => {
const appState = React.useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = React.useState(appState.current);
const appStateIsAvailable = AppState.isAvailable;
React.useEffect(() => {
const subscription = AppState.addEventListener("change", nextAppState => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
});
return () => {
subscription.remove();
};
}, []);
return (
<View style={styles.container}>
<Text>Current state is: {appStateVisible}</Text>
<Text>Available: {appStateIsAvailable}</Text>
</View>
);
};
// ViewPagerAndroid
export class ViewPagerAndroidTest {
render() {
return (
<ViewPagerAndroid
style={{ height: 56 }}
initialPage={0}
keyboardDismissMode={'on-drag'}
onPageScroll={e => {
console.log(`position: ${e.nativeEvent.position}`);
console.log(`offset: ${e.nativeEvent.offset}`);
}}
onPageSelected={e => {
console.log(`position: ${e.nativeEvent.position}`);
}}
/>
);
}
}
const profiledJSONParse = Systrace.measure('JSON', 'parse', JSON.parse);
profiledJSONParse('[]');
InteractionManager.runAfterInteractions(() => {
// ...
}).then(() => 'done');
export class FlatListTest extends React.Component<FlatListProps<number>, {}> {
list: FlatList<any> | null = null;
componentDidMount(): void {
if (this.list) {
this.list.flashScrollIndicators();
}
}
_renderItem = (rowData: any) => {
return (
<View>
<Text> {rowData.item} </Text>
</View>
);
};
_cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
_renderSeparator = () => <View style={{ height: 1, width: '100%', backgroundColor: 'gray' }} />;
render() {
return (
<FlatList
ref={list => (this.list = list)}
data={[1, 2, 3, 4, 5]}
renderItem={this._renderItem}
ItemSeparatorComponent={this._renderSeparator}
ListFooterComponent={null}
ListFooterComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
ListHeaderComponent={null}
ListHeaderComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
CellRendererComponent={this._cellRenderer}
fadingEdgeLength={200}
/>
);
}
}
export class SectionListTest extends React.Component<SectionListProps<string>, {}> {
myList: React.RefObject<SectionList<string>>;
constructor(props: SectionListProps<string>) {
super(props);
this.myList = React.createRef();
}
scrollMe = () => {
this.myList.current && this.myList.current.scrollToLocation({ itemIndex: 0, sectionIndex: 1 });
};
render() {
const sections = [
{
title: 'Section 1',
data: ['A', 'B', 'C', 'D', 'E'],
},
{
title: 'Section 2',
data: ['A2', 'B2', 'C2', 'D2', 'E2'],
renderItem: (info: { item: string }) => (
<View>
<Text>{info.item}</Text>
</View>
),
},
];
const cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
return (
<React.Fragment>
<Button title="Press" onPress={this.scrollMe} />
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => (
<View>
<Text>{section.title}</Text>
</View>
)}
renderItem={(info: SectionListRenderItemInfo<string>) => (
<View>
<Text>{`${info.section.title} - ${info.item}`}</Text>
</View>
)}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
ListHeaderComponent={null}
ListHeaderComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
/>
</React.Fragment>
);
}
}
type SectionT = { displayTitle: false } | { displayTitle: true; title: string };
export class SectionListTypedSectionTest extends React.Component<SectionListProps<string, SectionT>, {}> {
myList: React.RefObject<SectionList<string, SectionT>>;
constructor(props: SectionListProps<string, SectionT>) {
super(props);
this.myList = React.createRef();
}
scrollMe = () => {
this.myList.current && this.myList.current.scrollToLocation({ itemIndex: 0, sectionIndex: 1 });
};
render() {
const sections: SectionListData<string, SectionT>[] = [
{
displayTitle: false,
data: ['A', 'B', 'C', 'D', 'E'],
},
{
displayTitle: true,
title: 'Section 2',
data: ['A2', 'B2', 'C2', 'D2', 'E2'],
renderItem: (info: { item: string }) => (
<View>
<Text>{info.item}</Text>
</View>
),
},
];
const cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
return (
<React.Fragment>
<Button title="Press" onPress={this.scrollMe} />
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
/>
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={null}
ListHeaderComponent={null}
ListHeaderComponentStyle={null}
/>
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={undefined}
ListHeaderComponent={null}
ListHeaderComponentStyle={undefined}
/>
</React.Fragment>
);
}
}
export class CapsLockComponent extends React.Component<TextProps> {
render() {
const content = (this.props.children || '') as string;
return <Text {...this.props}>{content.toUpperCase()}</Text>;
}
}
const getInitialUrlTest = () =>
Linking.getInitialURL().then(val => {
if (val !== null) {
val.indexOf('val is now a string');
}
});
LogBox.ignoreAllLogs();
LogBox.ignoreAllLogs(true);
LogBox.ignoreLogs(['someString', /^aRegex/]);
LogBox.install();
LogBox.uninstall();
class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListViewDataSource }> {
_stickyHeaderComponent = ({ children }: any) => {
return <View>{children}</View>;
};
eventHandler = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
console.log(event);
};
scrollView: ScrollView | null = null;
testNativeMethods() {
if (this.scrollView) {
this.scrollView.setNativeProps({ scrollEnabled: false });
// Dummy values for scroll dimensions changes
this.scrollView.getScrollResponder().scrollResponderZoomTo({
x: 0,
y: 0,
width: 300,
height: 500,
animated: true,
});
}
}
render() {
const scrollViewStyle1 = StyleSheet.create({
scrollView: {
backgroundColor: 'red',
},
});
const scrollViewStyle2 = {
flex: 1,
};
return (
<ListView
dataSource={this.state.dataSource}
renderScrollComponent={props => {
if (props.scrollEnabled) {
throw new Error('Expected scroll to be enabled.');
}
return (
<ScrollView
ref={ref => (this.scrollView = ref)}
horizontal={true}
nestedScrollEnabled={true}
invertStickyHeaders={true}
contentOffset={{ x: 0, y: 0 }}
snapToStart={false}
snapToEnd={false}
snapToOffsets={[100, 300, 500]}
{...props}
style={[scrollViewStyle1.scrollView, scrollViewStyle2]}
onScrollToTop={() => {}}
scrollToOverflowEnabled={true}
fadingEdgeLength={200}
StickyHeaderComponent={this._stickyHeaderComponent}
stickyHeaderHiddenOnScroll={true}
automaticallyAdjustKeyboardInsets
/>
);
}}
renderRow={({ type, data }, _, row) => {
return <Text>Filler</Text>;
}}
onScroll={this.eventHandler}
onScrollBeginDrag={this.eventHandler}
onScrollEndDrag={this.eventHandler}
onMomentumScrollBegin={this.eventHandler}
onMomentumScrollEnd={this.eventHandler}
/>
);
}
}
class TabBarTest extends React.Component {
render() {
return (
<TabBarIOS
barTintColor="darkslateblue"
itemPositioning="center"
tintColor="white"
translucent={true}
unselectedTintColor="black"
unselectedItemTintColor="red"
>
<TabBarIOS.Item
badge={0}
badgeColor="red"
icon={{ uri: undefined }}
selected={true}
onPress={() => {}}
renderAsOriginal={true}
selectedIcon={undefined}
systemIcon="history"
title="Item 1"
/>
</TabBarIOS>
);
}
}
class AlertTest extends React.Component {
showAlert() {
Alert.alert(
'Title',
'Message',
[
{ text: 'First button', onPress: () => {} },
{ text: 'Second button', onPress: () => {} },
{ text: 'Third button', onPress: () => {} },
],
{
cancelable: false,
onDismiss: () => {},
},
);
}
render() {
return <Button title="Press me" onPress={this.showAlert} />;
}
}
Alert.prompt(
'Enter password',
'Enter your password to claim your $1.5B in lottery winnings',
text => {
console.log(text);
},
'secure-text',
);
Alert.prompt(
'Enter password',
'Enter your password to claim your $1.5B in lottery winnings',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'OK',
onPress: password => console.log('OK Pressed, password: ' + password),
},
],
'secure-text',
);
class MaskedViewTest extends React.Component {
render() {
return (
<MaskedViewIOS maskElement={<View />}>
<View />
</MaskedViewIOS>
);
}
}
class InputAccessoryViewTest extends React.Component {
render() {
const uniqueID = 'foobar';
return (
<InputAccessoryView nativeID={uniqueID}>
<TextInput inputAccessoryViewID={uniqueID} />
</InputAccessoryView>
);
}
}
// DataSourceAssetCallback
const dataSourceAssetCallback1: DataSourceAssetCallback = {
rowHasChanged: (r1, r2) => true,
sectionHeaderHasChanged: (h1, h2) => true,
getRowData: (dataBlob, sectionID, rowID) => (sectionID as number) + (rowID as number),
getSectionHeaderData: (dataBlob, sectionID) => sectionID as string,
};
const dataSourceAssetCallback2: DataSourceAssetCallback = {};
// DeviceEventEmitterStatic
const deviceEventEmitterStatic: DeviceEventEmitterStatic = DeviceEventEmitter;
deviceEventEmitterStatic.addListener('keyboardWillShow', data => true);
deviceEventEmitterStatic.addListener('keyboardWillShow', data => true, {});
// NativeEventEmitter - Android
const androidEventEmitter = new NativeEventEmitter();
const sub1 = androidEventEmitter.addListener('event', (event: object) => event);
const sub2 = androidEventEmitter.addListener('event', (event: object) => event, {});
androidEventEmitter.listenerCount('event'); // $ExpectType number
sub2.remove();
androidEventEmitter.removeAllListeners('event');
androidEventEmitter.removeSubscription(sub1);
// NativeEventEmitter - IOS
const nativeModule: NativeModule = {
addListener(eventType: string) {},
removeListeners(count: number) {},
};
const iosEventEmitter = new NativeEventEmitter(nativeModule);
const sub3 = iosEventEmitter.addListener('event', (event: object) => event);
const sub4 = iosEventEmitter.addListener('event', (event: object) => event, {});
iosEventEmitter.listenerCount('event');
sub4.remove();
iosEventEmitter.removeAllListeners('event');
iosEventEmitter.removeSubscription(sub3);
class CustomEventEmitter extends NativeEventEmitter {}
const customEventEmitter = new CustomEventEmitter();
customEventEmitter.addListener('event', () => {});
class TextInputTest extends React.Component<{}, { username: string }> {
username: TextInput | null = null;
handleUsernameChange = (text: string) => {
console.log(`text: ${text}`);
};
onScroll = (e: NativeSyntheticEvent<TextInputScrollEventData>) => {
testNativeSyntheticEvent(e);
console.log(`x: ${e.nativeEvent.contentOffset.x}`);
console.log(`y: ${e.nativeEvent.contentOffset.y}`);
};
handleOnBlur = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
};
handleOnFocus = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
};
handleOnSelectionChange = (e: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`target: ${e.nativeEvent.target}`);
console.log(`start: ${e.nativeEvent.selection.start}`);
console.log(`end: ${e.nativeEvent.selection.end}`);
};
handleOnKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
testNativeSyntheticEvent(e);
console.log(`key: ${e.nativeEvent.key}`);
};
handleOnChange = (e: NativeSyntheticEvent<TextInputChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`eventCount: ${e.nativeEvent.eventCount}`);
console.log(`target: ${e.nativeEvent.target}`);
console.log(`text: ${e.nativeEvent.text}`);
};
handleOnContentSizeChange = (e: NativeSyntheticEvent<TextInputContentSizeChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`contentSize.width: ${e.nativeEvent.contentSize.width}`);
console.log(`contentSize.height: ${e.nativeEvent.contentSize.height}`);
};
handleOnEndEditing = (e: NativeSyntheticEvent<TextInputEndEditingEventData>) => {
testNativeSyntheticEvent(e);
console.log(`text: ${e.nativeEvent.text}`);
};
handleOnSubmitEditing = (e: NativeSyntheticEvent<TextInputSubmitEditingEventData>) => {
testNativeSyntheticEvent(e);
console.log(`text: ${e.nativeEvent.text}`);
};
render() {
return (
<View>
<Text onPress={() => this.username && this.username.focus()}>Username</Text>
<TextInput
ref={input => (this.username = input)}
textContentType="username"
autoComplete="username"
value={this.state.username}
onChangeText={this.handleUsernameChange}
/>
<TextInput multiline onScroll={this.onScroll} />
<TextInput onBlur={this.handleOnBlur} onFocus={this.handleOnFocus} />
<TextInput onSelectionChange={this.handleOnSelectionChange} />
<TextInput onKeyPress={this.handleOnKeyPress} />
<TextInput onChange={this.handleOnChange} />
<TextInput onChange={this.handleOnChange} />
<TextInput onEndEditing={this.handleOnEndEditing} />
<TextInput onSubmitEditing={this.handleOnSubmitEditing} />
<TextInput multiline onContentSizeChange={this.handleOnContentSizeChange} />
<TextInput contextMenuHidden={true} textAlignVertical="top" />
<TextInput textAlign="center" />
</View>
);
}
}
class TextTest extends React.Component {
handleOnLayout = (e: LayoutChangeEvent) => {
testNativeSyntheticEvent(e);
const x = e.nativeEvent.layout.x; // $ExpectType number
const y = e.nativeEvent.layout.y; // $ExpectType number
const width = e.nativeEvent.layout.width; // $ExpectType number
const height = e.nativeEvent.layout.height; // $ExpectType number
};
handleOnTextLayout = (e: NativeSyntheticEvent<TextLayoutEventData>) => {
testNativeSyntheticEvent(e);
e.nativeEvent.lines.forEach(line => {
const ascender = line.ascender; // $ExpectType number
const capHeight = line.capHeight; // $ExpectType number
const descender = line.descender; // $ExpectType number
const height = line.height; // $ExpectType number
const text = line.text; // $ExpectType string
const width = line.width; // $ExpectType number
const x = line.x; // $ExpectType number
const xHeight = line.xHeight; // $ExpectType number
const y = line.y; // $ExpectType number
});
};
render() {
return (
<Text
allowFontScaling={false}
ellipsizeMode="head"
lineBreakMode="clip"
numberOfLines={2}
onLayout={this.handleOnLayout}
onTextLayout={this.handleOnTextLayout}
>
Test text
</Text>
);
}
}
class StatusBarTest extends React.Component {
render() {
StatusBar.setBarStyle('dark-content', true);
console.log('height:', StatusBar.currentHeight);
return <StatusBar backgroundColor="blue" barStyle="light-content" translucent />;
}
}
export class ImageTest extends React.Component {
componentDidMount(): void {
const uri = 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png';
const headers = { Authorization: 'Bearer test' };
const image: ImageResolvedAssetSource = Image.resolveAssetSource({ uri });
console.log(image.width, image.height, image.scale, image.uri);
Image.queryCache &&
Image.queryCache([uri]).then(({ [uri]: status }) => {
if (status === undefined) {
console.log('Image is not in cache');
} else {
console.log(`Image is in ${status} cache`);
}
});
Image.getSize(uri, (width, height) => console.log(width, height));
Image.getSize(
uri,
(width, height) => console.log(width, height),
error => console.error(error),
);
Image.getSizeWithHeaders(uri, headers, (width, height) => console.log(width, height));
Image.getSizeWithHeaders(
uri,
headers,
(width, height) => console.log(width, height),
error => console.error(error),
);
Image.prefetch(uri); // $ExpectType Promise<boolean>
}
handleOnLoad = (e: NativeSyntheticEvent<ImageLoadEventData>) => {
testNativeSyntheticEvent(e);
console.log('height:', e.nativeEvent.source.height);
console.log('width:', e.nativeEvent.source.width);
console.log('uri:', e.nativeEvent.source.uri);
};
handleOnError = (e: NativeSyntheticEvent<ImageErrorEventData>) => {
testNativeSyntheticEvent(e);
console.log('error:', e.nativeEvent.error);
};
render() {
const resizeMode: ImageResizeMode = 'contain';
return (
<View>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
onLoad={this.handleOnLoad}
onError={this.handleOnError}
/>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
resizeMode={resizeMode}
/>
</View>
);
}
}
export class ImageBackgroundProps extends React.Component {
private _imageRef: Image | null = null;
setImageRef = (image: Image) => {
this._imageRef = image;
};
render() {
return (
<View>
<ImageBackground
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
imageRef={this.setImageRef}
>
<Text>Some text</Text>
</ImageBackground>
</View>
);
}
}
const listViewDataSourceTest = new ListView.DataSource({ rowHasChanged: () => true });
class AccessibilityTest extends React.Component {
render() {
return (
<View
accessibilityElementsHidden={true}
importantForAccessibility={'no-hide-descendants'}
onAccessibilityTap={() => {}}
accessibilityRole="header"
accessibilityState={{ checked: true }}
accessibilityHint="Very important header"
accessibilityValue={{ min: 60, max: 120, now: 80 }}
onMagicTap={() => {}}
onAccessibilityEscape={() => {}}
>
<Text accessibilityIgnoresInvertColors>Text</Text>
<View />
</View>
);
}
}
AccessibilityInfo.isBoldTextEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),
);
AccessibilityInfo.isGrayscaleEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isGrayscaleEnabled => ${isEnabled}`),
);
AccessibilityInfo.isInvertColorsEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isInvertColorsEnabled => ${isEnabled}`),
);
AccessibilityInfo.isReduceMotionEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isReduceMotionEnabled => ${isEnabled}`),
);
AccessibilityInfo.isReduceTransparencyEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isReduceTransparencyEnabled => ${isEnabled}`),
);
AccessibilityInfo.isScreenReaderEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isScreenReaderEnabled => ${isEnabled}`),
);
AccessibilityInfo.getRecommendedTimeoutMillis(5000).then(timeoutMiles =>
console.log(`AccessibilityInfo.getRecommendedTimeoutMillis => ${timeoutMiles}`)
);
AccessibilityInfo.addEventListener('announcementFinished', ({ announcement, success }) =>
console.log(`A11y Event: announcementFinished: ${announcement}, ${success}`),
);
AccessibilityInfo.addEventListener('boldTextChanged', isEnabled =>
console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('grayscaleChanged', isEnabled =>
console.log(`AccessibilityInfo.isGrayscaleEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('invertColorsChanged', isEnabled =>
console.log(`AccessibilityInfo.isInvertColorsEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('reduceMotionChanged', isEnabled =>
console.log(`AccessibilityInfo.isReduceMotionEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('reduceTransparencyChanged', isEnabled =>
console.log(`AccessibilityInfo.isReduceTransparencyEnabled => ${isEnabled}`),
);
const screenReaderChangedListener = (isEnabled: boolean): void => console.log(`AccessibilityInfo.isScreenReaderEnabled => ${isEnabled}`);
AccessibilityInfo.addEventListener('screenReaderChanged', screenReaderChangedListener,
).remove();
AccessibilityInfo.removeEventListener('screenReaderChanged', screenReaderChangedListener);
const KeyboardAvoidingViewTest = () => <KeyboardAvoidingView enabled />;
const ModalTest = () => <Modal hardwareAccelerated />;
const ModalTest2 = () => <Modal hardwareAccelerated testID="modal-test-2" />;
const TimePickerAndroidTest = () => {
TimePickerAndroid.open({
hour: 8,
minute: 15,
is24Hour: true,
mode: 'spinner',
}).then(result => {
if (result.action === TimePickerAndroid.timeSetAction) {
console.log('Time', result.hour, result.minute);
}
});
};
const DatePickerAndroidTest = () => {
DatePickerAndroid.open({
date: new Date(),
mode: 'calendar',
}).then(result => {
if (result.action === DatePickerAndroid.dateSetAction) {
console.log('Date', result.year, result.month, result.day);
}
});
};
const NativeBridgedComponent = requireNativeComponent<{ nativeProp: string }>('NativeBridgedComponent'); // $ExpectType HostComponent<{ nativeProp: string; }>
class BridgedComponentTest extends React.Component {
static propTypes = {
jsProp: PropTypes.string.isRequired,
};
nativeComponentRef: React.ElementRef<typeof NativeBridgedComponent> | null;
callNativeMethod = () => {
UIManager.dispatchViewManagerCommand(findNodeHandle(this.nativeComponentRef), 'someNativeMethod', []);
};
measureNativeComponent() {
if (this.nativeComponentRef) {
this.nativeComponentRef.measure(
(x, y, width, height, pageX, pageY) => x + y + width + height + pageX + pageY,
);
}
}
render() {
return (
<NativeBridgedComponent {...this.props} nativeProp="test" ref={ref => (this.nativeComponentRef = ref)} />
);
}
}
const SwitchColorTest = () => <Switch trackColor={{ true: 'pink', false: 'red' }} />;
const SwitchColorOptionalTrueTest = () => <Switch trackColor={{ false: 'red' }} />;
const SwitchColorOptionalFalseTest = () => <Switch trackColor={{ true: 'pink' }} />;
const SwitchColorNullTest = () => <Switch trackColor={{ true: 'pink', false: null }} />;
const SwitchThumbColorTest = () => <Switch thumbColor={'red'} />;
const SwitchOnChangeWithoutParamsTest = () => <Switch onChange={() => console.log('test')} />;
const SwitchOnChangeUndefinedTest = () => <Switch onChange={undefined} />;
const SwitchOnChangeNullTest = () => <Switch onChange={null} />;
const SwitchOnChangePromiseTest = () => <Switch onChange={(event) => {
const e: SwitchChangeEvent = event;
return new Promise(() => e.value);
}} />;
const SwitchOnValueChangeWithoutParamsTest = () => <Switch onValueChange={() => console.log('test')} />;
const SwitchOnValueChangeUndefinedTest = () => <Switch onValueChange={undefined} />;
const SwitchOnValueChangeNullTest = () => <Switch onValueChange={null} />;
const SwitchOnValueChangePromiseTest = () => <Switch onValueChange={(value) => {
const v: boolean = value;
return new Promise(() => v)
}} />;
const NativeIDTest = () => (
<ScrollView nativeID={'nativeID'}>
<View nativeID={'nativeID'} />
<Text nativeID={'nativeID'}>Text</Text>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
nativeID={'nativeID'}
/>
</ScrollView>
);
const ScrollViewMaintainVisibleContentPositionTest = () => (
<ScrollView maintainVisibleContentPosition={{ autoscrollToTopThreshold: 1, minIndexForVisible: 10 }}></ScrollView>
);
const ScrollViewInsetsTest = () => (
<>
<ScrollView automaticallyAdjustKeyboardInsets />
<ScrollView automaticallyAdjustKeyboardInsets={false} />
</>
);
const MaxFontSizeMultiplierTest = () => <Text maxFontSizeMultiplier={0}>Text</Text>;
const ShareTest = () => {
Share.share(
{ title: 'title', message: 'message' },
{ dialogTitle: 'dialogTitle', excludedActivityTypes: ['activity'], tintColor: 'red', subject: 'Email subject' },
);
Share.share({ title: 'title', url: 'url' });
Share.share({ message: 'message' }).then(result => {
if (result.action === Share.sharedAction) {
const activity = result.activityType;
} else if (result.action === Share.dismissedAction) {
}
});
};
const KeyboardTest = () => {
const subscriber = Keyboard.addListener('keyboardDidHide', event => {
event;
});
subscriber.remove();
Keyboard.dismiss();
// Android Keyboard Event
Keyboard.scheduleLayoutAnimation({
duration: 0,
easing: 'keyboard',
endCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
});
// IOS Keyboard Event
Keyboard.scheduleLayoutAnimation({
duration: 0,
easing: 'easeInEaseOut',
endCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
startCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
isEventFromThisApp: true,
});
};
const PermissionsAndroidTest = () => {
PermissionsAndroid.request('android.permission.CAMERA').then(result => {
switch (result) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
PermissionsAndroid.requestMultiple([
'android.permission.CAMERA',
'android.permission.ACCESS_FINE_LOCATION',
'android.permission.ACCESS_BACKGROUND_LOCATION',
]).then(results => {
switch (results['android.permission.CAMERA']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.ACCESS_FINE_LOCATION']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.ACCESS_BACKGROUND_LOCATION']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
PermissionsAndroid.requestMultiple([
'android.permission.BLUETOOTH_SCAN',
'android.permission.BLUETOOTH_CONNECT',
'android.permission.BLUETOOTH_ADVERTISE'
]).then(results => {
switch (results['android.permission.BLUETOOTH_SCAN']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.BLUETOOTH_CONNECT']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.BLUETOOTH_ADVERTISE']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
};
// Platform
const PlatformTest = () => {
switch (Platform.OS) {
case 'ios':
if (!Platform.isPad) {
return 32;
} else {
return 44;
}
case 'android':
case 'macos':
case 'windows':
return Platform.isTV ? 64 : 56;
default:
return Platform.isTV ? 40 : 44;
}
};
const PlatformConstantsTest = () => {
const testing: boolean = Platform.constants.isTesting;
if (Platform.OS === 'ios') {
const hasForceTouch: boolean = Platform.constants.forceTouchAvailable;
} else if (Platform.OS === 'android') {
const { major, prerelease } = Platform.constants.reactNativeVersion;
const v = Platform.constants.Version;
const host: string | undefined = Platform.constants.ServerHost;
}
};
Platform.select({ native: 1 }); // $ExpectType number | undefined
Platform.select({ native: 1, web: 2, default: 0 }); // $ExpectType number
Platform.select({ android: 1 }); // $ExpectType number | undefined
Platform.select({ android: 1, ios: 2, default: 0 }); // $ExpectType number
Platform.select({ android: 1, ios: 2, macos: 3, web: 4, windows: 5 }); // $ExpectType number | undefined
Platform.select({ android: 1, ios: 2, macos: 3, web: 4, windows: 5, default: 0 }); // $ExpectType number
PlatformColor('?attr/colorControlNormal');
PlatformColor('?attr/colorControlNormal', '?attr/colorAccent', 'another');
DynamicColorIOS({
dark: 'lightskyblue',
light: 'midnightblue',
});
DynamicColorIOS({
dark: 'lightskyblue',
light: PlatformColor('labelColor'),
});
// Test you cannot set internals of ColorValue directly
const OpaqueTest1 = () => (
<View
// @ts-expect-error
style={{
backgroundColor: {
resource_paths: ['?attr/colorControlNormal'],
},
}}
/>
);
const OpaqueTest2 = () => (
<View
// @ts-expect-error
style={{
backgroundColor: {
semantic: 'string',
dynamic: {
light: 'light',
dark: 'dark',
},
},
}}
/>
);
// Test you cannot amend opaque type
// @ts-expect-error
PlatformColor('?attr/colorControlNormal').resource_paths.push('foo');
const someColorProp: ColorValue = PlatformColor('test');
// Test PlatformColor inside Platform select with stylesheet
StyleSheet.create({
labelCell: {
flex: 1,
alignItems: 'stretch',
...Platform.select({
ios: { color: DynamicColorIOS({ dark: 'lightskyblue', light: PlatformColor('labelColor') }) },
android: {
color: PlatformColor('?attr/colorControlNormal'),
},
default: { color: PlatformColor('?attr/colorControlNormal') },
}),
},
});
// PlatformColor in style colors
StyleSheet.create({
labelCell: {
flex: 1,
alignItems: 'stretch',
color: PlatformColor('test'),
backgroundColor: PlatformColor('test'),
borderBottomColor: PlatformColor('test'),
borderColor: PlatformColor('test'),
borderEndColor: PlatformColor('test'),
borderLeftColor: PlatformColor('test'),
borderRightColor: PlatformColor('test'),
borderStartColor: PlatformColor('test'),
borderTopColor: PlatformColor('test'),
overlayColor: PlatformColor('test'),
shadowColor: PlatformColor('test'),
textDecorationColor: PlatformColor('test'),
textShadowColor: PlatformColor('test'),
tintColor: PlatformColor('test'),
},
});
function someColorString(): ColorValue {
return '#000000';
}
function somePlatformColor(): ColorValue {
return PlatformColor('test');
}
const colors = {
color: someColorString(),
backgroundColor: somePlatformColor(),
};
StyleSheet.create({
labelCell: {
color: colors.color,
backgroundColor: colors.backgroundColor,
},
});
const OpaqueTest3 = () => (
<View
style={{
backgroundColor: colors.backgroundColor,
}}
/>
);
// ProgressBarAndroid
const ProgressBarAndroidTest = () => {
<ProgressBarAndroid animating color="white" styleAttr="Horizontal" progress={0.42} />;
};
// Push notification
const PushNotificationTest = () => {
PushNotificationIOS.presentLocalNotification({
alertBody: 'notificatus',
userInfo: 'informius',
alertTitle: 'Titulus',
alertAction: 'view',
});
PushNotificationIOS.scheduleLocalNotification({
alertAction: 'view',
alertBody: 'Look at me!',
alertTitle: 'Hello!',
applicationIconBadgeNumber: 999,
category: 'engagement',
fireDate: new Date().toISOString(),
isSilent: false,
repeatInterval: 'minute',
userInfo: {
abc: 123,
},
});
};
// YellowBox
const YellowBoxTest = () => <YellowBox />;
// Appearance
const DarkMode = () => {
const color = useColorScheme();
const isDarkMode = Appearance.getColorScheme() === 'dark';
const subscription = Appearance.addChangeListener(({ colorScheme }) => {
console.log(colorScheme);
});
React.useEffect(() => {
console.log('-color', color);
return () => {
subscription.remove();
};
}, [color]);
return <Text>Is dark mode enabled? {isDarkMode}</Text>;
};
// VirtualizedList
// Test inspired by: https://reactnative.dev/docs/virtualizedlist
const VirtualizedListTest = () => {
const DATA = [1, 2, 3];
const getItem = (data: number[], index: number) => {
return {
title: `Item ${data[index]}`,
};
};
const getItemCount = (data: number[]) => data.length;
return (
<VirtualizedList
data={DATA}
initialNumToRender={4}
renderItem={({ item }: ListRenderItemInfo<ReturnType<typeof getItem>>) => <Text>{item.title}</Text>}
getItemCount={getItemCount}
getItem={getItem}
/>
);
};
// DevSettings
DevSettings.addMenuItem('alert', () => {
Alert.alert('alert');
});
DevSettings.reload();
DevSettings.reload('reload with reason');
// Accessibility custom actions
const AccessibilityCustomActionsTest = () => {
return (
<View
accessible={true}
accessibilityActions={[
// should support custom defined actions
{ name: 'cut', label: 'cut' },
{ name: 'copy', label: 'copy' },
{ name: 'paste', label: 'paste' },
]}
onAccessibilityAction={event => {
switch (event.nativeEvent.actionName) {
case 'cut':
Alert.alert('Alert', 'cut action success');
break;
case 'copy':
Alert.alert('Alert', 'copy action success');
break;
case 'paste':
Alert.alert('Alert', 'paste action success');
break;
}
}}
/>
);
};
// DrawerLayoutAndroidTest
export class DrawerLayoutAndroidTest extends React.Component {
drawerRef = React.createRef<DrawerLayoutAndroid>();
readonly styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 50,
backgroundColor: '#ecf0f1',
padding: 8,
},
navigationContainer: {
flex: 1,
paddingTop: 50,
backgroundColor: '#fff',
padding: 8,
},
});
readonly navigationView = (
<View style={this.styles.navigationContainer}>
<Text style={{ margin: 10, fontSize: 15 }}>I'm in the Drawer!</Text>
</View>
);
handleDrawerClose = () => {
console.log('handleDrawerClose');
};
handleDrawerOpen = () => {
console.log('handleDrawerOpen');
};
handleDrawerSlide = (event: DrawerSlideEvent) => {
console.log('handleDrawerSlide', event);
};
handleDrawerStateChanged = (event: 'Idle' | 'Dragging' | 'Settling') => {
console.log('handleDrawerStateChanged', event);
};
render() {
return (
<DrawerLayoutAndroid
ref={this.drawerRef}
drawerBackgroundColor="rgba(0,0,0,0.5)"
drawerLockMode="locked-closed"
drawerPosition="right"
drawerWidth={300}
keyboardDismissMode="on-drag"
onDrawerClose={this.handleDrawerClose}
onDrawerOpen={this.handleDrawerOpen}
onDrawerSlide={this.handleDrawerSlide}
onDrawerStateChanged={this.handleDrawerStateChanged}
renderNavigationView={() => this.navigationView}
statusBarBackgroundColor="yellow"
>
<View style={this.styles.container}>
<Text style={{ margin: 10, fontSize: 15 }}>DrawerLayoutAndroid example</Text>
</View>
</DrawerLayoutAndroid>
);
}
}
// DataDetectorType for Text component
const DataDetectorTypeTest = () => {
return (
<>
<Text dataDetectorType={'all'}>http://test.com [email protected] +33123456789</Text>
<Text dataDetectorType={'email'}>[email protected]</Text>
<Text dataDetectorType={'link'}>http://test.com</Text>
<Text dataDetectorType={'none'}>Hi there !</Text>
<Text dataDetectorType={'phoneNumber'}>+33123456789</Text>
<Text dataDetectorType={null}>Must allow null value</Text>
</>
);
};
const ToastAndroidTest = () => {
ToastAndroid.showWithGravityAndOffset('My Toast', ToastAndroid.SHORT, ToastAndroid.BOTTOM, 0, 50);
};
const I18nManagerTest = () => {
I18nManager.allowRTL(true);
I18nManager.forceRTL(true);
I18nManager.swapLeftAndRightInRTL(true);
const { isRTL, doLeftAndRightSwapInRTL } = I18nManager.getConstants();
const isRtlFlag = I18nManager.isRTL;
const doLeftAndRightSwapInRtlFlag = I18nManager.doLeftAndRightSwapInRTL;
console.log(isRTL, isRtlFlag, doLeftAndRightSwapInRTL, doLeftAndRightSwapInRtlFlag);
};
// LayoutAnimations
LayoutAnimation.configureNext(
LayoutAnimation.create(123, LayoutAnimation.Types.easeIn, LayoutAnimation.Properties.opacity),
);
LayoutAnimation.configureNext(LayoutAnimation.create(123, 'easeIn', 'opacity'));
// ActionSheetIOS
const ActionSheetIOSTest = () => {
// test destructiveButtonIndex undefined
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: undefined,
}, () => undefined);
// test destructiveButtonIndex null
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: null,
}, () => undefined);
// test destructiveButtonIndex single number
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: 0,
}, () => undefined);
// test destructiveButtonIndex number array
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo', 'bar'],
destructiveButtonIndex: [0, 1],
}, () => undefined);
}
| types/react-native/v0.69/test/index.tsx | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00024903181474655867,
0.00017164082964882255,
0.00016560776566620916,
0.00016883559874258935,
0.00001000295378617011
]
|
{
"id": 0,
"code_window": [
" | 'timer'\n",
" | 'list'\n",
" | 'toolbar';\n",
"\n",
"export interface AccessibilityPropsAndroid {\n",
" /**\n",
" * Indicates to accessibility services whether the user should be notified when this view changes.\n",
" * Works for Android API >= 19 only.\n",
" * See http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion for references.\n",
" * @platform android\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * Specifies the nativeID of the associated label text. When the assistive technology focuses on the component with this props, the text is read aloud.\n",
" * @platform android\n",
" */\n",
" accessibilityLabelledBy?: string | string[] | undefined;\n",
"\n"
],
"file_path": "types/react-native/index.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | {
"compilerOptions": {
"module": "commonjs",
"lib": ["es6", "esnext.asynciterable"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"@absinthe/*": ["absinthe__*"]
}
},
"files": ["index.d.ts", "absinthe__socket-apollo-link-tests.ts"]
}
| types/absinthe__socket-apollo-link/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00016801297897472978,
0.00016716800746507943,
0.0001663230505073443,
0.00016716800746507943,
8.449642336927354e-7
]
|
{
"id": 0,
"code_window": [
" | 'timer'\n",
" | 'list'\n",
" | 'toolbar';\n",
"\n",
"export interface AccessibilityPropsAndroid {\n",
" /**\n",
" * Indicates to accessibility services whether the user should be notified when this view changes.\n",
" * Works for Android API >= 19 only.\n",
" * See http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion for references.\n",
" * @platform android\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * Specifies the nativeID of the associated label text. When the assistive technology focuses on the component with this props, the text is read aloud.\n",
" * @platform android\n",
" */\n",
" accessibilityLabelledBy?: string | string[] | undefined;\n",
"\n"
],
"file_path": "types/react-native/index.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | export { SearchAdvanced as default } from "../";
| types/carbon__icons-react/es/SearchAdvanced.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00017451969324611127,
0.00017451969324611127,
0.00017451969324611127,
0.00017451969324611127,
0
]
|
{
"id": 0,
"code_window": [
" | 'timer'\n",
" | 'list'\n",
" | 'toolbar';\n",
"\n",
"export interface AccessibilityPropsAndroid {\n",
" /**\n",
" * Indicates to accessibility services whether the user should be notified when this view changes.\n",
" * Works for Android API >= 19 only.\n",
" * See http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion for references.\n",
" * @platform android\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * Specifies the nativeID of the associated label text. When the assistive technology focuses on the component with this props, the text is read aloud.\n",
" * @platform android\n",
" */\n",
" accessibilityLabelledBy?: string | string[] | undefined;\n",
"\n"
],
"file_path": "types/react-native/index.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | // Type definitions for ttf2eot 2.0
// Project: https://github.com/fontello/ttf2eot#readme
// Definitions by: Kaspar Vollenweider <https://github.com/casaper>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare function ttf2eot(ttf: Uint8Array): Buffer;
export = ttf2eot;
| types/ttf2eot/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00017301144544035196,
0.0001719366409815848,
0.00017086185107473284,
0.0001719366409815848,
0.0000010747971828095615
]
|
{
"id": 3,
"code_window": [
" </View>\n",
" );\n",
" }\n",
"}\n",
"\n",
"AccessibilityInfo.isBoldTextEnabled().then(isEnabled =>\n",
" console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),\n",
");\n",
"AccessibilityInfo.isGrayscaleEnabled().then(isEnabled =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const AccessibilityLabelledByTest = () => (\n",
" <>\n",
" <View accessibilityLabelledBy=\"nativeID1\"></View>\n",
" <View accessibilityLabelledBy={[\"nativeID2\", \"nativeID3\"]}></View>\n",
" </>\n",
")\n",
"\n"
],
"file_path": "types/react-native/test/index.tsx",
"type": "add",
"edit_start_line_idx": 1008
} | /*
The content of index.io.js could be something like
'use strict';
import { AppRegistry } from 'react-native'
import Welcome from './gen/Welcome'
AppRegistry.registerComponent('MopNative', () => Welcome);
For a list of complete Typescript examples: check https://github.com/bgrieder/RNTSExplorer
*/
import * as PropTypes from 'prop-types';
import * as React from 'react';
import {
AccessibilityInfo,
ActionSheetIOS,
AsyncStorage,
Alert,
AppState,
AppStateStatus,
Appearance,
BackHandler,
Button,
ColorValue,
DataSourceAssetCallback,
DatePickerAndroid,
DevSettings,
DeviceEventEmitter,
DeviceEventEmitterStatic,
Dimensions,
DrawerLayoutAndroid,
DrawerSlideEvent,
DynamicColorIOS,
FlatList,
FlatListProps,
GestureResponderEvent,
HostComponent,
I18nManager,
Image,
ImageBackground,
ImageErrorEventData,
ImageLoadEventData,
ImageResizeMode,
ImageResolvedAssetSource,
ImageStyle,
InputAccessoryView,
InteractionManager,
Keyboard,
KeyboardAvoidingView,
LayoutChangeEvent,
Linking,
ListRenderItemInfo,
ListView,
ListViewDataSource,
LogBox,
MaskedViewIOS,
Modal,
NativeEventEmitter,
NativeModule, // Not actually exported, not sure why
NativeModules,
NativeScrollEvent,
NativeSyntheticEvent,
PermissionsAndroid,
Platform,
PlatformColor,
Pressable,
ProgressBarAndroid,
ProgressViewIOS,
PushNotificationIOS,
RefreshControl,
RegisteredStyle,
ScaledSize,
ScrollView,
ScrollViewProps,
SectionList,
SectionListProps,
SectionListRenderItemInfo,
Share,
ShareDismissedAction,
ShareSharedAction,
StatusBar,
StyleProp,
StyleSheet,
Switch,
SwitchIOS,
SwitchChangeEvent,
Systrace,
TabBarIOS,
Text,
TextInput,
TextInputChangeEventData,
TextInputContentSizeChangeEventData,
TextInputEndEditingEventData,
TextInputFocusEventData,
TextInputKeyPressEventData,
TextInputScrollEventData,
TextInputSelectionChangeEventData,
TextInputSubmitEditingEventData,
TextLayoutEventData,
TextProps,
TextStyle,
TimePickerAndroid,
TouchableNativeFeedback,
UIManager,
View,
ViewPagerAndroid,
ViewStyle,
VirtualizedList,
YellowBox,
findNodeHandle,
requireNativeComponent,
useColorScheme,
useWindowDimensions,
SectionListData,
ToastAndroid,
Touchable,
LayoutAnimation,
} from 'react-native';
declare module 'react-native' {
interface NativeTypedModule {
someFunction(): void;
someProperty: string;
}
interface NativeModulesStatic {
NativeTypedModule: NativeTypedModule;
}
}
NativeModules.NativeUntypedModule;
NativeModules.NativeTypedModule.someFunction();
NativeModules.NativeTypedModule.someProperty = '';
function dimensionsListener(dimensions: { window: ScaledSize; screen: ScaledSize }) {
console.log('window dimensions: ', dimensions.window);
console.log('screen dimensions: ', dimensions.screen);
}
function testDimensions() {
const { width, height, scale, fontScale } = Dimensions.get(1 === 1 ? 'window' : 'screen');
Dimensions.addEventListener('change', dimensionsListener);
Dimensions.removeEventListener('change', dimensionsListener);
}
function TextUseWindowDimensions() {
const { width, height, scale, fontScale } = useWindowDimensions();
}
BackHandler.addEventListener('hardwareBackPress', () => true).remove();
BackHandler.addEventListener('hardwareBackPress', () => false).remove();
BackHandler.addEventListener('hardwareBackPress', () => undefined).remove();
BackHandler.addEventListener('hardwareBackPress', () => null).remove();
interface LocalStyles {
container: ViewStyle;
welcome: TextStyle;
instructions: TextStyle;
}
const styles = StyleSheet.create<LocalStyles>({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
//alternative declaration of styles (inline typings)
const stylesAlt = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
StyleSheet.setStyleAttributePreprocessor('fontFamily', (family: string) => family);
const welcomeFontSize = StyleSheet.flatten(styles.welcome).fontSize;
const viewStyle: StyleProp<ViewStyle> = {
backgroundColor: '#F5FCFF',
};
const textStyle: StyleProp<TextStyle> = {
fontSize: 20,
};
const imageStyle: StyleProp<ImageStyle> = {
resizeMode: 'contain',
};
const fontVariantStyle: StyleProp<TextStyle> = {
fontVariant: ['tabular-nums'],
};
const viewProperty = StyleSheet.flatten(viewStyle).backgroundColor;
const textProperty = StyleSheet.flatten(textStyle).fontSize;
const imageProperty = StyleSheet.flatten(imageStyle).resizeMode;
const fontVariantProperty = StyleSheet.flatten(fontVariantStyle).fontVariant;
// correct use of the StyleSheet.flatten
const styleArray: StyleProp<ViewStyle>[] = [];
const flattenStyle = StyleSheet.flatten(styleArray);
const { top } = flattenStyle;
const s = StyleSheet.create({
shouldWork: {
fontWeight: '900', // if we comment this line, errors gone
marginTop: 5, // if this line commented, errors also gone
},
});
const f1: TextStyle = s.shouldWork;
// StyleSheet.compose
// It creates a new style object by composing two existing styles
const composeTextStyle: StyleProp<TextStyle> = {
color: '#000000',
fontSize: 20,
};
const composeImageStyle: StyleProp<ImageStyle> = {
resizeMode: 'contain',
};
// The following use of the compose method is valid
const combinedStyle: StyleProp<TextStyle> = StyleSheet.compose(composeTextStyle, composeTextStyle);
const combinedStyle1: StyleProp<ImageStyle> = StyleSheet.compose(composeImageStyle, composeImageStyle);
const combinedStyle2: StyleProp<TextStyle | ConcatArray<TextStyle>> = StyleSheet.compose(
[composeTextStyle],
[composeTextStyle],
);
const combinedStyle3: StyleProp<TextStyle | null> = StyleSheet.compose(composeTextStyle, null);
const combinedStyle4: StyleProp<TextStyle | ConcatArray<TextStyle> | null> = StyleSheet.compose(
[composeTextStyle],
null,
);
const combinedStyle5: StyleProp<TextStyle> = StyleSheet.compose(
composeTextStyle,
Math.random() < 0.5 ? composeTextStyle : null,
);
const combinedStyle6: StyleProp<TextStyle | null> = StyleSheet.compose(null, null);
// The following use of the compose method is invalid:
// @ts-expect-error
const combinedStyle7 = StyleSheet.compose(composeImageStyle, composeTextStyle);
// @ts-expect-error
const combinedStyle8: StyleProp<ImageStyle> = StyleSheet.compose(composeTextStyle, composeTextStyle);
// @ts-expect-error
const combinedStyle9: StyleProp<ImageStyle> = StyleSheet.compose([composeTextStyle], null);
// @ts-expect-error
const combinedStyle10: StyleProp<ImageStyle> = StyleSheet.compose(Math.random() < 0.5 ? composeTextStyle : null, null);
const testNativeSyntheticEvent = <T extends {}>(e: NativeSyntheticEvent<T>): void => {
e.isDefaultPrevented();
e.preventDefault();
e.isPropagationStopped();
e.stopPropagation();
e.persist();
e.cancelable;
e.bubbles;
e.currentTarget;
e.defaultPrevented;
e.eventPhase;
e.isTrusted;
e.nativeEvent;
e.target;
e.timeStamp;
e.type;
e.nativeEvent;
};
function eventHandler<T extends React.BaseSyntheticEvent>(e: T) {}
function handler(e: GestureResponderEvent) {
eventHandler(e);
}
type ElementProps<C> = C extends React.Component<infer P, any> ? P : never;
class CustomView extends React.Component {
render() {
return <Text style={[StyleSheet.absoluteFill, { ...StyleSheet.absoluteFillObject }]}>Custom View</Text>;
}
}
class Welcome extends React.Component<ElementProps<View> & { color: string }> {
// tslint:disable-next-line:no-object-literal-type-assertion
refs = {} as {
[key: string]: React.ReactInstance;
rootView: View;
customView: CustomView;
};
testNativeMethods() {
const { rootView } = this.refs;
rootView.setNativeProps({});
rootView.measure((x: number, y: number, width: number, height: number) => {});
}
testFindNodeHandle() {
const { rootView, customView } = this.refs;
const nativeComponentHandle = findNodeHandle(rootView);
const customComponentHandle = findNodeHandle(customView);
const fromHandle = findNodeHandle(customComponentHandle);
}
render() {
const { color, ...props } = this.props;
return (
<View {...props} ref="rootView" style={[[styles.container], undefined, null, false]}>
<Text style={styles.welcome}>Welcome to React Native</Text>
<Text style={styles.instructions}>To get started, edit index.ios.js</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
<CustomView ref="customView" />
</View>
);
}
}
export default Welcome;
// TouchableTest
function TouchableTest() {
function basicUsage() {
if (Touchable.TOUCH_TARGET_DEBUG) {
return Touchable.renderDebugView({
color: 'mediumspringgreen',
hitSlop: { bottom: 5, top: 5 },
});
}
}
function defaultHitSlop() {
return Touchable.renderDebugView({
color: 'red',
});
}
}
// TouchableNativeFeedbackTest
export class TouchableNativeFeedbackTest extends React.Component {
onPressButton = (e: GestureResponderEvent) => {
e.persist();
e.isPropagationStopped();
e.isDefaultPrevented();
};
render() {
return (
<>
<TouchableNativeFeedback onPress={this.onPressButton}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.Ripple('red', true)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.Ripple('red', true, 30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground()}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground(30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless()}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless(30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
</>
);
}
}
// PressableTest
export class PressableTest extends React.Component<{}> {
private readonly myRef: React.RefObject<View> = React.createRef();
onPressButton = (e: GestureResponderEvent) => {
e.persist();
e.isPropagationStopped();
e.isDefaultPrevented();
};
render() {
return (
<>
<Pressable ref={this.myRef} onPress={this.onPressButton} style={{ backgroundColor: 'blue' }} unstable_pressDelay={100}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
{/* Style function */}
<Pressable
onPress={this.onPressButton}
style={state => ({
backgroundColor: state.pressed ? 'red' : 'blue',
})}
>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
{/* Children function */}
<Pressable
onPress={this.onPressButton}
style={state => ({
backgroundColor: state.pressed ? 'red' : 'blue',
})}
>
{state =>
state.pressed ? (
<View>
<Text>Pressed</Text>
</View>
) : (
<View>
<Text>Not Pressed</Text>
</View>
)
}
</Pressable>
{/* Android Ripple */}
<Pressable
android_ripple={{
borderless: true,
color: 'green',
radius: 20,
foreground: true,
}}
onPress={this.onPressButton}
style={{ backgroundColor: 'blue' }}
>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
</>
);
}
}
// App State
function appStateListener(state: string) {
console.log('New state: ' + state);
}
function appStateTest() {
console.log('Current state: ' + AppState.currentState);
AppState.addEventListener('change', appStateListener);
AppState.addEventListener('blur', appStateListener);
AppState.addEventListener('focus', appStateListener);
}
let appState: AppStateStatus = 'active';
appState = 'background';
appState = 'inactive';
appState = 'unknown';
appState = 'extension';
const AppStateExample = () => {
const appState = React.useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = React.useState(appState.current);
const appStateIsAvailable = AppState.isAvailable;
React.useEffect(() => {
const subscription = AppState.addEventListener("change", nextAppState => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
});
return () => {
subscription.remove();
};
}, []);
return (
<View style={styles.container}>
<Text>Current state is: {appStateVisible}</Text>
<Text>Available: {appStateIsAvailable}</Text>
</View>
);
};
// ViewPagerAndroid
export class ViewPagerAndroidTest {
render() {
return (
<ViewPagerAndroid
style={{ height: 56 }}
initialPage={0}
keyboardDismissMode={'on-drag'}
onPageScroll={e => {
console.log(`position: ${e.nativeEvent.position}`);
console.log(`offset: ${e.nativeEvent.offset}`);
}}
onPageSelected={e => {
console.log(`position: ${e.nativeEvent.position}`);
}}
/>
);
}
}
const profiledJSONParse = Systrace.measure('JSON', 'parse', JSON.parse);
profiledJSONParse('[]');
InteractionManager.runAfterInteractions(() => {
// ...
}).then(() => 'done');
export class FlatListTest extends React.Component<FlatListProps<number>, {}> {
list: FlatList<any> | null = null;
componentDidMount(): void {
if (this.list) {
this.list.flashScrollIndicators();
}
}
_renderItem = (rowData: any) => {
return (
<View>
<Text> {rowData.item} </Text>
</View>
);
};
_cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
_renderSeparator = () => <View style={{ height: 1, width: '100%', backgroundColor: 'gray' }} />;
render() {
return (
<FlatList
ref={list => (this.list = list)}
data={[1, 2, 3, 4, 5]}
renderItem={this._renderItem}
ItemSeparatorComponent={this._renderSeparator}
ListFooterComponent={null}
ListFooterComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
ListHeaderComponent={null}
ListHeaderComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
CellRendererComponent={this._cellRenderer}
fadingEdgeLength={200}
/>
);
}
}
export class SectionListTest extends React.Component<SectionListProps<string>, {}> {
myList: React.RefObject<SectionList<string>>;
constructor(props: SectionListProps<string>) {
super(props);
this.myList = React.createRef();
}
scrollMe = () => {
this.myList.current && this.myList.current.scrollToLocation({ itemIndex: 0, sectionIndex: 1 });
};
render() {
const sections = [
{
title: 'Section 1',
data: ['A', 'B', 'C', 'D', 'E'],
},
{
title: 'Section 2',
data: ['A2', 'B2', 'C2', 'D2', 'E2'],
renderItem: (info: { item: string }) => (
<View>
<Text>{info.item}</Text>
</View>
),
},
];
const cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
return (
<React.Fragment>
<Button title="Press" onPress={this.scrollMe} />
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => (
<View>
<Text>{section.title}</Text>
</View>
)}
renderItem={(info: SectionListRenderItemInfo<string>) => (
<View>
<Text>{`${info.section.title} - ${info.item}`}</Text>
</View>
)}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
ListHeaderComponent={null}
ListHeaderComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
/>
</React.Fragment>
);
}
}
type SectionT = { displayTitle: false } | { displayTitle: true; title: string };
export class SectionListTypedSectionTest extends React.Component<SectionListProps<string, SectionT>, {}> {
myList: React.RefObject<SectionList<string, SectionT>>;
constructor(props: SectionListProps<string, SectionT>) {
super(props);
this.myList = React.createRef();
}
scrollMe = () => {
this.myList.current && this.myList.current.scrollToLocation({ itemIndex: 0, sectionIndex: 1 });
};
render() {
const sections: SectionListData<string, SectionT>[] = [
{
displayTitle: false,
data: ['A', 'B', 'C', 'D', 'E'],
},
{
displayTitle: true,
title: 'Section 2',
data: ['A2', 'B2', 'C2', 'D2', 'E2'],
renderItem: (info: { item: string }) => (
<View>
<Text>{info.item}</Text>
</View>
),
},
];
const cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
return (
<React.Fragment>
<Button title="Press" onPress={this.scrollMe} />
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
/>
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={null}
ListHeaderComponent={null}
ListHeaderComponentStyle={null}
/>
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={undefined}
ListHeaderComponent={null}
ListHeaderComponentStyle={undefined}
/>
</React.Fragment>
);
}
}
export class CapsLockComponent extends React.Component<TextProps> {
render() {
const content = (this.props.children || '') as string;
return <Text {...this.props}>{content.toUpperCase()}</Text>;
}
}
const getInitialUrlTest = () =>
Linking.getInitialURL().then(val => {
if (val !== null) {
val.indexOf('val is now a string');
}
});
LogBox.ignoreAllLogs();
LogBox.ignoreAllLogs(true);
LogBox.ignoreLogs(['someString', /^aRegex/]);
LogBox.install();
LogBox.uninstall();
class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListViewDataSource }> {
_stickyHeaderComponent = ({ children }: any) => {
return <View>{children}</View>;
};
eventHandler = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
console.log(event);
};
scrollView: ScrollView | null = null;
testNativeMethods() {
if (this.scrollView) {
this.scrollView.setNativeProps({ scrollEnabled: false });
// Dummy values for scroll dimensions changes
this.scrollView.getScrollResponder().scrollResponderZoomTo({
x: 0,
y: 0,
width: 300,
height: 500,
animated: true,
});
}
}
render() {
const scrollViewStyle1 = StyleSheet.create({
scrollView: {
backgroundColor: 'red',
},
});
const scrollViewStyle2 = {
flex: 1,
};
return (
<ListView
dataSource={this.state.dataSource}
renderScrollComponent={props => {
if (props.scrollEnabled) {
throw new Error('Expected scroll to be enabled.');
}
return (
<ScrollView
ref={ref => (this.scrollView = ref)}
horizontal={true}
nestedScrollEnabled={true}
invertStickyHeaders={true}
contentOffset={{ x: 0, y: 0 }}
snapToStart={false}
snapToEnd={false}
snapToOffsets={[100, 300, 500]}
{...props}
style={[scrollViewStyle1.scrollView, scrollViewStyle2]}
onScrollToTop={() => {}}
scrollToOverflowEnabled={true}
fadingEdgeLength={200}
StickyHeaderComponent={this._stickyHeaderComponent}
stickyHeaderHiddenOnScroll={true}
automaticallyAdjustKeyboardInsets
/>
);
}}
renderRow={({ type, data }, _, row) => {
return <Text>Filler</Text>;
}}
onScroll={this.eventHandler}
onScrollBeginDrag={this.eventHandler}
onScrollEndDrag={this.eventHandler}
onMomentumScrollBegin={this.eventHandler}
onMomentumScrollEnd={this.eventHandler}
/>
);
}
}
class TabBarTest extends React.Component {
render() {
return (
<TabBarIOS
barTintColor="darkslateblue"
itemPositioning="center"
tintColor="white"
translucent={true}
unselectedTintColor="black"
unselectedItemTintColor="red"
>
<TabBarIOS.Item
badge={0}
badgeColor="red"
icon={{ uri: undefined }}
selected={true}
onPress={() => {}}
renderAsOriginal={true}
selectedIcon={undefined}
systemIcon="history"
title="Item 1"
/>
</TabBarIOS>
);
}
}
class AlertTest extends React.Component {
showAlert() {
Alert.alert(
'Title',
'Message',
[
{ text: 'First button', onPress: () => {} },
{ text: 'Second button', onPress: () => {} },
{ text: 'Third button', onPress: () => {} },
],
{
cancelable: false,
onDismiss: () => {},
},
);
}
render() {
return <Button title="Press me" onPress={this.showAlert} />;
}
}
Alert.prompt(
'Enter password',
'Enter your password to claim your $1.5B in lottery winnings',
text => {
console.log(text);
},
'secure-text',
);
Alert.prompt(
'Enter password',
'Enter your password to claim your $1.5B in lottery winnings',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'OK',
onPress: password => console.log('OK Pressed, password: ' + password),
},
],
'secure-text',
);
class MaskedViewTest extends React.Component {
render() {
return (
<MaskedViewIOS maskElement={<View />}>
<View />
</MaskedViewIOS>
);
}
}
class InputAccessoryViewTest extends React.Component {
render() {
const uniqueID = 'foobar';
return (
<InputAccessoryView nativeID={uniqueID}>
<TextInput inputAccessoryViewID={uniqueID} />
</InputAccessoryView>
);
}
}
// DataSourceAssetCallback
const dataSourceAssetCallback1: DataSourceAssetCallback = {
rowHasChanged: (r1, r2) => true,
sectionHeaderHasChanged: (h1, h2) => true,
getRowData: (dataBlob, sectionID, rowID) => (sectionID as number) + (rowID as number),
getSectionHeaderData: (dataBlob, sectionID) => sectionID as string,
};
const dataSourceAssetCallback2: DataSourceAssetCallback = {};
// DeviceEventEmitterStatic
const deviceEventEmitterStatic: DeviceEventEmitterStatic = DeviceEventEmitter;
deviceEventEmitterStatic.addListener('keyboardWillShow', data => true);
deviceEventEmitterStatic.addListener('keyboardWillShow', data => true, {});
// NativeEventEmitter - Android
const androidEventEmitter = new NativeEventEmitter();
const sub1 = androidEventEmitter.addListener('event', (event: object) => event);
const sub2 = androidEventEmitter.addListener('event', (event: object) => event, {});
androidEventEmitter.listenerCount('event'); // $ExpectType number
sub2.remove();
androidEventEmitter.removeAllListeners('event');
androidEventEmitter.removeSubscription(sub1);
// NativeEventEmitter - IOS
const nativeModule: NativeModule = {
addListener(eventType: string) {},
removeListeners(count: number) {},
};
const iosEventEmitter = new NativeEventEmitter(nativeModule);
const sub3 = iosEventEmitter.addListener('event', (event: object) => event);
const sub4 = iosEventEmitter.addListener('event', (event: object) => event, {});
iosEventEmitter.listenerCount('event');
sub4.remove();
iosEventEmitter.removeAllListeners('event');
iosEventEmitter.removeSubscription(sub3);
class CustomEventEmitter extends NativeEventEmitter {}
const customEventEmitter = new CustomEventEmitter();
customEventEmitter.addListener('event', () => {});
class TextInputTest extends React.Component<{}, { username: string }> {
username: TextInput | null = null;
handleUsernameChange = (text: string) => {
console.log(`text: ${text}`);
};
onScroll = (e: NativeSyntheticEvent<TextInputScrollEventData>) => {
testNativeSyntheticEvent(e);
console.log(`x: ${e.nativeEvent.contentOffset.x}`);
console.log(`y: ${e.nativeEvent.contentOffset.y}`);
};
handleOnBlur = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
};
handleOnFocus = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
};
handleOnSelectionChange = (e: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`target: ${e.nativeEvent.target}`);
console.log(`start: ${e.nativeEvent.selection.start}`);
console.log(`end: ${e.nativeEvent.selection.end}`);
};
handleOnKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
testNativeSyntheticEvent(e);
console.log(`key: ${e.nativeEvent.key}`);
};
handleOnChange = (e: NativeSyntheticEvent<TextInputChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`eventCount: ${e.nativeEvent.eventCount}`);
console.log(`target: ${e.nativeEvent.target}`);
console.log(`text: ${e.nativeEvent.text}`);
};
handleOnContentSizeChange = (e: NativeSyntheticEvent<TextInputContentSizeChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`contentSize.width: ${e.nativeEvent.contentSize.width}`);
console.log(`contentSize.height: ${e.nativeEvent.contentSize.height}`);
};
handleOnEndEditing = (e: NativeSyntheticEvent<TextInputEndEditingEventData>) => {
testNativeSyntheticEvent(e);
console.log(`text: ${e.nativeEvent.text}`);
};
handleOnSubmitEditing = (e: NativeSyntheticEvent<TextInputSubmitEditingEventData>) => {
testNativeSyntheticEvent(e);
console.log(`text: ${e.nativeEvent.text}`);
};
render() {
return (
<View>
<Text onPress={() => this.username && this.username.focus()}>Username</Text>
<TextInput
ref={input => (this.username = input)}
textContentType="username"
autoComplete="username"
value={this.state.username}
onChangeText={this.handleUsernameChange}
/>
<TextInput multiline onScroll={this.onScroll} />
<TextInput onBlur={this.handleOnBlur} onFocus={this.handleOnFocus} />
<TextInput onSelectionChange={this.handleOnSelectionChange} />
<TextInput onKeyPress={this.handleOnKeyPress} />
<TextInput onChange={this.handleOnChange} />
<TextInput onChange={this.handleOnChange} />
<TextInput onEndEditing={this.handleOnEndEditing} />
<TextInput onSubmitEditing={this.handleOnSubmitEditing} />
<TextInput multiline onContentSizeChange={this.handleOnContentSizeChange} />
<TextInput contextMenuHidden={true} textAlignVertical="top" />
<TextInput textAlign="center" />
</View>
);
}
}
class TextTest extends React.Component {
handleOnLayout = (e: LayoutChangeEvent) => {
testNativeSyntheticEvent(e);
const x = e.nativeEvent.layout.x; // $ExpectType number
const y = e.nativeEvent.layout.y; // $ExpectType number
const width = e.nativeEvent.layout.width; // $ExpectType number
const height = e.nativeEvent.layout.height; // $ExpectType number
};
handleOnTextLayout = (e: NativeSyntheticEvent<TextLayoutEventData>) => {
testNativeSyntheticEvent(e);
e.nativeEvent.lines.forEach(line => {
const ascender = line.ascender; // $ExpectType number
const capHeight = line.capHeight; // $ExpectType number
const descender = line.descender; // $ExpectType number
const height = line.height; // $ExpectType number
const text = line.text; // $ExpectType string
const width = line.width; // $ExpectType number
const x = line.x; // $ExpectType number
const xHeight = line.xHeight; // $ExpectType number
const y = line.y; // $ExpectType number
});
};
render() {
return (
<Text
allowFontScaling={false}
ellipsizeMode="head"
lineBreakMode="clip"
numberOfLines={2}
onLayout={this.handleOnLayout}
onTextLayout={this.handleOnTextLayout}
>
Test text
</Text>
);
}
}
class StatusBarTest extends React.Component {
render() {
StatusBar.setBarStyle('dark-content', true);
console.log('height:', StatusBar.currentHeight);
return <StatusBar backgroundColor="blue" barStyle="light-content" translucent />;
}
}
export class ImageTest extends React.Component {
componentDidMount(): void {
const uri = 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png';
const headers = { Authorization: 'Bearer test' };
const image: ImageResolvedAssetSource = Image.resolveAssetSource({ uri });
console.log(image.width, image.height, image.scale, image.uri);
Image.queryCache &&
Image.queryCache([uri]).then(({ [uri]: status }) => {
if (status === undefined) {
console.log('Image is not in cache');
} else {
console.log(`Image is in ${status} cache`);
}
});
Image.getSize(uri, (width, height) => console.log(width, height));
Image.getSize(
uri,
(width, height) => console.log(width, height),
error => console.error(error),
);
Image.getSizeWithHeaders(uri, headers, (width, height) => console.log(width, height));
Image.getSizeWithHeaders(
uri,
headers,
(width, height) => console.log(width, height),
error => console.error(error),
);
Image.prefetch(uri); // $ExpectType Promise<boolean>
}
handleOnLoad = (e: NativeSyntheticEvent<ImageLoadEventData>) => {
testNativeSyntheticEvent(e);
console.log('height:', e.nativeEvent.source.height);
console.log('width:', e.nativeEvent.source.width);
console.log('uri:', e.nativeEvent.source.uri);
};
handleOnError = (e: NativeSyntheticEvent<ImageErrorEventData>) => {
testNativeSyntheticEvent(e);
console.log('error:', e.nativeEvent.error);
};
render() {
const resizeMode: ImageResizeMode = 'contain';
return (
<View>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
onLoad={this.handleOnLoad}
onError={this.handleOnError}
/>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
resizeMode={resizeMode}
/>
</View>
);
}
}
export class ImageBackgroundProps extends React.Component {
private _imageRef: Image | null = null;
setImageRef = (image: Image) => {
this._imageRef = image;
};
render() {
return (
<View>
<ImageBackground
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
imageRef={this.setImageRef}
>
<Text>Some text</Text>
</ImageBackground>
</View>
);
}
}
const listViewDataSourceTest = new ListView.DataSource({ rowHasChanged: () => true });
class AccessibilityTest extends React.Component {
render() {
return (
<View
accessibilityElementsHidden={true}
importantForAccessibility={'no-hide-descendants'}
onAccessibilityTap={() => {}}
accessibilityRole="header"
accessibilityState={{ checked: true }}
accessibilityHint="Very important header"
accessibilityValue={{ min: 60, max: 120, now: 80 }}
onMagicTap={() => {}}
onAccessibilityEscape={() => {}}
>
<Text accessibilityIgnoresInvertColors>Text</Text>
<View />
</View>
);
}
}
AccessibilityInfo.isBoldTextEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),
);
AccessibilityInfo.isGrayscaleEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isGrayscaleEnabled => ${isEnabled}`),
);
AccessibilityInfo.isInvertColorsEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isInvertColorsEnabled => ${isEnabled}`),
);
AccessibilityInfo.isReduceMotionEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isReduceMotionEnabled => ${isEnabled}`),
);
AccessibilityInfo.isReduceTransparencyEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isReduceTransparencyEnabled => ${isEnabled}`),
);
AccessibilityInfo.isScreenReaderEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isScreenReaderEnabled => ${isEnabled}`),
);
AccessibilityInfo.getRecommendedTimeoutMillis(5000).then(timeoutMiles =>
console.log(`AccessibilityInfo.getRecommendedTimeoutMillis => ${timeoutMiles}`)
);
AccessibilityInfo.addEventListener('announcementFinished', ({ announcement, success }) =>
console.log(`A11y Event: announcementFinished: ${announcement}, ${success}`),
);
AccessibilityInfo.addEventListener('boldTextChanged', isEnabled =>
console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('grayscaleChanged', isEnabled =>
console.log(`AccessibilityInfo.isGrayscaleEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('invertColorsChanged', isEnabled =>
console.log(`AccessibilityInfo.isInvertColorsEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('reduceMotionChanged', isEnabled =>
console.log(`AccessibilityInfo.isReduceMotionEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('reduceTransparencyChanged', isEnabled =>
console.log(`AccessibilityInfo.isReduceTransparencyEnabled => ${isEnabled}`),
);
const screenReaderChangedListener = (isEnabled: boolean): void => console.log(`AccessibilityInfo.isScreenReaderEnabled => ${isEnabled}`);
AccessibilityInfo.addEventListener('screenReaderChanged', screenReaderChangedListener,
).remove();
AccessibilityInfo.removeEventListener('screenReaderChanged', screenReaderChangedListener);
const KeyboardAvoidingViewTest = () => <KeyboardAvoidingView enabled />;
const ModalTest = () => <Modal hardwareAccelerated />;
const ModalTest2 = () => <Modal hardwareAccelerated testID="modal-test-2" />;
const TimePickerAndroidTest = () => {
TimePickerAndroid.open({
hour: 8,
minute: 15,
is24Hour: true,
mode: 'spinner',
}).then(result => {
if (result.action === TimePickerAndroid.timeSetAction) {
console.log('Time', result.hour, result.minute);
}
});
};
const DatePickerAndroidTest = () => {
DatePickerAndroid.open({
date: new Date(),
mode: 'calendar',
}).then(result => {
if (result.action === DatePickerAndroid.dateSetAction) {
console.log('Date', result.year, result.month, result.day);
}
});
};
const NativeBridgedComponent = requireNativeComponent<{ nativeProp: string }>('NativeBridgedComponent'); // $ExpectType HostComponent<{ nativeProp: string; }>
class BridgedComponentTest extends React.Component {
static propTypes = {
jsProp: PropTypes.string.isRequired,
};
nativeComponentRef: React.ElementRef<typeof NativeBridgedComponent> | null;
callNativeMethod = () => {
UIManager.dispatchViewManagerCommand(findNodeHandle(this.nativeComponentRef), 'someNativeMethod', []);
};
measureNativeComponent() {
if (this.nativeComponentRef) {
this.nativeComponentRef.measure(
(x, y, width, height, pageX, pageY) => x + y + width + height + pageX + pageY,
);
}
}
render() {
return (
<NativeBridgedComponent {...this.props} nativeProp="test" ref={ref => (this.nativeComponentRef = ref)} />
);
}
}
const SwitchColorTest = () => <Switch trackColor={{ true: 'pink', false: 'red' }} />;
const SwitchColorOptionalTrueTest = () => <Switch trackColor={{ false: 'red' }} />;
const SwitchColorOptionalFalseTest = () => <Switch trackColor={{ true: 'pink' }} />;
const SwitchColorNullTest = () => <Switch trackColor={{ true: 'pink', false: null }} />;
const SwitchThumbColorTest = () => <Switch thumbColor={'red'} />;
const SwitchOnChangeWithoutParamsTest = () => <Switch onChange={() => console.log('test')} />;
const SwitchOnChangeUndefinedTest = () => <Switch onChange={undefined} />;
const SwitchOnChangeNullTest = () => <Switch onChange={null} />;
const SwitchOnChangePromiseTest = () => <Switch onChange={(event) => {
const e: SwitchChangeEvent = event;
return new Promise(() => e.value);
}} />;
const SwitchOnValueChangeWithoutParamsTest = () => <Switch onValueChange={() => console.log('test')} />;
const SwitchOnValueChangeUndefinedTest = () => <Switch onValueChange={undefined} />;
const SwitchOnValueChangeNullTest = () => <Switch onValueChange={null} />;
const SwitchOnValueChangePromiseTest = () => <Switch onValueChange={(value) => {
const v: boolean = value;
return new Promise(() => v)
}} />;
const NativeIDTest = () => (
<ScrollView nativeID={'nativeID'}>
<View nativeID={'nativeID'} />
<Text nativeID={'nativeID'}>Text</Text>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
nativeID={'nativeID'}
/>
</ScrollView>
);
const ScrollViewMaintainVisibleContentPositionTest = () => (
<ScrollView maintainVisibleContentPosition={{ autoscrollToTopThreshold: 1, minIndexForVisible: 10 }}></ScrollView>
);
const ScrollViewInsetsTest = () => (
<>
<ScrollView automaticallyAdjustKeyboardInsets />
<ScrollView automaticallyAdjustKeyboardInsets={false} />
</>
);
const MaxFontSizeMultiplierTest = () => <Text maxFontSizeMultiplier={0}>Text</Text>;
const ShareTest = () => {
Share.share(
{ title: 'title', message: 'message' },
{ dialogTitle: 'dialogTitle', excludedActivityTypes: ['activity'], tintColor: 'red', subject: 'Email subject' },
);
Share.share({ title: 'title', url: 'url' });
Share.share({ message: 'message' }).then(result => {
if (result.action === Share.sharedAction) {
const activity = result.activityType;
} else if (result.action === Share.dismissedAction) {
}
});
};
const KeyboardTest = () => {
const subscriber = Keyboard.addListener('keyboardDidHide', event => {
event;
});
subscriber.remove();
Keyboard.dismiss();
// Android Keyboard Event
Keyboard.scheduleLayoutAnimation({
duration: 0,
easing: 'keyboard',
endCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
});
// IOS Keyboard Event
Keyboard.scheduleLayoutAnimation({
duration: 0,
easing: 'easeInEaseOut',
endCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
startCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
isEventFromThisApp: true,
});
};
const PermissionsAndroidTest = () => {
PermissionsAndroid.request('android.permission.CAMERA').then(result => {
switch (result) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
PermissionsAndroid.requestMultiple([
'android.permission.CAMERA',
'android.permission.ACCESS_FINE_LOCATION',
'android.permission.ACCESS_BACKGROUND_LOCATION',
]).then(results => {
switch (results['android.permission.CAMERA']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.ACCESS_FINE_LOCATION']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.ACCESS_BACKGROUND_LOCATION']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
PermissionsAndroid.requestMultiple([
'android.permission.BLUETOOTH_SCAN',
'android.permission.BLUETOOTH_CONNECT',
'android.permission.BLUETOOTH_ADVERTISE'
]).then(results => {
switch (results['android.permission.BLUETOOTH_SCAN']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.BLUETOOTH_CONNECT']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.BLUETOOTH_ADVERTISE']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
};
// Platform
const PlatformTest = () => {
switch (Platform.OS) {
case 'ios':
if (!Platform.isPad) {
return 32;
} else {
return 44;
}
case 'android':
case 'macos':
case 'windows':
return Platform.isTV ? 64 : 56;
default:
return Platform.isTV ? 40 : 44;
}
};
const PlatformConstantsTest = () => {
const testing: boolean = Platform.constants.isTesting;
if (Platform.OS === 'ios') {
const hasForceTouch: boolean = Platform.constants.forceTouchAvailable;
} else if (Platform.OS === 'android') {
const { major, prerelease } = Platform.constants.reactNativeVersion;
const v = Platform.constants.Version;
const host: string | undefined = Platform.constants.ServerHost;
}
};
Platform.select({ native: 1 }); // $ExpectType number | undefined
Platform.select({ native: 1, web: 2, default: 0 }); // $ExpectType number
Platform.select({ android: 1 }); // $ExpectType number | undefined
Platform.select({ android: 1, ios: 2, default: 0 }); // $ExpectType number
Platform.select({ android: 1, ios: 2, macos: 3, web: 4, windows: 5 }); // $ExpectType number | undefined
Platform.select({ android: 1, ios: 2, macos: 3, web: 4, windows: 5, default: 0 }); // $ExpectType number
PlatformColor('?attr/colorControlNormal');
PlatformColor('?attr/colorControlNormal', '?attr/colorAccent', 'another');
DynamicColorIOS({
dark: 'lightskyblue',
light: 'midnightblue',
});
DynamicColorIOS({
dark: 'lightskyblue',
light: PlatformColor('labelColor'),
});
// Test you cannot set internals of ColorValue directly
const OpaqueTest1 = () => (
<View
// @ts-expect-error
style={{
backgroundColor: {
resource_paths: ['?attr/colorControlNormal'],
},
}}
/>
);
const OpaqueTest2 = () => (
<View
// @ts-expect-error
style={{
backgroundColor: {
semantic: 'string',
dynamic: {
light: 'light',
dark: 'dark',
},
},
}}
/>
);
// Test you cannot amend opaque type
// @ts-expect-error
PlatformColor('?attr/colorControlNormal').resource_paths.push('foo');
const someColorProp: ColorValue = PlatformColor('test');
// Test PlatformColor inside Platform select with stylesheet
StyleSheet.create({
labelCell: {
flex: 1,
alignItems: 'stretch',
...Platform.select({
ios: { color: DynamicColorIOS({ dark: 'lightskyblue', light: PlatformColor('labelColor') }) },
android: {
color: PlatformColor('?attr/colorControlNormal'),
},
default: { color: PlatformColor('?attr/colorControlNormal') },
}),
},
});
// PlatformColor in style colors
StyleSheet.create({
labelCell: {
flex: 1,
alignItems: 'stretch',
color: PlatformColor('test'),
backgroundColor: PlatformColor('test'),
borderBottomColor: PlatformColor('test'),
borderColor: PlatformColor('test'),
borderEndColor: PlatformColor('test'),
borderLeftColor: PlatformColor('test'),
borderRightColor: PlatformColor('test'),
borderStartColor: PlatformColor('test'),
borderTopColor: PlatformColor('test'),
overlayColor: PlatformColor('test'),
shadowColor: PlatformColor('test'),
textDecorationColor: PlatformColor('test'),
textShadowColor: PlatformColor('test'),
tintColor: PlatformColor('test'),
},
});
function someColorString(): ColorValue {
return '#000000';
}
function somePlatformColor(): ColorValue {
return PlatformColor('test');
}
const colors = {
color: someColorString(),
backgroundColor: somePlatformColor(),
};
StyleSheet.create({
labelCell: {
color: colors.color,
backgroundColor: colors.backgroundColor,
},
});
const OpaqueTest3 = () => (
<View
style={{
backgroundColor: colors.backgroundColor,
}}
/>
);
// ProgressBarAndroid
const ProgressBarAndroidTest = () => {
<ProgressBarAndroid animating color="white" styleAttr="Horizontal" progress={0.42} />;
};
// Push notification
const PushNotificationTest = () => {
PushNotificationIOS.presentLocalNotification({
alertBody: 'notificatus',
userInfo: 'informius',
alertTitle: 'Titulus',
alertAction: 'view',
});
PushNotificationIOS.scheduleLocalNotification({
alertAction: 'view',
alertBody: 'Look at me!',
alertTitle: 'Hello!',
applicationIconBadgeNumber: 999,
category: 'engagement',
fireDate: new Date().toISOString(),
isSilent: false,
repeatInterval: 'minute',
userInfo: {
abc: 123,
},
});
};
// YellowBox
const YellowBoxTest = () => <YellowBox />;
// Appearance
const DarkMode = () => {
const color = useColorScheme();
const isDarkMode = Appearance.getColorScheme() === 'dark';
const subscription = Appearance.addChangeListener(({ colorScheme }) => {
console.log(colorScheme);
});
React.useEffect(() => {
console.log('-color', color);
return () => {
subscription.remove();
};
}, [color]);
return <Text>Is dark mode enabled? {isDarkMode}</Text>;
};
// VirtualizedList
// Test inspired by: https://reactnative.dev/docs/virtualizedlist
const VirtualizedListTest = () => {
const DATA = [1, 2, 3];
const getItem = (data: number[], index: number) => {
return {
title: `Item ${data[index]}`,
};
};
const getItemCount = (data: number[]) => data.length;
return (
<VirtualizedList
data={DATA}
initialNumToRender={4}
renderItem={({ item }: ListRenderItemInfo<ReturnType<typeof getItem>>) => <Text>{item.title}</Text>}
getItemCount={getItemCount}
getItem={getItem}
/>
);
};
// DevSettings
DevSettings.addMenuItem('alert', () => {
Alert.alert('alert');
});
DevSettings.reload();
DevSettings.reload('reload with reason');
// Accessibility custom actions
const AccessibilityCustomActionsTest = () => {
return (
<View
accessible={true}
accessibilityActions={[
// should support custom defined actions
{ name: 'cut', label: 'cut' },
{ name: 'copy', label: 'copy' },
{ name: 'paste', label: 'paste' },
]}
onAccessibilityAction={event => {
switch (event.nativeEvent.actionName) {
case 'cut':
Alert.alert('Alert', 'cut action success');
break;
case 'copy':
Alert.alert('Alert', 'copy action success');
break;
case 'paste':
Alert.alert('Alert', 'paste action success');
break;
}
}}
/>
);
};
// DrawerLayoutAndroidTest
export class DrawerLayoutAndroidTest extends React.Component {
drawerRef = React.createRef<DrawerLayoutAndroid>();
readonly styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 50,
backgroundColor: '#ecf0f1',
padding: 8,
},
navigationContainer: {
flex: 1,
paddingTop: 50,
backgroundColor: '#fff',
padding: 8,
},
});
readonly navigationView = (
<View style={this.styles.navigationContainer}>
<Text style={{ margin: 10, fontSize: 15 }}>I'm in the Drawer!</Text>
</View>
);
handleDrawerClose = () => {
console.log('handleDrawerClose');
};
handleDrawerOpen = () => {
console.log('handleDrawerOpen');
};
handleDrawerSlide = (event: DrawerSlideEvent) => {
console.log('handleDrawerSlide', event);
};
handleDrawerStateChanged = (event: 'Idle' | 'Dragging' | 'Settling') => {
console.log('handleDrawerStateChanged', event);
};
render() {
return (
<DrawerLayoutAndroid
ref={this.drawerRef}
drawerBackgroundColor="rgba(0,0,0,0.5)"
drawerLockMode="locked-closed"
drawerPosition="right"
drawerWidth={300}
keyboardDismissMode="on-drag"
onDrawerClose={this.handleDrawerClose}
onDrawerOpen={this.handleDrawerOpen}
onDrawerSlide={this.handleDrawerSlide}
onDrawerStateChanged={this.handleDrawerStateChanged}
renderNavigationView={() => this.navigationView}
statusBarBackgroundColor="yellow"
>
<View style={this.styles.container}>
<Text style={{ margin: 10, fontSize: 15 }}>DrawerLayoutAndroid example</Text>
</View>
</DrawerLayoutAndroid>
);
}
}
// DataDetectorType for Text component
const DataDetectorTypeTest = () => {
return (
<>
<Text dataDetectorType={'all'}>http://test.com [email protected] +33123456789</Text>
<Text dataDetectorType={'email'}>[email protected]</Text>
<Text dataDetectorType={'link'}>http://test.com</Text>
<Text dataDetectorType={'none'}>Hi there !</Text>
<Text dataDetectorType={'phoneNumber'}>+33123456789</Text>
<Text dataDetectorType={null}>Must allow null value</Text>
</>
);
};
const ToastAndroidTest = () => {
ToastAndroid.showWithGravityAndOffset('My Toast', ToastAndroid.SHORT, ToastAndroid.BOTTOM, 0, 50);
};
const I18nManagerTest = () => {
I18nManager.allowRTL(true);
I18nManager.forceRTL(true);
I18nManager.swapLeftAndRightInRTL(true);
const { isRTL, doLeftAndRightSwapInRTL } = I18nManager.getConstants();
const isRtlFlag = I18nManager.isRTL;
const doLeftAndRightSwapInRtlFlag = I18nManager.doLeftAndRightSwapInRTL;
console.log(isRTL, isRtlFlag, doLeftAndRightSwapInRTL, doLeftAndRightSwapInRtlFlag);
};
// LayoutAnimations
LayoutAnimation.configureNext(
LayoutAnimation.create(123, LayoutAnimation.Types.easeIn, LayoutAnimation.Properties.opacity),
);
LayoutAnimation.configureNext(LayoutAnimation.create(123, 'easeIn', 'opacity'));
// ActionSheetIOS
const ActionSheetIOSTest = () => {
// test destructiveButtonIndex undefined
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: undefined,
}, () => undefined);
// test destructiveButtonIndex null
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: null,
}, () => undefined);
// test destructiveButtonIndex single number
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: 0,
}, () => undefined);
// test destructiveButtonIndex number array
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo', 'bar'],
destructiveButtonIndex: [0, 1],
}, () => undefined);
}
| types/react-native/v0.69/test/index.tsx | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.9726101756095886,
0.007744382135570049,
0.0001625873555894941,
0.00017026800196617842,
0.0769348293542862
]
|
{
"id": 3,
"code_window": [
" </View>\n",
" );\n",
" }\n",
"}\n",
"\n",
"AccessibilityInfo.isBoldTextEnabled().then(isEnabled =>\n",
" console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),\n",
");\n",
"AccessibilityInfo.isGrayscaleEnabled().then(isEnabled =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const AccessibilityLabelledByTest = () => (\n",
" <>\n",
" <View accessibilityLabelledBy=\"nativeID1\"></View>\n",
" <View accessibilityLabelledBy={[\"nativeID2\", \"nativeID3\"]}></View>\n",
" </>\n",
")\n",
"\n"
],
"file_path": "types/react-native/test/index.tsx",
"type": "add",
"edit_start_line_idx": 1008
} | import { Plugin } from '@ckeditor/ckeditor5-core';
import AlignmentEditing, { AlignmentFormat } from './alignmentediting';
import AlignmentUI from './alignmentui';
/**
* The text alignment plugin.
*
* For a detailed overview, check the {@glink features/text-alignment Text alignment feature documentation}
* and the {@glink api/alignment package page}.
*
* This is a "glue" plugin which loads the {@link module:alignment/alignmentediting~AlignmentEditing} and
* {@link module:alignment/alignmentui~AlignmentUI} plugins.
*/
export default class Alignment extends Plugin {
static readonly requires: [typeof AlignmentEditing, typeof AlignmentUI];
static readonly pluginName: 'Alignment';
}
export interface AlignmentConfig {
options: Array<AlignmentFormat['name'] | AlignmentFormat>;
}
declare module '@ckeditor/ckeditor5-core/src/plugincollection' {
interface Plugins {
Alignment: Alignment;
}
}
| types/ckeditor__ckeditor5-alignment/src/alignment.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.0001721598528092727,
0.00016904827498365194,
0.00016590538143645972,
0.0001690796052571386,
0.0000025534734504617518
]
|
{
"id": 3,
"code_window": [
" </View>\n",
" );\n",
" }\n",
"}\n",
"\n",
"AccessibilityInfo.isBoldTextEnabled().then(isEnabled =>\n",
" console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),\n",
");\n",
"AccessibilityInfo.isGrayscaleEnabled().then(isEnabled =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const AccessibilityLabelledByTest = () => (\n",
" <>\n",
" <View accessibilityLabelledBy=\"nativeID1\"></View>\n",
" <View accessibilityLabelledBy={[\"nativeID2\", \"nativeID3\"]}></View>\n",
" </>\n",
")\n",
"\n"
],
"file_path": "types/react-native/test/index.tsx",
"type": "add",
"edit_start_line_idx": 1008
} | {
"private": true,
"dependencies": {
"tapable": "^2.2.0",
"webpack": "^5"
}
}
| types/webpack/package.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00017353570729028434,
0.00017353570729028434,
0.00017353570729028434,
0.00017353570729028434,
0
]
|
{
"id": 3,
"code_window": [
" </View>\n",
" );\n",
" }\n",
"}\n",
"\n",
"AccessibilityInfo.isBoldTextEnabled().then(isEnabled =>\n",
" console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),\n",
");\n",
"AccessibilityInfo.isGrayscaleEnabled().then(isEnabled =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const AccessibilityLabelledByTest = () => (\n",
" <>\n",
" <View accessibilityLabelledBy=\"nativeID1\"></View>\n",
" <View accessibilityLabelledBy={[\"nativeID2\", \"nativeID3\"]}></View>\n",
" </>\n",
")\n",
"\n"
],
"file_path": "types/react-native/test/index.tsx",
"type": "add",
"edit_start_line_idx": 1008
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"jsx": "react",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"react-imgpro-tests.tsx"
]
}
| types/react-imgpro/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00017300584295298904,
0.00017283069610130042,
0.00017249095253646374,
0.00017299527826253325,
2.4027028189266275e-7
]
|
{
"id": 5,
"code_window": [
" */\n",
" accessibilityElementsHidden?: boolean | undefined;\n",
"\n",
" /**\n",
" * A Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver.\n",
" * @platform ios\n",
" */\n",
" accessibilityViewIsModal?: boolean | undefined;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * Indicates to the accessibility services that the UI component is in\n",
" * a specific language. The provided string should be formatted following\n",
" * the BCP 47 specification (https://www.rfc-editor.org/info/bcp47).\n",
" * @platform ios\n",
" */\n",
" accessibilityLanguage?: string | undefined;\n",
"\n"
],
"file_path": "types/react-native/v0.69/index.d.ts",
"type": "add",
"edit_start_line_idx": 1030
} | /*
The content of index.io.js could be something like
'use strict';
import { AppRegistry } from 'react-native'
import Welcome from './gen/Welcome'
AppRegistry.registerComponent('MopNative', () => Welcome);
For a list of complete Typescript examples: check https://github.com/bgrieder/RNTSExplorer
*/
import * as PropTypes from 'prop-types';
import * as React from 'react';
import {
AccessibilityInfo,
ActionSheetIOS,
AsyncStorage,
Alert,
AppState,
AppStateStatus,
Appearance,
BackHandler,
Button,
ColorValue,
DataSourceAssetCallback,
DatePickerAndroid,
DevSettings,
DeviceEventEmitter,
DeviceEventEmitterStatic,
Dimensions,
DrawerLayoutAndroid,
DrawerSlideEvent,
DynamicColorIOS,
FlatList,
FlatListProps,
GestureResponderEvent,
HostComponent,
I18nManager,
Image,
ImageBackground,
ImageErrorEventData,
ImageLoadEventData,
ImageResizeMode,
ImageResolvedAssetSource,
ImageStyle,
InputAccessoryView,
InteractionManager,
Keyboard,
KeyboardAvoidingView,
LayoutChangeEvent,
Linking,
ListRenderItemInfo,
ListView,
ListViewDataSource,
LogBox,
MaskedViewIOS,
Modal,
NativeEventEmitter,
NativeModule, // Not actually exported, not sure why
NativeModules,
NativeScrollEvent,
NativeSyntheticEvent,
PermissionsAndroid,
Platform,
PlatformColor,
Pressable,
ProgressBarAndroid,
ProgressViewIOS,
PushNotificationIOS,
RefreshControl,
RegisteredStyle,
ScaledSize,
ScrollView,
ScrollViewProps,
SectionList,
SectionListProps,
SectionListRenderItemInfo,
Share,
ShareDismissedAction,
ShareSharedAction,
StatusBar,
StyleProp,
StyleSheet,
Switch,
SwitchIOS,
SwitchChangeEvent,
Systrace,
TabBarIOS,
Text,
TextInput,
TextInputChangeEventData,
TextInputContentSizeChangeEventData,
TextInputEndEditingEventData,
TextInputFocusEventData,
TextInputKeyPressEventData,
TextInputScrollEventData,
TextInputSelectionChangeEventData,
TextInputSubmitEditingEventData,
TextLayoutEventData,
TextProps,
TextStyle,
TimePickerAndroid,
TouchableNativeFeedback,
UIManager,
View,
ViewPagerAndroid,
ViewStyle,
VirtualizedList,
YellowBox,
findNodeHandle,
requireNativeComponent,
useColorScheme,
useWindowDimensions,
SectionListData,
ToastAndroid,
Touchable,
LayoutAnimation,
} from 'react-native';
declare module 'react-native' {
interface NativeTypedModule {
someFunction(): void;
someProperty: string;
}
interface NativeModulesStatic {
NativeTypedModule: NativeTypedModule;
}
}
NativeModules.NativeUntypedModule;
NativeModules.NativeTypedModule.someFunction();
NativeModules.NativeTypedModule.someProperty = '';
function dimensionsListener(dimensions: { window: ScaledSize; screen: ScaledSize }) {
console.log('window dimensions: ', dimensions.window);
console.log('screen dimensions: ', dimensions.screen);
}
function testDimensions() {
const { width, height, scale, fontScale } = Dimensions.get(1 === 1 ? 'window' : 'screen');
Dimensions.addEventListener('change', dimensionsListener);
Dimensions.removeEventListener('change', dimensionsListener);
}
function TextUseWindowDimensions() {
const { width, height, scale, fontScale } = useWindowDimensions();
}
BackHandler.addEventListener('hardwareBackPress', () => true).remove();
BackHandler.addEventListener('hardwareBackPress', () => false).remove();
BackHandler.addEventListener('hardwareBackPress', () => undefined).remove();
BackHandler.addEventListener('hardwareBackPress', () => null).remove();
interface LocalStyles {
container: ViewStyle;
welcome: TextStyle;
instructions: TextStyle;
}
const styles = StyleSheet.create<LocalStyles>({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
//alternative declaration of styles (inline typings)
const stylesAlt = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
StyleSheet.setStyleAttributePreprocessor('fontFamily', (family: string) => family);
const welcomeFontSize = StyleSheet.flatten(styles.welcome).fontSize;
const viewStyle: StyleProp<ViewStyle> = {
backgroundColor: '#F5FCFF',
};
const textStyle: StyleProp<TextStyle> = {
fontSize: 20,
};
const imageStyle: StyleProp<ImageStyle> = {
resizeMode: 'contain',
};
const fontVariantStyle: StyleProp<TextStyle> = {
fontVariant: ['tabular-nums'],
};
const viewProperty = StyleSheet.flatten(viewStyle).backgroundColor;
const textProperty = StyleSheet.flatten(textStyle).fontSize;
const imageProperty = StyleSheet.flatten(imageStyle).resizeMode;
const fontVariantProperty = StyleSheet.flatten(fontVariantStyle).fontVariant;
// correct use of the StyleSheet.flatten
const styleArray: StyleProp<ViewStyle>[] = [];
const flattenStyle = StyleSheet.flatten(styleArray);
const { top } = flattenStyle;
const s = StyleSheet.create({
shouldWork: {
fontWeight: '900', // if we comment this line, errors gone
marginTop: 5, // if this line commented, errors also gone
},
});
const f1: TextStyle = s.shouldWork;
// StyleSheet.compose
// It creates a new style object by composing two existing styles
const composeTextStyle: StyleProp<TextStyle> = {
color: '#000000',
fontSize: 20,
};
const composeImageStyle: StyleProp<ImageStyle> = {
resizeMode: 'contain',
};
// The following use of the compose method is valid
const combinedStyle: StyleProp<TextStyle> = StyleSheet.compose(composeTextStyle, composeTextStyle);
const combinedStyle1: StyleProp<ImageStyle> = StyleSheet.compose(composeImageStyle, composeImageStyle);
const combinedStyle2: StyleProp<TextStyle | ConcatArray<TextStyle>> = StyleSheet.compose(
[composeTextStyle],
[composeTextStyle],
);
const combinedStyle3: StyleProp<TextStyle | null> = StyleSheet.compose(composeTextStyle, null);
const combinedStyle4: StyleProp<TextStyle | ConcatArray<TextStyle> | null> = StyleSheet.compose(
[composeTextStyle],
null,
);
const combinedStyle5: StyleProp<TextStyle> = StyleSheet.compose(
composeTextStyle,
Math.random() < 0.5 ? composeTextStyle : null,
);
const combinedStyle6: StyleProp<TextStyle | null> = StyleSheet.compose(null, null);
// The following use of the compose method is invalid:
// @ts-expect-error
const combinedStyle7 = StyleSheet.compose(composeImageStyle, composeTextStyle);
// @ts-expect-error
const combinedStyle8: StyleProp<ImageStyle> = StyleSheet.compose(composeTextStyle, composeTextStyle);
// @ts-expect-error
const combinedStyle9: StyleProp<ImageStyle> = StyleSheet.compose([composeTextStyle], null);
// @ts-expect-error
const combinedStyle10: StyleProp<ImageStyle> = StyleSheet.compose(Math.random() < 0.5 ? composeTextStyle : null, null);
const testNativeSyntheticEvent = <T extends {}>(e: NativeSyntheticEvent<T>): void => {
e.isDefaultPrevented();
e.preventDefault();
e.isPropagationStopped();
e.stopPropagation();
e.persist();
e.cancelable;
e.bubbles;
e.currentTarget;
e.defaultPrevented;
e.eventPhase;
e.isTrusted;
e.nativeEvent;
e.target;
e.timeStamp;
e.type;
e.nativeEvent;
};
function eventHandler<T extends React.BaseSyntheticEvent>(e: T) {}
function handler(e: GestureResponderEvent) {
eventHandler(e);
}
type ElementProps<C> = C extends React.Component<infer P, any> ? P : never;
class CustomView extends React.Component {
render() {
return <Text style={[StyleSheet.absoluteFill, { ...StyleSheet.absoluteFillObject }]}>Custom View</Text>;
}
}
class Welcome extends React.Component<ElementProps<View> & { color: string }> {
// tslint:disable-next-line:no-object-literal-type-assertion
refs = {} as {
[key: string]: React.ReactInstance;
rootView: View;
customView: CustomView;
};
testNativeMethods() {
const { rootView } = this.refs;
rootView.setNativeProps({});
rootView.measure((x: number, y: number, width: number, height: number) => {});
}
testFindNodeHandle() {
const { rootView, customView } = this.refs;
const nativeComponentHandle = findNodeHandle(rootView);
const customComponentHandle = findNodeHandle(customView);
const fromHandle = findNodeHandle(customComponentHandle);
}
render() {
const { color, ...props } = this.props;
return (
<View {...props} ref="rootView" style={[[styles.container], undefined, null, false]}>
<Text style={styles.welcome}>Welcome to React Native</Text>
<Text style={styles.instructions}>To get started, edit index.ios.js</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
<CustomView ref="customView" />
</View>
);
}
}
export default Welcome;
// TouchableTest
function TouchableTest() {
function basicUsage() {
if (Touchable.TOUCH_TARGET_DEBUG) {
return Touchable.renderDebugView({
color: 'mediumspringgreen',
hitSlop: { bottom: 5, top: 5 },
});
}
}
function defaultHitSlop() {
return Touchable.renderDebugView({
color: 'red',
});
}
}
// TouchableNativeFeedbackTest
export class TouchableNativeFeedbackTest extends React.Component {
onPressButton = (e: GestureResponderEvent) => {
e.persist();
e.isPropagationStopped();
e.isDefaultPrevented();
};
render() {
return (
<>
<TouchableNativeFeedback onPress={this.onPressButton}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.Ripple('red', true)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.Ripple('red', true, 30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground()}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground(30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless()}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless(30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
</>
);
}
}
// PressableTest
export class PressableTest extends React.Component<{}> {
private readonly myRef: React.RefObject<View> = React.createRef();
onPressButton = (e: GestureResponderEvent) => {
e.persist();
e.isPropagationStopped();
e.isDefaultPrevented();
};
render() {
return (
<>
<Pressable ref={this.myRef} onPress={this.onPressButton} style={{ backgroundColor: 'blue' }} unstable_pressDelay={100}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
{/* Style function */}
<Pressable
onPress={this.onPressButton}
style={state => ({
backgroundColor: state.pressed ? 'red' : 'blue',
})}
>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
{/* Children function */}
<Pressable
onPress={this.onPressButton}
style={state => ({
backgroundColor: state.pressed ? 'red' : 'blue',
})}
>
{state =>
state.pressed ? (
<View>
<Text>Pressed</Text>
</View>
) : (
<View>
<Text>Not Pressed</Text>
</View>
)
}
</Pressable>
{/* Android Ripple */}
<Pressable
android_ripple={{
borderless: true,
color: 'green',
radius: 20,
foreground: true,
}}
onPress={this.onPressButton}
style={{ backgroundColor: 'blue' }}
>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
</>
);
}
}
// App State
function appStateListener(state: string) {
console.log('New state: ' + state);
}
function appStateTest() {
console.log('Current state: ' + AppState.currentState);
AppState.addEventListener('change', appStateListener);
AppState.addEventListener('blur', appStateListener);
AppState.addEventListener('focus', appStateListener);
}
let appState: AppStateStatus = 'active';
appState = 'background';
appState = 'inactive';
appState = 'unknown';
appState = 'extension';
const AppStateExample = () => {
const appState = React.useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = React.useState(appState.current);
const appStateIsAvailable = AppState.isAvailable;
React.useEffect(() => {
const subscription = AppState.addEventListener("change", nextAppState => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
});
return () => {
subscription.remove();
};
}, []);
return (
<View style={styles.container}>
<Text>Current state is: {appStateVisible}</Text>
<Text>Available: {appStateIsAvailable}</Text>
</View>
);
};
// ViewPagerAndroid
export class ViewPagerAndroidTest {
render() {
return (
<ViewPagerAndroid
style={{ height: 56 }}
initialPage={0}
keyboardDismissMode={'on-drag'}
onPageScroll={e => {
console.log(`position: ${e.nativeEvent.position}`);
console.log(`offset: ${e.nativeEvent.offset}`);
}}
onPageSelected={e => {
console.log(`position: ${e.nativeEvent.position}`);
}}
/>
);
}
}
const profiledJSONParse = Systrace.measure('JSON', 'parse', JSON.parse);
profiledJSONParse('[]');
InteractionManager.runAfterInteractions(() => {
// ...
}).then(() => 'done');
export class FlatListTest extends React.Component<FlatListProps<number>, {}> {
list: FlatList<any> | null = null;
componentDidMount(): void {
if (this.list) {
this.list.flashScrollIndicators();
}
}
_renderItem = (rowData: any) => {
return (
<View>
<Text> {rowData.item} </Text>
</View>
);
};
_cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
_renderSeparator = () => <View style={{ height: 1, width: '100%', backgroundColor: 'gray' }} />;
render() {
return (
<FlatList
ref={list => (this.list = list)}
data={[1, 2, 3, 4, 5]}
renderItem={this._renderItem}
ItemSeparatorComponent={this._renderSeparator}
ListFooterComponent={null}
ListFooterComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
ListHeaderComponent={null}
ListHeaderComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
CellRendererComponent={this._cellRenderer}
fadingEdgeLength={200}
/>
);
}
}
export class SectionListTest extends React.Component<SectionListProps<string>, {}> {
myList: React.RefObject<SectionList<string>>;
constructor(props: SectionListProps<string>) {
super(props);
this.myList = React.createRef();
}
scrollMe = () => {
this.myList.current && this.myList.current.scrollToLocation({ itemIndex: 0, sectionIndex: 1 });
};
render() {
const sections = [
{
title: 'Section 1',
data: ['A', 'B', 'C', 'D', 'E'],
},
{
title: 'Section 2',
data: ['A2', 'B2', 'C2', 'D2', 'E2'],
renderItem: (info: { item: string }) => (
<View>
<Text>{info.item}</Text>
</View>
),
},
];
const cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
return (
<React.Fragment>
<Button title="Press" onPress={this.scrollMe} />
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => (
<View>
<Text>{section.title}</Text>
</View>
)}
renderItem={(info: SectionListRenderItemInfo<string>) => (
<View>
<Text>{`${info.section.title} - ${info.item}`}</Text>
</View>
)}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
ListHeaderComponent={null}
ListHeaderComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
/>
</React.Fragment>
);
}
}
type SectionT = { displayTitle: false } | { displayTitle: true; title: string };
export class SectionListTypedSectionTest extends React.Component<SectionListProps<string, SectionT>, {}> {
myList: React.RefObject<SectionList<string, SectionT>>;
constructor(props: SectionListProps<string, SectionT>) {
super(props);
this.myList = React.createRef();
}
scrollMe = () => {
this.myList.current && this.myList.current.scrollToLocation({ itemIndex: 0, sectionIndex: 1 });
};
render() {
const sections: SectionListData<string, SectionT>[] = [
{
displayTitle: false,
data: ['A', 'B', 'C', 'D', 'E'],
},
{
displayTitle: true,
title: 'Section 2',
data: ['A2', 'B2', 'C2', 'D2', 'E2'],
renderItem: (info: { item: string }) => (
<View>
<Text>{info.item}</Text>
</View>
),
},
];
const cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
return (
<React.Fragment>
<Button title="Press" onPress={this.scrollMe} />
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
/>
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={null}
ListHeaderComponent={null}
ListHeaderComponentStyle={null}
/>
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={undefined}
ListHeaderComponent={null}
ListHeaderComponentStyle={undefined}
/>
</React.Fragment>
);
}
}
export class CapsLockComponent extends React.Component<TextProps> {
render() {
const content = (this.props.children || '') as string;
return <Text {...this.props}>{content.toUpperCase()}</Text>;
}
}
const getInitialUrlTest = () =>
Linking.getInitialURL().then(val => {
if (val !== null) {
val.indexOf('val is now a string');
}
});
LogBox.ignoreAllLogs();
LogBox.ignoreAllLogs(true);
LogBox.ignoreLogs(['someString', /^aRegex/]);
LogBox.install();
LogBox.uninstall();
class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListViewDataSource }> {
_stickyHeaderComponent = ({ children }: any) => {
return <View>{children}</View>;
};
eventHandler = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
console.log(event);
};
scrollView: ScrollView | null = null;
testNativeMethods() {
if (this.scrollView) {
this.scrollView.setNativeProps({ scrollEnabled: false });
// Dummy values for scroll dimensions changes
this.scrollView.getScrollResponder().scrollResponderZoomTo({
x: 0,
y: 0,
width: 300,
height: 500,
animated: true,
});
}
}
render() {
const scrollViewStyle1 = StyleSheet.create({
scrollView: {
backgroundColor: 'red',
},
});
const scrollViewStyle2 = {
flex: 1,
};
return (
<ListView
dataSource={this.state.dataSource}
renderScrollComponent={props => {
if (props.scrollEnabled) {
throw new Error('Expected scroll to be enabled.');
}
return (
<ScrollView
ref={ref => (this.scrollView = ref)}
horizontal={true}
nestedScrollEnabled={true}
invertStickyHeaders={true}
contentOffset={{ x: 0, y: 0 }}
snapToStart={false}
snapToEnd={false}
snapToOffsets={[100, 300, 500]}
{...props}
style={[scrollViewStyle1.scrollView, scrollViewStyle2]}
onScrollToTop={() => {}}
scrollToOverflowEnabled={true}
fadingEdgeLength={200}
StickyHeaderComponent={this._stickyHeaderComponent}
stickyHeaderHiddenOnScroll={true}
automaticallyAdjustKeyboardInsets
/>
);
}}
renderRow={({ type, data }, _, row) => {
return <Text>Filler</Text>;
}}
onScroll={this.eventHandler}
onScrollBeginDrag={this.eventHandler}
onScrollEndDrag={this.eventHandler}
onMomentumScrollBegin={this.eventHandler}
onMomentumScrollEnd={this.eventHandler}
/>
);
}
}
class TabBarTest extends React.Component {
render() {
return (
<TabBarIOS
barTintColor="darkslateblue"
itemPositioning="center"
tintColor="white"
translucent={true}
unselectedTintColor="black"
unselectedItemTintColor="red"
>
<TabBarIOS.Item
badge={0}
badgeColor="red"
icon={{ uri: undefined }}
selected={true}
onPress={() => {}}
renderAsOriginal={true}
selectedIcon={undefined}
systemIcon="history"
title="Item 1"
/>
</TabBarIOS>
);
}
}
class AlertTest extends React.Component {
showAlert() {
Alert.alert(
'Title',
'Message',
[
{ text: 'First button', onPress: () => {} },
{ text: 'Second button', onPress: () => {} },
{ text: 'Third button', onPress: () => {} },
],
{
cancelable: false,
onDismiss: () => {},
},
);
}
render() {
return <Button title="Press me" onPress={this.showAlert} />;
}
}
Alert.prompt(
'Enter password',
'Enter your password to claim your $1.5B in lottery winnings',
text => {
console.log(text);
},
'secure-text',
);
Alert.prompt(
'Enter password',
'Enter your password to claim your $1.5B in lottery winnings',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'OK',
onPress: password => console.log('OK Pressed, password: ' + password),
},
],
'secure-text',
);
class MaskedViewTest extends React.Component {
render() {
return (
<MaskedViewIOS maskElement={<View />}>
<View />
</MaskedViewIOS>
);
}
}
class InputAccessoryViewTest extends React.Component {
render() {
const uniqueID = 'foobar';
return (
<InputAccessoryView nativeID={uniqueID}>
<TextInput inputAccessoryViewID={uniqueID} />
</InputAccessoryView>
);
}
}
// DataSourceAssetCallback
const dataSourceAssetCallback1: DataSourceAssetCallback = {
rowHasChanged: (r1, r2) => true,
sectionHeaderHasChanged: (h1, h2) => true,
getRowData: (dataBlob, sectionID, rowID) => (sectionID as number) + (rowID as number),
getSectionHeaderData: (dataBlob, sectionID) => sectionID as string,
};
const dataSourceAssetCallback2: DataSourceAssetCallback = {};
// DeviceEventEmitterStatic
const deviceEventEmitterStatic: DeviceEventEmitterStatic = DeviceEventEmitter;
deviceEventEmitterStatic.addListener('keyboardWillShow', data => true);
deviceEventEmitterStatic.addListener('keyboardWillShow', data => true, {});
// NativeEventEmitter - Android
const androidEventEmitter = new NativeEventEmitter();
const sub1 = androidEventEmitter.addListener('event', (event: object) => event);
const sub2 = androidEventEmitter.addListener('event', (event: object) => event, {});
androidEventEmitter.listenerCount('event'); // $ExpectType number
sub2.remove();
androidEventEmitter.removeAllListeners('event');
androidEventEmitter.removeSubscription(sub1);
// NativeEventEmitter - IOS
const nativeModule: NativeModule = {
addListener(eventType: string) {},
removeListeners(count: number) {},
};
const iosEventEmitter = new NativeEventEmitter(nativeModule);
const sub3 = iosEventEmitter.addListener('event', (event: object) => event);
const sub4 = iosEventEmitter.addListener('event', (event: object) => event, {});
iosEventEmitter.listenerCount('event');
sub4.remove();
iosEventEmitter.removeAllListeners('event');
iosEventEmitter.removeSubscription(sub3);
class CustomEventEmitter extends NativeEventEmitter {}
const customEventEmitter = new CustomEventEmitter();
customEventEmitter.addListener('event', () => {});
class TextInputTest extends React.Component<{}, { username: string }> {
username: TextInput | null = null;
handleUsernameChange = (text: string) => {
console.log(`text: ${text}`);
};
onScroll = (e: NativeSyntheticEvent<TextInputScrollEventData>) => {
testNativeSyntheticEvent(e);
console.log(`x: ${e.nativeEvent.contentOffset.x}`);
console.log(`y: ${e.nativeEvent.contentOffset.y}`);
};
handleOnBlur = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
};
handleOnFocus = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
};
handleOnSelectionChange = (e: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`target: ${e.nativeEvent.target}`);
console.log(`start: ${e.nativeEvent.selection.start}`);
console.log(`end: ${e.nativeEvent.selection.end}`);
};
handleOnKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
testNativeSyntheticEvent(e);
console.log(`key: ${e.nativeEvent.key}`);
};
handleOnChange = (e: NativeSyntheticEvent<TextInputChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`eventCount: ${e.nativeEvent.eventCount}`);
console.log(`target: ${e.nativeEvent.target}`);
console.log(`text: ${e.nativeEvent.text}`);
};
handleOnContentSizeChange = (e: NativeSyntheticEvent<TextInputContentSizeChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`contentSize.width: ${e.nativeEvent.contentSize.width}`);
console.log(`contentSize.height: ${e.nativeEvent.contentSize.height}`);
};
handleOnEndEditing = (e: NativeSyntheticEvent<TextInputEndEditingEventData>) => {
testNativeSyntheticEvent(e);
console.log(`text: ${e.nativeEvent.text}`);
};
handleOnSubmitEditing = (e: NativeSyntheticEvent<TextInputSubmitEditingEventData>) => {
testNativeSyntheticEvent(e);
console.log(`text: ${e.nativeEvent.text}`);
};
render() {
return (
<View>
<Text onPress={() => this.username && this.username.focus()}>Username</Text>
<TextInput
ref={input => (this.username = input)}
textContentType="username"
autoComplete="username"
value={this.state.username}
onChangeText={this.handleUsernameChange}
/>
<TextInput multiline onScroll={this.onScroll} />
<TextInput onBlur={this.handleOnBlur} onFocus={this.handleOnFocus} />
<TextInput onSelectionChange={this.handleOnSelectionChange} />
<TextInput onKeyPress={this.handleOnKeyPress} />
<TextInput onChange={this.handleOnChange} />
<TextInput onChange={this.handleOnChange} />
<TextInput onEndEditing={this.handleOnEndEditing} />
<TextInput onSubmitEditing={this.handleOnSubmitEditing} />
<TextInput multiline onContentSizeChange={this.handleOnContentSizeChange} />
<TextInput contextMenuHidden={true} textAlignVertical="top" />
<TextInput textAlign="center" />
</View>
);
}
}
class TextTest extends React.Component {
handleOnLayout = (e: LayoutChangeEvent) => {
testNativeSyntheticEvent(e);
const x = e.nativeEvent.layout.x; // $ExpectType number
const y = e.nativeEvent.layout.y; // $ExpectType number
const width = e.nativeEvent.layout.width; // $ExpectType number
const height = e.nativeEvent.layout.height; // $ExpectType number
};
handleOnTextLayout = (e: NativeSyntheticEvent<TextLayoutEventData>) => {
testNativeSyntheticEvent(e);
e.nativeEvent.lines.forEach(line => {
const ascender = line.ascender; // $ExpectType number
const capHeight = line.capHeight; // $ExpectType number
const descender = line.descender; // $ExpectType number
const height = line.height; // $ExpectType number
const text = line.text; // $ExpectType string
const width = line.width; // $ExpectType number
const x = line.x; // $ExpectType number
const xHeight = line.xHeight; // $ExpectType number
const y = line.y; // $ExpectType number
});
};
render() {
return (
<Text
allowFontScaling={false}
ellipsizeMode="head"
lineBreakMode="clip"
numberOfLines={2}
onLayout={this.handleOnLayout}
onTextLayout={this.handleOnTextLayout}
>
Test text
</Text>
);
}
}
class StatusBarTest extends React.Component {
render() {
StatusBar.setBarStyle('dark-content', true);
console.log('height:', StatusBar.currentHeight);
return <StatusBar backgroundColor="blue" barStyle="light-content" translucent />;
}
}
export class ImageTest extends React.Component {
componentDidMount(): void {
const uri = 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png';
const headers = { Authorization: 'Bearer test' };
const image: ImageResolvedAssetSource = Image.resolveAssetSource({ uri });
console.log(image.width, image.height, image.scale, image.uri);
Image.queryCache &&
Image.queryCache([uri]).then(({ [uri]: status }) => {
if (status === undefined) {
console.log('Image is not in cache');
} else {
console.log(`Image is in ${status} cache`);
}
});
Image.getSize(uri, (width, height) => console.log(width, height));
Image.getSize(
uri,
(width, height) => console.log(width, height),
error => console.error(error),
);
Image.getSizeWithHeaders(uri, headers, (width, height) => console.log(width, height));
Image.getSizeWithHeaders(
uri,
headers,
(width, height) => console.log(width, height),
error => console.error(error),
);
Image.prefetch(uri); // $ExpectType Promise<boolean>
}
handleOnLoad = (e: NativeSyntheticEvent<ImageLoadEventData>) => {
testNativeSyntheticEvent(e);
console.log('height:', e.nativeEvent.source.height);
console.log('width:', e.nativeEvent.source.width);
console.log('uri:', e.nativeEvent.source.uri);
};
handleOnError = (e: NativeSyntheticEvent<ImageErrorEventData>) => {
testNativeSyntheticEvent(e);
console.log('error:', e.nativeEvent.error);
};
render() {
const resizeMode: ImageResizeMode = 'contain';
return (
<View>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
onLoad={this.handleOnLoad}
onError={this.handleOnError}
/>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
resizeMode={resizeMode}
/>
</View>
);
}
}
export class ImageBackgroundProps extends React.Component {
private _imageRef: Image | null = null;
setImageRef = (image: Image) => {
this._imageRef = image;
};
render() {
return (
<View>
<ImageBackground
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
imageRef={this.setImageRef}
>
<Text>Some text</Text>
</ImageBackground>
</View>
);
}
}
const listViewDataSourceTest = new ListView.DataSource({ rowHasChanged: () => true });
class AccessibilityTest extends React.Component {
render() {
return (
<View
accessibilityElementsHidden={true}
importantForAccessibility={'no-hide-descendants'}
onAccessibilityTap={() => {}}
accessibilityRole="header"
accessibilityState={{ checked: true }}
accessibilityHint="Very important header"
accessibilityValue={{ min: 60, max: 120, now: 80 }}
onMagicTap={() => {}}
onAccessibilityEscape={() => {}}
>
<Text accessibilityIgnoresInvertColors>Text</Text>
<View />
</View>
);
}
}
AccessibilityInfo.isBoldTextEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),
);
AccessibilityInfo.isGrayscaleEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isGrayscaleEnabled => ${isEnabled}`),
);
AccessibilityInfo.isInvertColorsEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isInvertColorsEnabled => ${isEnabled}`),
);
AccessibilityInfo.isReduceMotionEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isReduceMotionEnabled => ${isEnabled}`),
);
AccessibilityInfo.isReduceTransparencyEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isReduceTransparencyEnabled => ${isEnabled}`),
);
AccessibilityInfo.isScreenReaderEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isScreenReaderEnabled => ${isEnabled}`),
);
AccessibilityInfo.getRecommendedTimeoutMillis(5000).then(timeoutMiles =>
console.log(`AccessibilityInfo.getRecommendedTimeoutMillis => ${timeoutMiles}`)
);
AccessibilityInfo.addEventListener('announcementFinished', ({ announcement, success }) =>
console.log(`A11y Event: announcementFinished: ${announcement}, ${success}`),
);
AccessibilityInfo.addEventListener('boldTextChanged', isEnabled =>
console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('grayscaleChanged', isEnabled =>
console.log(`AccessibilityInfo.isGrayscaleEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('invertColorsChanged', isEnabled =>
console.log(`AccessibilityInfo.isInvertColorsEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('reduceMotionChanged', isEnabled =>
console.log(`AccessibilityInfo.isReduceMotionEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('reduceTransparencyChanged', isEnabled =>
console.log(`AccessibilityInfo.isReduceTransparencyEnabled => ${isEnabled}`),
);
const screenReaderChangedListener = (isEnabled: boolean): void => console.log(`AccessibilityInfo.isScreenReaderEnabled => ${isEnabled}`);
AccessibilityInfo.addEventListener('screenReaderChanged', screenReaderChangedListener,
).remove();
AccessibilityInfo.removeEventListener('screenReaderChanged', screenReaderChangedListener);
const KeyboardAvoidingViewTest = () => <KeyboardAvoidingView enabled />;
const ModalTest = () => <Modal hardwareAccelerated />;
const ModalTest2 = () => <Modal hardwareAccelerated testID="modal-test-2" />;
const TimePickerAndroidTest = () => {
TimePickerAndroid.open({
hour: 8,
minute: 15,
is24Hour: true,
mode: 'spinner',
}).then(result => {
if (result.action === TimePickerAndroid.timeSetAction) {
console.log('Time', result.hour, result.minute);
}
});
};
const DatePickerAndroidTest = () => {
DatePickerAndroid.open({
date: new Date(),
mode: 'calendar',
}).then(result => {
if (result.action === DatePickerAndroid.dateSetAction) {
console.log('Date', result.year, result.month, result.day);
}
});
};
const NativeBridgedComponent = requireNativeComponent<{ nativeProp: string }>('NativeBridgedComponent'); // $ExpectType HostComponent<{ nativeProp: string; }>
class BridgedComponentTest extends React.Component {
static propTypes = {
jsProp: PropTypes.string.isRequired,
};
nativeComponentRef: React.ElementRef<typeof NativeBridgedComponent> | null;
callNativeMethod = () => {
UIManager.dispatchViewManagerCommand(findNodeHandle(this.nativeComponentRef), 'someNativeMethod', []);
};
measureNativeComponent() {
if (this.nativeComponentRef) {
this.nativeComponentRef.measure(
(x, y, width, height, pageX, pageY) => x + y + width + height + pageX + pageY,
);
}
}
render() {
return (
<NativeBridgedComponent {...this.props} nativeProp="test" ref={ref => (this.nativeComponentRef = ref)} />
);
}
}
const SwitchColorTest = () => <Switch trackColor={{ true: 'pink', false: 'red' }} />;
const SwitchColorOptionalTrueTest = () => <Switch trackColor={{ false: 'red' }} />;
const SwitchColorOptionalFalseTest = () => <Switch trackColor={{ true: 'pink' }} />;
const SwitchColorNullTest = () => <Switch trackColor={{ true: 'pink', false: null }} />;
const SwitchThumbColorTest = () => <Switch thumbColor={'red'} />;
const SwitchOnChangeWithoutParamsTest = () => <Switch onChange={() => console.log('test')} />;
const SwitchOnChangeUndefinedTest = () => <Switch onChange={undefined} />;
const SwitchOnChangeNullTest = () => <Switch onChange={null} />;
const SwitchOnChangePromiseTest = () => <Switch onChange={(event) => {
const e: SwitchChangeEvent = event;
return new Promise(() => e.value);
}} />;
const SwitchOnValueChangeWithoutParamsTest = () => <Switch onValueChange={() => console.log('test')} />;
const SwitchOnValueChangeUndefinedTest = () => <Switch onValueChange={undefined} />;
const SwitchOnValueChangeNullTest = () => <Switch onValueChange={null} />;
const SwitchOnValueChangePromiseTest = () => <Switch onValueChange={(value) => {
const v: boolean = value;
return new Promise(() => v)
}} />;
const NativeIDTest = () => (
<ScrollView nativeID={'nativeID'}>
<View nativeID={'nativeID'} />
<Text nativeID={'nativeID'}>Text</Text>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
nativeID={'nativeID'}
/>
</ScrollView>
);
const ScrollViewMaintainVisibleContentPositionTest = () => (
<ScrollView maintainVisibleContentPosition={{ autoscrollToTopThreshold: 1, minIndexForVisible: 10 }}></ScrollView>
);
const ScrollViewInsetsTest = () => (
<>
<ScrollView automaticallyAdjustKeyboardInsets />
<ScrollView automaticallyAdjustKeyboardInsets={false} />
</>
);
const MaxFontSizeMultiplierTest = () => <Text maxFontSizeMultiplier={0}>Text</Text>;
const ShareTest = () => {
Share.share(
{ title: 'title', message: 'message' },
{ dialogTitle: 'dialogTitle', excludedActivityTypes: ['activity'], tintColor: 'red', subject: 'Email subject' },
);
Share.share({ title: 'title', url: 'url' });
Share.share({ message: 'message' }).then(result => {
if (result.action === Share.sharedAction) {
const activity = result.activityType;
} else if (result.action === Share.dismissedAction) {
}
});
};
const KeyboardTest = () => {
const subscriber = Keyboard.addListener('keyboardDidHide', event => {
event;
});
subscriber.remove();
Keyboard.dismiss();
// Android Keyboard Event
Keyboard.scheduleLayoutAnimation({
duration: 0,
easing: 'keyboard',
endCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
});
// IOS Keyboard Event
Keyboard.scheduleLayoutAnimation({
duration: 0,
easing: 'easeInEaseOut',
endCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
startCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
isEventFromThisApp: true,
});
};
const PermissionsAndroidTest = () => {
PermissionsAndroid.request('android.permission.CAMERA').then(result => {
switch (result) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
PermissionsAndroid.requestMultiple([
'android.permission.CAMERA',
'android.permission.ACCESS_FINE_LOCATION',
'android.permission.ACCESS_BACKGROUND_LOCATION',
]).then(results => {
switch (results['android.permission.CAMERA']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.ACCESS_FINE_LOCATION']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.ACCESS_BACKGROUND_LOCATION']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
PermissionsAndroid.requestMultiple([
'android.permission.BLUETOOTH_SCAN',
'android.permission.BLUETOOTH_CONNECT',
'android.permission.BLUETOOTH_ADVERTISE'
]).then(results => {
switch (results['android.permission.BLUETOOTH_SCAN']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.BLUETOOTH_CONNECT']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.BLUETOOTH_ADVERTISE']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
};
// Platform
const PlatformTest = () => {
switch (Platform.OS) {
case 'ios':
if (!Platform.isPad) {
return 32;
} else {
return 44;
}
case 'android':
case 'macos':
case 'windows':
return Platform.isTV ? 64 : 56;
default:
return Platform.isTV ? 40 : 44;
}
};
const PlatformConstantsTest = () => {
const testing: boolean = Platform.constants.isTesting;
if (Platform.OS === 'ios') {
const hasForceTouch: boolean = Platform.constants.forceTouchAvailable;
} else if (Platform.OS === 'android') {
const { major, prerelease } = Platform.constants.reactNativeVersion;
const v = Platform.constants.Version;
const host: string | undefined = Platform.constants.ServerHost;
}
};
Platform.select({ native: 1 }); // $ExpectType number | undefined
Platform.select({ native: 1, web: 2, default: 0 }); // $ExpectType number
Platform.select({ android: 1 }); // $ExpectType number | undefined
Platform.select({ android: 1, ios: 2, default: 0 }); // $ExpectType number
Platform.select({ android: 1, ios: 2, macos: 3, web: 4, windows: 5 }); // $ExpectType number | undefined
Platform.select({ android: 1, ios: 2, macos: 3, web: 4, windows: 5, default: 0 }); // $ExpectType number
PlatformColor('?attr/colorControlNormal');
PlatformColor('?attr/colorControlNormal', '?attr/colorAccent', 'another');
DynamicColorIOS({
dark: 'lightskyblue',
light: 'midnightblue',
});
DynamicColorIOS({
dark: 'lightskyblue',
light: PlatformColor('labelColor'),
});
// Test you cannot set internals of ColorValue directly
const OpaqueTest1 = () => (
<View
// @ts-expect-error
style={{
backgroundColor: {
resource_paths: ['?attr/colorControlNormal'],
},
}}
/>
);
const OpaqueTest2 = () => (
<View
// @ts-expect-error
style={{
backgroundColor: {
semantic: 'string',
dynamic: {
light: 'light',
dark: 'dark',
},
},
}}
/>
);
// Test you cannot amend opaque type
// @ts-expect-error
PlatformColor('?attr/colorControlNormal').resource_paths.push('foo');
const someColorProp: ColorValue = PlatformColor('test');
// Test PlatformColor inside Platform select with stylesheet
StyleSheet.create({
labelCell: {
flex: 1,
alignItems: 'stretch',
...Platform.select({
ios: { color: DynamicColorIOS({ dark: 'lightskyblue', light: PlatformColor('labelColor') }) },
android: {
color: PlatformColor('?attr/colorControlNormal'),
},
default: { color: PlatformColor('?attr/colorControlNormal') },
}),
},
});
// PlatformColor in style colors
StyleSheet.create({
labelCell: {
flex: 1,
alignItems: 'stretch',
color: PlatformColor('test'),
backgroundColor: PlatformColor('test'),
borderBottomColor: PlatformColor('test'),
borderColor: PlatformColor('test'),
borderEndColor: PlatformColor('test'),
borderLeftColor: PlatformColor('test'),
borderRightColor: PlatformColor('test'),
borderStartColor: PlatformColor('test'),
borderTopColor: PlatformColor('test'),
overlayColor: PlatformColor('test'),
shadowColor: PlatformColor('test'),
textDecorationColor: PlatformColor('test'),
textShadowColor: PlatformColor('test'),
tintColor: PlatformColor('test'),
},
});
function someColorString(): ColorValue {
return '#000000';
}
function somePlatformColor(): ColorValue {
return PlatformColor('test');
}
const colors = {
color: someColorString(),
backgroundColor: somePlatformColor(),
};
StyleSheet.create({
labelCell: {
color: colors.color,
backgroundColor: colors.backgroundColor,
},
});
const OpaqueTest3 = () => (
<View
style={{
backgroundColor: colors.backgroundColor,
}}
/>
);
// ProgressBarAndroid
const ProgressBarAndroidTest = () => {
<ProgressBarAndroid animating color="white" styleAttr="Horizontal" progress={0.42} />;
};
// Push notification
const PushNotificationTest = () => {
PushNotificationIOS.presentLocalNotification({
alertBody: 'notificatus',
userInfo: 'informius',
alertTitle: 'Titulus',
alertAction: 'view',
});
PushNotificationIOS.scheduleLocalNotification({
alertAction: 'view',
alertBody: 'Look at me!',
alertTitle: 'Hello!',
applicationIconBadgeNumber: 999,
category: 'engagement',
fireDate: new Date().toISOString(),
isSilent: false,
repeatInterval: 'minute',
userInfo: {
abc: 123,
},
});
};
// YellowBox
const YellowBoxTest = () => <YellowBox />;
// Appearance
const DarkMode = () => {
const color = useColorScheme();
const isDarkMode = Appearance.getColorScheme() === 'dark';
const subscription = Appearance.addChangeListener(({ colorScheme }) => {
console.log(colorScheme);
});
React.useEffect(() => {
console.log('-color', color);
return () => {
subscription.remove();
};
}, [color]);
return <Text>Is dark mode enabled? {isDarkMode}</Text>;
};
// VirtualizedList
// Test inspired by: https://reactnative.dev/docs/virtualizedlist
const VirtualizedListTest = () => {
const DATA = [1, 2, 3];
const getItem = (data: number[], index: number) => {
return {
title: `Item ${data[index]}`,
};
};
const getItemCount = (data: number[]) => data.length;
return (
<VirtualizedList
data={DATA}
initialNumToRender={4}
renderItem={({ item }: ListRenderItemInfo<ReturnType<typeof getItem>>) => <Text>{item.title}</Text>}
getItemCount={getItemCount}
getItem={getItem}
/>
);
};
// DevSettings
DevSettings.addMenuItem('alert', () => {
Alert.alert('alert');
});
DevSettings.reload();
DevSettings.reload('reload with reason');
// Accessibility custom actions
const AccessibilityCustomActionsTest = () => {
return (
<View
accessible={true}
accessibilityActions={[
// should support custom defined actions
{ name: 'cut', label: 'cut' },
{ name: 'copy', label: 'copy' },
{ name: 'paste', label: 'paste' },
]}
onAccessibilityAction={event => {
switch (event.nativeEvent.actionName) {
case 'cut':
Alert.alert('Alert', 'cut action success');
break;
case 'copy':
Alert.alert('Alert', 'copy action success');
break;
case 'paste':
Alert.alert('Alert', 'paste action success');
break;
}
}}
/>
);
};
// DrawerLayoutAndroidTest
export class DrawerLayoutAndroidTest extends React.Component {
drawerRef = React.createRef<DrawerLayoutAndroid>();
readonly styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 50,
backgroundColor: '#ecf0f1',
padding: 8,
},
navigationContainer: {
flex: 1,
paddingTop: 50,
backgroundColor: '#fff',
padding: 8,
},
});
readonly navigationView = (
<View style={this.styles.navigationContainer}>
<Text style={{ margin: 10, fontSize: 15 }}>I'm in the Drawer!</Text>
</View>
);
handleDrawerClose = () => {
console.log('handleDrawerClose');
};
handleDrawerOpen = () => {
console.log('handleDrawerOpen');
};
handleDrawerSlide = (event: DrawerSlideEvent) => {
console.log('handleDrawerSlide', event);
};
handleDrawerStateChanged = (event: 'Idle' | 'Dragging' | 'Settling') => {
console.log('handleDrawerStateChanged', event);
};
render() {
return (
<DrawerLayoutAndroid
ref={this.drawerRef}
drawerBackgroundColor="rgba(0,0,0,0.5)"
drawerLockMode="locked-closed"
drawerPosition="right"
drawerWidth={300}
keyboardDismissMode="on-drag"
onDrawerClose={this.handleDrawerClose}
onDrawerOpen={this.handleDrawerOpen}
onDrawerSlide={this.handleDrawerSlide}
onDrawerStateChanged={this.handleDrawerStateChanged}
renderNavigationView={() => this.navigationView}
statusBarBackgroundColor="yellow"
>
<View style={this.styles.container}>
<Text style={{ margin: 10, fontSize: 15 }}>DrawerLayoutAndroid example</Text>
</View>
</DrawerLayoutAndroid>
);
}
}
// DataDetectorType for Text component
const DataDetectorTypeTest = () => {
return (
<>
<Text dataDetectorType={'all'}>http://test.com [email protected] +33123456789</Text>
<Text dataDetectorType={'email'}>[email protected]</Text>
<Text dataDetectorType={'link'}>http://test.com</Text>
<Text dataDetectorType={'none'}>Hi there !</Text>
<Text dataDetectorType={'phoneNumber'}>+33123456789</Text>
<Text dataDetectorType={null}>Must allow null value</Text>
</>
);
};
const ToastAndroidTest = () => {
ToastAndroid.showWithGravityAndOffset('My Toast', ToastAndroid.SHORT, ToastAndroid.BOTTOM, 0, 50);
};
const I18nManagerTest = () => {
I18nManager.allowRTL(true);
I18nManager.forceRTL(true);
I18nManager.swapLeftAndRightInRTL(true);
const { isRTL, doLeftAndRightSwapInRTL } = I18nManager.getConstants();
const isRtlFlag = I18nManager.isRTL;
const doLeftAndRightSwapInRtlFlag = I18nManager.doLeftAndRightSwapInRTL;
console.log(isRTL, isRtlFlag, doLeftAndRightSwapInRTL, doLeftAndRightSwapInRtlFlag);
};
// LayoutAnimations
LayoutAnimation.configureNext(
LayoutAnimation.create(123, LayoutAnimation.Types.easeIn, LayoutAnimation.Properties.opacity),
);
LayoutAnimation.configureNext(LayoutAnimation.create(123, 'easeIn', 'opacity'));
// ActionSheetIOS
const ActionSheetIOSTest = () => {
// test destructiveButtonIndex undefined
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: undefined,
}, () => undefined);
// test destructiveButtonIndex null
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: null,
}, () => undefined);
// test destructiveButtonIndex single number
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: 0,
}, () => undefined);
// test destructiveButtonIndex number array
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo', 'bar'],
destructiveButtonIndex: [0, 1],
}, () => undefined);
}
| types/react-native/v0.69/test/index.tsx | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.04034795984625816,
0.00037966412492096424,
0.00016357227286789566,
0.00017411306907888502,
0.0028622120153158903
]
|
{
"id": 5,
"code_window": [
" */\n",
" accessibilityElementsHidden?: boolean | undefined;\n",
"\n",
" /**\n",
" * A Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver.\n",
" * @platform ios\n",
" */\n",
" accessibilityViewIsModal?: boolean | undefined;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * Indicates to the accessibility services that the UI component is in\n",
" * a specific language. The provided string should be formatted following\n",
" * the BCP 47 specification (https://www.rfc-editor.org/info/bcp47).\n",
" * @platform ios\n",
" */\n",
" accessibilityLanguage?: string | undefined;\n",
"\n"
],
"file_path": "types/react-native/v0.69/index.d.ts",
"type": "add",
"edit_start_line_idx": 1030
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"esnext"
],
"strictFunctionTypes": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jsreport-phantom-pdf-tests.ts"
]
}
| types/jsreport-phantom-pdf/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00017635829863138497,
0.00017587696493137628,
0.0001752350653987378,
0.00017603757441975176,
4.7240962430805666e-7
]
|
{
"id": 5,
"code_window": [
" */\n",
" accessibilityElementsHidden?: boolean | undefined;\n",
"\n",
" /**\n",
" * A Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver.\n",
" * @platform ios\n",
" */\n",
" accessibilityViewIsModal?: boolean | undefined;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * Indicates to the accessibility services that the UI component is in\n",
" * a specific language. The provided string should be formatted following\n",
" * the BCP 47 specification (https://www.rfc-editor.org/info/bcp47).\n",
" * @platform ios\n",
" */\n",
" accessibilityLanguage?: string | undefined;\n",
"\n"
],
"file_path": "types/react-native/v0.69/index.d.ts",
"type": "add",
"edit_start_line_idx": 1030
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es2018"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"@adeira/*": ["adeira__*"]
}
},
"files": [
"index.d.ts",
"adeira__graphql-global-id-tests.ts"
]
}
| types/adeira__graphql-global-id/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00017625137115828693,
0.00017523272254038602,
0.00017435253539588302,
0.00017509424651507288,
7.813556521796272e-7
]
|
{
"id": 5,
"code_window": [
" */\n",
" accessibilityElementsHidden?: boolean | undefined;\n",
"\n",
" /**\n",
" * A Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver.\n",
" * @platform ios\n",
" */\n",
" accessibilityViewIsModal?: boolean | undefined;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * Indicates to the accessibility services that the UI component is in\n",
" * a specific language. The provided string should be formatted following\n",
" * the BCP 47 specification (https://www.rfc-editor.org/info/bcp47).\n",
" * @platform ios\n",
" */\n",
" accessibilityLanguage?: string | undefined;\n",
"\n"
],
"file_path": "types/react-native/v0.69/index.d.ts",
"type": "add",
"edit_start_line_idx": 1030
} | import * as materialize from "materialize-css";
const elem = document.querySelector('.whatever')!;
// $ExpectType Materialbox
const _materialbox = new M.Materialbox(elem);
// $ExpectType Materialbox
const el = M.Materialbox.init(elem);
// $ExpectType Materialbox[]
const els = M.Materialbox.init(document.querySelectorAll('.whatever'));
// $ExpectType Materialbox
const materialbox = new materialize.Materialbox(elem, {
inDuration: 1,
outDuration: 1,
onCloseEnd(el) {
// $ExpectType Element
el;
},
onCloseStart(el) {
// $ExpectType Element
el;
},
onOpenEnd(el) {
// $ExpectType Element
el;
},
onOpenStart(el) {
// $ExpectType Element
el;
}
});
// $ExpectType void
materialbox.close();
// $ExpectType void
materialbox.destroy();
// $ExpectType void
materialbox.open();
// $ExpectType Element
materialbox.el;
// $ExpectType MaterialboxOptions
materialbox.options;
$(".whatever").materialbox();
$(".whatever").materialbox({ inDuration: 2 });
$(".whatever").materialbox("open");
$(".whatever").materialbox("destroy");
$(".whatever").materialbox("close");
| types/materialize-css/test/materialbox.test.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.000179273949470371,
0.00017831954755820334,
0.00017769243277143687,
0.00017837552877608687,
5.719543878512923e-7
]
|
{
"id": 6,
"code_window": [
" accessibilityHint=\"Very important header\"\n",
" accessibilityValue={{ min: 60, max: 120, now: 80 }}\n",
" onMagicTap={() => {}}\n",
" onAccessibilityEscape={() => {}}\n",
" >\n",
" <Text accessibilityIgnoresInvertColors>Text</Text>\n",
" <View />\n",
" </View>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accessibilityLanguage=\"sv-SE\"\n"
],
"file_path": "types/react-native/v0.69/test/index.tsx",
"type": "add",
"edit_start_line_idx": 1000
} | /*
The content of index.io.js could be something like
'use strict';
import { AppRegistry } from 'react-native'
import Welcome from './gen/Welcome'
AppRegistry.registerComponent('MopNative', () => Welcome);
For a list of complete Typescript examples: check https://github.com/bgrieder/RNTSExplorer
*/
import * as PropTypes from 'prop-types';
import * as React from 'react';
import {
AccessibilityInfo,
ActionSheetIOS,
AsyncStorage,
Alert,
AppState,
AppStateStatus,
Appearance,
BackHandler,
Button,
ColorValue,
DataSourceAssetCallback,
DatePickerAndroid,
DevSettings,
DeviceEventEmitter,
DeviceEventEmitterStatic,
Dimensions,
DrawerLayoutAndroid,
DrawerSlideEvent,
DynamicColorIOS,
FlatList,
FlatListProps,
GestureResponderEvent,
HostComponent,
I18nManager,
Image,
ImageBackground,
ImageErrorEventData,
ImageLoadEventData,
ImageResizeMode,
ImageResolvedAssetSource,
ImageStyle,
InputAccessoryView,
InteractionManager,
Keyboard,
KeyboardAvoidingView,
LayoutChangeEvent,
Linking,
ListRenderItemInfo,
ListView,
ListViewDataSource,
LogBox,
MaskedViewIOS,
Modal,
NativeEventEmitter,
NativeModule, // Not actually exported, not sure why
NativeModules,
NativeScrollEvent,
NativeSyntheticEvent,
PermissionsAndroid,
Platform,
PlatformColor,
Pressable,
ProgressBarAndroid,
ProgressViewIOS,
PushNotificationIOS,
RefreshControl,
RegisteredStyle,
ScaledSize,
ScrollView,
ScrollViewProps,
SectionList,
SectionListProps,
SectionListRenderItemInfo,
Share,
ShareDismissedAction,
ShareSharedAction,
StatusBar,
StyleProp,
StyleSheet,
Switch,
SwitchIOS,
SwitchChangeEvent,
Systrace,
TabBarIOS,
Text,
TextInput,
TextInputChangeEventData,
TextInputContentSizeChangeEventData,
TextInputEndEditingEventData,
TextInputFocusEventData,
TextInputKeyPressEventData,
TextInputScrollEventData,
TextInputSelectionChangeEventData,
TextInputSubmitEditingEventData,
TextLayoutEventData,
TextProps,
TextStyle,
TimePickerAndroid,
TouchableNativeFeedback,
UIManager,
View,
ViewPagerAndroid,
ViewStyle,
VirtualizedList,
YellowBox,
findNodeHandle,
requireNativeComponent,
useColorScheme,
useWindowDimensions,
SectionListData,
ToastAndroid,
Touchable,
LayoutAnimation,
} from 'react-native';
declare module 'react-native' {
interface NativeTypedModule {
someFunction(): void;
someProperty: string;
}
interface NativeModulesStatic {
NativeTypedModule: NativeTypedModule;
}
}
NativeModules.NativeUntypedModule;
NativeModules.NativeTypedModule.someFunction();
NativeModules.NativeTypedModule.someProperty = '';
function dimensionsListener(dimensions: { window: ScaledSize; screen: ScaledSize }) {
console.log('window dimensions: ', dimensions.window);
console.log('screen dimensions: ', dimensions.screen);
}
function testDimensions() {
const { width, height, scale, fontScale } = Dimensions.get(1 === 1 ? 'window' : 'screen');
Dimensions.addEventListener('change', dimensionsListener);
Dimensions.removeEventListener('change', dimensionsListener);
}
function TextUseWindowDimensions() {
const { width, height, scale, fontScale } = useWindowDimensions();
}
BackHandler.addEventListener('hardwareBackPress', () => true).remove();
BackHandler.addEventListener('hardwareBackPress', () => false).remove();
BackHandler.addEventListener('hardwareBackPress', () => undefined).remove();
BackHandler.addEventListener('hardwareBackPress', () => null).remove();
interface LocalStyles {
container: ViewStyle;
welcome: TextStyle;
instructions: TextStyle;
}
const styles = StyleSheet.create<LocalStyles>({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
//alternative declaration of styles (inline typings)
const stylesAlt = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
StyleSheet.setStyleAttributePreprocessor('fontFamily', (family: string) => family);
const welcomeFontSize = StyleSheet.flatten(styles.welcome).fontSize;
const viewStyle: StyleProp<ViewStyle> = {
backgroundColor: '#F5FCFF',
};
const textStyle: StyleProp<TextStyle> = {
fontSize: 20,
};
const imageStyle: StyleProp<ImageStyle> = {
resizeMode: 'contain',
};
const fontVariantStyle: StyleProp<TextStyle> = {
fontVariant: ['tabular-nums'],
};
const viewProperty = StyleSheet.flatten(viewStyle).backgroundColor;
const textProperty = StyleSheet.flatten(textStyle).fontSize;
const imageProperty = StyleSheet.flatten(imageStyle).resizeMode;
const fontVariantProperty = StyleSheet.flatten(fontVariantStyle).fontVariant;
// correct use of the StyleSheet.flatten
const styleArray: StyleProp<ViewStyle>[] = [];
const flattenStyle = StyleSheet.flatten(styleArray);
const { top } = flattenStyle;
const s = StyleSheet.create({
shouldWork: {
fontWeight: '900', // if we comment this line, errors gone
marginTop: 5, // if this line commented, errors also gone
},
});
const f1: TextStyle = s.shouldWork;
// StyleSheet.compose
// It creates a new style object by composing two existing styles
const composeTextStyle: StyleProp<TextStyle> = {
color: '#000000',
fontSize: 20,
};
const composeImageStyle: StyleProp<ImageStyle> = {
resizeMode: 'contain',
};
// The following use of the compose method is valid
const combinedStyle: StyleProp<TextStyle> = StyleSheet.compose(composeTextStyle, composeTextStyle);
const combinedStyle1: StyleProp<ImageStyle> = StyleSheet.compose(composeImageStyle, composeImageStyle);
const combinedStyle2: StyleProp<TextStyle | ConcatArray<TextStyle>> = StyleSheet.compose(
[composeTextStyle],
[composeTextStyle],
);
const combinedStyle3: StyleProp<TextStyle | null> = StyleSheet.compose(composeTextStyle, null);
const combinedStyle4: StyleProp<TextStyle | ConcatArray<TextStyle> | null> = StyleSheet.compose(
[composeTextStyle],
null,
);
const combinedStyle5: StyleProp<TextStyle> = StyleSheet.compose(
composeTextStyle,
Math.random() < 0.5 ? composeTextStyle : null,
);
const combinedStyle6: StyleProp<TextStyle | null> = StyleSheet.compose(null, null);
// The following use of the compose method is invalid:
// @ts-expect-error
const combinedStyle7 = StyleSheet.compose(composeImageStyle, composeTextStyle);
// @ts-expect-error
const combinedStyle8: StyleProp<ImageStyle> = StyleSheet.compose(composeTextStyle, composeTextStyle);
// @ts-expect-error
const combinedStyle9: StyleProp<ImageStyle> = StyleSheet.compose([composeTextStyle], null);
// @ts-expect-error
const combinedStyle10: StyleProp<ImageStyle> = StyleSheet.compose(Math.random() < 0.5 ? composeTextStyle : null, null);
const testNativeSyntheticEvent = <T extends {}>(e: NativeSyntheticEvent<T>): void => {
e.isDefaultPrevented();
e.preventDefault();
e.isPropagationStopped();
e.stopPropagation();
e.persist();
e.cancelable;
e.bubbles;
e.currentTarget;
e.defaultPrevented;
e.eventPhase;
e.isTrusted;
e.nativeEvent;
e.target;
e.timeStamp;
e.type;
e.nativeEvent;
};
function eventHandler<T extends React.BaseSyntheticEvent>(e: T) {}
function handler(e: GestureResponderEvent) {
eventHandler(e);
}
type ElementProps<C> = C extends React.Component<infer P, any> ? P : never;
class CustomView extends React.Component {
render() {
return <Text style={[StyleSheet.absoluteFill, { ...StyleSheet.absoluteFillObject }]}>Custom View</Text>;
}
}
class Welcome extends React.Component<ElementProps<View> & { color: string }> {
// tslint:disable-next-line:no-object-literal-type-assertion
refs = {} as {
[key: string]: React.ReactInstance;
rootView: View;
customView: CustomView;
};
testNativeMethods() {
const { rootView } = this.refs;
rootView.setNativeProps({});
rootView.measure((x: number, y: number, width: number, height: number) => {});
}
testFindNodeHandle() {
const { rootView, customView } = this.refs;
const nativeComponentHandle = findNodeHandle(rootView);
const customComponentHandle = findNodeHandle(customView);
const fromHandle = findNodeHandle(customComponentHandle);
}
render() {
const { color, ...props } = this.props;
return (
<View {...props} ref="rootView" style={[[styles.container], undefined, null, false]}>
<Text style={styles.welcome}>Welcome to React Native</Text>
<Text style={styles.instructions}>To get started, edit index.ios.js</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
<CustomView ref="customView" />
</View>
);
}
}
export default Welcome;
// TouchableTest
function TouchableTest() {
function basicUsage() {
if (Touchable.TOUCH_TARGET_DEBUG) {
return Touchable.renderDebugView({
color: 'mediumspringgreen',
hitSlop: { bottom: 5, top: 5 },
});
}
}
function defaultHitSlop() {
return Touchable.renderDebugView({
color: 'red',
});
}
}
// TouchableNativeFeedbackTest
export class TouchableNativeFeedbackTest extends React.Component {
onPressButton = (e: GestureResponderEvent) => {
e.persist();
e.isPropagationStopped();
e.isDefaultPrevented();
};
render() {
return (
<>
<TouchableNativeFeedback onPress={this.onPressButton}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.Ripple('red', true)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.Ripple('red', true, 30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground()}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground(30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless()}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless(30)}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</TouchableNativeFeedback>
</>
);
}
}
// PressableTest
export class PressableTest extends React.Component<{}> {
private readonly myRef: React.RefObject<View> = React.createRef();
onPressButton = (e: GestureResponderEvent) => {
e.persist();
e.isPropagationStopped();
e.isDefaultPrevented();
};
render() {
return (
<>
<Pressable ref={this.myRef} onPress={this.onPressButton} style={{ backgroundColor: 'blue' }} unstable_pressDelay={100}>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
{/* Style function */}
<Pressable
onPress={this.onPressButton}
style={state => ({
backgroundColor: state.pressed ? 'red' : 'blue',
})}
>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
{/* Children function */}
<Pressable
onPress={this.onPressButton}
style={state => ({
backgroundColor: state.pressed ? 'red' : 'blue',
})}
>
{state =>
state.pressed ? (
<View>
<Text>Pressed</Text>
</View>
) : (
<View>
<Text>Not Pressed</Text>
</View>
)
}
</Pressable>
{/* Android Ripple */}
<Pressable
android_ripple={{
borderless: true,
color: 'green',
radius: 20,
foreground: true,
}}
onPress={this.onPressButton}
style={{ backgroundColor: 'blue' }}
>
<View style={{ width: 150, height: 100, backgroundColor: 'red' }}>
<Text style={{ margin: 30 }}>Button</Text>
</View>
</Pressable>
</>
);
}
}
// App State
function appStateListener(state: string) {
console.log('New state: ' + state);
}
function appStateTest() {
console.log('Current state: ' + AppState.currentState);
AppState.addEventListener('change', appStateListener);
AppState.addEventListener('blur', appStateListener);
AppState.addEventListener('focus', appStateListener);
}
let appState: AppStateStatus = 'active';
appState = 'background';
appState = 'inactive';
appState = 'unknown';
appState = 'extension';
const AppStateExample = () => {
const appState = React.useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = React.useState(appState.current);
const appStateIsAvailable = AppState.isAvailable;
React.useEffect(() => {
const subscription = AppState.addEventListener("change", nextAppState => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
});
return () => {
subscription.remove();
};
}, []);
return (
<View style={styles.container}>
<Text>Current state is: {appStateVisible}</Text>
<Text>Available: {appStateIsAvailable}</Text>
</View>
);
};
// ViewPagerAndroid
export class ViewPagerAndroidTest {
render() {
return (
<ViewPagerAndroid
style={{ height: 56 }}
initialPage={0}
keyboardDismissMode={'on-drag'}
onPageScroll={e => {
console.log(`position: ${e.nativeEvent.position}`);
console.log(`offset: ${e.nativeEvent.offset}`);
}}
onPageSelected={e => {
console.log(`position: ${e.nativeEvent.position}`);
}}
/>
);
}
}
const profiledJSONParse = Systrace.measure('JSON', 'parse', JSON.parse);
profiledJSONParse('[]');
InteractionManager.runAfterInteractions(() => {
// ...
}).then(() => 'done');
export class FlatListTest extends React.Component<FlatListProps<number>, {}> {
list: FlatList<any> | null = null;
componentDidMount(): void {
if (this.list) {
this.list.flashScrollIndicators();
}
}
_renderItem = (rowData: any) => {
return (
<View>
<Text> {rowData.item} </Text>
</View>
);
};
_cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
_renderSeparator = () => <View style={{ height: 1, width: '100%', backgroundColor: 'gray' }} />;
render() {
return (
<FlatList
ref={list => (this.list = list)}
data={[1, 2, 3, 4, 5]}
renderItem={this._renderItem}
ItemSeparatorComponent={this._renderSeparator}
ListFooterComponent={null}
ListFooterComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
ListHeaderComponent={null}
ListHeaderComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
CellRendererComponent={this._cellRenderer}
fadingEdgeLength={200}
/>
);
}
}
export class SectionListTest extends React.Component<SectionListProps<string>, {}> {
myList: React.RefObject<SectionList<string>>;
constructor(props: SectionListProps<string>) {
super(props);
this.myList = React.createRef();
}
scrollMe = () => {
this.myList.current && this.myList.current.scrollToLocation({ itemIndex: 0, sectionIndex: 1 });
};
render() {
const sections = [
{
title: 'Section 1',
data: ['A', 'B', 'C', 'D', 'E'],
},
{
title: 'Section 2',
data: ['A2', 'B2', 'C2', 'D2', 'E2'],
renderItem: (info: { item: string }) => (
<View>
<Text>{info.item}</Text>
</View>
),
},
];
const cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
return (
<React.Fragment>
<Button title="Press" onPress={this.scrollMe} />
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => (
<View>
<Text>{section.title}</Text>
</View>
)}
renderItem={(info: SectionListRenderItemInfo<string>) => (
<View>
<Text>{`${info.section.title} - ${info.item}`}</Text>
</View>
)}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
ListHeaderComponent={null}
ListHeaderComponentStyle={[{ padding: 8 }, [{ backgroundColor: 'transparent' }]]}
/>
</React.Fragment>
);
}
}
type SectionT = { displayTitle: false } | { displayTitle: true; title: string };
export class SectionListTypedSectionTest extends React.Component<SectionListProps<string, SectionT>, {}> {
myList: React.RefObject<SectionList<string, SectionT>>;
constructor(props: SectionListProps<string, SectionT>) {
super(props);
this.myList = React.createRef();
}
scrollMe = () => {
this.myList.current && this.myList.current.scrollToLocation({ itemIndex: 0, sectionIndex: 1 });
};
render() {
const sections: SectionListData<string, SectionT>[] = [
{
displayTitle: false,
data: ['A', 'B', 'C', 'D', 'E'],
},
{
displayTitle: true,
title: 'Section 2',
data: ['A2', 'B2', 'C2', 'D2', 'E2'],
renderItem: (info: { item: string }) => (
<View>
<Text>{info.item}</Text>
</View>
),
},
];
const cellRenderer = ({ children }: any) => {
return <View>{children}</View>;
};
return (
<React.Fragment>
<Button title="Press" onPress={this.scrollMe} />
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
/>
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={null}
ListHeaderComponent={null}
ListHeaderComponentStyle={null}
/>
<SectionList
ref={this.myList}
sections={sections}
renderSectionHeader={({ section }) => {
section; // $ExpectType SectionListData<string, SectionT>
return section.displayTitle ? (
<View>
<Text>{section.title}</Text>
</View>
) : null;
}}
renderItem={info => {
info; // $ExpectType SectionListRenderItemInfo<string, SectionT>
return (
<View>
<Text>
{info.section.displayTitle ? <Text>{`${info.section.title} - `}</Text> : null}
<Text>{info.item}</Text>
</Text>
</View>
);
}}
CellRendererComponent={cellRenderer}
maxToRenderPerBatch={5}
ListFooterComponent={null}
ListFooterComponentStyle={undefined}
ListHeaderComponent={null}
ListHeaderComponentStyle={undefined}
/>
</React.Fragment>
);
}
}
export class CapsLockComponent extends React.Component<TextProps> {
render() {
const content = (this.props.children || '') as string;
return <Text {...this.props}>{content.toUpperCase()}</Text>;
}
}
const getInitialUrlTest = () =>
Linking.getInitialURL().then(val => {
if (val !== null) {
val.indexOf('val is now a string');
}
});
LogBox.ignoreAllLogs();
LogBox.ignoreAllLogs(true);
LogBox.ignoreLogs(['someString', /^aRegex/]);
LogBox.install();
LogBox.uninstall();
class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListViewDataSource }> {
_stickyHeaderComponent = ({ children }: any) => {
return <View>{children}</View>;
};
eventHandler = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
console.log(event);
};
scrollView: ScrollView | null = null;
testNativeMethods() {
if (this.scrollView) {
this.scrollView.setNativeProps({ scrollEnabled: false });
// Dummy values for scroll dimensions changes
this.scrollView.getScrollResponder().scrollResponderZoomTo({
x: 0,
y: 0,
width: 300,
height: 500,
animated: true,
});
}
}
render() {
const scrollViewStyle1 = StyleSheet.create({
scrollView: {
backgroundColor: 'red',
},
});
const scrollViewStyle2 = {
flex: 1,
};
return (
<ListView
dataSource={this.state.dataSource}
renderScrollComponent={props => {
if (props.scrollEnabled) {
throw new Error('Expected scroll to be enabled.');
}
return (
<ScrollView
ref={ref => (this.scrollView = ref)}
horizontal={true}
nestedScrollEnabled={true}
invertStickyHeaders={true}
contentOffset={{ x: 0, y: 0 }}
snapToStart={false}
snapToEnd={false}
snapToOffsets={[100, 300, 500]}
{...props}
style={[scrollViewStyle1.scrollView, scrollViewStyle2]}
onScrollToTop={() => {}}
scrollToOverflowEnabled={true}
fadingEdgeLength={200}
StickyHeaderComponent={this._stickyHeaderComponent}
stickyHeaderHiddenOnScroll={true}
automaticallyAdjustKeyboardInsets
/>
);
}}
renderRow={({ type, data }, _, row) => {
return <Text>Filler</Text>;
}}
onScroll={this.eventHandler}
onScrollBeginDrag={this.eventHandler}
onScrollEndDrag={this.eventHandler}
onMomentumScrollBegin={this.eventHandler}
onMomentumScrollEnd={this.eventHandler}
/>
);
}
}
class TabBarTest extends React.Component {
render() {
return (
<TabBarIOS
barTintColor="darkslateblue"
itemPositioning="center"
tintColor="white"
translucent={true}
unselectedTintColor="black"
unselectedItemTintColor="red"
>
<TabBarIOS.Item
badge={0}
badgeColor="red"
icon={{ uri: undefined }}
selected={true}
onPress={() => {}}
renderAsOriginal={true}
selectedIcon={undefined}
systemIcon="history"
title="Item 1"
/>
</TabBarIOS>
);
}
}
class AlertTest extends React.Component {
showAlert() {
Alert.alert(
'Title',
'Message',
[
{ text: 'First button', onPress: () => {} },
{ text: 'Second button', onPress: () => {} },
{ text: 'Third button', onPress: () => {} },
],
{
cancelable: false,
onDismiss: () => {},
},
);
}
render() {
return <Button title="Press me" onPress={this.showAlert} />;
}
}
Alert.prompt(
'Enter password',
'Enter your password to claim your $1.5B in lottery winnings',
text => {
console.log(text);
},
'secure-text',
);
Alert.prompt(
'Enter password',
'Enter your password to claim your $1.5B in lottery winnings',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'OK',
onPress: password => console.log('OK Pressed, password: ' + password),
},
],
'secure-text',
);
class MaskedViewTest extends React.Component {
render() {
return (
<MaskedViewIOS maskElement={<View />}>
<View />
</MaskedViewIOS>
);
}
}
class InputAccessoryViewTest extends React.Component {
render() {
const uniqueID = 'foobar';
return (
<InputAccessoryView nativeID={uniqueID}>
<TextInput inputAccessoryViewID={uniqueID} />
</InputAccessoryView>
);
}
}
// DataSourceAssetCallback
const dataSourceAssetCallback1: DataSourceAssetCallback = {
rowHasChanged: (r1, r2) => true,
sectionHeaderHasChanged: (h1, h2) => true,
getRowData: (dataBlob, sectionID, rowID) => (sectionID as number) + (rowID as number),
getSectionHeaderData: (dataBlob, sectionID) => sectionID as string,
};
const dataSourceAssetCallback2: DataSourceAssetCallback = {};
// DeviceEventEmitterStatic
const deviceEventEmitterStatic: DeviceEventEmitterStatic = DeviceEventEmitter;
deviceEventEmitterStatic.addListener('keyboardWillShow', data => true);
deviceEventEmitterStatic.addListener('keyboardWillShow', data => true, {});
// NativeEventEmitter - Android
const androidEventEmitter = new NativeEventEmitter();
const sub1 = androidEventEmitter.addListener('event', (event: object) => event);
const sub2 = androidEventEmitter.addListener('event', (event: object) => event, {});
androidEventEmitter.listenerCount('event'); // $ExpectType number
sub2.remove();
androidEventEmitter.removeAllListeners('event');
androidEventEmitter.removeSubscription(sub1);
// NativeEventEmitter - IOS
const nativeModule: NativeModule = {
addListener(eventType: string) {},
removeListeners(count: number) {},
};
const iosEventEmitter = new NativeEventEmitter(nativeModule);
const sub3 = iosEventEmitter.addListener('event', (event: object) => event);
const sub4 = iosEventEmitter.addListener('event', (event: object) => event, {});
iosEventEmitter.listenerCount('event');
sub4.remove();
iosEventEmitter.removeAllListeners('event');
iosEventEmitter.removeSubscription(sub3);
class CustomEventEmitter extends NativeEventEmitter {}
const customEventEmitter = new CustomEventEmitter();
customEventEmitter.addListener('event', () => {});
class TextInputTest extends React.Component<{}, { username: string }> {
username: TextInput | null = null;
handleUsernameChange = (text: string) => {
console.log(`text: ${text}`);
};
onScroll = (e: NativeSyntheticEvent<TextInputScrollEventData>) => {
testNativeSyntheticEvent(e);
console.log(`x: ${e.nativeEvent.contentOffset.x}`);
console.log(`y: ${e.nativeEvent.contentOffset.y}`);
};
handleOnBlur = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
};
handleOnFocus = (e: NativeSyntheticEvent<TextInputFocusEventData>) => {
testNativeSyntheticEvent(e);
};
handleOnSelectionChange = (e: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`target: ${e.nativeEvent.target}`);
console.log(`start: ${e.nativeEvent.selection.start}`);
console.log(`end: ${e.nativeEvent.selection.end}`);
};
handleOnKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
testNativeSyntheticEvent(e);
console.log(`key: ${e.nativeEvent.key}`);
};
handleOnChange = (e: NativeSyntheticEvent<TextInputChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`eventCount: ${e.nativeEvent.eventCount}`);
console.log(`target: ${e.nativeEvent.target}`);
console.log(`text: ${e.nativeEvent.text}`);
};
handleOnContentSizeChange = (e: NativeSyntheticEvent<TextInputContentSizeChangeEventData>) => {
testNativeSyntheticEvent(e);
console.log(`contentSize.width: ${e.nativeEvent.contentSize.width}`);
console.log(`contentSize.height: ${e.nativeEvent.contentSize.height}`);
};
handleOnEndEditing = (e: NativeSyntheticEvent<TextInputEndEditingEventData>) => {
testNativeSyntheticEvent(e);
console.log(`text: ${e.nativeEvent.text}`);
};
handleOnSubmitEditing = (e: NativeSyntheticEvent<TextInputSubmitEditingEventData>) => {
testNativeSyntheticEvent(e);
console.log(`text: ${e.nativeEvent.text}`);
};
render() {
return (
<View>
<Text onPress={() => this.username && this.username.focus()}>Username</Text>
<TextInput
ref={input => (this.username = input)}
textContentType="username"
autoComplete="username"
value={this.state.username}
onChangeText={this.handleUsernameChange}
/>
<TextInput multiline onScroll={this.onScroll} />
<TextInput onBlur={this.handleOnBlur} onFocus={this.handleOnFocus} />
<TextInput onSelectionChange={this.handleOnSelectionChange} />
<TextInput onKeyPress={this.handleOnKeyPress} />
<TextInput onChange={this.handleOnChange} />
<TextInput onChange={this.handleOnChange} />
<TextInput onEndEditing={this.handleOnEndEditing} />
<TextInput onSubmitEditing={this.handleOnSubmitEditing} />
<TextInput multiline onContentSizeChange={this.handleOnContentSizeChange} />
<TextInput contextMenuHidden={true} textAlignVertical="top" />
<TextInput textAlign="center" />
</View>
);
}
}
class TextTest extends React.Component {
handleOnLayout = (e: LayoutChangeEvent) => {
testNativeSyntheticEvent(e);
const x = e.nativeEvent.layout.x; // $ExpectType number
const y = e.nativeEvent.layout.y; // $ExpectType number
const width = e.nativeEvent.layout.width; // $ExpectType number
const height = e.nativeEvent.layout.height; // $ExpectType number
};
handleOnTextLayout = (e: NativeSyntheticEvent<TextLayoutEventData>) => {
testNativeSyntheticEvent(e);
e.nativeEvent.lines.forEach(line => {
const ascender = line.ascender; // $ExpectType number
const capHeight = line.capHeight; // $ExpectType number
const descender = line.descender; // $ExpectType number
const height = line.height; // $ExpectType number
const text = line.text; // $ExpectType string
const width = line.width; // $ExpectType number
const x = line.x; // $ExpectType number
const xHeight = line.xHeight; // $ExpectType number
const y = line.y; // $ExpectType number
});
};
render() {
return (
<Text
allowFontScaling={false}
ellipsizeMode="head"
lineBreakMode="clip"
numberOfLines={2}
onLayout={this.handleOnLayout}
onTextLayout={this.handleOnTextLayout}
>
Test text
</Text>
);
}
}
class StatusBarTest extends React.Component {
render() {
StatusBar.setBarStyle('dark-content', true);
console.log('height:', StatusBar.currentHeight);
return <StatusBar backgroundColor="blue" barStyle="light-content" translucent />;
}
}
export class ImageTest extends React.Component {
componentDidMount(): void {
const uri = 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png';
const headers = { Authorization: 'Bearer test' };
const image: ImageResolvedAssetSource = Image.resolveAssetSource({ uri });
console.log(image.width, image.height, image.scale, image.uri);
Image.queryCache &&
Image.queryCache([uri]).then(({ [uri]: status }) => {
if (status === undefined) {
console.log('Image is not in cache');
} else {
console.log(`Image is in ${status} cache`);
}
});
Image.getSize(uri, (width, height) => console.log(width, height));
Image.getSize(
uri,
(width, height) => console.log(width, height),
error => console.error(error),
);
Image.getSizeWithHeaders(uri, headers, (width, height) => console.log(width, height));
Image.getSizeWithHeaders(
uri,
headers,
(width, height) => console.log(width, height),
error => console.error(error),
);
Image.prefetch(uri); // $ExpectType Promise<boolean>
}
handleOnLoad = (e: NativeSyntheticEvent<ImageLoadEventData>) => {
testNativeSyntheticEvent(e);
console.log('height:', e.nativeEvent.source.height);
console.log('width:', e.nativeEvent.source.width);
console.log('uri:', e.nativeEvent.source.uri);
};
handleOnError = (e: NativeSyntheticEvent<ImageErrorEventData>) => {
testNativeSyntheticEvent(e);
console.log('error:', e.nativeEvent.error);
};
render() {
const resizeMode: ImageResizeMode = 'contain';
return (
<View>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
onLoad={this.handleOnLoad}
onError={this.handleOnError}
/>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
resizeMode={resizeMode}
/>
</View>
);
}
}
export class ImageBackgroundProps extends React.Component {
private _imageRef: Image | null = null;
setImageRef = (image: Image) => {
this._imageRef = image;
};
render() {
return (
<View>
<ImageBackground
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
imageRef={this.setImageRef}
>
<Text>Some text</Text>
</ImageBackground>
</View>
);
}
}
const listViewDataSourceTest = new ListView.DataSource({ rowHasChanged: () => true });
class AccessibilityTest extends React.Component {
render() {
return (
<View
accessibilityElementsHidden={true}
importantForAccessibility={'no-hide-descendants'}
onAccessibilityTap={() => {}}
accessibilityRole="header"
accessibilityState={{ checked: true }}
accessibilityHint="Very important header"
accessibilityValue={{ min: 60, max: 120, now: 80 }}
onMagicTap={() => {}}
onAccessibilityEscape={() => {}}
>
<Text accessibilityIgnoresInvertColors>Text</Text>
<View />
</View>
);
}
}
AccessibilityInfo.isBoldTextEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),
);
AccessibilityInfo.isGrayscaleEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isGrayscaleEnabled => ${isEnabled}`),
);
AccessibilityInfo.isInvertColorsEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isInvertColorsEnabled => ${isEnabled}`),
);
AccessibilityInfo.isReduceMotionEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isReduceMotionEnabled => ${isEnabled}`),
);
AccessibilityInfo.isReduceTransparencyEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isReduceTransparencyEnabled => ${isEnabled}`),
);
AccessibilityInfo.isScreenReaderEnabled().then(isEnabled =>
console.log(`AccessibilityInfo.isScreenReaderEnabled => ${isEnabled}`),
);
AccessibilityInfo.getRecommendedTimeoutMillis(5000).then(timeoutMiles =>
console.log(`AccessibilityInfo.getRecommendedTimeoutMillis => ${timeoutMiles}`)
);
AccessibilityInfo.addEventListener('announcementFinished', ({ announcement, success }) =>
console.log(`A11y Event: announcementFinished: ${announcement}, ${success}`),
);
AccessibilityInfo.addEventListener('boldTextChanged', isEnabled =>
console.log(`AccessibilityInfo.isBoldTextEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('grayscaleChanged', isEnabled =>
console.log(`AccessibilityInfo.isGrayscaleEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('invertColorsChanged', isEnabled =>
console.log(`AccessibilityInfo.isInvertColorsEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('reduceMotionChanged', isEnabled =>
console.log(`AccessibilityInfo.isReduceMotionEnabled => ${isEnabled}`),
);
AccessibilityInfo.addEventListener('reduceTransparencyChanged', isEnabled =>
console.log(`AccessibilityInfo.isReduceTransparencyEnabled => ${isEnabled}`),
);
const screenReaderChangedListener = (isEnabled: boolean): void => console.log(`AccessibilityInfo.isScreenReaderEnabled => ${isEnabled}`);
AccessibilityInfo.addEventListener('screenReaderChanged', screenReaderChangedListener,
).remove();
AccessibilityInfo.removeEventListener('screenReaderChanged', screenReaderChangedListener);
const KeyboardAvoidingViewTest = () => <KeyboardAvoidingView enabled />;
const ModalTest = () => <Modal hardwareAccelerated />;
const ModalTest2 = () => <Modal hardwareAccelerated testID="modal-test-2" />;
const TimePickerAndroidTest = () => {
TimePickerAndroid.open({
hour: 8,
minute: 15,
is24Hour: true,
mode: 'spinner',
}).then(result => {
if (result.action === TimePickerAndroid.timeSetAction) {
console.log('Time', result.hour, result.minute);
}
});
};
const DatePickerAndroidTest = () => {
DatePickerAndroid.open({
date: new Date(),
mode: 'calendar',
}).then(result => {
if (result.action === DatePickerAndroid.dateSetAction) {
console.log('Date', result.year, result.month, result.day);
}
});
};
const NativeBridgedComponent = requireNativeComponent<{ nativeProp: string }>('NativeBridgedComponent'); // $ExpectType HostComponent<{ nativeProp: string; }>
class BridgedComponentTest extends React.Component {
static propTypes = {
jsProp: PropTypes.string.isRequired,
};
nativeComponentRef: React.ElementRef<typeof NativeBridgedComponent> | null;
callNativeMethod = () => {
UIManager.dispatchViewManagerCommand(findNodeHandle(this.nativeComponentRef), 'someNativeMethod', []);
};
measureNativeComponent() {
if (this.nativeComponentRef) {
this.nativeComponentRef.measure(
(x, y, width, height, pageX, pageY) => x + y + width + height + pageX + pageY,
);
}
}
render() {
return (
<NativeBridgedComponent {...this.props} nativeProp="test" ref={ref => (this.nativeComponentRef = ref)} />
);
}
}
const SwitchColorTest = () => <Switch trackColor={{ true: 'pink', false: 'red' }} />;
const SwitchColorOptionalTrueTest = () => <Switch trackColor={{ false: 'red' }} />;
const SwitchColorOptionalFalseTest = () => <Switch trackColor={{ true: 'pink' }} />;
const SwitchColorNullTest = () => <Switch trackColor={{ true: 'pink', false: null }} />;
const SwitchThumbColorTest = () => <Switch thumbColor={'red'} />;
const SwitchOnChangeWithoutParamsTest = () => <Switch onChange={() => console.log('test')} />;
const SwitchOnChangeUndefinedTest = () => <Switch onChange={undefined} />;
const SwitchOnChangeNullTest = () => <Switch onChange={null} />;
const SwitchOnChangePromiseTest = () => <Switch onChange={(event) => {
const e: SwitchChangeEvent = event;
return new Promise(() => e.value);
}} />;
const SwitchOnValueChangeWithoutParamsTest = () => <Switch onValueChange={() => console.log('test')} />;
const SwitchOnValueChangeUndefinedTest = () => <Switch onValueChange={undefined} />;
const SwitchOnValueChangeNullTest = () => <Switch onValueChange={null} />;
const SwitchOnValueChangePromiseTest = () => <Switch onValueChange={(value) => {
const v: boolean = value;
return new Promise(() => v)
}} />;
const NativeIDTest = () => (
<ScrollView nativeID={'nativeID'}>
<View nativeID={'nativeID'} />
<Text nativeID={'nativeID'}>Text</Text>
<Image
source={{ uri: 'https://seeklogo.com/images/T/typescript-logo-B29A3F462D-seeklogo.com.png' }}
nativeID={'nativeID'}
/>
</ScrollView>
);
const ScrollViewMaintainVisibleContentPositionTest = () => (
<ScrollView maintainVisibleContentPosition={{ autoscrollToTopThreshold: 1, minIndexForVisible: 10 }}></ScrollView>
);
const ScrollViewInsetsTest = () => (
<>
<ScrollView automaticallyAdjustKeyboardInsets />
<ScrollView automaticallyAdjustKeyboardInsets={false} />
</>
);
const MaxFontSizeMultiplierTest = () => <Text maxFontSizeMultiplier={0}>Text</Text>;
const ShareTest = () => {
Share.share(
{ title: 'title', message: 'message' },
{ dialogTitle: 'dialogTitle', excludedActivityTypes: ['activity'], tintColor: 'red', subject: 'Email subject' },
);
Share.share({ title: 'title', url: 'url' });
Share.share({ message: 'message' }).then(result => {
if (result.action === Share.sharedAction) {
const activity = result.activityType;
} else if (result.action === Share.dismissedAction) {
}
});
};
const KeyboardTest = () => {
const subscriber = Keyboard.addListener('keyboardDidHide', event => {
event;
});
subscriber.remove();
Keyboard.dismiss();
// Android Keyboard Event
Keyboard.scheduleLayoutAnimation({
duration: 0,
easing: 'keyboard',
endCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
});
// IOS Keyboard Event
Keyboard.scheduleLayoutAnimation({
duration: 0,
easing: 'easeInEaseOut',
endCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
startCoordinates: { screenX: 0, screenY: 0, width: 0, height: 0 },
isEventFromThisApp: true,
});
};
const PermissionsAndroidTest = () => {
PermissionsAndroid.request('android.permission.CAMERA').then(result => {
switch (result) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
PermissionsAndroid.requestMultiple([
'android.permission.CAMERA',
'android.permission.ACCESS_FINE_LOCATION',
'android.permission.ACCESS_BACKGROUND_LOCATION',
]).then(results => {
switch (results['android.permission.CAMERA']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.ACCESS_FINE_LOCATION']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.ACCESS_BACKGROUND_LOCATION']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
PermissionsAndroid.requestMultiple([
'android.permission.BLUETOOTH_SCAN',
'android.permission.BLUETOOTH_CONNECT',
'android.permission.BLUETOOTH_ADVERTISE'
]).then(results => {
switch (results['android.permission.BLUETOOTH_SCAN']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.BLUETOOTH_CONNECT']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
switch (results['android.permission.BLUETOOTH_ADVERTISE']) {
case 'granted':
break;
case 'denied':
break;
case 'never_ask_again':
break;
}
});
};
// Platform
const PlatformTest = () => {
switch (Platform.OS) {
case 'ios':
if (!Platform.isPad) {
return 32;
} else {
return 44;
}
case 'android':
case 'macos':
case 'windows':
return Platform.isTV ? 64 : 56;
default:
return Platform.isTV ? 40 : 44;
}
};
const PlatformConstantsTest = () => {
const testing: boolean = Platform.constants.isTesting;
if (Platform.OS === 'ios') {
const hasForceTouch: boolean = Platform.constants.forceTouchAvailable;
} else if (Platform.OS === 'android') {
const { major, prerelease } = Platform.constants.reactNativeVersion;
const v = Platform.constants.Version;
const host: string | undefined = Platform.constants.ServerHost;
}
};
Platform.select({ native: 1 }); // $ExpectType number | undefined
Platform.select({ native: 1, web: 2, default: 0 }); // $ExpectType number
Platform.select({ android: 1 }); // $ExpectType number | undefined
Platform.select({ android: 1, ios: 2, default: 0 }); // $ExpectType number
Platform.select({ android: 1, ios: 2, macos: 3, web: 4, windows: 5 }); // $ExpectType number | undefined
Platform.select({ android: 1, ios: 2, macos: 3, web: 4, windows: 5, default: 0 }); // $ExpectType number
PlatformColor('?attr/colorControlNormal');
PlatformColor('?attr/colorControlNormal', '?attr/colorAccent', 'another');
DynamicColorIOS({
dark: 'lightskyblue',
light: 'midnightblue',
});
DynamicColorIOS({
dark: 'lightskyblue',
light: PlatformColor('labelColor'),
});
// Test you cannot set internals of ColorValue directly
const OpaqueTest1 = () => (
<View
// @ts-expect-error
style={{
backgroundColor: {
resource_paths: ['?attr/colorControlNormal'],
},
}}
/>
);
const OpaqueTest2 = () => (
<View
// @ts-expect-error
style={{
backgroundColor: {
semantic: 'string',
dynamic: {
light: 'light',
dark: 'dark',
},
},
}}
/>
);
// Test you cannot amend opaque type
// @ts-expect-error
PlatformColor('?attr/colorControlNormal').resource_paths.push('foo');
const someColorProp: ColorValue = PlatformColor('test');
// Test PlatformColor inside Platform select with stylesheet
StyleSheet.create({
labelCell: {
flex: 1,
alignItems: 'stretch',
...Platform.select({
ios: { color: DynamicColorIOS({ dark: 'lightskyblue', light: PlatformColor('labelColor') }) },
android: {
color: PlatformColor('?attr/colorControlNormal'),
},
default: { color: PlatformColor('?attr/colorControlNormal') },
}),
},
});
// PlatformColor in style colors
StyleSheet.create({
labelCell: {
flex: 1,
alignItems: 'stretch',
color: PlatformColor('test'),
backgroundColor: PlatformColor('test'),
borderBottomColor: PlatformColor('test'),
borderColor: PlatformColor('test'),
borderEndColor: PlatformColor('test'),
borderLeftColor: PlatformColor('test'),
borderRightColor: PlatformColor('test'),
borderStartColor: PlatformColor('test'),
borderTopColor: PlatformColor('test'),
overlayColor: PlatformColor('test'),
shadowColor: PlatformColor('test'),
textDecorationColor: PlatformColor('test'),
textShadowColor: PlatformColor('test'),
tintColor: PlatformColor('test'),
},
});
function someColorString(): ColorValue {
return '#000000';
}
function somePlatformColor(): ColorValue {
return PlatformColor('test');
}
const colors = {
color: someColorString(),
backgroundColor: somePlatformColor(),
};
StyleSheet.create({
labelCell: {
color: colors.color,
backgroundColor: colors.backgroundColor,
},
});
const OpaqueTest3 = () => (
<View
style={{
backgroundColor: colors.backgroundColor,
}}
/>
);
// ProgressBarAndroid
const ProgressBarAndroidTest = () => {
<ProgressBarAndroid animating color="white" styleAttr="Horizontal" progress={0.42} />;
};
// Push notification
const PushNotificationTest = () => {
PushNotificationIOS.presentLocalNotification({
alertBody: 'notificatus',
userInfo: 'informius',
alertTitle: 'Titulus',
alertAction: 'view',
});
PushNotificationIOS.scheduleLocalNotification({
alertAction: 'view',
alertBody: 'Look at me!',
alertTitle: 'Hello!',
applicationIconBadgeNumber: 999,
category: 'engagement',
fireDate: new Date().toISOString(),
isSilent: false,
repeatInterval: 'minute',
userInfo: {
abc: 123,
},
});
};
// YellowBox
const YellowBoxTest = () => <YellowBox />;
// Appearance
const DarkMode = () => {
const color = useColorScheme();
const isDarkMode = Appearance.getColorScheme() === 'dark';
const subscription = Appearance.addChangeListener(({ colorScheme }) => {
console.log(colorScheme);
});
React.useEffect(() => {
console.log('-color', color);
return () => {
subscription.remove();
};
}, [color]);
return <Text>Is dark mode enabled? {isDarkMode}</Text>;
};
// VirtualizedList
// Test inspired by: https://reactnative.dev/docs/virtualizedlist
const VirtualizedListTest = () => {
const DATA = [1, 2, 3];
const getItem = (data: number[], index: number) => {
return {
title: `Item ${data[index]}`,
};
};
const getItemCount = (data: number[]) => data.length;
return (
<VirtualizedList
data={DATA}
initialNumToRender={4}
renderItem={({ item }: ListRenderItemInfo<ReturnType<typeof getItem>>) => <Text>{item.title}</Text>}
getItemCount={getItemCount}
getItem={getItem}
/>
);
};
// DevSettings
DevSettings.addMenuItem('alert', () => {
Alert.alert('alert');
});
DevSettings.reload();
DevSettings.reload('reload with reason');
// Accessibility custom actions
const AccessibilityCustomActionsTest = () => {
return (
<View
accessible={true}
accessibilityActions={[
// should support custom defined actions
{ name: 'cut', label: 'cut' },
{ name: 'copy', label: 'copy' },
{ name: 'paste', label: 'paste' },
]}
onAccessibilityAction={event => {
switch (event.nativeEvent.actionName) {
case 'cut':
Alert.alert('Alert', 'cut action success');
break;
case 'copy':
Alert.alert('Alert', 'copy action success');
break;
case 'paste':
Alert.alert('Alert', 'paste action success');
break;
}
}}
/>
);
};
// DrawerLayoutAndroidTest
export class DrawerLayoutAndroidTest extends React.Component {
drawerRef = React.createRef<DrawerLayoutAndroid>();
readonly styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 50,
backgroundColor: '#ecf0f1',
padding: 8,
},
navigationContainer: {
flex: 1,
paddingTop: 50,
backgroundColor: '#fff',
padding: 8,
},
});
readonly navigationView = (
<View style={this.styles.navigationContainer}>
<Text style={{ margin: 10, fontSize: 15 }}>I'm in the Drawer!</Text>
</View>
);
handleDrawerClose = () => {
console.log('handleDrawerClose');
};
handleDrawerOpen = () => {
console.log('handleDrawerOpen');
};
handleDrawerSlide = (event: DrawerSlideEvent) => {
console.log('handleDrawerSlide', event);
};
handleDrawerStateChanged = (event: 'Idle' | 'Dragging' | 'Settling') => {
console.log('handleDrawerStateChanged', event);
};
render() {
return (
<DrawerLayoutAndroid
ref={this.drawerRef}
drawerBackgroundColor="rgba(0,0,0,0.5)"
drawerLockMode="locked-closed"
drawerPosition="right"
drawerWidth={300}
keyboardDismissMode="on-drag"
onDrawerClose={this.handleDrawerClose}
onDrawerOpen={this.handleDrawerOpen}
onDrawerSlide={this.handleDrawerSlide}
onDrawerStateChanged={this.handleDrawerStateChanged}
renderNavigationView={() => this.navigationView}
statusBarBackgroundColor="yellow"
>
<View style={this.styles.container}>
<Text style={{ margin: 10, fontSize: 15 }}>DrawerLayoutAndroid example</Text>
</View>
</DrawerLayoutAndroid>
);
}
}
// DataDetectorType for Text component
const DataDetectorTypeTest = () => {
return (
<>
<Text dataDetectorType={'all'}>http://test.com [email protected] +33123456789</Text>
<Text dataDetectorType={'email'}>[email protected]</Text>
<Text dataDetectorType={'link'}>http://test.com</Text>
<Text dataDetectorType={'none'}>Hi there !</Text>
<Text dataDetectorType={'phoneNumber'}>+33123456789</Text>
<Text dataDetectorType={null}>Must allow null value</Text>
</>
);
};
const ToastAndroidTest = () => {
ToastAndroid.showWithGravityAndOffset('My Toast', ToastAndroid.SHORT, ToastAndroid.BOTTOM, 0, 50);
};
const I18nManagerTest = () => {
I18nManager.allowRTL(true);
I18nManager.forceRTL(true);
I18nManager.swapLeftAndRightInRTL(true);
const { isRTL, doLeftAndRightSwapInRTL } = I18nManager.getConstants();
const isRtlFlag = I18nManager.isRTL;
const doLeftAndRightSwapInRtlFlag = I18nManager.doLeftAndRightSwapInRTL;
console.log(isRTL, isRtlFlag, doLeftAndRightSwapInRTL, doLeftAndRightSwapInRtlFlag);
};
// LayoutAnimations
LayoutAnimation.configureNext(
LayoutAnimation.create(123, LayoutAnimation.Types.easeIn, LayoutAnimation.Properties.opacity),
);
LayoutAnimation.configureNext(LayoutAnimation.create(123, 'easeIn', 'opacity'));
// ActionSheetIOS
const ActionSheetIOSTest = () => {
// test destructiveButtonIndex undefined
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: undefined,
}, () => undefined);
// test destructiveButtonIndex null
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: null,
}, () => undefined);
// test destructiveButtonIndex single number
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo'],
destructiveButtonIndex: 0,
}, () => undefined);
// test destructiveButtonIndex number array
ActionSheetIOS.showActionSheetWithOptions({
options: ['foo', 'bar'],
destructiveButtonIndex: [0, 1],
}, () => undefined);
}
| types/react-native/v0.69/test/index.tsx | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.9970190525054932,
0.005299645476043224,
0.00016290065832436085,
0.00017140859563369304,
0.07101878523826599
]
|
{
"id": 6,
"code_window": [
" accessibilityHint=\"Very important header\"\n",
" accessibilityValue={{ min: 60, max: 120, now: 80 }}\n",
" onMagicTap={() => {}}\n",
" onAccessibilityEscape={() => {}}\n",
" >\n",
" <Text accessibilityIgnoresInvertColors>Text</Text>\n",
" <View />\n",
" </View>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accessibilityLanguage=\"sv-SE\"\n"
],
"file_path": "types/react-native/v0.69/test/index.tsx",
"type": "add",
"edit_start_line_idx": 1000
} | { "extends": "@definitelytyped/dtslint/dt.json" }
| types/node-crate/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00016798620345070958,
0.00016798620345070958,
0.00016798620345070958,
0.00016798620345070958,
0
]
|
{
"id": 6,
"code_window": [
" accessibilityHint=\"Very important header\"\n",
" accessibilityValue={{ min: 60, max: 120, now: 80 }}\n",
" onMagicTap={() => {}}\n",
" onAccessibilityEscape={() => {}}\n",
" >\n",
" <Text accessibilityIgnoresInvertColors>Text</Text>\n",
" <View />\n",
" </View>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accessibilityLanguage=\"sv-SE\"\n"
],
"file_path": "types/react-native/v0.69/test/index.tsx",
"type": "add",
"edit_start_line_idx": 1000
} | /**
* ValueAxesSettings settings sets settings for all ValueAxes.
* If you change a property after the chart is initialized,
* you should call stockChart.validateNow() method in order for it to work.
* If there is no default value specified, default value of ValueAxis class will be used.
*/
export default class ValueAxesSettings {
/**
* Specifies whether number for gridCount is specified automatically, according to the axis size.
* @default true
*/
autoGridCount: boolean;
/**
* Axis opacity.
*/
axisAlpha: number;
/**
* Axis color.
*/
axisColor: string;
/**
* Thickness of the axis.
*/
axisThickness: number;
/**
* Label color.
*/
color: string;
/**
* Length of a dash. By default, the grid line is not dashed.
*/
dashLength: number;
/**
* Fill opacity. Every second space between grid lines can be filled with color.
*/
fillAlpha: number;
/**
* Fill color. Every second space between grid lines can be filled with color.
* Set fillAlpha to a value greater than 0 to see the fills.
*/
fillColor: string;
/**
* Opacity of grid lines.
*/
gridAlpha: number;
/**
* Color of grid lines.
*/
gridColor: string;
/**
* Approximate number of grid lines. autoGridCount should be set to false,
* otherwise this property will be ignored.
*/
gridCount: number;
/**
* Thickness of grid lines.
*/
gridThickness: number;
/**
* Specifies whether guide values should be included when calculating min and max of the axis.
*/
includeGuidesInMinMax: boolean;
/**
* If true, the axis will include hidden graphs when calculating min and max values.
*/
includeHidden: boolean;
/**
* Specifies whether values should be placed inside or outside plot area.
* In case you set this to false, you'll have to adjust marginLeft or marginRight in
* [[PanelsSettings]] in order labels to be visible.
* @default true
*/
inside: boolean;
/**
* Specifies whether values on axis can only be integers or both integers and doubles.
*/
integersOnly: boolean;
/**
* Frequency at which labels should be placed.
*/
labelFrequency: number;
/**
* Specifies whether value labels are displayed.
*/
labelsEnabled: boolean;
/**
* Set to true if value axis is logarithmic, false otherwise.
*/
logarithmic: boolean;
/**
* The distance of the axis to the plot area, in pixels. Useful if you have more then one axis on the same side.
*/
offset: number;
/**
* Position of the value axis. Possible values are "left" and "right".
*/
position: string;
/**
* Set to true if value axis is reversed (smaller values on top), false otherwise.
*/
reversed: boolean;
/**
* Specifies if first label of value axis should be displayed.
*/
showFirstLabel: boolean;
/**
* Specifies if last label of value axis should be displayed.
*/
showLastLabel: boolean;
/**
* Stacking mode of the axis. Possible values are: "none", "regular", "100%", "3d".
*/
stackType: string;
/**
* Tick length.
*/
tickLength: number;
/**
* Unit which will be added to the value label.
*/
unit: string;
/**
* Position of the unit. Possible values are "left" or "right".
*/
unitPosition: string;
}
| types/amcharts/ValueAxesSettings.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.0001971914025489241,
0.00017292398842982948,
0.0001640305417822674,
0.0001728591014398262,
0.000007991597158252262
]
|
{
"id": 6,
"code_window": [
" accessibilityHint=\"Very important header\"\n",
" accessibilityValue={{ min: 60, max: 120, now: 80 }}\n",
" onMagicTap={() => {}}\n",
" onAccessibilityEscape={() => {}}\n",
" >\n",
" <Text accessibilityIgnoresInvertColors>Text</Text>\n",
" <View />\n",
" </View>\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accessibilityLanguage=\"sv-SE\"\n"
],
"file_path": "types/react-native/v0.69/test/index.tsx",
"type": "add",
"edit_start_line_idx": 1000
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"types": [],
"paths": {
"devexpress-web": [
"devexpress-web/v182"
],
"devexpress-web/*": [
"devexpress-web/v182/*"
]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"devexpress-web-tests.ts"
]
}
| types/devexpress-web/v182/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/889c1273d2359b7bd52d6c1cbf813fd74421ea8e | [
0.00017515187209937721,
0.00017295658471994102,
0.00017181711154989898,
0.00017242869944311678,
0.0000013031249181949534
]
|
{
"id": 0,
"code_window": [
" const client = axios.create({\n",
" baseURL: 'https://api.github.com/repos/grafana/grafana',\n",
" timeout: 10000,\n",
" });\n",
"\n",
" const res = await client.get('/issues', {\n",
" params: {\n",
" state: 'closed',\n",
" per_page: 100,\n",
" labels: 'add to changelog',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!/^\\d+$/.test(milestone)) {\n",
" console.log('Use milestone number not title, find number in milestone url');\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "add",
"edit_start_line_idx": 16
} | import axios from 'axios';
import _ from 'lodash';
import { Task, TaskRunner } from './task';
const githubGrafanaUrl = 'https://github.com/grafana/grafana';
interface ChangelogOptions {
milestone: string;
}
const changelogTaskRunner: TaskRunner<ChangelogOptions> = async ({ milestone }) => {
const client = axios.create({
baseURL: 'https://api.github.com/repos/grafana/grafana',
timeout: 10000,
});
const res = await client.get('/issues', {
params: {
state: 'closed',
per_page: 100,
labels: 'add to changelog',
},
});
const issues = res.data.filter(item => {
if (!item.milestone) {
console.log('Item missing milestone', item.number);
return false;
}
return item.milestone.title === milestone;
});
const bugs = _.sortBy(
issues.filter(item => {
if (item.title.match(/fix|fixes/i)) {
return true;
}
if (item.labels.find(label => label.name === 'type/bug')) {
return true;
}
return false;
}),
'title'
);
const notBugs = _.sortBy(issues.filter(item => !bugs.find(bug => bug === item)), 'title');
let markdown = '### Features / Enhancements\n';
for (const item of notBugs) {
markdown += getMarkdownLineForIssue(item);
}
markdown += '\n### Bug Fixes\n';
for (const item of bugs) {
markdown += getMarkdownLineForIssue(item);
}
console.log(markdown);
};
function getMarkdownLineForIssue(item: any) {
let markdown = '';
const title = item.title.replace(/^([^:]*)/, (match, g1) => {
return `**${g1}**`;
});
markdown += '* ' + title + '.';
markdown += ` [#${item.number}](${githubGrafanaUrl}/pull/${item.number})`;
markdown += `, [@${item.user.login}](${item.user.html_url})`;
markdown += '\n';
return markdown;
}
export const changelogTask = new Task<ChangelogOptions>();
changelogTask.setName('Changelog generator task');
changelogTask.setRunner(changelogTaskRunner);
| scripts/cli/tasks/changelog.ts | 1 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.9984177350997925,
0.2532159686088562,
0.00017252071120310575,
0.0009068697108887136,
0.4302103519439697
]
|
{
"id": 0,
"code_window": [
" const client = axios.create({\n",
" baseURL: 'https://api.github.com/repos/grafana/grafana',\n",
" timeout: 10000,\n",
" });\n",
"\n",
" const res = await client.get('/issues', {\n",
" params: {\n",
" state: 'closed',\n",
" per_page: 100,\n",
" labels: 'add to changelog',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!/^\\d+$/.test(milestone)) {\n",
" console.log('Use milestone number not title, find number in milestone url');\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "add",
"edit_start_line_idx": 16
} | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package timeseries implements a time series structure for stats collection.
package timeseries // import "golang.org/x/net/internal/timeseries"
import (
"fmt"
"log"
"time"
)
const (
timeSeriesNumBuckets = 64
minuteHourSeriesNumBuckets = 60
)
var timeSeriesResolutions = []time.Duration{
1 * time.Second,
10 * time.Second,
1 * time.Minute,
10 * time.Minute,
1 * time.Hour,
6 * time.Hour,
24 * time.Hour, // 1 day
7 * 24 * time.Hour, // 1 week
4 * 7 * 24 * time.Hour, // 4 weeks
16 * 7 * 24 * time.Hour, // 16 weeks
}
var minuteHourSeriesResolutions = []time.Duration{
1 * time.Second,
1 * time.Minute,
}
// An Observable is a kind of data that can be aggregated in a time series.
type Observable interface {
Multiply(ratio float64) // Multiplies the data in self by a given ratio
Add(other Observable) // Adds the data from a different observation to self
Clear() // Clears the observation so it can be reused.
CopyFrom(other Observable) // Copies the contents of a given observation to self
}
// Float attaches the methods of Observable to a float64.
type Float float64
// NewFloat returns a Float.
func NewFloat() Observable {
f := Float(0)
return &f
}
// String returns the float as a string.
func (f *Float) String() string { return fmt.Sprintf("%g", f.Value()) }
// Value returns the float's value.
func (f *Float) Value() float64 { return float64(*f) }
func (f *Float) Multiply(ratio float64) { *f *= Float(ratio) }
func (f *Float) Add(other Observable) {
o := other.(*Float)
*f += *o
}
func (f *Float) Clear() { *f = 0 }
func (f *Float) CopyFrom(other Observable) {
o := other.(*Float)
*f = *o
}
// A Clock tells the current time.
type Clock interface {
Time() time.Time
}
type defaultClock int
var defaultClockInstance defaultClock
func (defaultClock) Time() time.Time { return time.Now() }
// Information kept per level. Each level consists of a circular list of
// observations. The start of the level may be derived from end and the
// len(buckets) * sizeInMillis.
type tsLevel struct {
oldest int // index to oldest bucketed Observable
newest int // index to newest bucketed Observable
end time.Time // end timestamp for this level
size time.Duration // duration of the bucketed Observable
buckets []Observable // collections of observations
provider func() Observable // used for creating new Observable
}
func (l *tsLevel) Clear() {
l.oldest = 0
l.newest = len(l.buckets) - 1
l.end = time.Time{}
for i := range l.buckets {
if l.buckets[i] != nil {
l.buckets[i].Clear()
l.buckets[i] = nil
}
}
}
func (l *tsLevel) InitLevel(size time.Duration, numBuckets int, f func() Observable) {
l.size = size
l.provider = f
l.buckets = make([]Observable, numBuckets)
}
// Keeps a sequence of levels. Each level is responsible for storing data at
// a given resolution. For example, the first level stores data at a one
// minute resolution while the second level stores data at a one hour
// resolution.
// Each level is represented by a sequence of buckets. Each bucket spans an
// interval equal to the resolution of the level. New observations are added
// to the last bucket.
type timeSeries struct {
provider func() Observable // make more Observable
numBuckets int // number of buckets in each level
levels []*tsLevel // levels of bucketed Observable
lastAdd time.Time // time of last Observable tracked
total Observable // convenient aggregation of all Observable
clock Clock // Clock for getting current time
pending Observable // observations not yet bucketed
pendingTime time.Time // what time are we keeping in pending
dirty bool // if there are pending observations
}
// init initializes a level according to the supplied criteria.
func (ts *timeSeries) init(resolutions []time.Duration, f func() Observable, numBuckets int, clock Clock) {
ts.provider = f
ts.numBuckets = numBuckets
ts.clock = clock
ts.levels = make([]*tsLevel, len(resolutions))
for i := range resolutions {
if i > 0 && resolutions[i-1] >= resolutions[i] {
log.Print("timeseries: resolutions must be monotonically increasing")
break
}
newLevel := new(tsLevel)
newLevel.InitLevel(resolutions[i], ts.numBuckets, ts.provider)
ts.levels[i] = newLevel
}
ts.Clear()
}
// Clear removes all observations from the time series.
func (ts *timeSeries) Clear() {
ts.lastAdd = time.Time{}
ts.total = ts.resetObservation(ts.total)
ts.pending = ts.resetObservation(ts.pending)
ts.pendingTime = time.Time{}
ts.dirty = false
for i := range ts.levels {
ts.levels[i].Clear()
}
}
// Add records an observation at the current time.
func (ts *timeSeries) Add(observation Observable) {
ts.AddWithTime(observation, ts.clock.Time())
}
// AddWithTime records an observation at the specified time.
func (ts *timeSeries) AddWithTime(observation Observable, t time.Time) {
smallBucketDuration := ts.levels[0].size
if t.After(ts.lastAdd) {
ts.lastAdd = t
}
if t.After(ts.pendingTime) {
ts.advance(t)
ts.mergePendingUpdates()
ts.pendingTime = ts.levels[0].end
ts.pending.CopyFrom(observation)
ts.dirty = true
} else if t.After(ts.pendingTime.Add(-1 * smallBucketDuration)) {
// The observation is close enough to go into the pending bucket.
// This compensates for clock skewing and small scheduling delays
// by letting the update stay in the fast path.
ts.pending.Add(observation)
ts.dirty = true
} else {
ts.mergeValue(observation, t)
}
}
// mergeValue inserts the observation at the specified time in the past into all levels.
func (ts *timeSeries) mergeValue(observation Observable, t time.Time) {
for _, level := range ts.levels {
index := (ts.numBuckets - 1) - int(level.end.Sub(t)/level.size)
if 0 <= index && index < ts.numBuckets {
bucketNumber := (level.oldest + index) % ts.numBuckets
if level.buckets[bucketNumber] == nil {
level.buckets[bucketNumber] = level.provider()
}
level.buckets[bucketNumber].Add(observation)
}
}
ts.total.Add(observation)
}
// mergePendingUpdates applies the pending updates into all levels.
func (ts *timeSeries) mergePendingUpdates() {
if ts.dirty {
ts.mergeValue(ts.pending, ts.pendingTime)
ts.pending = ts.resetObservation(ts.pending)
ts.dirty = false
}
}
// advance cycles the buckets at each level until the latest bucket in
// each level can hold the time specified.
func (ts *timeSeries) advance(t time.Time) {
if !t.After(ts.levels[0].end) {
return
}
for i := 0; i < len(ts.levels); i++ {
level := ts.levels[i]
if !level.end.Before(t) {
break
}
// If the time is sufficiently far, just clear the level and advance
// directly.
if !t.Before(level.end.Add(level.size * time.Duration(ts.numBuckets))) {
for _, b := range level.buckets {
ts.resetObservation(b)
}
level.end = time.Unix(0, (t.UnixNano()/level.size.Nanoseconds())*level.size.Nanoseconds())
}
for t.After(level.end) {
level.end = level.end.Add(level.size)
level.newest = level.oldest
level.oldest = (level.oldest + 1) % ts.numBuckets
ts.resetObservation(level.buckets[level.newest])
}
t = level.end
}
}
// Latest returns the sum of the num latest buckets from the level.
func (ts *timeSeries) Latest(level, num int) Observable {
now := ts.clock.Time()
if ts.levels[0].end.Before(now) {
ts.advance(now)
}
ts.mergePendingUpdates()
result := ts.provider()
l := ts.levels[level]
index := l.newest
for i := 0; i < num; i++ {
if l.buckets[index] != nil {
result.Add(l.buckets[index])
}
if index == 0 {
index = ts.numBuckets
}
index--
}
return result
}
// LatestBuckets returns a copy of the num latest buckets from level.
func (ts *timeSeries) LatestBuckets(level, num int) []Observable {
if level < 0 || level > len(ts.levels) {
log.Print("timeseries: bad level argument: ", level)
return nil
}
if num < 0 || num >= ts.numBuckets {
log.Print("timeseries: bad num argument: ", num)
return nil
}
results := make([]Observable, num)
now := ts.clock.Time()
if ts.levels[0].end.Before(now) {
ts.advance(now)
}
ts.mergePendingUpdates()
l := ts.levels[level]
index := l.newest
for i := 0; i < num; i++ {
result := ts.provider()
results[i] = result
if l.buckets[index] != nil {
result.CopyFrom(l.buckets[index])
}
if index == 0 {
index = ts.numBuckets
}
index -= 1
}
return results
}
// ScaleBy updates observations by scaling by factor.
func (ts *timeSeries) ScaleBy(factor float64) {
for _, l := range ts.levels {
for i := 0; i < ts.numBuckets; i++ {
l.buckets[i].Multiply(factor)
}
}
ts.total.Multiply(factor)
ts.pending.Multiply(factor)
}
// Range returns the sum of observations added over the specified time range.
// If start or finish times don't fall on bucket boundaries of the same
// level, then return values are approximate answers.
func (ts *timeSeries) Range(start, finish time.Time) Observable {
return ts.ComputeRange(start, finish, 1)[0]
}
// Recent returns the sum of observations from the last delta.
func (ts *timeSeries) Recent(delta time.Duration) Observable {
now := ts.clock.Time()
return ts.Range(now.Add(-delta), now)
}
// Total returns the total of all observations.
func (ts *timeSeries) Total() Observable {
ts.mergePendingUpdates()
return ts.total
}
// ComputeRange computes a specified number of values into a slice using
// the observations recorded over the specified time period. The return
// values are approximate if the start or finish times don't fall on the
// bucket boundaries at the same level or if the number of buckets spanning
// the range is not an integral multiple of num.
func (ts *timeSeries) ComputeRange(start, finish time.Time, num int) []Observable {
if start.After(finish) {
log.Printf("timeseries: start > finish, %v>%v", start, finish)
return nil
}
if num < 0 {
log.Printf("timeseries: num < 0, %v", num)
return nil
}
results := make([]Observable, num)
for _, l := range ts.levels {
if !start.Before(l.end.Add(-l.size * time.Duration(ts.numBuckets))) {
ts.extract(l, start, finish, num, results)
return results
}
}
// Failed to find a level that covers the desired range. So just
// extract from the last level, even if it doesn't cover the entire
// desired range.
ts.extract(ts.levels[len(ts.levels)-1], start, finish, num, results)
return results
}
// RecentList returns the specified number of values in slice over the most
// recent time period of the specified range.
func (ts *timeSeries) RecentList(delta time.Duration, num int) []Observable {
if delta < 0 {
return nil
}
now := ts.clock.Time()
return ts.ComputeRange(now.Add(-delta), now, num)
}
// extract returns a slice of specified number of observations from a given
// level over a given range.
func (ts *timeSeries) extract(l *tsLevel, start, finish time.Time, num int, results []Observable) {
ts.mergePendingUpdates()
srcInterval := l.size
dstInterval := finish.Sub(start) / time.Duration(num)
dstStart := start
srcStart := l.end.Add(-srcInterval * time.Duration(ts.numBuckets))
srcIndex := 0
// Where should scanning start?
if dstStart.After(srcStart) {
advance := dstStart.Sub(srcStart) / srcInterval
srcIndex += int(advance)
srcStart = srcStart.Add(advance * srcInterval)
}
// The i'th value is computed as show below.
// interval = (finish/start)/num
// i'th value = sum of observation in range
// [ start + i * interval,
// start + (i + 1) * interval )
for i := 0; i < num; i++ {
results[i] = ts.resetObservation(results[i])
dstEnd := dstStart.Add(dstInterval)
for srcIndex < ts.numBuckets && srcStart.Before(dstEnd) {
srcEnd := srcStart.Add(srcInterval)
if srcEnd.After(ts.lastAdd) {
srcEnd = ts.lastAdd
}
if !srcEnd.Before(dstStart) {
srcValue := l.buckets[(srcIndex+l.oldest)%ts.numBuckets]
if !srcStart.Before(dstStart) && !srcEnd.After(dstEnd) {
// dst completely contains src.
if srcValue != nil {
results[i].Add(srcValue)
}
} else {
// dst partially overlaps src.
overlapStart := maxTime(srcStart, dstStart)
overlapEnd := minTime(srcEnd, dstEnd)
base := srcEnd.Sub(srcStart)
fraction := overlapEnd.Sub(overlapStart).Seconds() / base.Seconds()
used := ts.provider()
if srcValue != nil {
used.CopyFrom(srcValue)
}
used.Multiply(fraction)
results[i].Add(used)
}
if srcEnd.After(dstEnd) {
break
}
}
srcIndex++
srcStart = srcStart.Add(srcInterval)
}
dstStart = dstStart.Add(dstInterval)
}
}
// resetObservation clears the content so the struct may be reused.
func (ts *timeSeries) resetObservation(observation Observable) Observable {
if observation == nil {
observation = ts.provider()
} else {
observation.Clear()
}
return observation
}
// TimeSeries tracks data at granularities from 1 second to 16 weeks.
type TimeSeries struct {
timeSeries
}
// NewTimeSeries creates a new TimeSeries using the function provided for creating new Observable.
func NewTimeSeries(f func() Observable) *TimeSeries {
return NewTimeSeriesWithClock(f, defaultClockInstance)
}
// NewTimeSeriesWithClock creates a new TimeSeries using the function provided for creating new Observable and the clock for
// assigning timestamps.
func NewTimeSeriesWithClock(f func() Observable, clock Clock) *TimeSeries {
ts := new(TimeSeries)
ts.timeSeries.init(timeSeriesResolutions, f, timeSeriesNumBuckets, clock)
return ts
}
// MinuteHourSeries tracks data at granularities of 1 minute and 1 hour.
type MinuteHourSeries struct {
timeSeries
}
// NewMinuteHourSeries creates a new MinuteHourSeries using the function provided for creating new Observable.
func NewMinuteHourSeries(f func() Observable) *MinuteHourSeries {
return NewMinuteHourSeriesWithClock(f, defaultClockInstance)
}
// NewMinuteHourSeriesWithClock creates a new MinuteHourSeries using the function provided for creating new Observable and the clock for
// assigning timestamps.
func NewMinuteHourSeriesWithClock(f func() Observable, clock Clock) *MinuteHourSeries {
ts := new(MinuteHourSeries)
ts.timeSeries.init(minuteHourSeriesResolutions, f,
minuteHourSeriesNumBuckets, clock)
return ts
}
func (ts *MinuteHourSeries) Minute() Observable {
return ts.timeSeries.Latest(0, 60)
}
func (ts *MinuteHourSeries) Hour() Observable {
return ts.timeSeries.Latest(1, 60)
}
func minTime(a, b time.Time) time.Time {
if a.Before(b) {
return a
}
return b
}
func maxTime(a, b time.Time) time.Time {
if a.After(b) {
return a
}
return b
}
| vendor/golang.org/x/net/internal/timeseries/timeseries.go | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.0003666841075755656,
0.00017728048260323703,
0.00016358990978915244,
0.00017343676881864667,
0.000027939542633248493
]
|
{
"id": 0,
"code_window": [
" const client = axios.create({\n",
" baseURL: 'https://api.github.com/repos/grafana/grafana',\n",
" timeout: 10000,\n",
" });\n",
"\n",
" const res = await client.get('/issues', {\n",
" params: {\n",
" state: 'closed',\n",
" per_page: 100,\n",
" labels: 'add to changelog',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!/^\\d+$/.test(milestone)) {\n",
" console.log('Use milestone number not title, find number in milestone url');\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "add",
"edit_start_line_idx": 16
} | import _ from 'lodash';
import { PanelCtrl } from 'app/plugins/sdk';
import impressionSrv from 'app/core/services/impression_srv';
class DashListCtrl extends PanelCtrl {
static templateUrl = 'module.html';
static scrollable = true;
groups: any[];
modes: any[];
panelDefaults = {
query: '',
limit: 10,
tags: [],
recent: false,
search: false,
starred: true,
headings: true,
folderId: null,
};
/** @ngInject */
constructor($scope, $injector, private backendSrv, private dashboardSrv) {
super($scope, $injector);
_.defaults(this.panel, this.panelDefaults);
if (this.panel.tag) {
this.panel.tags = [this.panel.tag];
delete this.panel.tag;
}
this.events.on('refresh', this.onRefresh.bind(this));
this.events.on('init-edit-mode', this.onInitEditMode.bind(this));
this.groups = [
{ list: [], show: false, header: 'Starred dashboards' },
{ list: [], show: false, header: 'Recently viewed dashboards' },
{ list: [], show: false, header: 'Search' },
];
// update capability
if (this.panel.mode) {
if (this.panel.mode === 'starred') {
this.panel.starred = true;
this.panel.headings = false;
}
if (this.panel.mode === 'recently viewed') {
this.panel.recent = true;
this.panel.starred = false;
this.panel.headings = false;
}
if (this.panel.mode === 'search') {
this.panel.search = true;
this.panel.starred = false;
this.panel.headings = false;
}
delete this.panel.mode;
}
}
onInitEditMode() {
this.modes = ['starred', 'search', 'recently viewed'];
this.addEditorTab('Options', 'public/app/plugins/panel/dashlist/editor.html');
}
onRefresh() {
const promises = [];
promises.push(this.getRecentDashboards());
promises.push(this.getStarred());
promises.push(this.getSearch());
return Promise.all(promises).then(this.renderingCompleted.bind(this));
}
getSearch() {
this.groups[2].show = this.panel.search;
if (!this.panel.search) {
return Promise.resolve();
}
const params = {
limit: this.panel.limit,
query: this.panel.query,
tag: this.panel.tags,
folderIds: this.panel.folderId,
type: 'dash-db',
};
return this.backendSrv.search(params).then(result => {
this.groups[2].list = result;
});
}
getStarred() {
this.groups[0].show = this.panel.starred;
if (!this.panel.starred) {
return Promise.resolve();
}
const params = { limit: this.panel.limit, starred: 'true' };
return this.backendSrv.search(params).then(result => {
this.groups[0].list = result;
});
}
starDashboard(dash, evt) {
this.dashboardSrv.starDashboard(dash.id, dash.isStarred).then(newState => {
dash.isStarred = newState;
});
if (evt) {
evt.stopPropagation();
evt.preventDefault();
}
}
getRecentDashboards() {
this.groups[1].show = this.panel.recent;
if (!this.panel.recent) {
return Promise.resolve();
}
const dashIds = _.take(impressionSrv.getDashboardOpened(), this.panel.limit);
return this.backendSrv.search({ dashboardIds: dashIds, limit: this.panel.limit }).then(result => {
this.groups[1].list = dashIds
.map(orderId => {
return _.find(result, dashboard => {
return dashboard.id === orderId;
});
})
.filter(el => {
return el !== undefined;
});
});
}
onFolderChange(folder: any) {
this.panel.folderId = folder.id;
this.refresh();
}
}
export { DashListCtrl, DashListCtrl as PanelCtrl };
| public/app/plugins/panel/dashlist/module.ts | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.0012641118373721838,
0.0002420723030809313,
0.00016237449017353356,
0.00016818447329569608,
0.0002731742861215025
]
|
{
"id": 0,
"code_window": [
" const client = axios.create({\n",
" baseURL: 'https://api.github.com/repos/grafana/grafana',\n",
" timeout: 10000,\n",
" });\n",
"\n",
" const res = await client.get('/issues', {\n",
" params: {\n",
" state: 'closed',\n",
" per_page: 100,\n",
" labels: 'add to changelog',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!/^\\d+$/.test(milestone)) {\n",
" console.log('Use milestone number not title, find number in milestone url');\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "add",
"edit_start_line_idx": 16
} | import { Plugin, StoreState } from 'app/types';
import { ThunkAction } from 'redux-thunk';
import { getBackendSrv } from '../../../core/services/backend_srv';
import { LayoutMode } from '../../../core/components/LayoutSelector/LayoutSelector';
import { PluginDashboard } from '../../../types/plugins';
export enum ActionTypes {
LoadPlugins = 'LOAD_PLUGINS',
LoadPluginDashboards = 'LOAD_PLUGIN_DASHBOARDS',
LoadedPluginDashboards = 'LOADED_PLUGIN_DASHBOARDS',
SetPluginsSearchQuery = 'SET_PLUGIN_SEARCH_QUERY',
SetLayoutMode = 'SET_LAYOUT_MODE',
}
export interface LoadPluginsAction {
type: ActionTypes.LoadPlugins;
payload: Plugin[];
}
export interface LoadPluginDashboardsAction {
type: ActionTypes.LoadPluginDashboards;
}
export interface LoadedPluginDashboardsAction {
type: ActionTypes.LoadedPluginDashboards;
payload: PluginDashboard[];
}
export interface SetPluginsSearchQueryAction {
type: ActionTypes.SetPluginsSearchQuery;
payload: string;
}
export interface SetLayoutModeAction {
type: ActionTypes.SetLayoutMode;
payload: LayoutMode;
}
export const setPluginsLayoutMode = (mode: LayoutMode): SetLayoutModeAction => ({
type: ActionTypes.SetLayoutMode,
payload: mode,
});
export const setPluginsSearchQuery = (query: string): SetPluginsSearchQueryAction => ({
type: ActionTypes.SetPluginsSearchQuery,
payload: query,
});
const pluginsLoaded = (plugins: Plugin[]): LoadPluginsAction => ({
type: ActionTypes.LoadPlugins,
payload: plugins,
});
const pluginDashboardsLoad = (): LoadPluginDashboardsAction => ({
type: ActionTypes.LoadPluginDashboards,
});
const pluginDashboardsLoaded = (dashboards: PluginDashboard[]): LoadedPluginDashboardsAction => ({
type: ActionTypes.LoadedPluginDashboards,
payload: dashboards,
});
export type Action =
| LoadPluginsAction
| LoadPluginDashboardsAction
| LoadedPluginDashboardsAction
| SetPluginsSearchQueryAction
| SetLayoutModeAction;
type ThunkResult<R> = ThunkAction<R, StoreState, undefined, Action>;
export function loadPlugins(): ThunkResult<void> {
return async dispatch => {
const result = await getBackendSrv().get('api/plugins', { embedded: 0 });
dispatch(pluginsLoaded(result));
};
}
export function loadPluginDashboards(): ThunkResult<void> {
return async (dispatch, getStore) => {
dispatch(pluginDashboardsLoad());
const dataSourceType = getStore().dataSources.dataSource.type;
const response = await getBackendSrv().get(`api/plugins/${dataSourceType}/dashboards`);
dispatch(pluginDashboardsLoaded(response));
};
}
| public/app/features/plugins/state/actions.ts | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.00017480998940300196,
0.00017074852075893432,
0.0001664461597101763,
0.00017104556900449097,
0.0000033625137803028338
]
|
{
"id": 1,
"code_window": [
" state: 'closed',\n",
" per_page: 100,\n",
" labels: 'add to changelog',\n",
" },\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" milestone: milestone,\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "add",
"edit_start_line_idx": 21
} | import axios from 'axios';
import _ from 'lodash';
import { Task, TaskRunner } from './task';
const githubGrafanaUrl = 'https://github.com/grafana/grafana';
interface ChangelogOptions {
milestone: string;
}
const changelogTaskRunner: TaskRunner<ChangelogOptions> = async ({ milestone }) => {
const client = axios.create({
baseURL: 'https://api.github.com/repos/grafana/grafana',
timeout: 10000,
});
const res = await client.get('/issues', {
params: {
state: 'closed',
per_page: 100,
labels: 'add to changelog',
},
});
const issues = res.data.filter(item => {
if (!item.milestone) {
console.log('Item missing milestone', item.number);
return false;
}
return item.milestone.title === milestone;
});
const bugs = _.sortBy(
issues.filter(item => {
if (item.title.match(/fix|fixes/i)) {
return true;
}
if (item.labels.find(label => label.name === 'type/bug')) {
return true;
}
return false;
}),
'title'
);
const notBugs = _.sortBy(issues.filter(item => !bugs.find(bug => bug === item)), 'title');
let markdown = '### Features / Enhancements\n';
for (const item of notBugs) {
markdown += getMarkdownLineForIssue(item);
}
markdown += '\n### Bug Fixes\n';
for (const item of bugs) {
markdown += getMarkdownLineForIssue(item);
}
console.log(markdown);
};
function getMarkdownLineForIssue(item: any) {
let markdown = '';
const title = item.title.replace(/^([^:]*)/, (match, g1) => {
return `**${g1}**`;
});
markdown += '* ' + title + '.';
markdown += ` [#${item.number}](${githubGrafanaUrl}/pull/${item.number})`;
markdown += `, [@${item.user.login}](${item.user.html_url})`;
markdown += '\n';
return markdown;
}
export const changelogTask = new Task<ChangelogOptions>();
changelogTask.setName('Changelog generator task');
changelogTask.setRunner(changelogTaskRunner);
| scripts/cli/tasks/changelog.ts | 1 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.013679577969014645,
0.004052252974361181,
0.00016600536764599383,
0.0004337166319601238,
0.005227000918239355
]
|
{
"id": 1,
"code_window": [
" state: 'closed',\n",
" per_page: 100,\n",
" labels: 'add to changelog',\n",
" },\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" milestone: milestone,\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "add",
"edit_start_line_idx": 21
} | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package triegen
import (
"bytes"
"fmt"
"io"
"strings"
"text/template"
)
// print writes all the data structures as well as the code necessary to use the
// trie to w.
func (b *builder) print(w io.Writer) error {
b.Stats.NValueEntries = len(b.ValueBlocks) * blockSize
b.Stats.NValueBytes = len(b.ValueBlocks) * blockSize * b.ValueSize
b.Stats.NIndexEntries = len(b.IndexBlocks) * blockSize
b.Stats.NIndexBytes = len(b.IndexBlocks) * blockSize * b.IndexSize
b.Stats.NHandleBytes = len(b.Trie) * 2 * b.IndexSize
// If we only have one root trie, all starter blocks are at position 0 and
// we can access the arrays directly.
if len(b.Trie) == 1 {
// At this point we cannot refer to the generated tables directly.
b.ASCIIBlock = b.Name + "Values"
b.StarterBlock = b.Name + "Index"
} else {
// Otherwise we need to have explicit starter indexes in the trie
// structure.
b.ASCIIBlock = "t.ascii"
b.StarterBlock = "t.utf8Start"
}
b.SourceType = "[]byte"
if err := lookupGen.Execute(w, b); err != nil {
return err
}
b.SourceType = "string"
if err := lookupGen.Execute(w, b); err != nil {
return err
}
if err := trieGen.Execute(w, b); err != nil {
return err
}
for _, c := range b.Compactions {
if err := c.c.Print(w); err != nil {
return err
}
}
return nil
}
func printValues(n int, values []uint64) string {
w := &bytes.Buffer{}
boff := n * blockSize
fmt.Fprintf(w, "\t// Block %#x, offset %#x", n, boff)
var newline bool
for i, v := range values {
if i%6 == 0 {
newline = true
}
if v != 0 {
if newline {
fmt.Fprintf(w, "\n")
newline = false
}
fmt.Fprintf(w, "\t%#02x:%#04x, ", boff+i, v)
}
}
return w.String()
}
func printIndex(b *builder, nr int, n *node) string {
w := &bytes.Buffer{}
boff := nr * blockSize
fmt.Fprintf(w, "\t// Block %#x, offset %#x", nr, boff)
var newline bool
for i, c := range n.children {
if i%8 == 0 {
newline = true
}
if c != nil {
v := b.Compactions[c.index.compaction].Offset + uint32(c.index.index)
if v != 0 {
if newline {
fmt.Fprintf(w, "\n")
newline = false
}
fmt.Fprintf(w, "\t%#02x:%#02x, ", boff+i, v)
}
}
}
return w.String()
}
var (
trieGen = template.Must(template.New("trie").Funcs(template.FuncMap{
"printValues": printValues,
"printIndex": printIndex,
"title": strings.Title,
"dec": func(x int) int { return x - 1 },
"psize": func(n int) string {
return fmt.Sprintf("%d bytes (%.2f KiB)", n, float64(n)/1024)
},
}).Parse(trieTemplate))
lookupGen = template.Must(template.New("lookup").Parse(lookupTemplate))
)
// TODO: consider the return type of lookup. It could be uint64, even if the
// internal value type is smaller. We will have to verify this with the
// performance of unicode/norm, which is very sensitive to such changes.
const trieTemplate = `{{$b := .}}{{$multi := gt (len .Trie) 1}}
// {{.Name}}Trie. Total size: {{psize .Size}}. Checksum: {{printf "%08x" .Checksum}}.
type {{.Name}}Trie struct { {{if $multi}}
ascii []{{.ValueType}} // index for ASCII bytes
utf8Start []{{.IndexType}} // index for UTF-8 bytes >= 0xC0
{{end}}}
func new{{title .Name}}Trie(i int) *{{.Name}}Trie { {{if $multi}}
h := {{.Name}}TrieHandles[i]
return &{{.Name}}Trie{ {{.Name}}Values[uint32(h.ascii)<<6:], {{.Name}}Index[uint32(h.multi)<<6:] }
}
type {{.Name}}TrieHandle struct {
ascii, multi {{.IndexType}}
}
// {{.Name}}TrieHandles: {{len .Trie}} handles, {{.Stats.NHandleBytes}} bytes
var {{.Name}}TrieHandles = [{{len .Trie}}]{{.Name}}TrieHandle{
{{range .Trie}} { {{.ASCIIIndex}}, {{.StarterIndex}} }, // {{printf "%08x" .Checksum}}: {{.Name}}
{{end}}}{{else}}
return &{{.Name}}Trie{}
}
{{end}}
// lookupValue determines the type of block n and looks up the value for b.
func (t *{{.Name}}Trie) lookupValue(n uint32, b byte) {{.ValueType}}{{$last := dec (len .Compactions)}} {
switch { {{range $i, $c := .Compactions}}
{{if eq $i $last}}default{{else}}case n < {{$c.Cutoff}}{{end}}:{{if ne $i 0}}
n -= {{$c.Offset}}{{end}}
return {{print $b.ValueType}}({{$c.Handler}}){{end}}
}
}
// {{.Name}}Values: {{len .ValueBlocks}} blocks, {{.Stats.NValueEntries}} entries, {{.Stats.NValueBytes}} bytes
// The third block is the zero block.
var {{.Name}}Values = [{{.Stats.NValueEntries}}]{{.ValueType}} {
{{range $i, $v := .ValueBlocks}}{{printValues $i $v}}
{{end}}}
// {{.Name}}Index: {{len .IndexBlocks}} blocks, {{.Stats.NIndexEntries}} entries, {{.Stats.NIndexBytes}} bytes
// Block 0 is the zero block.
var {{.Name}}Index = [{{.Stats.NIndexEntries}}]{{.IndexType}} {
{{range $i, $v := .IndexBlocks}}{{printIndex $b $i $v}}
{{end}}}
`
// TODO: consider allowing zero-length strings after evaluating performance with
// unicode/norm.
const lookupTemplate = `
// lookup{{if eq .SourceType "string"}}String{{end}} returns the trie value for the first UTF-8 encoding in s and
// the width in bytes of this encoding. The size will be 0 if s does not
// hold enough bytes to complete the encoding. len(s) must be greater than 0.
func (t *{{.Name}}Trie) lookup{{if eq .SourceType "string"}}String{{end}}(s {{.SourceType}}) (v {{.ValueType}}, sz int) {
c0 := s[0]
switch {
case c0 < 0x80: // is ASCII
return {{.ASCIIBlock}}[c0], 1
case c0 < 0xC2:
return 0, 1 // Illegal UTF-8: not a starter, not ASCII.
case c0 < 0xE0: // 2-byte UTF-8
if len(s) < 2 {
return 0, 0
}
i := {{.StarterBlock}}[c0]
c1 := s[1]
if c1 < 0x80 || 0xC0 <= c1 {
return 0, 1 // Illegal UTF-8: not a continuation byte.
}
return t.lookupValue(uint32(i), c1), 2
case c0 < 0xF0: // 3-byte UTF-8
if len(s) < 3 {
return 0, 0
}
i := {{.StarterBlock}}[c0]
c1 := s[1]
if c1 < 0x80 || 0xC0 <= c1 {
return 0, 1 // Illegal UTF-8: not a continuation byte.
}
o := uint32(i)<<6 + uint32(c1)
i = {{.Name}}Index[o]
c2 := s[2]
if c2 < 0x80 || 0xC0 <= c2 {
return 0, 2 // Illegal UTF-8: not a continuation byte.
}
return t.lookupValue(uint32(i), c2), 3
case c0 < 0xF8: // 4-byte UTF-8
if len(s) < 4 {
return 0, 0
}
i := {{.StarterBlock}}[c0]
c1 := s[1]
if c1 < 0x80 || 0xC0 <= c1 {
return 0, 1 // Illegal UTF-8: not a continuation byte.
}
o := uint32(i)<<6 + uint32(c1)
i = {{.Name}}Index[o]
c2 := s[2]
if c2 < 0x80 || 0xC0 <= c2 {
return 0, 2 // Illegal UTF-8: not a continuation byte.
}
o = uint32(i)<<6 + uint32(c2)
i = {{.Name}}Index[o]
c3 := s[3]
if c3 < 0x80 || 0xC0 <= c3 {
return 0, 3 // Illegal UTF-8: not a continuation byte.
}
return t.lookupValue(uint32(i), c3), 4
}
// Illegal rune
return 0, 1
}
// lookup{{if eq .SourceType "string"}}String{{end}}Unsafe returns the trie value for the first UTF-8 encoding in s.
// s must start with a full and valid UTF-8 encoded rune.
func (t *{{.Name}}Trie) lookup{{if eq .SourceType "string"}}String{{end}}Unsafe(s {{.SourceType}}) {{.ValueType}} {
c0 := s[0]
if c0 < 0x80 { // is ASCII
return {{.ASCIIBlock}}[c0]
}
i := {{.StarterBlock}}[c0]
if c0 < 0xE0 { // 2-byte UTF-8
return t.lookupValue(uint32(i), s[1])
}
i = {{.Name}}Index[uint32(i)<<6+uint32(s[1])]
if c0 < 0xF0 { // 3-byte UTF-8
return t.lookupValue(uint32(i), s[2])
}
i = {{.Name}}Index[uint32(i)<<6+uint32(s[2])]
if c0 < 0xF8 { // 4-byte UTF-8
return t.lookupValue(uint32(i), s[3])
}
return 0
}
`
| vendor/golang.org/x/text/internal/triegen/print.go | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.00029824208468198776,
0.00017528804892208427,
0.00016625772695988417,
0.00017006395501084626,
0.000024724444301682524
]
|
{
"id": 1,
"code_window": [
" state: 'closed',\n",
" per_page: 100,\n",
" labels: 'add to changelog',\n",
" },\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" milestone: milestone,\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "add",
"edit_start_line_idx": 21
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="64px" height="64px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#52545c;}
.st1{fill:url(#SVGID_1_);}
</style>
<g>
<path class="st0" d="M33.9,47.9v-7.2c0-2.4,1.9-4.3,4.3-4.3h4.4v-4.4c0-2.4,1.9-4.3,4.3-4.3H54c2.4,0,4.3,1.9,4.3,4.3v4.4h1.4
L63.8,26c0.9-2.2-0.8-4.4-3.2-4.4H16.2c-1.9,0-3.5,1.2-4.1,2.9L3.3,51.4h6.4h26C34.6,50.6,33.9,49.3,33.9,47.9z"/>
<path class="st0" d="M14.6,18.2H60v-0.8c0-3.2-2.6-5.8-5.8-5.8h-25L28,8.5l0-0.1c-0.5-1-1.5-1.6-2.6-1.6H12.7
c-1.1,0-2.1,0.6-2.6,1.7l-1.2,3.2H5.8c-3.2,0-5.8,2.6-5.8,5.8v33.9l9.2-29.1C10,19.8,12.1,18.2,14.6,18.2z"/>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="50.3805" y1="69.5624" x2="50.3805" y2="18.6477">
<stop offset="0" style="stop-color:#FFF23A"/>
<stop offset="4.010540e-02" style="stop-color:#FEE62D"/>
<stop offset="0.1171" style="stop-color:#FED41A"/>
<stop offset="0.1964" style="stop-color:#FDC90F"/>
<stop offset="0.2809" style="stop-color:#FDC60B"/>
<stop offset="0.6685" style="stop-color:#F28F3F"/>
<stop offset="0.8876" style="stop-color:#ED693C"/>
<stop offset="1" style="stop-color:#E83E39"/>
</linearGradient>
<path class="st1" d="M62.6,40h-4.4h-0.3h-3.2v-7.9c0-0.4-0.3-0.7-0.7-0.7h-7.2c-0.4,0-0.7,0.3-0.7,0.7V40h-7.9
c-0.4,0-0.7,0.3-0.7,0.7v7.2c0,0.4,0.3,0.7,0.7,0.7h7.9v2.8v1.1v4c0,0.4,0.3,0.7,0.7,0.7H54c0.4,0,0.7-0.3,0.7-0.7v-7.9h7.9
c0.4,0,0.7-0.3,0.7-0.7v-7.2C63.3,40.4,63,40,62.6,40z"/>
</g>
</svg>
| public/img/icons_light_theme/icon_add_folder.svg | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.00016718021652195603,
0.00016646292351651937,
0.000165696837939322,
0.0001665117306401953,
6.065691877665813e-7
]
|
{
"id": 1,
"code_window": [
" state: 'closed',\n",
" per_page: 100,\n",
" labels: 'add to changelog',\n",
" },\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" milestone: milestone,\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "add",
"edit_start_line_idx": 21
} | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jaeger
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"log"
"net/url"
"strings"
"sync"
opentracing "github.com/opentracing/opentracing-go"
)
// Injector is responsible for injecting SpanContext instances in a manner suitable
// for propagation via a format-specific "carrier" object. Typically the
// injection will take place across an RPC boundary, but message queues and
// other IPC mechanisms are also reasonable places to use an Injector.
type Injector interface {
// Inject takes `SpanContext` and injects it into `carrier`. The actual type
// of `carrier` depends on the `format` passed to `Tracer.Inject()`.
//
// Implementations may return opentracing.ErrInvalidCarrier or any other
// implementation-specific error if injection fails.
Inject(ctx SpanContext, carrier interface{}) error
}
// Extractor is responsible for extracting SpanContext instances from a
// format-specific "carrier" object. Typically the extraction will take place
// on the server side of an RPC boundary, but message queues and other IPC
// mechanisms are also reasonable places to use an Extractor.
type Extractor interface {
// Extract decodes a SpanContext instance from the given `carrier`,
// or (nil, opentracing.ErrSpanContextNotFound) if no context could
// be found in the `carrier`.
Extract(carrier interface{}) (SpanContext, error)
}
type textMapPropagator struct {
headerKeys *HeadersConfig
metrics Metrics
encodeValue func(string) string
decodeValue func(string) string
}
func newTextMapPropagator(headerKeys *HeadersConfig, metrics Metrics) *textMapPropagator {
return &textMapPropagator{
headerKeys: headerKeys,
metrics: metrics,
encodeValue: func(val string) string {
return val
},
decodeValue: func(val string) string {
return val
},
}
}
func newHTTPHeaderPropagator(headerKeys *HeadersConfig, metrics Metrics) *textMapPropagator {
return &textMapPropagator{
headerKeys: headerKeys,
metrics: metrics,
encodeValue: func(val string) string {
return url.QueryEscape(val)
},
decodeValue: func(val string) string {
// ignore decoding errors, cannot do anything about them
if v, err := url.QueryUnescape(val); err == nil {
return v
}
return val
},
}
}
type binaryPropagator struct {
tracer *Tracer
buffers sync.Pool
}
func newBinaryPropagator(tracer *Tracer) *binaryPropagator {
return &binaryPropagator{
tracer: tracer,
buffers: sync.Pool{New: func() interface{} { return &bytes.Buffer{} }},
}
}
func (p *textMapPropagator) Inject(
sc SpanContext,
abstractCarrier interface{},
) error {
textMapWriter, ok := abstractCarrier.(opentracing.TextMapWriter)
if !ok {
return opentracing.ErrInvalidCarrier
}
// Do not encode the string with trace context to avoid accidental double-encoding
// if people are using opentracing < 0.10.0. Our colon-separated representation
// of the trace context is already safe for HTTP headers.
textMapWriter.Set(p.headerKeys.TraceContextHeaderName, sc.String())
for k, v := range sc.baggage {
safeKey := p.addBaggageKeyPrefix(k)
safeVal := p.encodeValue(v)
textMapWriter.Set(safeKey, safeVal)
}
return nil
}
func (p *textMapPropagator) Extract(abstractCarrier interface{}) (SpanContext, error) {
textMapReader, ok := abstractCarrier.(opentracing.TextMapReader)
if !ok {
return emptyContext, opentracing.ErrInvalidCarrier
}
var ctx SpanContext
var baggage map[string]string
err := textMapReader.ForeachKey(func(rawKey, value string) error {
key := strings.ToLower(rawKey) // TODO not necessary for plain TextMap
if key == p.headerKeys.TraceContextHeaderName {
var err error
safeVal := p.decodeValue(value)
if ctx, err = ContextFromString(safeVal); err != nil {
return err
}
} else if key == p.headerKeys.JaegerDebugHeader {
ctx.debugID = p.decodeValue(value)
} else if key == p.headerKeys.JaegerBaggageHeader {
if baggage == nil {
baggage = make(map[string]string)
}
for k, v := range p.parseCommaSeparatedMap(value) {
baggage[k] = v
}
} else if strings.HasPrefix(key, p.headerKeys.TraceBaggageHeaderPrefix) {
if baggage == nil {
baggage = make(map[string]string)
}
safeKey := p.removeBaggageKeyPrefix(key)
safeVal := p.decodeValue(value)
baggage[safeKey] = safeVal
}
return nil
})
if err != nil {
p.metrics.DecodingErrors.Inc(1)
return emptyContext, err
}
if !ctx.traceID.IsValid() && ctx.debugID == "" && len(baggage) == 0 {
return emptyContext, opentracing.ErrSpanContextNotFound
}
ctx.baggage = baggage
return ctx, nil
}
func (p *binaryPropagator) Inject(
sc SpanContext,
abstractCarrier interface{},
) error {
carrier, ok := abstractCarrier.(io.Writer)
if !ok {
return opentracing.ErrInvalidCarrier
}
// Handle the tracer context
if err := binary.Write(carrier, binary.BigEndian, sc.traceID); err != nil {
return err
}
if err := binary.Write(carrier, binary.BigEndian, sc.spanID); err != nil {
return err
}
if err := binary.Write(carrier, binary.BigEndian, sc.parentID); err != nil {
return err
}
if err := binary.Write(carrier, binary.BigEndian, sc.flags); err != nil {
return err
}
// Handle the baggage items
if err := binary.Write(carrier, binary.BigEndian, int32(len(sc.baggage))); err != nil {
return err
}
for k, v := range sc.baggage {
if err := binary.Write(carrier, binary.BigEndian, int32(len(k))); err != nil {
return err
}
io.WriteString(carrier, k)
if err := binary.Write(carrier, binary.BigEndian, int32(len(v))); err != nil {
return err
}
io.WriteString(carrier, v)
}
return nil
}
func (p *binaryPropagator) Extract(abstractCarrier interface{}) (SpanContext, error) {
carrier, ok := abstractCarrier.(io.Reader)
if !ok {
return emptyContext, opentracing.ErrInvalidCarrier
}
var ctx SpanContext
if err := binary.Read(carrier, binary.BigEndian, &ctx.traceID); err != nil {
return emptyContext, opentracing.ErrSpanContextCorrupted
}
if err := binary.Read(carrier, binary.BigEndian, &ctx.spanID); err != nil {
return emptyContext, opentracing.ErrSpanContextCorrupted
}
if err := binary.Read(carrier, binary.BigEndian, &ctx.parentID); err != nil {
return emptyContext, opentracing.ErrSpanContextCorrupted
}
if err := binary.Read(carrier, binary.BigEndian, &ctx.flags); err != nil {
return emptyContext, opentracing.ErrSpanContextCorrupted
}
// Handle the baggage items
var numBaggage int32
if err := binary.Read(carrier, binary.BigEndian, &numBaggage); err != nil {
return emptyContext, opentracing.ErrSpanContextCorrupted
}
if iNumBaggage := int(numBaggage); iNumBaggage > 0 {
ctx.baggage = make(map[string]string, iNumBaggage)
buf := p.buffers.Get().(*bytes.Buffer)
defer p.buffers.Put(buf)
var keyLen, valLen int32
for i := 0; i < iNumBaggage; i++ {
if err := binary.Read(carrier, binary.BigEndian, &keyLen); err != nil {
return emptyContext, opentracing.ErrSpanContextCorrupted
}
buf.Reset()
buf.Grow(int(keyLen))
if n, err := io.CopyN(buf, carrier, int64(keyLen)); err != nil || int32(n) != keyLen {
return emptyContext, opentracing.ErrSpanContextCorrupted
}
key := buf.String()
if err := binary.Read(carrier, binary.BigEndian, &valLen); err != nil {
return emptyContext, opentracing.ErrSpanContextCorrupted
}
buf.Reset()
buf.Grow(int(valLen))
if n, err := io.CopyN(buf, carrier, int64(valLen)); err != nil || int32(n) != valLen {
return emptyContext, opentracing.ErrSpanContextCorrupted
}
ctx.baggage[key] = buf.String()
}
}
return ctx, nil
}
// Converts a comma separated key value pair list into a map
// e.g. key1=value1, key2=value2, key3 = value3
// is converted to map[string]string { "key1" : "value1",
// "key2" : "value2",
// "key3" : "value3" }
func (p *textMapPropagator) parseCommaSeparatedMap(value string) map[string]string {
baggage := make(map[string]string)
value, err := url.QueryUnescape(value)
if err != nil {
log.Printf("Unable to unescape %s, %v", value, err)
return baggage
}
for _, kvpair := range strings.Split(value, ",") {
kv := strings.Split(strings.TrimSpace(kvpair), "=")
if len(kv) == 2 {
baggage[kv[0]] = kv[1]
} else {
log.Printf("Malformed value passed in for %s", p.headerKeys.JaegerBaggageHeader)
}
}
return baggage
}
// Converts a baggage item key into an http header format,
// by prepending TraceBaggageHeaderPrefix and encoding the key string
func (p *textMapPropagator) addBaggageKeyPrefix(key string) string {
// TODO encodeBaggageKeyAsHeader add caching and escaping
return fmt.Sprintf("%v%v", p.headerKeys.TraceBaggageHeaderPrefix, key)
}
func (p *textMapPropagator) removeBaggageKeyPrefix(key string) string {
// TODO decodeBaggageHeaderKey add caching and escaping
return key[len(p.headerKeys.TraceBaggageHeaderPrefix):]
}
| vendor/github.com/uber/jaeger-client-go/propagation.go | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.0028161483351141214,
0.00035397123428992927,
0.0001643392606638372,
0.00017122864664997905,
0.0005760029307566583
]
|
{
"id": 2,
"code_window": [
" },\n",
" });\n",
"\n",
" const issues = res.data.filter(item => {\n",
" if (!item.milestone) {\n",
" console.log('Item missing milestone', item.number);\n",
" return false;\n",
" }\n",
" return item.milestone.title === milestone;\n",
" });\n",
"\n",
" const bugs = _.sortBy(\n",
" issues.filter(item => {\n",
" if (item.title.match(/fix|fixes/i)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const issues = res.data;\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "replace",
"edit_start_line_idx": 24
} | import axios from 'axios';
import _ from 'lodash';
import { Task, TaskRunner } from './task';
const githubGrafanaUrl = 'https://github.com/grafana/grafana';
interface ChangelogOptions {
milestone: string;
}
const changelogTaskRunner: TaskRunner<ChangelogOptions> = async ({ milestone }) => {
const client = axios.create({
baseURL: 'https://api.github.com/repos/grafana/grafana',
timeout: 10000,
});
const res = await client.get('/issues', {
params: {
state: 'closed',
per_page: 100,
labels: 'add to changelog',
},
});
const issues = res.data.filter(item => {
if (!item.milestone) {
console.log('Item missing milestone', item.number);
return false;
}
return item.milestone.title === milestone;
});
const bugs = _.sortBy(
issues.filter(item => {
if (item.title.match(/fix|fixes/i)) {
return true;
}
if (item.labels.find(label => label.name === 'type/bug')) {
return true;
}
return false;
}),
'title'
);
const notBugs = _.sortBy(issues.filter(item => !bugs.find(bug => bug === item)), 'title');
let markdown = '### Features / Enhancements\n';
for (const item of notBugs) {
markdown += getMarkdownLineForIssue(item);
}
markdown += '\n### Bug Fixes\n';
for (const item of bugs) {
markdown += getMarkdownLineForIssue(item);
}
console.log(markdown);
};
function getMarkdownLineForIssue(item: any) {
let markdown = '';
const title = item.title.replace(/^([^:]*)/, (match, g1) => {
return `**${g1}**`;
});
markdown += '* ' + title + '.';
markdown += ` [#${item.number}](${githubGrafanaUrl}/pull/${item.number})`;
markdown += `, [@${item.user.login}](${item.user.html_url})`;
markdown += '\n';
return markdown;
}
export const changelogTask = new Task<ChangelogOptions>();
changelogTask.setName('Changelog generator task');
changelogTask.setRunner(changelogTaskRunner);
| scripts/cli/tasks/changelog.ts | 1 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.9981424808502197,
0.4846873879432678,
0.00016557048365939409,
0.4494437873363495,
0.48488345742225647
]
|
{
"id": 2,
"code_window": [
" },\n",
" });\n",
"\n",
" const issues = res.data.filter(item => {\n",
" if (!item.milestone) {\n",
" console.log('Item missing milestone', item.number);\n",
" return false;\n",
" }\n",
" return item.milestone.title === milestone;\n",
" });\n",
"\n",
" const bugs = _.sortBy(\n",
" issues.filter(item => {\n",
" if (item.title.match(/fix|fixes/i)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const issues = res.data;\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "replace",
"edit_start_line_idx": 24
} | import { refreshExplore, testDatasource, loadDatasource } from './actions';
import { ExploreId, ExploreUrlState, ExploreUpdateState } from 'app/types';
import { thunkTester } from 'test/core/thunk/thunkTester';
import { LogsDedupStrategy } from 'app/core/logs_model';
import {
initializeExploreAction,
InitializeExplorePayload,
changeTimeAction,
updateUIStateAction,
setQueriesAction,
testDataSourcePendingAction,
testDataSourceSuccessAction,
testDataSourceFailureAction,
loadDatasourcePendingAction,
loadDatasourceReadyAction,
} from './actionTypes';
import { Emitter } from 'app/core/core';
import { ActionOf } from 'app/core/redux/actionCreatorFactory';
import { makeInitialUpdateState } from './reducers';
import { DataQuery } from '@grafana/ui/src/types/datasource';
jest.mock('app/features/plugins/datasource_srv', () => ({
getDatasourceSrv: () => ({
getExternal: jest.fn().mockReturnValue([]),
get: jest.fn().mockReturnValue({
testDatasource: jest.fn(),
init: jest.fn(),
}),
}),
}));
const setup = (updateOverides?: Partial<ExploreUpdateState>) => {
const exploreId = ExploreId.left;
const containerWidth = 1920;
const eventBridge = {} as Emitter;
const ui = { dedupStrategy: LogsDedupStrategy.none, showingGraph: false, showingLogs: false, showingTable: false };
const range = { from: 'now', to: 'now' };
const urlState: ExploreUrlState = { datasource: 'some-datasource', queries: [], range, ui };
const updateDefaults = makeInitialUpdateState();
const update = { ...updateDefaults, ...updateOverides };
const initialState = {
explore: {
[exploreId]: {
initialized: true,
urlState,
containerWidth,
eventBridge,
update,
datasourceInstance: { name: 'some-datasource' },
queries: [] as DataQuery[],
range,
ui,
},
},
};
return {
initialState,
exploreId,
range,
ui,
containerWidth,
eventBridge,
};
};
describe('refreshExplore', () => {
describe('when explore is initialized', () => {
describe('and update datasource is set', () => {
it('then it should dispatch initializeExplore', async () => {
const { exploreId, ui, range, initialState, containerWidth, eventBridge } = setup({ datasource: true });
const dispatchedActions = await thunkTester(initialState)
.givenThunk(refreshExplore)
.whenThunkIsDispatched(exploreId);
const initializeExplore = dispatchedActions[2] as ActionOf<InitializeExplorePayload>;
const { type, payload } = initializeExplore;
expect(type).toEqual(initializeExploreAction.type);
expect(payload.containerWidth).toEqual(containerWidth);
expect(payload.eventBridge).toEqual(eventBridge);
expect(payload.queries.length).toBe(1); // Queries have generated keys hard to expect on
expect(payload.range).toEqual(range);
expect(payload.ui).toEqual(ui);
});
});
describe('and update range is set', () => {
it('then it should dispatch changeTimeAction', async () => {
const { exploreId, range, initialState } = setup({ range: true });
const dispatchedActions = await thunkTester(initialState)
.givenThunk(refreshExplore)
.whenThunkIsDispatched(exploreId);
expect(dispatchedActions[0].type).toEqual(changeTimeAction.type);
expect(dispatchedActions[0].payload).toEqual({ exploreId, range });
});
});
describe('and update ui is set', () => {
it('then it should dispatch updateUIStateAction', async () => {
const { exploreId, initialState, ui } = setup({ ui: true });
const dispatchedActions = await thunkTester(initialState)
.givenThunk(refreshExplore)
.whenThunkIsDispatched(exploreId);
expect(dispatchedActions[0].type).toEqual(updateUIStateAction.type);
expect(dispatchedActions[0].payload).toEqual({ ...ui, exploreId });
});
});
describe('and update queries is set', () => {
it('then it should dispatch setQueriesAction', async () => {
const { exploreId, initialState } = setup({ queries: true });
const dispatchedActions = await thunkTester(initialState)
.givenThunk(refreshExplore)
.whenThunkIsDispatched(exploreId);
expect(dispatchedActions[0].type).toEqual(setQueriesAction.type);
expect(dispatchedActions[0].payload).toEqual({ exploreId, queries: [] });
});
});
});
describe('when update is not initialized', () => {
it('then it should not dispatch any actions', async () => {
const exploreId = ExploreId.left;
const initialState = { explore: { [exploreId]: { initialized: false } } };
const dispatchedActions = await thunkTester(initialState)
.givenThunk(refreshExplore)
.whenThunkIsDispatched(exploreId);
expect(dispatchedActions).toEqual([]);
});
});
});
describe('test datasource', () => {
describe('when testDatasource thunk is dispatched', () => {
describe('and testDatasource call on instance is successful', () => {
it('then it should dispatch testDataSourceSuccessAction', async () => {
const exploreId = ExploreId.left;
const mockDatasourceInstance = {
testDatasource: () => {
return Promise.resolve({ status: 'success' });
},
};
const dispatchedActions = await thunkTester({})
.givenThunk(testDatasource)
.whenThunkIsDispatched(exploreId, mockDatasourceInstance);
expect(dispatchedActions).toEqual([
testDataSourcePendingAction({ exploreId }),
testDataSourceSuccessAction({ exploreId }),
]);
});
});
describe('and testDatasource call on instance is not successful', () => {
it('then it should dispatch testDataSourceFailureAction', async () => {
const exploreId = ExploreId.left;
const error = 'something went wrong';
const mockDatasourceInstance = {
testDatasource: () => {
return Promise.resolve({ status: 'fail', message: error });
},
};
const dispatchedActions = await thunkTester({})
.givenThunk(testDatasource)
.whenThunkIsDispatched(exploreId, mockDatasourceInstance);
expect(dispatchedActions).toEqual([
testDataSourcePendingAction({ exploreId }),
testDataSourceFailureAction({ exploreId, error }),
]);
});
});
describe('and testDatasource call on instance throws', () => {
it('then it should dispatch testDataSourceFailureAction', async () => {
const exploreId = ExploreId.left;
const error = 'something went wrong';
const mockDatasourceInstance = {
testDatasource: () => {
throw { statusText: error };
},
};
const dispatchedActions = await thunkTester({})
.givenThunk(testDatasource)
.whenThunkIsDispatched(exploreId, mockDatasourceInstance);
expect(dispatchedActions).toEqual([
testDataSourcePendingAction({ exploreId }),
testDataSourceFailureAction({ exploreId, error }),
]);
});
});
});
});
describe('loading datasource', () => {
describe('when loadDatasource thunk is dispatched', () => {
describe('and all goes fine', () => {
it('then it should dispatch correct actions', async () => {
const exploreId = ExploreId.left;
const name = 'some-datasource';
const initialState = { explore: { [exploreId]: { requestedDatasourceName: name } } };
const mockDatasourceInstance = {
testDatasource: () => {
return Promise.resolve({ status: 'success' });
},
name,
init: jest.fn(),
meta: { id: 'some id' },
};
const dispatchedActions = await thunkTester(initialState)
.givenThunk(loadDatasource)
.whenThunkIsDispatched(exploreId, mockDatasourceInstance);
expect(dispatchedActions).toEqual([
loadDatasourcePendingAction({
exploreId,
requestedDatasourceName: mockDatasourceInstance.name,
}),
testDataSourcePendingAction({ exploreId }),
testDataSourceSuccessAction({ exploreId }),
loadDatasourceReadyAction({ exploreId, history: [] }),
]);
});
});
describe('and user changes datasource during load', () => {
it('then it should dispatch correct actions', async () => {
const exploreId = ExploreId.left;
const name = 'some-datasource';
const initialState = { explore: { [exploreId]: { requestedDatasourceName: 'some-other-datasource' } } };
const mockDatasourceInstance = {
testDatasource: () => {
return Promise.resolve({ status: 'success' });
},
name,
init: jest.fn(),
meta: { id: 'some id' },
};
const dispatchedActions = await thunkTester(initialState)
.givenThunk(loadDatasource)
.whenThunkIsDispatched(exploreId, mockDatasourceInstance);
expect(dispatchedActions).toEqual([
loadDatasourcePendingAction({
exploreId,
requestedDatasourceName: mockDatasourceInstance.name,
}),
testDataSourcePendingAction({ exploreId }),
testDataSourceSuccessAction({ exploreId }),
]);
});
});
});
});
| public/app/features/explore/state/actions.test.ts | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.00017861499509308487,
0.00017356258467771113,
0.0001675272942520678,
0.0001735083933454007,
0.000002982483010782744
]
|
{
"id": 2,
"code_window": [
" },\n",
" });\n",
"\n",
" const issues = res.data.filter(item => {\n",
" if (!item.milestone) {\n",
" console.log('Item missing milestone', item.number);\n",
" return false;\n",
" }\n",
" return item.milestone.title === milestone;\n",
" });\n",
"\n",
" const bugs = _.sortBy(\n",
" issues.filter(item => {\n",
" if (item.title.match(/fix|fixes/i)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const issues = res.data;\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "replace",
"edit_start_line_idx": 24
} | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !gccgo
#include "textflag.h"
//
// System call support for ARM, OpenBSD
//
// Just jump to package syscall's implementation for all these functions.
// The runtime may know about them.
TEXT ·Syscall(SB),NOSPLIT,$0-28
B syscall·Syscall(SB)
TEXT ·Syscall6(SB),NOSPLIT,$0-40
B syscall·Syscall6(SB)
TEXT ·Syscall9(SB),NOSPLIT,$0-52
B syscall·Syscall9(SB)
TEXT ·RawSyscall(SB),NOSPLIT,$0-28
B syscall·RawSyscall(SB)
TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
B syscall·RawSyscall6(SB)
| vendor/golang.org/x/sys/unix/asm_openbsd_arm.s | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.00017990478954743594,
0.0001772768300725147,
0.00017576133541297168,
0.0001761643507052213,
0.000001865520971477963
]
|
{
"id": 2,
"code_window": [
" },\n",
" });\n",
"\n",
" const issues = res.data.filter(item => {\n",
" if (!item.milestone) {\n",
" console.log('Item missing milestone', item.number);\n",
" return false;\n",
" }\n",
" return item.milestone.title === milestone;\n",
" });\n",
"\n",
" const bugs = _.sortBy(\n",
" issues.filter(item => {\n",
" if (item.title.match(/fix|fixes/i)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const issues = res.data;\n"
],
"file_path": "scripts/cli/tasks/changelog.ts",
"type": "replace",
"edit_start_line_idx": 24
} | package models
import (
"errors"
"time"
)
// Typed errors
var (
ErrUserNotFound = errors.New("User not found")
ErrLastGrafanaAdmin = errors.New("Cannot remove last grafana admin")
)
type Password string
func (p Password) IsWeak() bool {
return len(p) <= 4
}
type User struct {
Id int64
Version int
Email string
Name string
Login string
Password string
Salt string
Rands string
Company string
EmailVerified bool
Theme string
HelpFlags1 HelpFlags1
IsAdmin bool
OrgId int64
Created time.Time
Updated time.Time
LastSeenAt time.Time
}
func (u *User) NameOrFallback() string {
if u.Name != "" {
return u.Name
} else if u.Login != "" {
return u.Login
} else {
return u.Email
}
}
// ---------------------
// COMMANDS
type CreateUserCommand struct {
Email string
Login string
Name string
Company string
OrgName string
Password string
EmailVerified bool
IsAdmin bool
SkipOrgSetup bool
DefaultOrgRole string
Result User
}
type UpdateUserCommand struct {
Name string `json:"name"`
Email string `json:"email"`
Login string `json:"login"`
Theme string `json:"theme"`
UserId int64 `json:"-"`
}
type ChangeUserPasswordCommand struct {
OldPassword string `json:"oldPassword"`
NewPassword string `json:"newPassword"`
UserId int64 `json:"-"`
}
type UpdateUserPermissionsCommand struct {
IsGrafanaAdmin bool
UserId int64 `json:"-"`
}
type DeleteUserCommand struct {
UserId int64
}
type SetUsingOrgCommand struct {
UserId int64
OrgId int64
}
// ----------------------
// QUERIES
type GetUserByLoginQuery struct {
LoginOrEmail string
Result *User
}
type GetUserByEmailQuery struct {
Email string
Result *User
}
type GetUserByIdQuery struct {
Id int64
Result *User
}
type GetSignedInUserQuery struct {
UserId int64
Login string
Email string
OrgId int64
Result *SignedInUser
}
type GetUserProfileQuery struct {
UserId int64
Result UserProfileDTO
}
type SearchUsersQuery struct {
OrgId int64
Query string
Page int
Limit int
Result SearchUserQueryResult
}
type SearchUserQueryResult struct {
TotalCount int64 `json:"totalCount"`
Users []*UserSearchHitDTO `json:"users"`
Page int `json:"page"`
PerPage int `json:"perPage"`
}
type GetUserOrgListQuery struct {
UserId int64
Result []*UserOrgDTO
}
// ------------------------
// DTO & Projections
type SignedInUser struct {
UserId int64
OrgId int64
OrgName string
OrgRole RoleType
Login string
Name string
Email string
ApiKeyId int64
OrgCount int
IsGrafanaAdmin bool
IsAnonymous bool
HelpFlags1 HelpFlags1
LastSeenAt time.Time
Teams []int64
}
func (u *SignedInUser) ShouldUpdateLastSeenAt() bool {
return u.UserId > 0 && time.Since(u.LastSeenAt) > time.Minute*5
}
func (u *SignedInUser) NameOrFallback() string {
if u.Name != "" {
return u.Name
} else if u.Login != "" {
return u.Login
} else {
return u.Email
}
}
type UpdateUserLastSeenAtCommand struct {
UserId int64
}
func (user *SignedInUser) HasRole(role RoleType) bool {
if user.IsGrafanaAdmin {
return true
}
return user.OrgRole.Includes(role)
}
type UserProfileDTO struct {
Id int64 `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
Login string `json:"login"`
Theme string `json:"theme"`
OrgId int64 `json:"orgId"`
IsGrafanaAdmin bool `json:"isGrafanaAdmin"`
}
type UserSearchHitDTO struct {
Id int64 `json:"id"`
Name string `json:"name"`
Login string `json:"login"`
Email string `json:"email"`
AvatarUrl string `json:"avatarUrl"`
IsAdmin bool `json:"isAdmin"`
LastSeenAt time.Time `json:"lastSeenAt"`
LastSeenAtAge string `json:"lastSeenAtAge"`
}
type UserIdDTO struct {
Id int64 `json:"id"`
Message string `json:"message"`
}
| pkg/models/user.go | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.00017784735246095806,
0.00017240631859749556,
0.000167491685715504,
0.00017246365314349532,
0.0000024126322841766523
]
|
{
"id": 3,
"code_window": [
" if (!item.milestone) {\n",
" console.log(item.number + ' missing milestone!');\n",
" continue;\n",
" }\n",
"\n",
" console.log(item.number + ' closed_at ' + item.closed_at + ' ' + item.html_url);\n",
" const issueDetails = await client.get(item.pull_request.url);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" console.log(`${item.title} (${item.number}) closed_at ${item.closed_at}`);\n",
" console.log(`\\tURL: ${item.closed_at} ${item.html_url}`);\n"
],
"file_path": "scripts/cli/tasks/cherrypick.ts",
"type": "replace",
"edit_start_line_idx": 29
} | import axios from 'axios';
import _ from 'lodash';
import { Task, TaskRunner } from './task';
const githubGrafanaUrl = 'https://github.com/grafana/grafana';
interface ChangelogOptions {
milestone: string;
}
const changelogTaskRunner: TaskRunner<ChangelogOptions> = async ({ milestone }) => {
const client = axios.create({
baseURL: 'https://api.github.com/repos/grafana/grafana',
timeout: 10000,
});
const res = await client.get('/issues', {
params: {
state: 'closed',
per_page: 100,
labels: 'add to changelog',
},
});
const issues = res.data.filter(item => {
if (!item.milestone) {
console.log('Item missing milestone', item.number);
return false;
}
return item.milestone.title === milestone;
});
const bugs = _.sortBy(
issues.filter(item => {
if (item.title.match(/fix|fixes/i)) {
return true;
}
if (item.labels.find(label => label.name === 'type/bug')) {
return true;
}
return false;
}),
'title'
);
const notBugs = _.sortBy(issues.filter(item => !bugs.find(bug => bug === item)), 'title');
let markdown = '### Features / Enhancements\n';
for (const item of notBugs) {
markdown += getMarkdownLineForIssue(item);
}
markdown += '\n### Bug Fixes\n';
for (const item of bugs) {
markdown += getMarkdownLineForIssue(item);
}
console.log(markdown);
};
function getMarkdownLineForIssue(item: any) {
let markdown = '';
const title = item.title.replace(/^([^:]*)/, (match, g1) => {
return `**${g1}**`;
});
markdown += '* ' + title + '.';
markdown += ` [#${item.number}](${githubGrafanaUrl}/pull/${item.number})`;
markdown += `, [@${item.user.login}](${item.user.html_url})`;
markdown += '\n';
return markdown;
}
export const changelogTask = new Task<ChangelogOptions>();
changelogTask.setName('Changelog generator task');
changelogTask.setRunner(changelogTaskRunner);
| scripts/cli/tasks/changelog.ts | 1 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.03079855628311634,
0.006333398167043924,
0.0001729778159642592,
0.0017977971583604813,
0.009807716123759747
]
|
{
"id": 3,
"code_window": [
" if (!item.milestone) {\n",
" console.log(item.number + ' missing milestone!');\n",
" continue;\n",
" }\n",
"\n",
" console.log(item.number + ' closed_at ' + item.closed_at + ' ' + item.html_url);\n",
" const issueDetails = await client.get(item.pull_request.url);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" console.log(`${item.title} (${item.number}) closed_at ${item.closed_at}`);\n",
" console.log(`\\tURL: ${item.closed_at} ${item.html_url}`);\n"
],
"file_path": "scripts/cli/tasks/cherrypick.ts",
"type": "replace",
"edit_start_line_idx": 29
} | import React from 'react';
import classNames from 'classnames';
export class SearchResult extends React.Component<any, any> {
constructor(props) {
super(props);
this.state = {
search: '',
};
}
render() {
return this.state.search.sections.map(section => {
return <SearchResultSection section={section} key={section.id} />;
});
}
}
export interface SectionProps {
section: any;
}
export class SearchResultSection extends React.Component<SectionProps, any> {
constructor(props) {
super(props);
}
renderItem(item) {
return (
<a className="search-item" href={item.url} key={item.id}>
<span className="search-item__icon">
<i className="fa fa-th-large" />
</span>
<span className="search-item__body">
<div className="search-item__body-title">{item.title}</div>
</span>
</a>
);
}
toggleSection = () => {
this.props.section.toggle();
};
render() {
const collapseClassNames = classNames({
fa: true,
'fa-plus': !this.props.section.expanded,
'fa-minus': this.props.section.expanded,
'search-section__header__toggle': true,
});
return (
<div className="search-section" key={this.props.section.id}>
<div className="search-section__header">
<i className={classNames('search-section__header__icon', this.props.section.icon)} />
<span className="search-section__header__text">{this.props.section.title}</span>
<i className={collapseClassNames} onClick={this.toggleSection} />
</div>
{this.props.section.expanded && (
<div className="search-section__items">{this.props.section.items.map(this.renderItem)}</div>
)}
</div>
);
}
}
| public/app/core/components/search/SearchResult.tsx | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.00041645378223620355,
0.00020470295567065477,
0.00016502704238519073,
0.00017012996249832213,
0.00008652635006001219
]
|
{
"id": 3,
"code_window": [
" if (!item.milestone) {\n",
" console.log(item.number + ' missing milestone!');\n",
" continue;\n",
" }\n",
"\n",
" console.log(item.number + ' closed_at ' + item.closed_at + ' ' + item.html_url);\n",
" const issueDetails = await client.get(item.pull_request.url);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" console.log(`${item.title} (${item.number}) closed_at ${item.closed_at}`);\n",
" console.log(`\\tURL: ${item.closed_at} ${item.html_url}`);\n"
],
"file_path": "scripts/cli/tasks/cherrypick.ts",
"type": "replace",
"edit_start_line_idx": 29
} | import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import sourceMaps from 'rollup-plugin-sourcemaps';
import { terser } from 'rollup-plugin-terser';
const pkg = require('./package.json');
const libraryName = pkg.name;
const buildCjsPackage = ({ env }) => {
return {
input: `compiled/index.js`,
output: [
{
file: `dist/index.${env}.js`,
name: libraryName,
format: 'cjs',
sourcemap: true,
exports: 'named',
globals: {
react: 'React',
'prop-types': 'PropTypes',
},
},
],
external: ['react', 'react-dom'],
plugins: [
commonjs({
include: /node_modules/,
namedExports: {
'../../node_modules/lodash/lodash.js': [
'flatten',
'find',
'upperFirst',
'debounce',
'isNil',
'isNumber',
'flattenDeep',
'map',
'chunk',
'sortBy',
'uniqueId',
'zip',
],
'../../node_modules/react-color/lib/components/common': ['Saturation', 'Hue', 'Alpha'],
},
}),
resolve(),
sourceMaps(),
env === 'production' && terser(),
],
};
};
export default [buildCjsPackage({ env: 'development' }), buildCjsPackage({ env: 'production' })];
| packages/grafana-ui/rollup.config.ts | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.00017715276044327766,
0.00017437105998396873,
0.00017248223593924195,
0.00017405074322596192,
0.000001644707481318619
]
|
{
"id": 3,
"code_window": [
" if (!item.milestone) {\n",
" console.log(item.number + ' missing milestone!');\n",
" continue;\n",
" }\n",
"\n",
" console.log(item.number + ' closed_at ' + item.closed_at + ' ' + item.html_url);\n",
" const issueDetails = await client.get(item.pull_request.url);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" console.log(`${item.title} (${item.number}) closed_at ${item.closed_at}`);\n",
" console.log(`\\tURL: ${item.closed_at} ${item.html_url}`);\n"
],
"file_path": "scripts/cli/tasks/cherrypick.ts",
"type": "replace",
"edit_start_line_idx": 29
} | // mksyscall.pl -tags freebsd,amd64 syscall_bsd.go syscall_freebsd.go syscall_freebsd_amd64.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build freebsd,amd64
package unix
import (
"syscall"
"unsafe"
)
var _ syscall.Errno
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setgroups(ngid int, gid *_Gid_t) (err error) {
_, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) {
r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0)
wpid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socket(domain int, typ int, proto int) (fd int, err error) {
r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
_, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Shutdown(s int, how int) (err error) {
_, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
var _p0 unsafe.Pointer
if len(mib) > 0 {
_p0 = unsafe.Pointer(&mib[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimes(path string, timeval *[2]Timeval) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func futimes(fd int, timeval *[2]Timeval) (err error) {
_, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fcntl(fd int, cmd int, arg int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func poll(fds *PollFd, nfds int, timeout int) (n int, err error) {
r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Madvise(b []byte, behav int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlockall(flags int) (err error) {
_, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mprotect(b []byte, prot int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Msync(b []byte, flags int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlockall() (err error) {
_, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pipe() (r int, w int, err error) {
r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
r = int(r0)
w = int(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getcwd(buf []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ioctl(fd int, req uint, arg uintptr) (err error) {
_, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Access(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
_, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func CapEnter() (err error) {
_, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func capRightsGet(version int, fd int, rightsp *CapRights) (err error) {
_, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func capRightsLimit(fd int, rightsp *CapRights) (err error) {
_, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chflags(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chmod(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chroot(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Close(fd int) (err error) {
_, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup(fd int) (nfd int, err error) {
r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup2(from int, to int) (err error) {
_, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exit(code int) {
Syscall(SYS_EXIT, uintptr(code), 0, 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(attrname)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0)
ret = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(attrname)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0)
ret = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(attrname)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
ret = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(file)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(attrname)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
ret = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(file)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(attrname)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
ret = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(file)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(attrname)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(file)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
ret = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(link)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(attrname)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
ret = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(link)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(attrname)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
ret = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(link)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(attrname)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(link)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
ret = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
_, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchdir(fd int) (err error) {
_, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchflags(fd int, flags int) (err error) {
_, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmod(fd int, mode uint32) (err error) {
_, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchown(fd int, uid int, gid int) (err error) {
_, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Flock(fd int, how int) (err error) {
_, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fpathconf(fd int, name int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatfs(fd int, stat *Statfs_t) (err error) {
_, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fsync(fd int) (err error) {
_, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Ftruncate(fd int, length int64) (err error) {
_, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdents(fd int, buf []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdtablesize() (size int) {
r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
size = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getegid() (egid int) {
r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0)
egid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Geteuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getgid() (gid int) {
r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgid(pid int) (pgid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0)
pgid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgrp() (pgrp int) {
r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
pgrp = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpid() (pid int) {
r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
pid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getppid() (ppid int) {
r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0)
ppid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpriority(which int, who int) (prio int, err error) {
r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0)
prio = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getsid(pid int) (sid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0)
sid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Gettimeofday(tv *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Issetugid() (tainted bool) {
r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
tainted = bool(r0 != 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kill(pid int, signum syscall.Signal) (err error) {
_, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kqueue() (fd int, err error) {
r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lchown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Link(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Listen(s int, backlog int) (err error) {
_, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lstat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkfifo(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Nanosleep(time *Timespec, leftover *Timespec) (err error) {
_, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Open(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pathconf(path string, name int) (val int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pread(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func read(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlink(path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rename(from string, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Renameat(fromfd int, from string, tofd int, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Revoke(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rmdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
newoffset = int64(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
_, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setegid(egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seteuid(euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setgid(gid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setlogin(name string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpgid(pid int, pgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpriority(which int, who int, prio int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setregid(rgid int, egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setreuid(ruid int, euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setresgid(rgid int, egid int, sgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setresuid(ruid int, euid int, suid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setsid() (pid int, err error) {
r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0)
pid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Settimeofday(tp *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setuid(uid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Stat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Statfs(path string, stat *Statfs_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlink(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(oldpath)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(newpath)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Sync() (err error) {
_, _, e1 := Syscall(SYS_SYNC, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Truncate(path string, length int64) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Umask(newmask int) (oldmask int) {
r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
oldmask = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Undelete(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlink(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlinkat(dirfd int, path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unmount(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func write(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos))
ret = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func munmap(addr uintptr, length uintptr) (err error) {
_, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) {
r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
| vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.00021889893105253577,
0.00016936069005168974,
0.0001619285758351907,
0.00016854093701113015,
0.000005539903213502839
]
|
{
"id": 4,
"code_window": [
" const issueDetails = await client.get(item.pull_request.url);\n",
" const commits = await client.get(issueDetails.data.commits_url);\n",
"\n",
" for (const commit of commits.data) {\n",
" console.log(commit.commit.message + ' sha: ' + commit.sha);\n",
" }\n",
" }\n",
"};\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log(`\\tMerge sha: ${issueDetails.data.merge_commit_sha}`);\n"
],
"file_path": "scripts/cli/tasks/cherrypick.ts",
"type": "replace",
"edit_start_line_idx": 31
} | import axios from 'axios';
import _ from 'lodash';
import { Task, TaskRunner } from './task';
const githubGrafanaUrl = 'https://github.com/grafana/grafana';
interface ChangelogOptions {
milestone: string;
}
const changelogTaskRunner: TaskRunner<ChangelogOptions> = async ({ milestone }) => {
const client = axios.create({
baseURL: 'https://api.github.com/repos/grafana/grafana',
timeout: 10000,
});
const res = await client.get('/issues', {
params: {
state: 'closed',
per_page: 100,
labels: 'add to changelog',
},
});
const issues = res.data.filter(item => {
if (!item.milestone) {
console.log('Item missing milestone', item.number);
return false;
}
return item.milestone.title === milestone;
});
const bugs = _.sortBy(
issues.filter(item => {
if (item.title.match(/fix|fixes/i)) {
return true;
}
if (item.labels.find(label => label.name === 'type/bug')) {
return true;
}
return false;
}),
'title'
);
const notBugs = _.sortBy(issues.filter(item => !bugs.find(bug => bug === item)), 'title');
let markdown = '### Features / Enhancements\n';
for (const item of notBugs) {
markdown += getMarkdownLineForIssue(item);
}
markdown += '\n### Bug Fixes\n';
for (const item of bugs) {
markdown += getMarkdownLineForIssue(item);
}
console.log(markdown);
};
function getMarkdownLineForIssue(item: any) {
let markdown = '';
const title = item.title.replace(/^([^:]*)/, (match, g1) => {
return `**${g1}**`;
});
markdown += '* ' + title + '.';
markdown += ` [#${item.number}](${githubGrafanaUrl}/pull/${item.number})`;
markdown += `, [@${item.user.login}](${item.user.html_url})`;
markdown += '\n';
return markdown;
}
export const changelogTask = new Task<ChangelogOptions>();
changelogTask.setName('Changelog generator task');
changelogTask.setRunner(changelogTaskRunner);
| scripts/cli/tasks/changelog.ts | 1 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.003273978130891919,
0.0012245004763826728,
0.00016657222295179963,
0.00044042832450941205,
0.0012561866315081716
]
|
{
"id": 4,
"code_window": [
" const issueDetails = await client.get(item.pull_request.url);\n",
" const commits = await client.get(issueDetails.data.commits_url);\n",
"\n",
" for (const commit of commits.data) {\n",
" console.log(commit.commit.message + ' sha: ' + commit.sha);\n",
" }\n",
" }\n",
"};\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log(`\\tMerge sha: ${issueDetails.data.merge_commit_sha}`);\n"
],
"file_path": "scripts/cli/tasks/cherrypick.ts",
"type": "replace",
"edit_start_line_idx": 31
} | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package google
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"time"
"golang.org/x/net/context"
"golang.org/x/oauth2"
)
type sdkCredentials struct {
Data []struct {
Credential struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenExpiry *time.Time `json:"token_expiry"`
} `json:"credential"`
Key struct {
Account string `json:"account"`
Scope string `json:"scope"`
} `json:"key"`
}
}
// An SDKConfig provides access to tokens from an account already
// authorized via the Google Cloud SDK.
type SDKConfig struct {
conf oauth2.Config
initialToken *oauth2.Token
}
// NewSDKConfig creates an SDKConfig for the given Google Cloud SDK
// account. If account is empty, the account currently active in
// Google Cloud SDK properties is used.
// Google Cloud SDK credentials must be created by running `gcloud auth`
// before using this function.
// The Google Cloud SDK is available at https://cloud.google.com/sdk/.
func NewSDKConfig(account string) (*SDKConfig, error) {
configPath, err := sdkConfigPath()
if err != nil {
return nil, fmt.Errorf("oauth2/google: error getting SDK config path: %v", err)
}
credentialsPath := filepath.Join(configPath, "credentials")
f, err := os.Open(credentialsPath)
if err != nil {
return nil, fmt.Errorf("oauth2/google: failed to load SDK credentials: %v", err)
}
defer f.Close()
var c sdkCredentials
if err := json.NewDecoder(f).Decode(&c); err != nil {
return nil, fmt.Errorf("oauth2/google: failed to decode SDK credentials from %q: %v", credentialsPath, err)
}
if len(c.Data) == 0 {
return nil, fmt.Errorf("oauth2/google: no credentials found in %q, run `gcloud auth login` to create one", credentialsPath)
}
if account == "" {
propertiesPath := filepath.Join(configPath, "properties")
f, err := os.Open(propertiesPath)
if err != nil {
return nil, fmt.Errorf("oauth2/google: failed to load SDK properties: %v", err)
}
defer f.Close()
ini, err := parseINI(f)
if err != nil {
return nil, fmt.Errorf("oauth2/google: failed to parse SDK properties %q: %v", propertiesPath, err)
}
core, ok := ini["core"]
if !ok {
return nil, fmt.Errorf("oauth2/google: failed to find [core] section in %v", ini)
}
active, ok := core["account"]
if !ok {
return nil, fmt.Errorf("oauth2/google: failed to find %q attribute in %v", "account", core)
}
account = active
}
for _, d := range c.Data {
if account == "" || d.Key.Account == account {
if d.Credential.AccessToken == "" && d.Credential.RefreshToken == "" {
return nil, fmt.Errorf("oauth2/google: no token available for account %q", account)
}
var expiry time.Time
if d.Credential.TokenExpiry != nil {
expiry = *d.Credential.TokenExpiry
}
return &SDKConfig{
conf: oauth2.Config{
ClientID: d.Credential.ClientID,
ClientSecret: d.Credential.ClientSecret,
Scopes: strings.Split(d.Key.Scope, " "),
Endpoint: Endpoint,
RedirectURL: "oob",
},
initialToken: &oauth2.Token{
AccessToken: d.Credential.AccessToken,
RefreshToken: d.Credential.RefreshToken,
Expiry: expiry,
},
}, nil
}
}
return nil, fmt.Errorf("oauth2/google: no such credentials for account %q", account)
}
// Client returns an HTTP client using Google Cloud SDK credentials to
// authorize requests. The token will auto-refresh as necessary. The
// underlying http.RoundTripper will be obtained using the provided
// context. The returned client and its Transport should not be
// modified.
func (c *SDKConfig) Client(ctx context.Context) *http.Client {
return &http.Client{
Transport: &oauth2.Transport{
Source: c.TokenSource(ctx),
},
}
}
// TokenSource returns an oauth2.TokenSource that retrieve tokens from
// Google Cloud SDK credentials using the provided context.
// It will returns the current access token stored in the credentials,
// and refresh it when it expires, but it won't update the credentials
// with the new access token.
func (c *SDKConfig) TokenSource(ctx context.Context) oauth2.TokenSource {
return c.conf.TokenSource(ctx, c.initialToken)
}
// Scopes are the OAuth 2.0 scopes the current account is authorized for.
func (c *SDKConfig) Scopes() []string {
return c.conf.Scopes
}
func parseINI(ini io.Reader) (map[string]map[string]string, error) {
result := map[string]map[string]string{
"": {}, // root section
}
scanner := bufio.NewScanner(ini)
currentSection := ""
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, ";") {
// comment.
continue
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
currentSection = strings.TrimSpace(line[1 : len(line)-1])
result[currentSection] = map[string]string{}
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 && parts[0] != "" {
result[currentSection][strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error scanning ini: %v", err)
}
return result, nil
}
// sdkConfigPath tries to guess where the gcloud config is located.
// It can be overridden during tests.
var sdkConfigPath = func() (string, error) {
if runtime.GOOS == "windows" {
return filepath.Join(os.Getenv("APPDATA"), "gcloud"), nil
}
homeDir := guessUnixHomeDir()
if homeDir == "" {
return "", errors.New("unable to get current user home directory: os/user lookup failed; $HOME is empty")
}
return filepath.Join(homeDir, ".config", "gcloud"), nil
}
func guessUnixHomeDir() string {
// Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470
if v := os.Getenv("HOME"); v != "" {
return v
}
// Else, fall back to user.Current:
if u, err := user.Current(); err == nil {
return u.HomeDir
}
return ""
}
| vendor/golang.org/x/oauth2/google/sdk.go | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.0009852692019194365,
0.0002102709113387391,
0.00016181805403903127,
0.00017190100334119052,
0.00017334376752842218
]
|
{
"id": 4,
"code_window": [
" const issueDetails = await client.get(item.pull_request.url);\n",
" const commits = await client.get(issueDetails.data.commits_url);\n",
"\n",
" for (const commit of commits.data) {\n",
" console.log(commit.commit.message + ' sha: ' + commit.sha);\n",
" }\n",
" }\n",
"};\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log(`\\tMerge sha: ${issueDetails.data.merge_commit_sha}`);\n"
],
"file_path": "scripts/cli/tasks/cherrypick.ts",
"type": "replace",
"edit_start_line_idx": 31
} | function getIndent(text) {
let offset = text.length - text.trimLeft().length;
if (offset) {
let indent = text[0];
while (--offset) {
indent += text[0];
}
return indent;
}
return '';
}
export default function NewlinePlugin() {
return {
onKeyDown(event, change) {
const { value } = change;
if (!value.isCollapsed) {
return undefined;
}
if (event.key === 'Enter' && event.shiftKey) {
event.preventDefault();
const { startBlock } = value;
const currentLineText = startBlock.text;
const indent = getIndent(currentLineText);
return change
.splitBlock()
.insertText(indent)
.focus();
}
},
};
}
| public/app/features/explore/slate-plugins/newline.ts | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.0001713480451144278,
0.0001696474355412647,
0.00016822392353788018,
0.00016950888675637543,
0.0000011236767250011326
]
|
{
"id": 4,
"code_window": [
" const issueDetails = await client.get(item.pull_request.url);\n",
" const commits = await client.get(issueDetails.data.commits_url);\n",
"\n",
" for (const commit of commits.data) {\n",
" console.log(commit.commit.message + ' sha: ' + commit.sha);\n",
" }\n",
" }\n",
"};\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log(`\\tMerge sha: ${issueDetails.data.merge_commit_sha}`);\n"
],
"file_path": "scripts/cli/tasks/cherrypick.ts",
"type": "replace",
"edit_start_line_idx": 31
} | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Code from https://github.com/gogits/gogs/blob/v0.7.0/modules/avatar/avatar.go
package avatar
import (
"bufio"
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/setting"
"gopkg.in/macaron.v1"
gocache "github.com/patrickmn/go-cache"
)
var gravatarSource string
func UpdateGravatarSource() {
srcCfg := "//secure.gravatar.com/avatar/"
gravatarSource = srcCfg
if strings.HasPrefix(gravatarSource, "//") {
gravatarSource = "http:" + gravatarSource
} else if !strings.HasPrefix(gravatarSource, "http://") &&
!strings.HasPrefix(gravatarSource, "https://") {
gravatarSource = "http://" + gravatarSource
}
}
// hash email to md5 string
// keep this func in order to make this package independent
func HashEmail(email string) string {
// https://en.gravatar.com/site/implement/hash/
email = strings.TrimSpace(email)
email = strings.ToLower(email)
h := md5.New()
h.Write([]byte(email))
return hex.EncodeToString(h.Sum(nil))
}
// Avatar represents the avatar object.
type Avatar struct {
hash string
reqParams string
data *bytes.Buffer
notFound bool
timestamp time.Time
}
func New(hash string) *Avatar {
return &Avatar{
hash: hash,
reqParams: url.Values{
"d": {"retro"},
"size": {"200"},
"r": {"pg"}}.Encode(),
}
}
func (this *Avatar) Expired() bool {
return time.Since(this.timestamp) > (time.Minute * 10)
}
func (this *Avatar) Encode(wr io.Writer) error {
_, err := wr.Write(this.data.Bytes())
return err
}
func (this *Avatar) Update() (err error) {
select {
case <-time.After(time.Second * 3):
err = fmt.Errorf("get gravatar image %s timeout", this.hash)
case err = <-thunder.GoFetch(gravatarSource+this.hash+"?"+this.reqParams, this):
}
return err
}
type CacheServer struct {
notFound *Avatar
cache *gocache.Cache
}
func (this *CacheServer) Handler(ctx *macaron.Context) {
urlPath := ctx.Req.URL.Path
hash := urlPath[strings.LastIndex(urlPath, "/")+1:]
var avatar *Avatar
if obj, exist := this.cache.Get(hash); exist {
avatar = obj.(*Avatar)
} else {
avatar = New(hash)
}
if avatar.Expired() {
if err := avatar.Update(); err != nil {
log.Trace("avatar update error: %v", err)
avatar = this.notFound
}
}
if avatar.notFound {
avatar = this.notFound
} else {
this.cache.Add(hash, avatar, gocache.DefaultExpiration)
}
ctx.Resp.Header().Add("Content-Type", "image/jpeg")
if !setting.EnableGzip {
ctx.Resp.Header().Add("Content-Length", strconv.Itoa(len(avatar.data.Bytes())))
}
ctx.Resp.Header().Add("Cache-Control", "private, max-age=3600")
if err := avatar.Encode(ctx.Resp); err != nil {
log.Warn("avatar encode error: %v", err)
ctx.WriteHeader(500)
}
}
func NewCacheServer() *CacheServer {
UpdateGravatarSource()
return &CacheServer{
notFound: newNotFound(),
cache: gocache.New(time.Hour, time.Hour*2),
}
}
func newNotFound() *Avatar {
avatar := &Avatar{notFound: true}
// load user_profile png into buffer
path := filepath.Join(setting.StaticRootPath, "img", "user_profile.png")
if data, err := ioutil.ReadFile(path); err != nil {
log.Error(3, "Failed to read user_profile.png, %v", path)
} else {
avatar.data = bytes.NewBuffer(data)
}
return avatar
}
// thunder downloader
var thunder = &Thunder{QueueSize: 10}
type Thunder struct {
QueueSize int // download queue size
q chan *thunderTask
once sync.Once
}
func (t *Thunder) init() {
if t.QueueSize < 1 {
t.QueueSize = 1
}
t.q = make(chan *thunderTask, t.QueueSize)
for i := 0; i < t.QueueSize; i++ {
go func() {
for {
task := <-t.q
task.Fetch()
}
}()
}
}
func (t *Thunder) Fetch(url string, avatar *Avatar) error {
t.once.Do(t.init)
task := &thunderTask{
Url: url,
Avatar: avatar,
}
task.Add(1)
t.q <- task
task.Wait()
return task.err
}
func (t *Thunder) GoFetch(url string, avatar *Avatar) chan error {
c := make(chan error)
go func() {
c <- t.Fetch(url, avatar)
}()
return c
}
// thunder download
type thunderTask struct {
Url string
Avatar *Avatar
sync.WaitGroup
err error
}
func (this *thunderTask) Fetch() {
this.err = this.fetch()
this.Done()
}
var client = &http.Client{
Timeout: time.Second * 2,
Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
}
func (this *thunderTask) fetch() error {
this.Avatar.timestamp = time.Now()
log.Debug("avatar.fetch(fetch new avatar): %s", this.Url)
req, _ := http.NewRequest("GET", this.Url, nil)
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/jpeg,image/png,*/*;q=0.8")
req.Header.Set("Accept-Encoding", "deflate,sdch")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36")
resp, err := client.Do(req)
if err != nil {
this.Avatar.notFound = true
return fmt.Errorf("gravatar unreachable, %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
this.Avatar.notFound = true
return fmt.Errorf("status code: %d", resp.StatusCode)
}
this.Avatar.data = &bytes.Buffer{}
writer := bufio.NewWriter(this.Avatar.data)
_, err = io.Copy(writer, resp.Body)
return err
}
| pkg/api/avatar/avatar.go | 0 | https://github.com/grafana/grafana/commit/5aea77fc958975fbfe086dd8d729eb6b6d5a1e44 | [
0.001229278277605772,
0.0002106727915816009,
0.00016280703130178154,
0.00016999623039737344,
0.00020374704035930336
]
|
{
"id": 0,
"code_window": [
"\n",
"### Debugging a Karma Test\n",
"\n",
"- Run test: `yarn bazel run packages/core/test:test_web_chromium` or `yarn bazel run packages/core/test:test_web_firefox`\n",
"- Open any browser at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html)\n",
"- Open the browser's DevTools to debug the tests (after, for example, having focused on specific tests via `fit` and/or `fdescribe` or having added `debugger` statements in them)\n",
"\n",
"### Debugging Bazel rules\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- Run test: `yarn bazel run packages/core/test:test_web_debug` (any `karma_web_test_suite` target has a `_debug` target)\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 107
} | # Building Angular with Bazel
Note: this doc is for developing Angular, it is _not_ public
documentation for building an Angular application with Bazel.
The Bazel build tool (https://bazel.build) provides fast, reliable
incremental builds. We plan to migrate Angular's build scripts to
Bazel.
## Installation
In order to ensure that everyone builds Angular in a _consistent_ way, Bazel
will be installed through NPM and therefore it's not necessary to install Bazel
manually.
The binaries for Bazel will be provided by the [`@bazel/bazelisk`](https://github.com/bazelbuild/bazelisk)
NPM package and its platform-specific dependencies.
You can access Bazel with the `yarn bazel` command
## Configuration
The `WORKSPACE` file indicates that our root directory is a
Bazel project. It contains the version of the Bazel rules we
use to execute build steps, from `npm_bazel_typescript`.
The sources on [GitHub] are published from Google's internal
repository (google3).
Bazel accepts a lot of options. We check in some options in the
`.bazelrc` file. See the [bazelrc doc]. For example, if you don't
want Bazel to create several symlinks in your project directory
(`bazel-*`) you can add the line `build --symlink_prefix=/` to your
`.bazelrc` file.
[GitHub]: https://github.com/bazelbuild/rules_typescript
[bazelrc doc]: https://bazel.build/versions/master/docs/bazel-user-manual.html#bazelrc
## Building Angular
- Build a package: `yarn bazel build packages/core`
- Build all packages: `yarn bazel build packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources. Note this is
new as of May 2017 and not very stable yet.
[ibazel]: https://github.com/bazelbuild/bazel-watcher
## Testing Angular
- Test package in node: `yarn bazel test packages/core/test:test`
- Test package in karma: `yarn bazel test packages/core/test:test_web`
- Test all packages: `yarn bazel test packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources.
### Various Flags Used For Tests
If you're experiencing problems with seemingly unrelated tests failing, it may be because you're not using the proper flags with your Bazel test runs in Angular.
- `--config=debug`: build and launch in debug mode (see [debugging](#debugging) instructions below)
- `--test_arg=--node_options=--inspect=9228`: change the inspector port.
- `--test_tag_filters=<tag>`: filter tests down to tags defined in the `tag` config of your rules in any given `BUILD.bazel`.
### Debugging a Node Test
<a id="debugging"></a>
- Open chrome at: [chrome://inspect](chrome://inspect)
- Click on `Open dedicated DevTools for Node` to launch a debugger.
- Run test: `yarn bazel test packages/core/test:test --config=debug`
The process should automatically connect to the debugger.
For more, see the [rules_nodejs Debugging documentation](https://bazelbuild.github.io/rules_nodejs/index.html#debugging).
For additional info and testing options, see the
[nodejs_test documentation](https://bazelbuild.github.io/rules_nodejs/Built-ins.html#nodejs_test).
- Click on "Resume script execution" to let the code run until the first `debugger` statement or a previously set breakpoint.
- If you're debugging a test and you want to inspect the generated template instructions, find the template of your component in the call stack and click on `(source mapped from [CompName].js)` at the bottom of the code. You can also disable sourcemaps in the options or go to sources and look into ng:// namespace to see all the generated code.
### Debugging a Node Test in VSCode
First time setup:
- Go to Debug > Add configuration (in the menu bar) to open `launch.json`
- Add the following to the `configurations` array:
```json
{
"type": "node",
"request": "attach",
"name": "Attach to Remote",
"port": 9229
}
```
**Setting breakpoints directly in your code files may not work in VSCode**. This is because the files you're actually debugging are built files that exist in a `./private/...` folder.
The easiest way to debug a test for now is to add a `debugger` statement in the code
and launch the bazel corresponding test (`yarn bazel test <target> --config=debug`).
Bazel will wait on a connection. Go to the debug view (by clicking on the sidebar or
Apple+Shift+D on Mac) and click on the green play icon next to the configuration name
(ie `Attach to Remote`).
### Debugging a Karma Test
- Run test: `yarn bazel run packages/core/test:test_web_chromium` or `yarn bazel run packages/core/test:test_web_firefox`
- Open any browser at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html)
- Open the browser's DevTools to debug the tests (after, for example, having focused on specific tests via `fit` and/or `fdescribe` or having added `debugger` statements in them)
### Debugging Bazel rules
Open `external` directory which contains everything that bazel downloaded while executing the workspace file:
```sh
open $(yarn -s bazel info output_base)/external
```
See subcommands that bazel executes (helpful for debugging):
```sh
yarn bazel build //packages/core:package -s
```
To debug nodejs_binary executable paths uncomment `find . -name rollup 1>&2` (~ line 96) in
```sh
open $(yarn -s bazel info output_base)/external/build_bazel_rules_nodejs/internal/node_launcher.sh
```
## Stamping
Bazel supports the ability to include non-hermetic information from the version control system in built artifacts. This is called stamping.
You can see an overview at https://www.kchodorow.com/blog/2017/03/27/stamping-your-builds/
In our repo, here is how it's configured:
1) In `tools/bazel_stamp_vars.js` we run the `git` commands to generate our versioning info.
1) In `.bazelrc` we register this script as the value for the `workspace_status_command` flag. Bazel will run the script when it needs to stamp a binary.
Note that Bazel has a `--stamp` argument to `yarn bazel build`, but this has no effect since our stamping takes place in Skylark rules. See https://github.com/bazelbuild/bazel/issues/1054
## Remote cache
Bazel supports fetching action results from a cache, allowing a clean build to pick up artifacts from prior builds.
This makes builds incremental, even on CI.
It works because Bazel assigns a content-based hash to all action inputs, which is used as the cache key for the action outputs.
Thanks to the hermeticity property, we can skip executing an action if the inputs hash is already present in the cache.
Of course, non-hermeticity in an action can cause problems.
At worst, you can fetch a broken artifact from the cache, making your build non-reproducible.
For this reason, we are careful to implement our Bazel rules to depend only on their inputs.
Currently we only use remote caching on CircleCI and we let Angular core developers enable remote caching to speed up their builds.
### Remote cache in development
To enable remote caching for your build:
1. Go to the service accounts for the ["internal" project](https://console.cloud.google.com/iam-admin/serviceaccounts?project=internal-200822)
1. Select "Angular local dev", click on "Edit", scroll to the bottom, and click "Create key"
1. When the pop-up shows, select "JSON" for "Key type" and click "Create"
1. Save the key in a secure location
1. Create a file called `.bazelrc.user` in the root directory of the workspace, and add the following content:
```
build --config=angular-team --google_credentials=[ABSOLUTE_PATH_TO_SERVICE_KEY]
```
### Remote cache for Circle CI
This feature is experimental, and developed by the CircleCI team with guidance from Angular.
Contact Alex Eagle with questions.
*How it's configured*:
1. In `.circleci/config.yml`, each CircleCI job downloads a proxy binary, which is built from https://github.com/notnoopci/bazel-remote-proxy. The download is done by running `.circleci/setup_cache.sh`. When the feature graduates from experimental, this proxy will be installed by default on every CircleCI worker, and this step will not be needed.
1. Next, each job runs the `setup-bazel-remote-cache` anchor. This starts up the proxy running in the background. In the CircleCI UI, you'll see this step continues running while later steps run, and you can see logging from the proxy process.
1. Bazel must be configured to connect to the proxy on a local port. This configuration lives in `.circleci/bazel.linux.rc` and is enabled because we overwrite the system Bazel settings in /etc/bazel.bazelrc with this file.
1. Each `bazel` command in `.circleci/config.yml` picks up and uses the caching flags.
## Diagnosing slow builds
If a build seems slow you can use Bazel to diagnose where time is spent.
The first step is to generate a profile of the build using the `--profile filename_name.profile` flag.
```
yarn bazel build //packages/compiler --profile filename_name.profile
```
This will generate a `filename_name.profile` that you can then analyse using [analyze-profile](https://docs.bazel.build/versions/master/user-manual.html#analyze-profile) command.
## Using the console profile report
You can obtain a simple report directly in the console by running:
```
yarn bazel analyze-profile filename_name.profile
```
This will show the phase summary, individual phase information and critical path.
You can also list all individual tasks and the time they took using `--task_tree`.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*"
```
To show all tasks that take longer than a certain threshold, use the `--task_tree_threshold` flag.
The default behavior is to use a 50ms threshold.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*" --task_tree_threshold 5000
```
`--task_tree` takes a regexp as argument that filters by the text shown after the time taken.
Compiling TypeScript shows as:
```
70569 ACTION_EXECUTE (10974.826 ms) Compiling TypeScript (devmode) //packages/compiler:compiler []
```
To filter all tasks by TypeScript compilations that took more than 5 seconds, use:
```
yarn bazel analyze-profile filename_name.profile --task_tree "Compiling TypeScript" --task_tree_threshold 5000
```
### Using the HTML profile report
A more comprehensive way to visualize the profile information is through the HTML report:
```
yarn bazel analyze-profile filename_name.profile --html --html_details --html_histograms
```
This will generate a `filename_name.profile.html` file that you can open in your browser.
On the upper right corner that is a small table of contents with links to three areas: Tasks, Legend and Statistics.
In the Tasks section you will find a graph of where time is spent. Legend shows what the colors in the Tasks graph mean.
Hovering over the background will show what phase that is, while hovering over bars will show more details about that specific action.
The Statistics section shows how long each phase took and how time was spent in that phase.
Usually the longest one is the execution phase, which also includes critical path information.
Also in the Statistics section are the Skylark statistic, split in User-Defined and Builtin function execution time.
You can click the "self" header twice to order the table by functions where the most time (in ms) is spent.
When diagnosing slow builds you should focus on the top time spenders across all phases and functions.
Usually there is a single item (or multiple items of the same kind) where the overwhelming majority of time is spent.
## Known issues
### Windows
#### bazel run
If you see the following error:
```
Error: Cannot find module 'C:\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\c;C:\msys64\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\packages\core\test\bundling\hello_world\symbol_test_require_patch.js'
Require stack:
- internal/preload
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Module.require (internal/modules/cjs/loader.js:848:19)
at Module._preloadModules (internal/modules/cjs/loader.js:1133:12)
at loadPreloadModules (internal/bootstrap/pre_execution.js:443:5)
at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:62:3)
at internal/main/run_main_module.js:7:1 {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'internal/preload' ]
```
`bazel run` only works in Bazel Windows with non-test targets. Ensure that you are using `bazel test` instead.
e.g: `yarn bazel test packages/core/test/bundling/forms:symbol_test`
#### mkdir missing
If you see the following error::
```
ERROR: An error occurred during the fetch of repository 'npm':
Traceback (most recent call last):
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 618, column 15, in _yarn_install_impl
_copy_file(repository_ctx, repository_ctx.attr.package_json)
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 345, column 17, in _copy_file
fail("mkdir -p %s failed: \nSTDOUT:\n%s\nSTDERR:\n%s" % (dirname, result.stdout, result.stderr))
Error in fail: mkdir -p _ failed:
```
The `msys64` library and associated tools (like `mkdir`) are required to build Angular.
Make sure you have `C:\msys64\usr\bin` in the "system" `PATH` rather than the "user" `PATH`.
After that, a `git clean -xfd`, `yarn`, and `node scripts\build\build-packages-dist.js` should resolve this issue.
### Xcode
If you see the following error:
```
$ yarn bazel build packages/...
ERROR: /private/var/tmp/[...]/external/local_config_cc/BUILD:50:5: in apple_cc_toolchain rule @local_config_cc//:cc-compiler-darwin_x86_64: Xcode version must be specified to use an Apple CROSSTOOL
ERROR: Analysis of target '//packages/core/test/render3:render3' failed; build aborted: Analysis of target '@local_config_cc//:cc-compiler-darwin_x86_64' failed; build aborted
```
It might be linked to an interaction with VSCode.
If closing VSCode fixes the issue, you can add the following line to your VSCode configuration:
```
"files.exclude": {"bazel-*": true}
```
source: https://github.com/bazelbuild/bazel/issues/4603
If VSCode is not the root cause, you might try:
- Quit VSCode (make sure no VSCode is running).
```
bazel clean --expunge
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo xcodebuild -license
yarn bazel build //packages/core # Run a build outside VSCode to pre-build the xcode; then safe to run VSCode
```
Source: https://stackoverflow.com/questions/45276830/xcode-version-must-be-specified-to-use-an-apple-crosstool
| docs/BAZEL.md | 1 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.35026663541793823,
0.011086665093898773,
0.00016280733689200133,
0.00021901710715610534,
0.0599624365568161
]
|
{
"id": 0,
"code_window": [
"\n",
"### Debugging a Karma Test\n",
"\n",
"- Run test: `yarn bazel run packages/core/test:test_web_chromium` or `yarn bazel run packages/core/test:test_web_firefox`\n",
"- Open any browser at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html)\n",
"- Open the browser's DevTools to debug the tests (after, for example, having focused on specific tests via `fit` and/or `fdescribe` or having added `debugger` statements in them)\n",
"\n",
"### Debugging Bazel rules\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- Run test: `yarn bazel run packages/core/test:test_web_debug` (any `karma_web_test_suite` target has a `_debug` target)\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 107
} | <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
xmlns:moz="http://www.mozilla.org/2006/browser/search/">
<ShortName>Angular</ShortName>
<Description>Search Angular</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16" type="image/x-icon">images/favicons/favicon-16x16.png</Image>
<Url type="text/html" method="get" template="PLACEHOLDER_URL?search={searchTerms}"/>
<moz:SearchForm>PLACEHOLDER_URL?search={searchTerms}</moz:SearchForm>
</OpenSearchDescription> | aio/src/assets/opensearch.xml | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.00016999295621644706,
0.00016999295621644706,
0.00016999295621644706,
0.00016999295621644706,
0
]
|
{
"id": 0,
"code_window": [
"\n",
"### Debugging a Karma Test\n",
"\n",
"- Run test: `yarn bazel run packages/core/test:test_web_chromium` or `yarn bazel run packages/core/test:test_web_firefox`\n",
"- Open any browser at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html)\n",
"- Open the browser's DevTools to debug the tests (after, for example, having focused on specific tests via `fit` and/or `fdescribe` or having added `debugger` statements in them)\n",
"\n",
"### Debugging Bazel rules\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- Run test: `yarn bazel run packages/core/test:test_web_debug` (any `karma_web_test_suite` target has a `_debug` target)\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 107
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentExplorerViewQuery, DirectiveMetadata, DirectivesProperties, ElementPosition, PropertyQueryTypes, UpdatedStateData,} from 'protocol';
import {buildDirectiveTree, getLViewFromDirectiveOrElementInstance} from './directive-forest/index';
import {deeplySerializeSelectedProperties, serializeDirectiveState} from './state-serializer/state-serializer';
// Need to be kept in sync with Angular framework
// We can't directly import it from framework now
// because this also pulls up the security policies
// for Trusted Types, which we reinstantiate.
enum ChangeDetectionStrategy {
OnPush = 0,
Default = 1,
}
import {ComponentTreeNode, DirectiveInstanceType, ComponentInstanceType} from './interfaces';
const ngDebug = () => (window as any).ng;
export const getLatestComponentState =
(query: ComponentExplorerViewQuery, directiveForest?: ComponentTreeNode[]):
DirectivesProperties|undefined => {
// if a directive forest is passed in we don't have to build the forest again.
directiveForest = directiveForest ?? buildDirectiveForest();
const node = queryDirectiveForest(query.selectedElement, directiveForest);
if (!node) {
return;
}
const result: DirectivesProperties = {};
const populateResultSet = (dir: DirectiveInstanceType|ComponentInstanceType) => {
if (query.propertyQuery.type === PropertyQueryTypes.All) {
result[dir.name] = {
props: serializeDirectiveState(dir.instance),
metadata: getDirectiveMetadata(dir.instance),
};
}
if (query.propertyQuery.type === PropertyQueryTypes.Specified) {
result[dir.name] = {
props: deeplySerializeSelectedProperties(
dir.instance, query.propertyQuery.properties[dir.name] || []),
metadata: getDirectiveMetadata(dir.instance),
};
}
};
node.directives.forEach(populateResultSet);
if (node.component) {
populateResultSet(node.component);
}
return result;
};
const enum DirectiveMetadataKey {
INPUTS = 'inputs',
OUTPUTS = 'outputs',
ENCAPSULATION = 'encapsulation',
ON_PUSH = 'onPush',
}
// Gets directive metadata. For newer versions of Angular (v12+) it uses
// the global `getDirectiveMetadata`. For prior versions of the framework
// the method directly interacts with the directive/component definition.
export const getDirectiveMetadata = (dir: any): DirectiveMetadata => {
const getMetadata = (window as any).ng.getDirectiveMetadata;
if (getMetadata) {
const metadata = getMetadata(dir);
if (metadata) {
return {
inputs: metadata.inputs,
outputs: metadata.outputs,
encapsulation: metadata.encapsulation,
onPush: metadata.changeDetection === ChangeDetectionStrategy.OnPush,
};
}
}
// Used in older Angular versions, prior to the introduction of `getDirectiveMetadata`.
const safelyGrabMetadata = (key: DirectiveMetadataKey) => {
try {
return dir.constructor.ɵcmp ? dir.constructor.ɵcmp[key] : dir.constructor.ɵdir[key];
} catch {
console.warn(`Could not find metadata for key: ${key} in directive:`, dir);
return undefined;
}
};
return {
inputs: safelyGrabMetadata(DirectiveMetadataKey.INPUTS),
outputs: safelyGrabMetadata(DirectiveMetadataKey.OUTPUTS),
encapsulation: safelyGrabMetadata(DirectiveMetadataKey.ENCAPSULATION),
onPush: safelyGrabMetadata(DirectiveMetadataKey.ON_PUSH),
};
};
const getRootLViewsHelper = (element: Element, rootLViews = new Set<any>()): Set<any> => {
if (!(element instanceof HTMLElement)) {
return rootLViews;
}
const lView = getLViewFromDirectiveOrElementInstance(element);
if (lView) {
rootLViews.add(lView);
return rootLViews;
}
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < element.children.length; i++) {
getRootLViewsHelper(element.children[i], rootLViews);
}
return rootLViews;
};
const getRoots = () => {
const roots =
Array.from(document.documentElement.querySelectorAll('[ng-version]')) as HTMLElement[];
const isTopLevel = (element: HTMLElement) => {
let parent: HTMLElement|null = element;
while (parent?.parentElement) {
parent = parent.parentElement;
if (parent.hasAttribute('ng-version')) {
return false;
}
}
return true;
};
return roots.filter(isTopLevel);
};
export const buildDirectiveForest = (): ComponentTreeNode[] => {
const roots = getRoots();
return Array.prototype.concat.apply([], Array.from(roots).map(buildDirectiveTree));
};
// Based on an ElementID we return a specific component node.
// If we can't find any, we return null.
export const queryDirectiveForest =
(position: ElementPosition, forest: ComponentTreeNode[]): ComponentTreeNode|null => {
if (!position.length) {
return null;
}
let node: null|ComponentTreeNode = null;
for (const i of position) {
node = forest[i];
if (!node) {
return null;
}
forest = node.children;
}
return node;
};
export const findNodeInForest =
(position: ElementPosition, forest: ComponentTreeNode[]): HTMLElement|null => {
const foundComponent: ComponentTreeNode|null = queryDirectiveForest(position, forest);
return foundComponent ? (foundComponent.nativeElement as HTMLElement) : null;
};
export const findNodeFromSerializedPosition =
(serializedPosition: string): ComponentTreeNode|null => {
const position: number[] = serializedPosition.split(',').map((index) => parseInt(index, 10));
return queryDirectiveForest(position, buildDirectiveForest());
};
export const updateState = (updatedStateData: UpdatedStateData): void => {
const ngd = ngDebug();
const node = queryDirectiveForest(updatedStateData.directiveId.element, buildDirectiveForest());
if (!node) {
console.warn(
'Could not update the state of component', updatedStateData,
'because the component was not found');
return;
}
if (updatedStateData.directiveId.directive !== undefined) {
const directive = node.directives[updatedStateData.directiveId.directive].instance;
mutateComponentOrDirective(updatedStateData, directive);
ngd.applyChanges(ngd.getOwningComponent(directive));
return;
}
if (node.component) {
const comp = node.component.instance;
mutateComponentOrDirective(updatedStateData, comp);
ngd.applyChanges(comp);
return;
}
};
const mutateComponentOrDirective = (updatedStateData: UpdatedStateData, compOrDirective: any) => {
const valueKey = updatedStateData.keyPath.pop();
if (valueKey === undefined) {
return;
}
let parentObjectOfValueToUpdate = compOrDirective;
updatedStateData.keyPath.forEach((key) => {
parentObjectOfValueToUpdate = parentObjectOfValueToUpdate[key];
});
// When we try to set a property which only has a getter
// the line below could throw an error.
try {
parentObjectOfValueToUpdate[valueKey] = updatedStateData.newValue;
} catch {
}
};
| devtools/projects/ng-devtools-backend/src/lib/component-tree.ts | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.00017568189650774002,
0.0001710101932985708,
0.0001670079946052283,
0.00017227427451871336,
0.0000025361368898302317
]
|
{
"id": 0,
"code_window": [
"\n",
"### Debugging a Karma Test\n",
"\n",
"- Run test: `yarn bazel run packages/core/test:test_web_chromium` or `yarn bazel run packages/core/test:test_web_firefox`\n",
"- Open any browser at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html)\n",
"- Open the browser's DevTools to debug the tests (after, for example, having focused on specific tests via `fit` and/or `fdescribe` or having added `debugger` statements in them)\n",
"\n",
"### Debugging Bazel rules\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"- Run test: `yarn bazel run packages/core/test:test_web_debug` (any `karma_web_test_suite` target has a `_debug` target)\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 107
} | import { Component, ViewEncapsulation } from '@angular/core';
// #docregion
@Component({
selector: 'app-shadow-dom-encapsulation',
template: `
<h2>ShadowDom</h2>
<div class="shadow-message">Shadow DOM encapsulation</div>
<app-emulated-encapsulation></app-emulated-encapsulation>
<app-no-encapsulation></app-no-encapsulation>
`,
styles: ['h2, .shadow-message { color: blue; }'],
encapsulation: ViewEncapsulation.ShadowDom,
})
export class ShadowDomEncapsulationComponent { }
| aio/content/examples/view-encapsulation/src/app/shadow-dom-encapsulation.component.ts | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.00017405471589881927,
0.00017313938587903976,
0.00017222405585926026,
0.00017313938587903976,
9.153300197795033e-7
]
|
{
"id": 1,
"code_window": [
"e.g: `yarn bazel test packages/core/test/bundling/forms:symbol_test`\n",
"\n",
"#### mkdir missing\n",
"If you see the following error::\n",
"```\n",
" \n",
"ERROR: An error occurred during the fetch of repository 'npm':\n",
" Traceback (most recent call last):\n",
" File \"C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl\", line 618, column 15, in _yarn_install_impl\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 276
} | # Building Angular with Bazel
Note: this doc is for developing Angular, it is _not_ public
documentation for building an Angular application with Bazel.
The Bazel build tool (https://bazel.build) provides fast, reliable
incremental builds. We plan to migrate Angular's build scripts to
Bazel.
## Installation
In order to ensure that everyone builds Angular in a _consistent_ way, Bazel
will be installed through NPM and therefore it's not necessary to install Bazel
manually.
The binaries for Bazel will be provided by the [`@bazel/bazelisk`](https://github.com/bazelbuild/bazelisk)
NPM package and its platform-specific dependencies.
You can access Bazel with the `yarn bazel` command
## Configuration
The `WORKSPACE` file indicates that our root directory is a
Bazel project. It contains the version of the Bazel rules we
use to execute build steps, from `npm_bazel_typescript`.
The sources on [GitHub] are published from Google's internal
repository (google3).
Bazel accepts a lot of options. We check in some options in the
`.bazelrc` file. See the [bazelrc doc]. For example, if you don't
want Bazel to create several symlinks in your project directory
(`bazel-*`) you can add the line `build --symlink_prefix=/` to your
`.bazelrc` file.
[GitHub]: https://github.com/bazelbuild/rules_typescript
[bazelrc doc]: https://bazel.build/versions/master/docs/bazel-user-manual.html#bazelrc
## Building Angular
- Build a package: `yarn bazel build packages/core`
- Build all packages: `yarn bazel build packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources. Note this is
new as of May 2017 and not very stable yet.
[ibazel]: https://github.com/bazelbuild/bazel-watcher
## Testing Angular
- Test package in node: `yarn bazel test packages/core/test:test`
- Test package in karma: `yarn bazel test packages/core/test:test_web`
- Test all packages: `yarn bazel test packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources.
### Various Flags Used For Tests
If you're experiencing problems with seemingly unrelated tests failing, it may be because you're not using the proper flags with your Bazel test runs in Angular.
- `--config=debug`: build and launch in debug mode (see [debugging](#debugging) instructions below)
- `--test_arg=--node_options=--inspect=9228`: change the inspector port.
- `--test_tag_filters=<tag>`: filter tests down to tags defined in the `tag` config of your rules in any given `BUILD.bazel`.
### Debugging a Node Test
<a id="debugging"></a>
- Open chrome at: [chrome://inspect](chrome://inspect)
- Click on `Open dedicated DevTools for Node` to launch a debugger.
- Run test: `yarn bazel test packages/core/test:test --config=debug`
The process should automatically connect to the debugger.
For more, see the [rules_nodejs Debugging documentation](https://bazelbuild.github.io/rules_nodejs/index.html#debugging).
For additional info and testing options, see the
[nodejs_test documentation](https://bazelbuild.github.io/rules_nodejs/Built-ins.html#nodejs_test).
- Click on "Resume script execution" to let the code run until the first `debugger` statement or a previously set breakpoint.
- If you're debugging a test and you want to inspect the generated template instructions, find the template of your component in the call stack and click on `(source mapped from [CompName].js)` at the bottom of the code. You can also disable sourcemaps in the options or go to sources and look into ng:// namespace to see all the generated code.
### Debugging a Node Test in VSCode
First time setup:
- Go to Debug > Add configuration (in the menu bar) to open `launch.json`
- Add the following to the `configurations` array:
```json
{
"type": "node",
"request": "attach",
"name": "Attach to Remote",
"port": 9229
}
```
**Setting breakpoints directly in your code files may not work in VSCode**. This is because the files you're actually debugging are built files that exist in a `./private/...` folder.
The easiest way to debug a test for now is to add a `debugger` statement in the code
and launch the bazel corresponding test (`yarn bazel test <target> --config=debug`).
Bazel will wait on a connection. Go to the debug view (by clicking on the sidebar or
Apple+Shift+D on Mac) and click on the green play icon next to the configuration name
(ie `Attach to Remote`).
### Debugging a Karma Test
- Run test: `yarn bazel run packages/core/test:test_web_chromium` or `yarn bazel run packages/core/test:test_web_firefox`
- Open any browser at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html)
- Open the browser's DevTools to debug the tests (after, for example, having focused on specific tests via `fit` and/or `fdescribe` or having added `debugger` statements in them)
### Debugging Bazel rules
Open `external` directory which contains everything that bazel downloaded while executing the workspace file:
```sh
open $(yarn -s bazel info output_base)/external
```
See subcommands that bazel executes (helpful for debugging):
```sh
yarn bazel build //packages/core:package -s
```
To debug nodejs_binary executable paths uncomment `find . -name rollup 1>&2` (~ line 96) in
```sh
open $(yarn -s bazel info output_base)/external/build_bazel_rules_nodejs/internal/node_launcher.sh
```
## Stamping
Bazel supports the ability to include non-hermetic information from the version control system in built artifacts. This is called stamping.
You can see an overview at https://www.kchodorow.com/blog/2017/03/27/stamping-your-builds/
In our repo, here is how it's configured:
1) In `tools/bazel_stamp_vars.js` we run the `git` commands to generate our versioning info.
1) In `.bazelrc` we register this script as the value for the `workspace_status_command` flag. Bazel will run the script when it needs to stamp a binary.
Note that Bazel has a `--stamp` argument to `yarn bazel build`, but this has no effect since our stamping takes place in Skylark rules. See https://github.com/bazelbuild/bazel/issues/1054
## Remote cache
Bazel supports fetching action results from a cache, allowing a clean build to pick up artifacts from prior builds.
This makes builds incremental, even on CI.
It works because Bazel assigns a content-based hash to all action inputs, which is used as the cache key for the action outputs.
Thanks to the hermeticity property, we can skip executing an action if the inputs hash is already present in the cache.
Of course, non-hermeticity in an action can cause problems.
At worst, you can fetch a broken artifact from the cache, making your build non-reproducible.
For this reason, we are careful to implement our Bazel rules to depend only on their inputs.
Currently we only use remote caching on CircleCI and we let Angular core developers enable remote caching to speed up their builds.
### Remote cache in development
To enable remote caching for your build:
1. Go to the service accounts for the ["internal" project](https://console.cloud.google.com/iam-admin/serviceaccounts?project=internal-200822)
1. Select "Angular local dev", click on "Edit", scroll to the bottom, and click "Create key"
1. When the pop-up shows, select "JSON" for "Key type" and click "Create"
1. Save the key in a secure location
1. Create a file called `.bazelrc.user` in the root directory of the workspace, and add the following content:
```
build --config=angular-team --google_credentials=[ABSOLUTE_PATH_TO_SERVICE_KEY]
```
### Remote cache for Circle CI
This feature is experimental, and developed by the CircleCI team with guidance from Angular.
Contact Alex Eagle with questions.
*How it's configured*:
1. In `.circleci/config.yml`, each CircleCI job downloads a proxy binary, which is built from https://github.com/notnoopci/bazel-remote-proxy. The download is done by running `.circleci/setup_cache.sh`. When the feature graduates from experimental, this proxy will be installed by default on every CircleCI worker, and this step will not be needed.
1. Next, each job runs the `setup-bazel-remote-cache` anchor. This starts up the proxy running in the background. In the CircleCI UI, you'll see this step continues running while later steps run, and you can see logging from the proxy process.
1. Bazel must be configured to connect to the proxy on a local port. This configuration lives in `.circleci/bazel.linux.rc` and is enabled because we overwrite the system Bazel settings in /etc/bazel.bazelrc with this file.
1. Each `bazel` command in `.circleci/config.yml` picks up and uses the caching flags.
## Diagnosing slow builds
If a build seems slow you can use Bazel to diagnose where time is spent.
The first step is to generate a profile of the build using the `--profile filename_name.profile` flag.
```
yarn bazel build //packages/compiler --profile filename_name.profile
```
This will generate a `filename_name.profile` that you can then analyse using [analyze-profile](https://docs.bazel.build/versions/master/user-manual.html#analyze-profile) command.
## Using the console profile report
You can obtain a simple report directly in the console by running:
```
yarn bazel analyze-profile filename_name.profile
```
This will show the phase summary, individual phase information and critical path.
You can also list all individual tasks and the time they took using `--task_tree`.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*"
```
To show all tasks that take longer than a certain threshold, use the `--task_tree_threshold` flag.
The default behavior is to use a 50ms threshold.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*" --task_tree_threshold 5000
```
`--task_tree` takes a regexp as argument that filters by the text shown after the time taken.
Compiling TypeScript shows as:
```
70569 ACTION_EXECUTE (10974.826 ms) Compiling TypeScript (devmode) //packages/compiler:compiler []
```
To filter all tasks by TypeScript compilations that took more than 5 seconds, use:
```
yarn bazel analyze-profile filename_name.profile --task_tree "Compiling TypeScript" --task_tree_threshold 5000
```
### Using the HTML profile report
A more comprehensive way to visualize the profile information is through the HTML report:
```
yarn bazel analyze-profile filename_name.profile --html --html_details --html_histograms
```
This will generate a `filename_name.profile.html` file that you can open in your browser.
On the upper right corner that is a small table of contents with links to three areas: Tasks, Legend and Statistics.
In the Tasks section you will find a graph of where time is spent. Legend shows what the colors in the Tasks graph mean.
Hovering over the background will show what phase that is, while hovering over bars will show more details about that specific action.
The Statistics section shows how long each phase took and how time was spent in that phase.
Usually the longest one is the execution phase, which also includes critical path information.
Also in the Statistics section are the Skylark statistic, split in User-Defined and Builtin function execution time.
You can click the "self" header twice to order the table by functions where the most time (in ms) is spent.
When diagnosing slow builds you should focus on the top time spenders across all phases and functions.
Usually there is a single item (or multiple items of the same kind) where the overwhelming majority of time is spent.
## Known issues
### Windows
#### bazel run
If you see the following error:
```
Error: Cannot find module 'C:\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\c;C:\msys64\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\packages\core\test\bundling\hello_world\symbol_test_require_patch.js'
Require stack:
- internal/preload
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Module.require (internal/modules/cjs/loader.js:848:19)
at Module._preloadModules (internal/modules/cjs/loader.js:1133:12)
at loadPreloadModules (internal/bootstrap/pre_execution.js:443:5)
at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:62:3)
at internal/main/run_main_module.js:7:1 {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'internal/preload' ]
```
`bazel run` only works in Bazel Windows with non-test targets. Ensure that you are using `bazel test` instead.
e.g: `yarn bazel test packages/core/test/bundling/forms:symbol_test`
#### mkdir missing
If you see the following error::
```
ERROR: An error occurred during the fetch of repository 'npm':
Traceback (most recent call last):
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 618, column 15, in _yarn_install_impl
_copy_file(repository_ctx, repository_ctx.attr.package_json)
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 345, column 17, in _copy_file
fail("mkdir -p %s failed: \nSTDOUT:\n%s\nSTDERR:\n%s" % (dirname, result.stdout, result.stderr))
Error in fail: mkdir -p _ failed:
```
The `msys64` library and associated tools (like `mkdir`) are required to build Angular.
Make sure you have `C:\msys64\usr\bin` in the "system" `PATH` rather than the "user" `PATH`.
After that, a `git clean -xfd`, `yarn`, and `node scripts\build\build-packages-dist.js` should resolve this issue.
### Xcode
If you see the following error:
```
$ yarn bazel build packages/...
ERROR: /private/var/tmp/[...]/external/local_config_cc/BUILD:50:5: in apple_cc_toolchain rule @local_config_cc//:cc-compiler-darwin_x86_64: Xcode version must be specified to use an Apple CROSSTOOL
ERROR: Analysis of target '//packages/core/test/render3:render3' failed; build aborted: Analysis of target '@local_config_cc//:cc-compiler-darwin_x86_64' failed; build aborted
```
It might be linked to an interaction with VSCode.
If closing VSCode fixes the issue, you can add the following line to your VSCode configuration:
```
"files.exclude": {"bazel-*": true}
```
source: https://github.com/bazelbuild/bazel/issues/4603
If VSCode is not the root cause, you might try:
- Quit VSCode (make sure no VSCode is running).
```
bazel clean --expunge
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo xcodebuild -license
yarn bazel build //packages/core # Run a build outside VSCode to pre-build the xcode; then safe to run VSCode
```
Source: https://stackoverflow.com/questions/45276830/xcode-version-must-be-specified-to-use-an-apple-crosstool
| docs/BAZEL.md | 1 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.9976636171340942,
0.03082134947180748,
0.00016196686192415655,
0.00017234987171832472,
0.17092108726501465
]
|
{
"id": 1,
"code_window": [
"e.g: `yarn bazel test packages/core/test/bundling/forms:symbol_test`\n",
"\n",
"#### mkdir missing\n",
"If you see the following error::\n",
"```\n",
" \n",
"ERROR: An error occurred during the fetch of repository 'npm':\n",
" Traceback (most recent call last):\n",
" File \"C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl\", line 618, column 15, in _yarn_install_impl\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 276
} | module.exports = function() {
return {name: 'codeGenApi'};
};
| aio/tools/transforms/angular-api-package/tag-defs/codeGenApi.js | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.0001717520790407434,
0.0001717520790407434,
0.0001717520790407434,
0.0001717520790407434,
0
]
|
{
"id": 1,
"code_window": [
"e.g: `yarn bazel test packages/core/test/bundling/forms:symbol_test`\n",
"\n",
"#### mkdir missing\n",
"If you see the following error::\n",
"```\n",
" \n",
"ERROR: An error occurred during the fetch of repository 'npm':\n",
" Traceback (most recent call last):\n",
" File \"C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl\", line 618, column 15, in _yarn_install_impl\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 276
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {getIntParameter} from '../util';
export class TreeNode {
transitiveChildCount: number;
children: TreeNode[];
constructor(
public value: string, public depth: number, public maxDepth: number,
public left: TreeNode|null, public right: TreeNode|null) {
this.transitiveChildCount = Math.pow(2, (this.maxDepth - this.depth + 1)) - 1;
this.children = this.left ? [this.left, this.right!] : [];
}
// Needed for Polymer as it does not support ternary nor modulo operator
// in expressions
get style(): string {
return this.depth % 2 === 0 ? 'background-color: grey' : '';
}
}
let treeCreateCount: number;
let maxDepth: number;
let numberData: TreeNode;
let charData: TreeNode;
export function getMaxDepth() {
return maxDepth;
}
export function initTreeUtils() {
maxDepth = getIntParameter('depth');
treeCreateCount = 0;
numberData = _buildTree(0, numberValues);
charData = _buildTree(0, charValues);
}
function _buildTree(currDepth: number, valueFn: (depth: number) => string): TreeNode {
const children = currDepth < maxDepth ? _buildTree(currDepth + 1, valueFn) : null;
return new TreeNode(valueFn(currDepth), currDepth, maxDepth, children, children);
}
export const emptyTree = new TreeNode('', 0, 0, null, null);
export function buildTree(): TreeNode {
treeCreateCount++;
return treeCreateCount % 2 ? numberData : charData;
}
function numberValues(depth: number): string {
return depth.toString();
}
function charValues(depth: number): string {
return String.fromCharCode('A'.charCodeAt(0) + (depth % 26));
}
export function flattenTree(node: TreeNode, target: TreeNode[] = []): TreeNode[] {
target.push(node);
if (node.left) {
flattenTree(node.left, target);
}
if (node.right) {
flattenTree(node.right, target);
}
return target;
}
export function newArray<T = any>(size: number): T[];
export function newArray<T>(size: number, value: T): T[];
export function newArray<T>(size: number, value?: T): T[] {
const list: T[] = [];
for (let i = 0; i < size; i++) {
list.push(value!);
}
return list;
}
| modules/benchmarks/src/tree/util.ts | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.00017375093011651188,
0.00017042123363353312,
0.00016646157018840313,
0.0001710483484202996,
0.000002209113972639898
]
|
{
"id": 1,
"code_window": [
"e.g: `yarn bazel test packages/core/test/bundling/forms:symbol_test`\n",
"\n",
"#### mkdir missing\n",
"If you see the following error::\n",
"```\n",
" \n",
"ERROR: An error occurred during the fetch of repository 'npm':\n",
" Traceback (most recent call last):\n",
" File \"C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl\", line 618, column 15, in _yarn_install_impl\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 276
} | @use 'sass:map';
@use '../../constants';
@mixin theme($theme) {
$is-dark-theme: map.get($theme, is-dark);
.alert {
color: if($is-dark-theme, constants.$offwhite, constants.$darkgray);
&.is-critical {
border-left: 8px solid constants.$brightred;
background-color: if($is-dark-theme, constants.$deepgray, rgba(constants.$brightred, 0.05));
h1,
h2,
h3,
h4,
h5,
h6 {
color: constants.$brightred;
}
}
&.is-important {
border-left: 8px solid constants.$orange;
background-color: if($is-dark-theme, constants.$deepgray, rgba(constants.$orange, 0.05));
h1,
h2,
h3,
h4,
h5,
h6 {
color: constants.$orange;
}
}
&.is-helpful {
border-left: 8px solid constants.$blue;
background-color: if($is-dark-theme, constants.$deepgray, rgba(constants.$blue, 0.05));
h1,
h2,
h3,
h4,
h5,
h6 {
color: constants.$blue;
}
}
&.archive-warning {
background-color: if($is-dark-theme, constants.$deepgray, constants.$darkred);
* {
color: constants.$white;
}
a {
color: constants.$white;
}
}
}
}
| aio/src/styles/2-modules/alert/_alert-theme.scss | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.0001765696215443313,
0.00017421964730601758,
0.00017121509881690145,
0.00017480032693129033,
0.000001766524064805708
]
|
{
"id": 2,
"code_window": [
"```\n",
"The `msys64` library and associated tools (like `mkdir`) are required to build Angular.\n",
"\n",
"Make sure you have `C:\\msys64\\usr\\bin` in the \"system\" `PATH` rather than the \"user\" `PATH`. \n",
"\n",
"After that, a `git clean -xfd`, `yarn`, and `node scripts\\build\\build-packages-dist.js` should resolve this issue.\n",
"\n",
"### Xcode\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"Make sure you have `C:\\msys64\\usr\\bin` in the \"system\" `PATH` rather than the \"user\" `PATH`.\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 288
} | # Building Angular with Bazel
Note: this doc is for developing Angular, it is _not_ public
documentation for building an Angular application with Bazel.
The Bazel build tool (https://bazel.build) provides fast, reliable
incremental builds. We plan to migrate Angular's build scripts to
Bazel.
## Installation
In order to ensure that everyone builds Angular in a _consistent_ way, Bazel
will be installed through NPM and therefore it's not necessary to install Bazel
manually.
The binaries for Bazel will be provided by the [`@bazel/bazelisk`](https://github.com/bazelbuild/bazelisk)
NPM package and its platform-specific dependencies.
You can access Bazel with the `yarn bazel` command
## Configuration
The `WORKSPACE` file indicates that our root directory is a
Bazel project. It contains the version of the Bazel rules we
use to execute build steps, from `npm_bazel_typescript`.
The sources on [GitHub] are published from Google's internal
repository (google3).
Bazel accepts a lot of options. We check in some options in the
`.bazelrc` file. See the [bazelrc doc]. For example, if you don't
want Bazel to create several symlinks in your project directory
(`bazel-*`) you can add the line `build --symlink_prefix=/` to your
`.bazelrc` file.
[GitHub]: https://github.com/bazelbuild/rules_typescript
[bazelrc doc]: https://bazel.build/versions/master/docs/bazel-user-manual.html#bazelrc
## Building Angular
- Build a package: `yarn bazel build packages/core`
- Build all packages: `yarn bazel build packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources. Note this is
new as of May 2017 and not very stable yet.
[ibazel]: https://github.com/bazelbuild/bazel-watcher
## Testing Angular
- Test package in node: `yarn bazel test packages/core/test:test`
- Test package in karma: `yarn bazel test packages/core/test:test_web`
- Test all packages: `yarn bazel test packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources.
### Various Flags Used For Tests
If you're experiencing problems with seemingly unrelated tests failing, it may be because you're not using the proper flags with your Bazel test runs in Angular.
- `--config=debug`: build and launch in debug mode (see [debugging](#debugging) instructions below)
- `--test_arg=--node_options=--inspect=9228`: change the inspector port.
- `--test_tag_filters=<tag>`: filter tests down to tags defined in the `tag` config of your rules in any given `BUILD.bazel`.
### Debugging a Node Test
<a id="debugging"></a>
- Open chrome at: [chrome://inspect](chrome://inspect)
- Click on `Open dedicated DevTools for Node` to launch a debugger.
- Run test: `yarn bazel test packages/core/test:test --config=debug`
The process should automatically connect to the debugger.
For more, see the [rules_nodejs Debugging documentation](https://bazelbuild.github.io/rules_nodejs/index.html#debugging).
For additional info and testing options, see the
[nodejs_test documentation](https://bazelbuild.github.io/rules_nodejs/Built-ins.html#nodejs_test).
- Click on "Resume script execution" to let the code run until the first `debugger` statement or a previously set breakpoint.
- If you're debugging a test and you want to inspect the generated template instructions, find the template of your component in the call stack and click on `(source mapped from [CompName].js)` at the bottom of the code. You can also disable sourcemaps in the options or go to sources and look into ng:// namespace to see all the generated code.
### Debugging a Node Test in VSCode
First time setup:
- Go to Debug > Add configuration (in the menu bar) to open `launch.json`
- Add the following to the `configurations` array:
```json
{
"type": "node",
"request": "attach",
"name": "Attach to Remote",
"port": 9229
}
```
**Setting breakpoints directly in your code files may not work in VSCode**. This is because the files you're actually debugging are built files that exist in a `./private/...` folder.
The easiest way to debug a test for now is to add a `debugger` statement in the code
and launch the bazel corresponding test (`yarn bazel test <target> --config=debug`).
Bazel will wait on a connection. Go to the debug view (by clicking on the sidebar or
Apple+Shift+D on Mac) and click on the green play icon next to the configuration name
(ie `Attach to Remote`).
### Debugging a Karma Test
- Run test: `yarn bazel run packages/core/test:test_web_chromium` or `yarn bazel run packages/core/test:test_web_firefox`
- Open any browser at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html)
- Open the browser's DevTools to debug the tests (after, for example, having focused on specific tests via `fit` and/or `fdescribe` or having added `debugger` statements in them)
### Debugging Bazel rules
Open `external` directory which contains everything that bazel downloaded while executing the workspace file:
```sh
open $(yarn -s bazel info output_base)/external
```
See subcommands that bazel executes (helpful for debugging):
```sh
yarn bazel build //packages/core:package -s
```
To debug nodejs_binary executable paths uncomment `find . -name rollup 1>&2` (~ line 96) in
```sh
open $(yarn -s bazel info output_base)/external/build_bazel_rules_nodejs/internal/node_launcher.sh
```
## Stamping
Bazel supports the ability to include non-hermetic information from the version control system in built artifacts. This is called stamping.
You can see an overview at https://www.kchodorow.com/blog/2017/03/27/stamping-your-builds/
In our repo, here is how it's configured:
1) In `tools/bazel_stamp_vars.js` we run the `git` commands to generate our versioning info.
1) In `.bazelrc` we register this script as the value for the `workspace_status_command` flag. Bazel will run the script when it needs to stamp a binary.
Note that Bazel has a `--stamp` argument to `yarn bazel build`, but this has no effect since our stamping takes place in Skylark rules. See https://github.com/bazelbuild/bazel/issues/1054
## Remote cache
Bazel supports fetching action results from a cache, allowing a clean build to pick up artifacts from prior builds.
This makes builds incremental, even on CI.
It works because Bazel assigns a content-based hash to all action inputs, which is used as the cache key for the action outputs.
Thanks to the hermeticity property, we can skip executing an action if the inputs hash is already present in the cache.
Of course, non-hermeticity in an action can cause problems.
At worst, you can fetch a broken artifact from the cache, making your build non-reproducible.
For this reason, we are careful to implement our Bazel rules to depend only on their inputs.
Currently we only use remote caching on CircleCI and we let Angular core developers enable remote caching to speed up their builds.
### Remote cache in development
To enable remote caching for your build:
1. Go to the service accounts for the ["internal" project](https://console.cloud.google.com/iam-admin/serviceaccounts?project=internal-200822)
1. Select "Angular local dev", click on "Edit", scroll to the bottom, and click "Create key"
1. When the pop-up shows, select "JSON" for "Key type" and click "Create"
1. Save the key in a secure location
1. Create a file called `.bazelrc.user` in the root directory of the workspace, and add the following content:
```
build --config=angular-team --google_credentials=[ABSOLUTE_PATH_TO_SERVICE_KEY]
```
### Remote cache for Circle CI
This feature is experimental, and developed by the CircleCI team with guidance from Angular.
Contact Alex Eagle with questions.
*How it's configured*:
1. In `.circleci/config.yml`, each CircleCI job downloads a proxy binary, which is built from https://github.com/notnoopci/bazel-remote-proxy. The download is done by running `.circleci/setup_cache.sh`. When the feature graduates from experimental, this proxy will be installed by default on every CircleCI worker, and this step will not be needed.
1. Next, each job runs the `setup-bazel-remote-cache` anchor. This starts up the proxy running in the background. In the CircleCI UI, you'll see this step continues running while later steps run, and you can see logging from the proxy process.
1. Bazel must be configured to connect to the proxy on a local port. This configuration lives in `.circleci/bazel.linux.rc` and is enabled because we overwrite the system Bazel settings in /etc/bazel.bazelrc with this file.
1. Each `bazel` command in `.circleci/config.yml` picks up and uses the caching flags.
## Diagnosing slow builds
If a build seems slow you can use Bazel to diagnose where time is spent.
The first step is to generate a profile of the build using the `--profile filename_name.profile` flag.
```
yarn bazel build //packages/compiler --profile filename_name.profile
```
This will generate a `filename_name.profile` that you can then analyse using [analyze-profile](https://docs.bazel.build/versions/master/user-manual.html#analyze-profile) command.
## Using the console profile report
You can obtain a simple report directly in the console by running:
```
yarn bazel analyze-profile filename_name.profile
```
This will show the phase summary, individual phase information and critical path.
You can also list all individual tasks and the time they took using `--task_tree`.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*"
```
To show all tasks that take longer than a certain threshold, use the `--task_tree_threshold` flag.
The default behavior is to use a 50ms threshold.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*" --task_tree_threshold 5000
```
`--task_tree` takes a regexp as argument that filters by the text shown after the time taken.
Compiling TypeScript shows as:
```
70569 ACTION_EXECUTE (10974.826 ms) Compiling TypeScript (devmode) //packages/compiler:compiler []
```
To filter all tasks by TypeScript compilations that took more than 5 seconds, use:
```
yarn bazel analyze-profile filename_name.profile --task_tree "Compiling TypeScript" --task_tree_threshold 5000
```
### Using the HTML profile report
A more comprehensive way to visualize the profile information is through the HTML report:
```
yarn bazel analyze-profile filename_name.profile --html --html_details --html_histograms
```
This will generate a `filename_name.profile.html` file that you can open in your browser.
On the upper right corner that is a small table of contents with links to three areas: Tasks, Legend and Statistics.
In the Tasks section you will find a graph of where time is spent. Legend shows what the colors in the Tasks graph mean.
Hovering over the background will show what phase that is, while hovering over bars will show more details about that specific action.
The Statistics section shows how long each phase took and how time was spent in that phase.
Usually the longest one is the execution phase, which also includes critical path information.
Also in the Statistics section are the Skylark statistic, split in User-Defined and Builtin function execution time.
You can click the "self" header twice to order the table by functions where the most time (in ms) is spent.
When diagnosing slow builds you should focus on the top time spenders across all phases and functions.
Usually there is a single item (or multiple items of the same kind) where the overwhelming majority of time is spent.
## Known issues
### Windows
#### bazel run
If you see the following error:
```
Error: Cannot find module 'C:\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\c;C:\msys64\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\packages\core\test\bundling\hello_world\symbol_test_require_patch.js'
Require stack:
- internal/preload
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Module.require (internal/modules/cjs/loader.js:848:19)
at Module._preloadModules (internal/modules/cjs/loader.js:1133:12)
at loadPreloadModules (internal/bootstrap/pre_execution.js:443:5)
at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:62:3)
at internal/main/run_main_module.js:7:1 {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'internal/preload' ]
```
`bazel run` only works in Bazel Windows with non-test targets. Ensure that you are using `bazel test` instead.
e.g: `yarn bazel test packages/core/test/bundling/forms:symbol_test`
#### mkdir missing
If you see the following error::
```
ERROR: An error occurred during the fetch of repository 'npm':
Traceback (most recent call last):
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 618, column 15, in _yarn_install_impl
_copy_file(repository_ctx, repository_ctx.attr.package_json)
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 345, column 17, in _copy_file
fail("mkdir -p %s failed: \nSTDOUT:\n%s\nSTDERR:\n%s" % (dirname, result.stdout, result.stderr))
Error in fail: mkdir -p _ failed:
```
The `msys64` library and associated tools (like `mkdir`) are required to build Angular.
Make sure you have `C:\msys64\usr\bin` in the "system" `PATH` rather than the "user" `PATH`.
After that, a `git clean -xfd`, `yarn`, and `node scripts\build\build-packages-dist.js` should resolve this issue.
### Xcode
If you see the following error:
```
$ yarn bazel build packages/...
ERROR: /private/var/tmp/[...]/external/local_config_cc/BUILD:50:5: in apple_cc_toolchain rule @local_config_cc//:cc-compiler-darwin_x86_64: Xcode version must be specified to use an Apple CROSSTOOL
ERROR: Analysis of target '//packages/core/test/render3:render3' failed; build aborted: Analysis of target '@local_config_cc//:cc-compiler-darwin_x86_64' failed; build aborted
```
It might be linked to an interaction with VSCode.
If closing VSCode fixes the issue, you can add the following line to your VSCode configuration:
```
"files.exclude": {"bazel-*": true}
```
source: https://github.com/bazelbuild/bazel/issues/4603
If VSCode is not the root cause, you might try:
- Quit VSCode (make sure no VSCode is running).
```
bazel clean --expunge
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo xcodebuild -license
yarn bazel build //packages/core # Run a build outside VSCode to pre-build the xcode; then safe to run VSCode
```
Source: https://stackoverflow.com/questions/45276830/xcode-version-must-be-specified-to-use-an-apple-crosstool
| docs/BAZEL.md | 1 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.6633713245391846,
0.020623639225959778,
0.00016334348765667528,
0.00019241051631979644,
0.11362747848033905
]
|
{
"id": 2,
"code_window": [
"```\n",
"The `msys64` library and associated tools (like `mkdir`) are required to build Angular.\n",
"\n",
"Make sure you have `C:\\msys64\\usr\\bin` in the \"system\" `PATH` rather than the \"user\" `PATH`. \n",
"\n",
"After that, a `git clean -xfd`, `yarn`, and `node scripts\\build\\build-packages-dist.js` should resolve this issue.\n",
"\n",
"### Xcode\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"Make sure you have `C:\\msys64\\usr\\bin` in the \"system\" `PATH` rather than the \"user\" `PATH`.\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 288
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AbsoluteFsPath, isLocalRelativePath, relative} from '../../../src/ngtsc/file_system';
import {DependencyTracker} from '../../../src/ngtsc/incremental/api';
export function isWithinPackage(packagePath: AbsoluteFsPath, filePath: AbsoluteFsPath): boolean {
const relativePath = relative(packagePath, filePath);
return isLocalRelativePath(relativePath) && !relativePath.startsWith('node_modules/');
}
class NoopDependencyTracker implements DependencyTracker {
addDependency(): void {}
addResourceDependency(): void {}
recordDependencyAnalysisFailure(): void {}
}
export const NOOP_DEPENDENCY_TRACKER: DependencyTracker = new NoopDependencyTracker();
| packages/compiler-cli/ngcc/src/analysis/util.ts | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.0012476672418415546,
0.0005287863314151764,
0.00016852559929247946,
0.00017016615311149508,
0.0005083259893581271
]
|
{
"id": 2,
"code_window": [
"```\n",
"The `msys64` library and associated tools (like `mkdir`) are required to build Angular.\n",
"\n",
"Make sure you have `C:\\msys64\\usr\\bin` in the \"system\" `PATH` rather than the \"user\" `PATH`. \n",
"\n",
"After that, a `git clean -xfd`, `yarn`, and `node scripts\\build\\build-packages-dist.js` should resolve this issue.\n",
"\n",
"### Xcode\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"Make sure you have `C:\\msys64\\usr\\bin` in the \"system\" `PATH` rather than the \"user\" `PATH`.\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 288
} | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
ts_library(
name = "selector_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/platform-browser/testing",
],
)
jasmine_node_test(
name = "selector",
bootstrap = ["//tools/testing:node_es2015"],
deps = [
":selector_lib",
],
)
karma_web_test_suite(
name = "selector_web",
deps = [
":selector_lib",
],
)
| packages/compiler/test/selector/BUILD.bazel | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.0002172463427996263,
0.00018582619668450207,
0.00016974691243376583,
0.0001704852911643684,
0.00002221945396740921
]
|
{
"id": 2,
"code_window": [
"```\n",
"The `msys64` library and associated tools (like `mkdir`) are required to build Angular.\n",
"\n",
"Make sure you have `C:\\msys64\\usr\\bin` in the \"system\" `PATH` rather than the \"user\" `PATH`. \n",
"\n",
"After that, a `git clean -xfd`, `yarn`, and `node scripts\\build\\build-packages-dist.js` should resolve this issue.\n",
"\n",
"### Xcode\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"Make sure you have `C:\\msys64\\usr\\bin` in the \"system\" `PATH` rather than the \"user\" `PATH`.\n"
],
"file_path": "docs/BAZEL.md",
"type": "replace",
"edit_start_line_idx": 288
} | function MyComponent_div_0_Template(rf, ctx) {
if (rf & 1) {
const $s$ = $r3$.ɵɵgetCurrentView();
$r3$.ɵɵelementStart(0, "div", 1);
$r3$.ɵɵlistener("click", function MyComponent_div_0_Template_div_click_0_listener() {
const $sr$ = $r3$.ɵɵrestoreView($s$);
const $d$ = $sr$.$implicit;
const $i$ = $sr$.index;
const $comp$ = $r3$.ɵɵnextContext();
return $comp$._handleClick($d$, $i$);
});
$r3$.ɵɵelementEnd();
}
}
…
consts: [
[__AttributeMarker.Bindings__, "click", __AttributeMarker.Template__, "ngFor", "ngForOf"],
[__AttributeMarker.Bindings__, "click"]
],
template: function MyComponent_Template(rf, ctx) {
if (rf & 1) {
$r3$.ɵɵtemplate(0, MyComponent_div_0_Template, 1, 0, "div", 0);
}
if (rf & 2) {
$r3$.ɵɵproperty("ngForOf", ctx._data);
}
}
| packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/nested_template_context_many_bindings_template.js | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.00017331246635876596,
0.0001709818170638755,
0.00016930159472394735,
0.0001703314046608284,
0.0000017007948827085784
]
|
{
"id": 3,
"code_window": [
"\"\"\"Re-export of some bazel rules with repository-wide defaults.\"\"\"\n",
"\n",
"load(\"@rules_pkg//:pkg.bzl\", \"pkg_tar\")\n",
"load(\"@build_bazel_rules_nodejs//:index.bzl\", _nodejs_binary = \"nodejs_binary\", _pkg_npm = \"pkg_npm\")\n",
"load(\"@npm//@bazel/jasmine:index.bzl\", _jasmine_node_test = \"jasmine_node_test\")\n",
"load(\"@npm//@bazel/concatjs:index.bzl\", _concatjs_devserver = \"concatjs_devserver\", _karma_web_test = \"karma_web_test\", _karma_web_test_suite = \"karma_web_test_suite\")\n",
"load(\"@npm//@bazel/rollup:index.bzl\", _rollup_bundle = \"rollup_bundle\")\n",
"load(\"@npm//@bazel/terser:index.bzl\", \"terser_minified\")\n",
"load(\"@npm//@bazel/typescript:index.bzl\", _ts_config = \"ts_config\", _ts_library = \"ts_library\")\n",
"load(\"@npm//@bazel/protractor:index.bzl\", _protractor_web_test_suite = \"protractor_web_test_suite\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"@npm//@bazel/concatjs:index.bzl\", _concatjs_devserver = \"concatjs_devserver\")\n"
],
"file_path": "tools/defaults.bzl",
"type": "replace",
"edit_start_line_idx": 5
} | # Building Angular with Bazel
Note: this doc is for developing Angular, it is _not_ public
documentation for building an Angular application with Bazel.
The Bazel build tool (https://bazel.build) provides fast, reliable
incremental builds. We plan to migrate Angular's build scripts to
Bazel.
## Installation
In order to ensure that everyone builds Angular in a _consistent_ way, Bazel
will be installed through NPM and therefore it's not necessary to install Bazel
manually.
The binaries for Bazel will be provided by the [`@bazel/bazelisk`](https://github.com/bazelbuild/bazelisk)
NPM package and its platform-specific dependencies.
You can access Bazel with the `yarn bazel` command
## Configuration
The `WORKSPACE` file indicates that our root directory is a
Bazel project. It contains the version of the Bazel rules we
use to execute build steps, from `npm_bazel_typescript`.
The sources on [GitHub] are published from Google's internal
repository (google3).
Bazel accepts a lot of options. We check in some options in the
`.bazelrc` file. See the [bazelrc doc]. For example, if you don't
want Bazel to create several symlinks in your project directory
(`bazel-*`) you can add the line `build --symlink_prefix=/` to your
`.bazelrc` file.
[GitHub]: https://github.com/bazelbuild/rules_typescript
[bazelrc doc]: https://bazel.build/versions/master/docs/bazel-user-manual.html#bazelrc
## Building Angular
- Build a package: `yarn bazel build packages/core`
- Build all packages: `yarn bazel build packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources. Note this is
new as of May 2017 and not very stable yet.
[ibazel]: https://github.com/bazelbuild/bazel-watcher
## Testing Angular
- Test package in node: `yarn bazel test packages/core/test:test`
- Test package in karma: `yarn bazel test packages/core/test:test_web`
- Test all packages: `yarn bazel test packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources.
### Various Flags Used For Tests
If you're experiencing problems with seemingly unrelated tests failing, it may be because you're not using the proper flags with your Bazel test runs in Angular.
- `--config=debug`: build and launch in debug mode (see [debugging](#debugging) instructions below)
- `--test_arg=--node_options=--inspect=9228`: change the inspector port.
- `--test_tag_filters=<tag>`: filter tests down to tags defined in the `tag` config of your rules in any given `BUILD.bazel`.
### Debugging a Node Test
<a id="debugging"></a>
- Open chrome at: [chrome://inspect](chrome://inspect)
- Click on `Open dedicated DevTools for Node` to launch a debugger.
- Run test: `yarn bazel test packages/core/test:test --config=debug`
The process should automatically connect to the debugger.
For more, see the [rules_nodejs Debugging documentation](https://bazelbuild.github.io/rules_nodejs/index.html#debugging).
For additional info and testing options, see the
[nodejs_test documentation](https://bazelbuild.github.io/rules_nodejs/Built-ins.html#nodejs_test).
- Click on "Resume script execution" to let the code run until the first `debugger` statement or a previously set breakpoint.
- If you're debugging a test and you want to inspect the generated template instructions, find the template of your component in the call stack and click on `(source mapped from [CompName].js)` at the bottom of the code. You can also disable sourcemaps in the options or go to sources and look into ng:// namespace to see all the generated code.
### Debugging a Node Test in VSCode
First time setup:
- Go to Debug > Add configuration (in the menu bar) to open `launch.json`
- Add the following to the `configurations` array:
```json
{
"type": "node",
"request": "attach",
"name": "Attach to Remote",
"port": 9229
}
```
**Setting breakpoints directly in your code files may not work in VSCode**. This is because the files you're actually debugging are built files that exist in a `./private/...` folder.
The easiest way to debug a test for now is to add a `debugger` statement in the code
and launch the bazel corresponding test (`yarn bazel test <target> --config=debug`).
Bazel will wait on a connection. Go to the debug view (by clicking on the sidebar or
Apple+Shift+D on Mac) and click on the green play icon next to the configuration name
(ie `Attach to Remote`).
### Debugging a Karma Test
- Run test: `yarn bazel run packages/core/test:test_web_chromium` or `yarn bazel run packages/core/test:test_web_firefox`
- Open any browser at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html)
- Open the browser's DevTools to debug the tests (after, for example, having focused on specific tests via `fit` and/or `fdescribe` or having added `debugger` statements in them)
### Debugging Bazel rules
Open `external` directory which contains everything that bazel downloaded while executing the workspace file:
```sh
open $(yarn -s bazel info output_base)/external
```
See subcommands that bazel executes (helpful for debugging):
```sh
yarn bazel build //packages/core:package -s
```
To debug nodejs_binary executable paths uncomment `find . -name rollup 1>&2` (~ line 96) in
```sh
open $(yarn -s bazel info output_base)/external/build_bazel_rules_nodejs/internal/node_launcher.sh
```
## Stamping
Bazel supports the ability to include non-hermetic information from the version control system in built artifacts. This is called stamping.
You can see an overview at https://www.kchodorow.com/blog/2017/03/27/stamping-your-builds/
In our repo, here is how it's configured:
1) In `tools/bazel_stamp_vars.js` we run the `git` commands to generate our versioning info.
1) In `.bazelrc` we register this script as the value for the `workspace_status_command` flag. Bazel will run the script when it needs to stamp a binary.
Note that Bazel has a `--stamp` argument to `yarn bazel build`, but this has no effect since our stamping takes place in Skylark rules. See https://github.com/bazelbuild/bazel/issues/1054
## Remote cache
Bazel supports fetching action results from a cache, allowing a clean build to pick up artifacts from prior builds.
This makes builds incremental, even on CI.
It works because Bazel assigns a content-based hash to all action inputs, which is used as the cache key for the action outputs.
Thanks to the hermeticity property, we can skip executing an action if the inputs hash is already present in the cache.
Of course, non-hermeticity in an action can cause problems.
At worst, you can fetch a broken artifact from the cache, making your build non-reproducible.
For this reason, we are careful to implement our Bazel rules to depend only on their inputs.
Currently we only use remote caching on CircleCI and we let Angular core developers enable remote caching to speed up their builds.
### Remote cache in development
To enable remote caching for your build:
1. Go to the service accounts for the ["internal" project](https://console.cloud.google.com/iam-admin/serviceaccounts?project=internal-200822)
1. Select "Angular local dev", click on "Edit", scroll to the bottom, and click "Create key"
1. When the pop-up shows, select "JSON" for "Key type" and click "Create"
1. Save the key in a secure location
1. Create a file called `.bazelrc.user` in the root directory of the workspace, and add the following content:
```
build --config=angular-team --google_credentials=[ABSOLUTE_PATH_TO_SERVICE_KEY]
```
### Remote cache for Circle CI
This feature is experimental, and developed by the CircleCI team with guidance from Angular.
Contact Alex Eagle with questions.
*How it's configured*:
1. In `.circleci/config.yml`, each CircleCI job downloads a proxy binary, which is built from https://github.com/notnoopci/bazel-remote-proxy. The download is done by running `.circleci/setup_cache.sh`. When the feature graduates from experimental, this proxy will be installed by default on every CircleCI worker, and this step will not be needed.
1. Next, each job runs the `setup-bazel-remote-cache` anchor. This starts up the proxy running in the background. In the CircleCI UI, you'll see this step continues running while later steps run, and you can see logging from the proxy process.
1. Bazel must be configured to connect to the proxy on a local port. This configuration lives in `.circleci/bazel.linux.rc` and is enabled because we overwrite the system Bazel settings in /etc/bazel.bazelrc with this file.
1. Each `bazel` command in `.circleci/config.yml` picks up and uses the caching flags.
## Diagnosing slow builds
If a build seems slow you can use Bazel to diagnose where time is spent.
The first step is to generate a profile of the build using the `--profile filename_name.profile` flag.
```
yarn bazel build //packages/compiler --profile filename_name.profile
```
This will generate a `filename_name.profile` that you can then analyse using [analyze-profile](https://docs.bazel.build/versions/master/user-manual.html#analyze-profile) command.
## Using the console profile report
You can obtain a simple report directly in the console by running:
```
yarn bazel analyze-profile filename_name.profile
```
This will show the phase summary, individual phase information and critical path.
You can also list all individual tasks and the time they took using `--task_tree`.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*"
```
To show all tasks that take longer than a certain threshold, use the `--task_tree_threshold` flag.
The default behavior is to use a 50ms threshold.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*" --task_tree_threshold 5000
```
`--task_tree` takes a regexp as argument that filters by the text shown after the time taken.
Compiling TypeScript shows as:
```
70569 ACTION_EXECUTE (10974.826 ms) Compiling TypeScript (devmode) //packages/compiler:compiler []
```
To filter all tasks by TypeScript compilations that took more than 5 seconds, use:
```
yarn bazel analyze-profile filename_name.profile --task_tree "Compiling TypeScript" --task_tree_threshold 5000
```
### Using the HTML profile report
A more comprehensive way to visualize the profile information is through the HTML report:
```
yarn bazel analyze-profile filename_name.profile --html --html_details --html_histograms
```
This will generate a `filename_name.profile.html` file that you can open in your browser.
On the upper right corner that is a small table of contents with links to three areas: Tasks, Legend and Statistics.
In the Tasks section you will find a graph of where time is spent. Legend shows what the colors in the Tasks graph mean.
Hovering over the background will show what phase that is, while hovering over bars will show more details about that specific action.
The Statistics section shows how long each phase took and how time was spent in that phase.
Usually the longest one is the execution phase, which also includes critical path information.
Also in the Statistics section are the Skylark statistic, split in User-Defined and Builtin function execution time.
You can click the "self" header twice to order the table by functions where the most time (in ms) is spent.
When diagnosing slow builds you should focus on the top time spenders across all phases and functions.
Usually there is a single item (or multiple items of the same kind) where the overwhelming majority of time is spent.
## Known issues
### Windows
#### bazel run
If you see the following error:
```
Error: Cannot find module 'C:\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\c;C:\msys64\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\packages\core\test\bundling\hello_world\symbol_test_require_patch.js'
Require stack:
- internal/preload
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Module.require (internal/modules/cjs/loader.js:848:19)
at Module._preloadModules (internal/modules/cjs/loader.js:1133:12)
at loadPreloadModules (internal/bootstrap/pre_execution.js:443:5)
at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:62:3)
at internal/main/run_main_module.js:7:1 {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'internal/preload' ]
```
`bazel run` only works in Bazel Windows with non-test targets. Ensure that you are using `bazel test` instead.
e.g: `yarn bazel test packages/core/test/bundling/forms:symbol_test`
#### mkdir missing
If you see the following error::
```
ERROR: An error occurred during the fetch of repository 'npm':
Traceback (most recent call last):
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 618, column 15, in _yarn_install_impl
_copy_file(repository_ctx, repository_ctx.attr.package_json)
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 345, column 17, in _copy_file
fail("mkdir -p %s failed: \nSTDOUT:\n%s\nSTDERR:\n%s" % (dirname, result.stdout, result.stderr))
Error in fail: mkdir -p _ failed:
```
The `msys64` library and associated tools (like `mkdir`) are required to build Angular.
Make sure you have `C:\msys64\usr\bin` in the "system" `PATH` rather than the "user" `PATH`.
After that, a `git clean -xfd`, `yarn`, and `node scripts\build\build-packages-dist.js` should resolve this issue.
### Xcode
If you see the following error:
```
$ yarn bazel build packages/...
ERROR: /private/var/tmp/[...]/external/local_config_cc/BUILD:50:5: in apple_cc_toolchain rule @local_config_cc//:cc-compiler-darwin_x86_64: Xcode version must be specified to use an Apple CROSSTOOL
ERROR: Analysis of target '//packages/core/test/render3:render3' failed; build aborted: Analysis of target '@local_config_cc//:cc-compiler-darwin_x86_64' failed; build aborted
```
It might be linked to an interaction with VSCode.
If closing VSCode fixes the issue, you can add the following line to your VSCode configuration:
```
"files.exclude": {"bazel-*": true}
```
source: https://github.com/bazelbuild/bazel/issues/4603
If VSCode is not the root cause, you might try:
- Quit VSCode (make sure no VSCode is running).
```
bazel clean --expunge
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo xcodebuild -license
yarn bazel build //packages/core # Run a build outside VSCode to pre-build the xcode; then safe to run VSCode
```
Source: https://stackoverflow.com/questions/45276830/xcode-version-must-be-specified-to-use-an-apple-crosstool
| docs/BAZEL.md | 1 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.002160996198654175,
0.00032080773962661624,
0.00016096765466500074,
0.00017252154066227376,
0.00038315707934089005
]
|
{
"id": 3,
"code_window": [
"\"\"\"Re-export of some bazel rules with repository-wide defaults.\"\"\"\n",
"\n",
"load(\"@rules_pkg//:pkg.bzl\", \"pkg_tar\")\n",
"load(\"@build_bazel_rules_nodejs//:index.bzl\", _nodejs_binary = \"nodejs_binary\", _pkg_npm = \"pkg_npm\")\n",
"load(\"@npm//@bazel/jasmine:index.bzl\", _jasmine_node_test = \"jasmine_node_test\")\n",
"load(\"@npm//@bazel/concatjs:index.bzl\", _concatjs_devserver = \"concatjs_devserver\", _karma_web_test = \"karma_web_test\", _karma_web_test_suite = \"karma_web_test_suite\")\n",
"load(\"@npm//@bazel/rollup:index.bzl\", _rollup_bundle = \"rollup_bundle\")\n",
"load(\"@npm//@bazel/terser:index.bzl\", \"terser_minified\")\n",
"load(\"@npm//@bazel/typescript:index.bzl\", _ts_config = \"ts_config\", _ts_library = \"ts_library\")\n",
"load(\"@npm//@bazel/protractor:index.bzl\", _protractor_web_test_suite = \"protractor_web_test_suite\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"@npm//@bazel/concatjs:index.bzl\", _concatjs_devserver = \"concatjs_devserver\")\n"
],
"file_path": "tools/defaults.bzl",
"type": "replace",
"edit_start_line_idx": 5
} |
<div>
<h1>Binding syntax</h1>
<hr />
<div>
<h2>Button disabled state bound to isUnchanged property</h2>
<!-- #docregion disabled-button -->
<!-- Bind button disabled state to `isUnchanged` property -->
<button type="button" [disabled]="isUnchanged">Save</button>
<!-- #enddocregion disabled-button -->
</div>
<hr />
<div (keyup)="0">
<h2>HTML attributes and DOM properties</h2>
<p>1. Use the inspector to see the HTML attribute and DOM property values. Click the buttons to log values to the console.</p>
<label>HTML Attribute Initializes to "Sarah":
<input type="text" value="Sarah" #bindingInput></label>
<div>
<button type="button" (click)="getHTMLAttributeValue()">Get HTML attribute value</button> Won't change.
</div>
<div>
<button type="button" (click)="getDOMPropertyValue()">Get DOM property value</button> Changeable. Angular works with these.
</div>
<p>2. Change the name in the input and click the buttons again.</p>
</div>
<hr />
<div>
<h3>Disabled property vs. attribute</h3>
<p>Use the inspector to see the Test Button work and its disabled property toggle.</p>
<div>
<button type="button" id="testButton" (click)="working()">Test Button</button>
</div>
<div>
<button type="button" (click)="toggleDisabled()">Toggle disabled property for Test Button</button>
</div>
</div>
| aio/content/examples/binding-syntax/src/app/app.component.html | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.00017314001161139458,
0.0001711439690552652,
0.00016665579460095614,
0.00017259179730899632,
0.0000023940799565025372
]
|
{
"id": 3,
"code_window": [
"\"\"\"Re-export of some bazel rules with repository-wide defaults.\"\"\"\n",
"\n",
"load(\"@rules_pkg//:pkg.bzl\", \"pkg_tar\")\n",
"load(\"@build_bazel_rules_nodejs//:index.bzl\", _nodejs_binary = \"nodejs_binary\", _pkg_npm = \"pkg_npm\")\n",
"load(\"@npm//@bazel/jasmine:index.bzl\", _jasmine_node_test = \"jasmine_node_test\")\n",
"load(\"@npm//@bazel/concatjs:index.bzl\", _concatjs_devserver = \"concatjs_devserver\", _karma_web_test = \"karma_web_test\", _karma_web_test_suite = \"karma_web_test_suite\")\n",
"load(\"@npm//@bazel/rollup:index.bzl\", _rollup_bundle = \"rollup_bundle\")\n",
"load(\"@npm//@bazel/terser:index.bzl\", \"terser_minified\")\n",
"load(\"@npm//@bazel/typescript:index.bzl\", _ts_config = \"ts_config\", _ts_library = \"ts_library\")\n",
"load(\"@npm//@bazel/protractor:index.bzl\", _protractor_web_test_suite = \"protractor_web_test_suite\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"@npm//@bazel/concatjs:index.bzl\", _concatjs_devserver = \"concatjs_devserver\")\n"
],
"file_path": "tools/defaults.bzl",
"type": "replace",
"edit_start_line_idx": 5
} | @use 'sass:math';
@use '../../mixins';
$tocItemLineHeight: 24;
$tocItemTopPadding: 9;
$tocMarkerRailSize: 1;
$tocMarkerSize: 6;
@mixin tocMarker() {
border-radius: 50%;
content: "";
height: #{$tocMarkerSize}px;
left: -#{math.div($tocMarkerSize - $tocMarkerRailSize, 2)}px;
position: absolute;
top: calc(#{$tocItemTopPadding}px + #{math.div($tocItemLineHeight, 2)}px - #{math.div($tocMarkerSize, 2)}px);
top: calc(#{$tocItemTopPadding}px + #{math.div($tocItemLineHeight, 2 * 10)}rem - #{math.div($tocMarkerSize, 2)}px);
width: #{$tocMarkerSize}px;
}
.toc-container {
width: 18vw;
position: fixed;
top: 76px;
right: 0;
bottom: 12px;
overflow-y: auto;
overflow-x: hidden;
}
aio-toc {
.toc-inner {
@include mixins.font-size(13);
overflow-y: visible;
padding: 4px 0 0 10px;
.toc-heading,
.toc-list .h1 {
@include mixins.font-size(16);
}
.toc-heading {
font-weight: 500;
margin: 0 0 16px 8px;
padding: 0;
&.secondary {
position: relative;
top: -8px;
}
}
button {
&.toc-heading,
&.toc-more-items {
cursor: pointer;
display: inline-block;
background: 0;
background-color: transparent;
border: none;
box-shadow: none;
padding: 0;
text-align: start;
&.embedded:focus {
outline: none;
}
}
&.toc-heading {
mat-icon.rotating-icon {
height: 18px;
width: 18px;
position: relative;
left: -4px;
top: 5px;
}
}
&.toc-more-items {
top: 10px;
position: relative;
&::after {
content: "expand_less";
}
&.collapsed::after {
content: "more_horiz";
}
}
}
.mat-icon {
&.collapsed {
@include mixins.rotate(0deg);
}
&:not(.collapsed) {
@include mixins.rotate(90deg);
}
}
ul.toc-list {
list-style-type: none;
margin: 0;
padding: 0 8px 0 0;
@media (max-width: 800px) {
width: auto;
}
li {
box-sizing: border-box;
@include mixins.line-height($tocItemLineHeight);
padding: #{$tocItemTopPadding}px 0 #{$tocItemTopPadding}px 12px;
position: relative;
transition: all 0.3s ease-in-out;
&.h1:after {
content: "";
display: block;
height: 1px;
width: 40%;
margin: 7px 0 4px 0;
clear: both;
}
&.h3 {
padding-left: 24px;
}
a {
overflow: visible;
@include mixins.font-size(14);
line-height: inherit;
display: table-cell;
}
&.active {
* {
font-weight: 500;
}
a:before {
@include tocMarker();
}
}
}
&:not(.embedded) li {
&:before {
bottom: 0;
content: "";
left: 0;
position: absolute;
top: 0;
border-left-width: #{$tocMarkerRailSize}px;
border-left-style: solid;
}
&:first-child:before {
top: calc(#{$tocItemTopPadding}px + #{math.div($tocItemLineHeight, 2)}px - #{math.div($tocMarkerSize, 2)}px);
top: calc(#{$tocItemTopPadding}px + #{math.div($tocItemLineHeight, 2 * 10)}rem - #{math.div($tocMarkerSize, 2)}px);
}
&:last-child:before {
bottom: calc(100% - (#{$tocItemTopPadding}px + #{math.div($tocItemLineHeight, 2)}px + #{math.div($tocMarkerSize, 2)}px));
bottom: calc(100% - (#{$tocItemTopPadding}px + #{math.div($tocItemLineHeight, 2 * 10)}rem + #{math.div($tocMarkerSize, 2)}px));
}
&:not(.active):hover {
a:before {
@include tocMarker();
}
}
}
}
}
// Alternative TOC View for Smaller Screens
&.embedded {
@media (min-width: 801px) {
display: none;
}
.toc-inner {
padding: 12px 0 0 0;
.toc-heading {
margin: 0 0 8px;
}
&.collapsed {
.secondary {
display: none;
}
}
}
}
}
| aio/src/styles/2-modules/toc/_toc.scss | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.00018217229808215052,
0.00017321074847131968,
0.00016959937056526542,
0.00017269582895096391,
0.000002462796828694991
]
|
{
"id": 3,
"code_window": [
"\"\"\"Re-export of some bazel rules with repository-wide defaults.\"\"\"\n",
"\n",
"load(\"@rules_pkg//:pkg.bzl\", \"pkg_tar\")\n",
"load(\"@build_bazel_rules_nodejs//:index.bzl\", _nodejs_binary = \"nodejs_binary\", _pkg_npm = \"pkg_npm\")\n",
"load(\"@npm//@bazel/jasmine:index.bzl\", _jasmine_node_test = \"jasmine_node_test\")\n",
"load(\"@npm//@bazel/concatjs:index.bzl\", _concatjs_devserver = \"concatjs_devserver\", _karma_web_test = \"karma_web_test\", _karma_web_test_suite = \"karma_web_test_suite\")\n",
"load(\"@npm//@bazel/rollup:index.bzl\", _rollup_bundle = \"rollup_bundle\")\n",
"load(\"@npm//@bazel/terser:index.bzl\", \"terser_minified\")\n",
"load(\"@npm//@bazel/typescript:index.bzl\", _ts_config = \"ts_config\", _ts_library = \"ts_library\")\n",
"load(\"@npm//@bazel/protractor:index.bzl\", _protractor_web_test_suite = \"protractor_web_test_suite\")\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"@npm//@bazel/concatjs:index.bzl\", _concatjs_devserver = \"concatjs_devserver\")\n"
],
"file_path": "tools/defaults.bzl",
"type": "replace",
"edit_start_line_idx": 5
} | load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary")
load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
exports_files(["launcher_template.sh"])
ts_library(
name = "dev-server_lib",
srcs = [
"dev-server.ts",
"ibazel.ts",
"main.ts",
],
# TODO(ESM): remove this once the Bazel NodeJS rules can handle ESM with `nodejs_binary`.
devmode_module = "commonjs",
deps = [
"@npm//@types/browser-sync",
"@npm//@types/minimist",
"@npm//@types/node",
"@npm//@types/send",
"@npm//browser-sync",
"@npm//minimist",
"@npm//send",
],
)
nodejs_binary(
name = "dev-server_bin",
data = [
":dev-server_lib",
],
entry_point = ":main.ts",
# TODO(josephperrott): update dependency usages to no longer need bazel patch module resolver
# See: https://github.com/bazelbuild/rules_nodejs/wiki#--bazel_patch_module_resolver-now-defaults-to-false-2324
templated_args = ["--bazel_patch_module_resolver"],
)
| devtools/tools/dev-server/BUILD.bazel | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.003984108567237854,
0.0012083626352250576,
0.00016761438746470958,
0.000340863800374791,
0.001604140386916697
]
|
{
"id": 4,
"code_window": [
"load(\"@npm//typescript:index.bzl\", \"tsc\")\n",
"load(\"//packages/bazel:index.bzl\", _ng_module = \"ng_module\", _ng_package = \"ng_package\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/benchmark/app_bundling:index.bzl\", _app_bundle = \"app_bundle\")\n",
"load(\"//tools:ng_benchmark.bzl\", _ng_benchmark = \"ng_benchmark\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/api-golden:index.bzl\", _api_golden_test = \"api_golden_test\", _api_golden_test_npm_package = \"api_golden_test_npm_package\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel:extract_js_module_output.bzl\", \"extract_js_module_output\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/esbuild:index.bzl\", _esbuild = \"esbuild\", _esbuild_config = \"esbuild_config\")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"@npm//@angular/dev-infra-private/bazel/karma:index.bzl\", _karma_web_test = \"karma_web_test\", _karma_web_test_suite = \"karma_web_test_suite\")\n"
],
"file_path": "tools/defaults.bzl",
"type": "add",
"edit_start_line_idx": 14
} | # Building Angular with Bazel
Note: this doc is for developing Angular, it is _not_ public
documentation for building an Angular application with Bazel.
The Bazel build tool (https://bazel.build) provides fast, reliable
incremental builds. We plan to migrate Angular's build scripts to
Bazel.
## Installation
In order to ensure that everyone builds Angular in a _consistent_ way, Bazel
will be installed through NPM and therefore it's not necessary to install Bazel
manually.
The binaries for Bazel will be provided by the [`@bazel/bazelisk`](https://github.com/bazelbuild/bazelisk)
NPM package and its platform-specific dependencies.
You can access Bazel with the `yarn bazel` command
## Configuration
The `WORKSPACE` file indicates that our root directory is a
Bazel project. It contains the version of the Bazel rules we
use to execute build steps, from `npm_bazel_typescript`.
The sources on [GitHub] are published from Google's internal
repository (google3).
Bazel accepts a lot of options. We check in some options in the
`.bazelrc` file. See the [bazelrc doc]. For example, if you don't
want Bazel to create several symlinks in your project directory
(`bazel-*`) you can add the line `build --symlink_prefix=/` to your
`.bazelrc` file.
[GitHub]: https://github.com/bazelbuild/rules_typescript
[bazelrc doc]: https://bazel.build/versions/master/docs/bazel-user-manual.html#bazelrc
## Building Angular
- Build a package: `yarn bazel build packages/core`
- Build all packages: `yarn bazel build packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources. Note this is
new as of May 2017 and not very stable yet.
[ibazel]: https://github.com/bazelbuild/bazel-watcher
## Testing Angular
- Test package in node: `yarn bazel test packages/core/test:test`
- Test package in karma: `yarn bazel test packages/core/test:test_web`
- Test all packages: `yarn bazel test packages/...`
You can use [ibazel] to get a "watch mode" that continuously
keeps the outputs up-to-date as you save sources.
### Various Flags Used For Tests
If you're experiencing problems with seemingly unrelated tests failing, it may be because you're not using the proper flags with your Bazel test runs in Angular.
- `--config=debug`: build and launch in debug mode (see [debugging](#debugging) instructions below)
- `--test_arg=--node_options=--inspect=9228`: change the inspector port.
- `--test_tag_filters=<tag>`: filter tests down to tags defined in the `tag` config of your rules in any given `BUILD.bazel`.
### Debugging a Node Test
<a id="debugging"></a>
- Open chrome at: [chrome://inspect](chrome://inspect)
- Click on `Open dedicated DevTools for Node` to launch a debugger.
- Run test: `yarn bazel test packages/core/test:test --config=debug`
The process should automatically connect to the debugger.
For more, see the [rules_nodejs Debugging documentation](https://bazelbuild.github.io/rules_nodejs/index.html#debugging).
For additional info and testing options, see the
[nodejs_test documentation](https://bazelbuild.github.io/rules_nodejs/Built-ins.html#nodejs_test).
- Click on "Resume script execution" to let the code run until the first `debugger` statement or a previously set breakpoint.
- If you're debugging a test and you want to inspect the generated template instructions, find the template of your component in the call stack and click on `(source mapped from [CompName].js)` at the bottom of the code. You can also disable sourcemaps in the options or go to sources and look into ng:// namespace to see all the generated code.
### Debugging a Node Test in VSCode
First time setup:
- Go to Debug > Add configuration (in the menu bar) to open `launch.json`
- Add the following to the `configurations` array:
```json
{
"type": "node",
"request": "attach",
"name": "Attach to Remote",
"port": 9229
}
```
**Setting breakpoints directly in your code files may not work in VSCode**. This is because the files you're actually debugging are built files that exist in a `./private/...` folder.
The easiest way to debug a test for now is to add a `debugger` statement in the code
and launch the bazel corresponding test (`yarn bazel test <target> --config=debug`).
Bazel will wait on a connection. Go to the debug view (by clicking on the sidebar or
Apple+Shift+D on Mac) and click on the green play icon next to the configuration name
(ie `Attach to Remote`).
### Debugging a Karma Test
- Run test: `yarn bazel run packages/core/test:test_web_chromium` or `yarn bazel run packages/core/test:test_web_firefox`
- Open any browser at: [http://localhost:9876/debug.html](http://localhost:9876/debug.html)
- Open the browser's DevTools to debug the tests (after, for example, having focused on specific tests via `fit` and/or `fdescribe` or having added `debugger` statements in them)
### Debugging Bazel rules
Open `external` directory which contains everything that bazel downloaded while executing the workspace file:
```sh
open $(yarn -s bazel info output_base)/external
```
See subcommands that bazel executes (helpful for debugging):
```sh
yarn bazel build //packages/core:package -s
```
To debug nodejs_binary executable paths uncomment `find . -name rollup 1>&2` (~ line 96) in
```sh
open $(yarn -s bazel info output_base)/external/build_bazel_rules_nodejs/internal/node_launcher.sh
```
## Stamping
Bazel supports the ability to include non-hermetic information from the version control system in built artifacts. This is called stamping.
You can see an overview at https://www.kchodorow.com/blog/2017/03/27/stamping-your-builds/
In our repo, here is how it's configured:
1) In `tools/bazel_stamp_vars.js` we run the `git` commands to generate our versioning info.
1) In `.bazelrc` we register this script as the value for the `workspace_status_command` flag. Bazel will run the script when it needs to stamp a binary.
Note that Bazel has a `--stamp` argument to `yarn bazel build`, but this has no effect since our stamping takes place in Skylark rules. See https://github.com/bazelbuild/bazel/issues/1054
## Remote cache
Bazel supports fetching action results from a cache, allowing a clean build to pick up artifacts from prior builds.
This makes builds incremental, even on CI.
It works because Bazel assigns a content-based hash to all action inputs, which is used as the cache key for the action outputs.
Thanks to the hermeticity property, we can skip executing an action if the inputs hash is already present in the cache.
Of course, non-hermeticity in an action can cause problems.
At worst, you can fetch a broken artifact from the cache, making your build non-reproducible.
For this reason, we are careful to implement our Bazel rules to depend only on their inputs.
Currently we only use remote caching on CircleCI and we let Angular core developers enable remote caching to speed up their builds.
### Remote cache in development
To enable remote caching for your build:
1. Go to the service accounts for the ["internal" project](https://console.cloud.google.com/iam-admin/serviceaccounts?project=internal-200822)
1. Select "Angular local dev", click on "Edit", scroll to the bottom, and click "Create key"
1. When the pop-up shows, select "JSON" for "Key type" and click "Create"
1. Save the key in a secure location
1. Create a file called `.bazelrc.user` in the root directory of the workspace, and add the following content:
```
build --config=angular-team --google_credentials=[ABSOLUTE_PATH_TO_SERVICE_KEY]
```
### Remote cache for Circle CI
This feature is experimental, and developed by the CircleCI team with guidance from Angular.
Contact Alex Eagle with questions.
*How it's configured*:
1. In `.circleci/config.yml`, each CircleCI job downloads a proxy binary, which is built from https://github.com/notnoopci/bazel-remote-proxy. The download is done by running `.circleci/setup_cache.sh`. When the feature graduates from experimental, this proxy will be installed by default on every CircleCI worker, and this step will not be needed.
1. Next, each job runs the `setup-bazel-remote-cache` anchor. This starts up the proxy running in the background. In the CircleCI UI, you'll see this step continues running while later steps run, and you can see logging from the proxy process.
1. Bazel must be configured to connect to the proxy on a local port. This configuration lives in `.circleci/bazel.linux.rc` and is enabled because we overwrite the system Bazel settings in /etc/bazel.bazelrc with this file.
1. Each `bazel` command in `.circleci/config.yml` picks up and uses the caching flags.
## Diagnosing slow builds
If a build seems slow you can use Bazel to diagnose where time is spent.
The first step is to generate a profile of the build using the `--profile filename_name.profile` flag.
```
yarn bazel build //packages/compiler --profile filename_name.profile
```
This will generate a `filename_name.profile` that you can then analyse using [analyze-profile](https://docs.bazel.build/versions/master/user-manual.html#analyze-profile) command.
## Using the console profile report
You can obtain a simple report directly in the console by running:
```
yarn bazel analyze-profile filename_name.profile
```
This will show the phase summary, individual phase information and critical path.
You can also list all individual tasks and the time they took using `--task_tree`.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*"
```
To show all tasks that take longer than a certain threshold, use the `--task_tree_threshold` flag.
The default behavior is to use a 50ms threshold.
```
yarn bazel analyze-profile filename_name.profile --task_tree ".*" --task_tree_threshold 5000
```
`--task_tree` takes a regexp as argument that filters by the text shown after the time taken.
Compiling TypeScript shows as:
```
70569 ACTION_EXECUTE (10974.826 ms) Compiling TypeScript (devmode) //packages/compiler:compiler []
```
To filter all tasks by TypeScript compilations that took more than 5 seconds, use:
```
yarn bazel analyze-profile filename_name.profile --task_tree "Compiling TypeScript" --task_tree_threshold 5000
```
### Using the HTML profile report
A more comprehensive way to visualize the profile information is through the HTML report:
```
yarn bazel analyze-profile filename_name.profile --html --html_details --html_histograms
```
This will generate a `filename_name.profile.html` file that you can open in your browser.
On the upper right corner that is a small table of contents with links to three areas: Tasks, Legend and Statistics.
In the Tasks section you will find a graph of where time is spent. Legend shows what the colors in the Tasks graph mean.
Hovering over the background will show what phase that is, while hovering over bars will show more details about that specific action.
The Statistics section shows how long each phase took and how time was spent in that phase.
Usually the longest one is the execution phase, which also includes critical path information.
Also in the Statistics section are the Skylark statistic, split in User-Defined and Builtin function execution time.
You can click the "self" header twice to order the table by functions where the most time (in ms) is spent.
When diagnosing slow builds you should focus on the top time spenders across all phases and functions.
Usually there is a single item (or multiple items of the same kind) where the overwhelming majority of time is spent.
## Known issues
### Windows
#### bazel run
If you see the following error:
```
Error: Cannot find module 'C:\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\c;C:\msys64\users\xxxx\_bazel_xxxx\7lxopdvs\execroot\angular\bazel-out\x64_windows-fastbuild\bin\packages\core\test\bundling\hello_world\symbol_test.bat.runfiles\angular\packages\core\test\bundling\hello_world\symbol_test_require_patch.js'
Require stack:
- internal/preload
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Module.require (internal/modules/cjs/loader.js:848:19)
at Module._preloadModules (internal/modules/cjs/loader.js:1133:12)
at loadPreloadModules (internal/bootstrap/pre_execution.js:443:5)
at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:62:3)
at internal/main/run_main_module.js:7:1 {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'internal/preload' ]
```
`bazel run` only works in Bazel Windows with non-test targets. Ensure that you are using `bazel test` instead.
e.g: `yarn bazel test packages/core/test/bundling/forms:symbol_test`
#### mkdir missing
If you see the following error::
```
ERROR: An error occurred during the fetch of repository 'npm':
Traceback (most recent call last):
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 618, column 15, in _yarn_install_impl
_copy_file(repository_ctx, repository_ctx.attr.package_json)
File "C:/users/anusername/_bazel_anusername/idexbm2i/external/build_bazel_rules_nodejs/internal/npm_install/npm_install.bzl", line 345, column 17, in _copy_file
fail("mkdir -p %s failed: \nSTDOUT:\n%s\nSTDERR:\n%s" % (dirname, result.stdout, result.stderr))
Error in fail: mkdir -p _ failed:
```
The `msys64` library and associated tools (like `mkdir`) are required to build Angular.
Make sure you have `C:\msys64\usr\bin` in the "system" `PATH` rather than the "user" `PATH`.
After that, a `git clean -xfd`, `yarn`, and `node scripts\build\build-packages-dist.js` should resolve this issue.
### Xcode
If you see the following error:
```
$ yarn bazel build packages/...
ERROR: /private/var/tmp/[...]/external/local_config_cc/BUILD:50:5: in apple_cc_toolchain rule @local_config_cc//:cc-compiler-darwin_x86_64: Xcode version must be specified to use an Apple CROSSTOOL
ERROR: Analysis of target '//packages/core/test/render3:render3' failed; build aborted: Analysis of target '@local_config_cc//:cc-compiler-darwin_x86_64' failed; build aborted
```
It might be linked to an interaction with VSCode.
If closing VSCode fixes the issue, you can add the following line to your VSCode configuration:
```
"files.exclude": {"bazel-*": true}
```
source: https://github.com/bazelbuild/bazel/issues/4603
If VSCode is not the root cause, you might try:
- Quit VSCode (make sure no VSCode is running).
```
bazel clean --expunge
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo xcodebuild -license
yarn bazel build //packages/core # Run a build outside VSCode to pre-build the xcode; then safe to run VSCode
```
Source: https://stackoverflow.com/questions/45276830/xcode-version-must-be-specified-to-use-an-apple-crosstool
| docs/BAZEL.md | 1 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.0009350748732686043,
0.0002113606606144458,
0.00015928068023640662,
0.00017072261834982783,
0.00013562360254582018
]
|
{
"id": 4,
"code_window": [
"load(\"@npm//typescript:index.bzl\", \"tsc\")\n",
"load(\"//packages/bazel:index.bzl\", _ng_module = \"ng_module\", _ng_package = \"ng_package\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/benchmark/app_bundling:index.bzl\", _app_bundle = \"app_bundle\")\n",
"load(\"//tools:ng_benchmark.bzl\", _ng_benchmark = \"ng_benchmark\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/api-golden:index.bzl\", _api_golden_test = \"api_golden_test\", _api_golden_test_npm_package = \"api_golden_test_npm_package\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel:extract_js_module_output.bzl\", \"extract_js_module_output\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/esbuild:index.bzl\", _esbuild = \"esbuild\", _esbuild_config = \"esbuild_config\")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"@npm//@angular/dev-infra-private/bazel/karma:index.bzl\", _karma_web_test = \"karma_web_test\", _karma_web_test_suite = \"karma_web_test_suite\")\n"
],
"file_path": "tools/defaults.bzl",
"type": "add",
"edit_start_line_idx": 14
} | {
"name": "@angular/core/testing"
}
| packages/core/testing/package.json | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.00016493942530360073,
0.00016493942530360073,
0.00016493942530360073,
0.00016493942530360073,
0
]
|
{
"id": 4,
"code_window": [
"load(\"@npm//typescript:index.bzl\", \"tsc\")\n",
"load(\"//packages/bazel:index.bzl\", _ng_module = \"ng_module\", _ng_package = \"ng_package\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/benchmark/app_bundling:index.bzl\", _app_bundle = \"app_bundle\")\n",
"load(\"//tools:ng_benchmark.bzl\", _ng_benchmark = \"ng_benchmark\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/api-golden:index.bzl\", _api_golden_test = \"api_golden_test\", _api_golden_test_npm_package = \"api_golden_test_npm_package\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel:extract_js_module_output.bzl\", \"extract_js_module_output\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/esbuild:index.bzl\", _esbuild = \"esbuild\", _esbuild_config = \"esbuild_config\")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"@npm//@angular/dev-infra-private/bazel/karma:index.bzl\", _karma_web_test = \"karma_web_test\", _karma_web_test_suite = \"karma_web_test_suite\")\n"
],
"file_path": "tools/defaults.bzl",
"type": "add",
"edit_start_line_idx": 14
} | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/common/http/testing/index.js",
deps = ["//packages/common/http/testing"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(
["**/*.ts"],
),
# Visible to //:saucelabs_unit_tests_poc target
visibility = ["//:__pkg__"],
deps = [
"//packages/common/http",
"//packages/common/http/testing",
"@npm//rxjs",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_es2015"],
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_web",
deps = [
":test_lib",
],
)
| packages/common/http/testing/test/BUILD.bazel | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.0001747505011735484,
0.00017058949742931873,
0.00016691342170815915,
0.0001703470479696989,
0.0000029136879220459377
]
|
{
"id": 4,
"code_window": [
"load(\"@npm//typescript:index.bzl\", \"tsc\")\n",
"load(\"//packages/bazel:index.bzl\", _ng_module = \"ng_module\", _ng_package = \"ng_package\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/benchmark/app_bundling:index.bzl\", _app_bundle = \"app_bundle\")\n",
"load(\"//tools:ng_benchmark.bzl\", _ng_benchmark = \"ng_benchmark\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/api-golden:index.bzl\", _api_golden_test = \"api_golden_test\", _api_golden_test_npm_package = \"api_golden_test_npm_package\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel:extract_js_module_output.bzl\", \"extract_js_module_output\")\n",
"load(\"@npm//@angular/dev-infra-private/bazel/esbuild:index.bzl\", _esbuild = \"esbuild\", _esbuild_config = \"esbuild_config\")\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"load(\"@npm//@angular/dev-infra-private/bazel/karma:index.bzl\", _karma_web_test = \"karma_web_test\", _karma_web_test_suite = \"karma_web_test_suite\")\n"
],
"file_path": "tools/defaults.bzl",
"type": "add",
"edit_start_line_idx": 14
} | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {isThenable, SyncPromise} from '../src/promise_util';
describe('isThenable()', () => {
it('should return false for primitive values', () => {
expect(isThenable(undefined)).toBe(false);
expect(isThenable(null)).toBe(false);
expect(isThenable(false)).toBe(false);
expect(isThenable(true)).toBe(false);
expect(isThenable(0)).toBe(false);
expect(isThenable(1)).toBe(false);
expect(isThenable('')).toBe(false);
expect(isThenable('foo')).toBe(false);
});
it('should return false if `.then` is not a function', () => {
expect(isThenable([])).toBe(false);
expect(isThenable(['then'])).toBe(false);
expect(isThenable(function() {})).toBe(false);
expect(isThenable({})).toBe(false);
expect(isThenable({then: true})).toBe(false);
expect(isThenable({then: 'not a function'})).toBe(false);
});
it('should return true if `.then` is a function', () => {
expect(isThenable({then: function() {}})).toBe(true);
expect(isThenable({then: () => {}})).toBe(true);
expect(isThenable(Object.assign('thenable', {then: () => {}}))).toBe(true);
});
});
describe('SyncPromise', () => {
it('should call all callbacks once resolved', () => {
const spy1 = jasmine.createSpy('spy1');
const spy2 = jasmine.createSpy('spy2');
const promise = new SyncPromise<string>();
promise.then(spy1);
promise.then(spy2);
expect(spy1).not.toHaveBeenCalled();
expect(spy2).not.toHaveBeenCalled();
promise.resolve('foo');
expect(spy1).toHaveBeenCalledWith('foo');
expect(spy2).toHaveBeenCalledWith('foo');
});
it('should call callbacks immediately if already resolved', () => {
const spy = jasmine.createSpy('spy');
const promise = new SyncPromise<string>();
promise.resolve('foo');
promise.then(spy);
expect(spy).toHaveBeenCalledWith('foo');
});
it('should ignore subsequent calls to `resolve()`', () => {
const spy = jasmine.createSpy('spy');
const promise = new SyncPromise<string>();
promise.then(spy);
promise.resolve('foo');
expect(spy).toHaveBeenCalledWith('foo');
spy.calls.reset();
promise.resolve('bar');
expect(spy).not.toHaveBeenCalled();
promise.then(spy);
promise.resolve('baz');
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith('foo');
});
describe('.all()', () => {
it('should return a `SyncPromise` instance', () => {
expect(SyncPromise.all([])).toEqual(jasmine.any(SyncPromise));
});
it('should resolve immediately if the provided values are not thenable', () => {
const spy = jasmine.createSpy('spy');
const promise = SyncPromise.all(['foo', 1, {then: false}, []]);
promise.then(spy);
expect(spy).toHaveBeenCalledWith(['foo', 1, {then: false}, []]);
});
it('should wait for any thenables to resolve', async () => {
const spy = jasmine.createSpy('spy');
const v1 = 'foo';
const v2 = new SyncPromise<string>();
const v3 = Promise.resolve('baz');
const promise = SyncPromise.all([v1, v2, v3]);
promise.then(spy);
expect(spy).not.toHaveBeenCalled();
v2.resolve('bar');
expect(spy).not.toHaveBeenCalled();
await v3;
expect(spy).toHaveBeenCalledWith(['foo', 'bar', 'baz']);
});
});
});
| packages/upgrade/src/common/test/promise_util_spec.ts | 0 | https://github.com/angular/angular/commit/2f7fc3d87cbe35ae1c8e2a2418893438c075bca1 | [
0.00017572898650541902,
0.0001730812364257872,
0.00016704814333934337,
0.00017301442858297378,
0.0000020990262328268727
]
|
{
"id": 0,
"code_window": [
" this.state.goToMarker(marker);\n",
" this.state.verifyDocCommentTemplate({ newText: expectedText.replace(/\\r?\\n/g, \"\\r\\n\"), caretOffset: expectedOffset });\n",
" }\n",
"\n",
" public noDocCommentTemplateAt(marker: string | FourSlash.Marker) {\n",
" this.state.goToMarker(marker);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" public emptyDocCommentTemplateAt(marker: string | FourSlash.Marker) {\n"
],
"file_path": "src/harness/fourslash.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | /// <reference path='fourslash.ts' />
// @Filename: regex.ts
////var regex = /*0*///*1*/asdf/*2*/ /*3*///*4*/;
for (const marker of test.markers()) {
verify.noDocCommentTemplateAt(marker);
}
| tests/cases/fourslash/docCommentTemplateRegex.ts | 1 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.998634397983551,
0.998634397983551,
0.998634397983551,
0.998634397983551,
0
]
|
{
"id": 0,
"code_window": [
" this.state.goToMarker(marker);\n",
" this.state.verifyDocCommentTemplate({ newText: expectedText.replace(/\\r?\\n/g, \"\\r\\n\"), caretOffset: expectedOffset });\n",
" }\n",
"\n",
" public noDocCommentTemplateAt(marker: string | FourSlash.Marker) {\n",
" this.state.goToMarker(marker);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" public emptyDocCommentTemplateAt(marker: string | FourSlash.Marker) {\n"
],
"file_path": "src/harness/fourslash.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | //// [tests/cases/conformance/externalModules/importTsBeforeDTs.ts] ////
//// [foo_0.d.ts]
export var x: number = 42;
//// [foo_0.ts]
export var y: number = 42;
//// [foo_1.ts]
import foo = require("./foo_0");
var z1 = foo.x + 10; // Should error, as .ts preferred over .d.ts
var z2 = foo.y + 10; // Should resolve
//// [foo_0.js]
"use strict";
exports.__esModule = true;
exports.y = 42;
//// [foo_1.js]
"use strict";
exports.__esModule = true;
var foo = require("./foo_0");
var z1 = foo.x + 10; // Should error, as .ts preferred over .d.ts
var z2 = foo.y + 10; // Should resolve
| tests/baselines/reference/importTsBeforeDTs.js | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.0001794027048163116,
0.00017795112216845155,
0.00017715917783789337,
0.0001772914984030649,
0.0000010278409945385647
]
|
{
"id": 0,
"code_window": [
" this.state.goToMarker(marker);\n",
" this.state.verifyDocCommentTemplate({ newText: expectedText.replace(/\\r?\\n/g, \"\\r\\n\"), caretOffset: expectedOffset });\n",
" }\n",
"\n",
" public noDocCommentTemplateAt(marker: string | FourSlash.Marker) {\n",
" this.state.goToMarker(marker);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" public emptyDocCommentTemplateAt(marker: string | FourSlash.Marker) {\n"
],
"file_path": "src/harness/fourslash.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | tests/cases/compiler/duplicateTypeParameters3.ts(2,14): error TS2300: Duplicate identifier 'A'.
==== tests/cases/compiler/duplicateTypeParameters3.ts (1 errors) ====
interface X {
x: () => <A, A>() => void;
~
!!! error TS2300: Duplicate identifier 'A'.
}
| tests/baselines/reference/duplicateTypeParameters3.errors.txt | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.00017499578825663775,
0.00017317771562375128,
0.0001713596429908648,
0.00017317771562375128,
0.0000018180726328864694
]
|
{
"id": 0,
"code_window": [
" this.state.goToMarker(marker);\n",
" this.state.verifyDocCommentTemplate({ newText: expectedText.replace(/\\r?\\n/g, \"\\r\\n\"), caretOffset: expectedOffset });\n",
" }\n",
"\n",
" public noDocCommentTemplateAt(marker: string | FourSlash.Marker) {\n",
" this.state.goToMarker(marker);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" public emptyDocCommentTemplateAt(marker: string | FourSlash.Marker) {\n"
],
"file_path": "src/harness/fourslash.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | {
"kind": "UnionType",
"pos": 1,
"end": 14,
"flags": "JSDoc",
"types": {
"0": {
"kind": "NumberKeyword",
"pos": 1,
"end": 7,
"flags": "JSDoc"
},
"1": {
"kind": "StringKeyword",
"pos": 8,
"end": 14,
"flags": "JSDoc"
},
"length": 2,
"pos": 1,
"end": 14
}
} | tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.topLevelNoParenUnionType.json | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.00017557623505126685,
0.0001744045875966549,
0.00017338171892333776,
0.00017425580881536007,
9.020630500344851e-7
]
|
{
"id": 1,
"code_window": [
" this.state.goToMarker(marker);\n",
" this.state.verifyDocCommentTemplate(/*expected*/ undefined);\n",
" }\n",
"\n",
" public rangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number): void {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.state.verifyDocCommentTemplate({ newText: \"\", caretOffset: 0 });\n"
],
"file_path": "src/harness/fourslash.ts",
"type": "replace",
"edit_start_line_idx": 1002
} | /// <reference path='fourslash.ts' />
// @Filename: justAComment.ts
//// // We want to check off-by-one errors in assessing the end of the comment, so we check twice,
//// // first with a trailing space and then without.
//// // /*0*/
//// // /*1*/
//// // We also want to check EOF handling at the end of a comment
//// // /*2*/
for (const marker of test.markers()) {
verify.noDocCommentTemplateAt(marker);
}
| tests/cases/fourslash/docCommentTemplateInSingleLineComment.ts | 1 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.0018147558439522982,
0.0009905403712764382,
0.000166324942256324,
0.0009905403712764382,
0.000824215414468199
]
|
{
"id": 1,
"code_window": [
" this.state.goToMarker(marker);\n",
" this.state.verifyDocCommentTemplate(/*expected*/ undefined);\n",
" }\n",
"\n",
" public rangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number): void {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.state.verifyDocCommentTemplate({ newText: \"\", caretOffset: 0 });\n"
],
"file_path": "src/harness/fourslash.ts",
"type": "replace",
"edit_start_line_idx": 1002
} | tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList10.ts(2,8): error TS2370: A rest parameter must be of an array type.
tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList10.ts(2,11): error TS1048: A rest parameter cannot have an initializer.
==== tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList10.ts (2 errors) ====
class C {
foo(...bar = 0) { }
~~~~~~~~~~
!!! error TS2370: A rest parameter must be of an array type.
~~~
!!! error TS1048: A rest parameter cannot have an initializer.
} | tests/baselines/reference/parserParameterList10.errors.txt | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.0001732027594698593,
0.00017236277926713228,
0.00017152279906440526,
0.00017236277926713228,
8.399802027270198e-7
]
|
{
"id": 1,
"code_window": [
" this.state.goToMarker(marker);\n",
" this.state.verifyDocCommentTemplate(/*expected*/ undefined);\n",
" }\n",
"\n",
" public rangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number): void {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.state.verifyDocCommentTemplate({ newText: \"\", caretOffset: 0 });\n"
],
"file_path": "src/harness/fourslash.ts",
"type": "replace",
"edit_start_line_idx": 1002
} | tests/cases/compiler/collisionExportsRequireAndInternalModuleAlias.ts(5,8): error TS2441: Duplicate identifier 'exports'. Compiler reserves name 'exports' in top level scope of a module.
tests/cases/compiler/collisionExportsRequireAndInternalModuleAlias.ts(6,8): error TS2441: Duplicate identifier 'require'. Compiler reserves name 'require' in top level scope of a module.
==== tests/cases/compiler/collisionExportsRequireAndInternalModuleAlias.ts (2 errors) ====
export module m {
export class c {
}
}
import exports = m.c;
~~~~~~~
!!! error TS2441: Duplicate identifier 'exports'. Compiler reserves name 'exports' in top level scope of a module.
import require = m.c;
~~~~~~~
!!! error TS2441: Duplicate identifier 'require'. Compiler reserves name 'require' in top level scope of a module.
new exports();
new require();
module m1 {
import exports = m.c;
import require = m.c;
new exports();
new require();
}
module m2 {
export import exports = m.c;
export import require = m.c;
new exports();
new require();
} | tests/baselines/reference/collisionExportsRequireAndInternalModuleAlias.errors.txt | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.00017749803373590112,
0.00017632264643907547,
0.00017518526874482632,
0.000176303627085872,
8.429448712377052e-7
]
|
{
"id": 1,
"code_window": [
" this.state.goToMarker(marker);\n",
" this.state.verifyDocCommentTemplate(/*expected*/ undefined);\n",
" }\n",
"\n",
" public rangeAfterCodeFix(expectedText: string, includeWhiteSpace?: boolean, errorCode?: number, index?: number): void {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.state.verifyDocCommentTemplate({ newText: \"\", caretOffset: 0 });\n"
],
"file_path": "src/harness/fourslash.ts",
"type": "replace",
"edit_start_line_idx": 1002
} | //@module: commonjs
export module m1 {
export module m1_M1_public {
export class c1 {
}
export function f1() {
return new c1;
}
export var v1 = c1;
export var v2: c1;
}
module m1_M2_private {
export class c1 {
}
export function f1() {
return new c1;
}
export var v1 = c1;
export var v2: c1;
}
export declare module "m1_M3_public" {
export function f1();
export class c1 {
}
export var v1: { new (): c1; };
export var v2: c1;
}
declare module "m1_M4_private" {
export function f1();
export class c1 {
}
export var v1: { new (): c1; };
export var v2: c1;
}
import m1_im1_private = m1_M1_public;
export var m1_im1_private_v1_public = m1_im1_private.c1;
export var m1_im1_private_v2_public = new m1_im1_private.c1();
export var m1_im1_private_v3_public = m1_im1_private.f1;
export var m1_im1_private_v4_public = m1_im1_private.f1();
var m1_im1_private_v1_private = m1_im1_private.c1;
var m1_im1_private_v2_private = new m1_im1_private.c1();
var m1_im1_private_v3_private = m1_im1_private.f1;
var m1_im1_private_v4_private = m1_im1_private.f1();
import m1_im2_private = m1_M2_private;
export var m1_im2_private_v1_public = m1_im2_private.c1;
export var m1_im2_private_v2_public = new m1_im2_private.c1();
export var m1_im2_private_v3_public = m1_im2_private.f1;
export var m1_im2_private_v4_public = m1_im2_private.f1();
var m1_im2_private_v1_private = m1_im2_private.c1;
var m1_im2_private_v2_private = new m1_im2_private.c1();
var m1_im2_private_v3_private = m1_im2_private.f1;
var m1_im2_private_v4_private = m1_im2_private.f1();
import m1_im3_private = require("m1_M3_public");
export var m1_im3_private_v1_public = m1_im3_private.c1;
export var m1_im3_private_v2_public = new m1_im3_private.c1();
export var m1_im3_private_v3_public = m1_im3_private.f1;
export var m1_im3_private_v4_public = m1_im3_private.f1();
var m1_im3_private_v1_private = m1_im3_private.c1;
var m1_im3_private_v2_private = new m1_im3_private.c1();
var m1_im3_private_v3_private = m1_im3_private.f1;
var m1_im3_private_v4_private = m1_im3_private.f1();
import m1_im4_private = require("m1_M4_private");
export var m1_im4_private_v1_public = m1_im4_private.c1;
export var m1_im4_private_v2_public = new m1_im4_private.c1();
export var m1_im4_private_v3_public = m1_im4_private.f1;
export var m1_im4_private_v4_public = m1_im4_private.f1();
var m1_im4_private_v1_private = m1_im4_private.c1;
var m1_im4_private_v2_private = new m1_im4_private.c1();
var m1_im4_private_v3_private = m1_im4_private.f1;
var m1_im4_private_v4_private = m1_im4_private.f1();
export import m1_im1_public = m1_M1_public;
export import m1_im2_public = m1_M2_private;
export import m1_im3_public = require("m1_M3_public");
export import m1_im4_public = require("m1_M4_private");
}
module m2 {
export module m2_M1_public {
export class c1 {
}
export function f1() {
return new c1;
}
export var v1 = c1;
export var v2: c1;
}
module m2_M2_private {
export class c1 {
}
export function f1() {
return new c1;
}
export var v1 = c1;
export var v2: c1;
}
export declare module "m2_M3_public" {
export function f1();
export class c1 {
}
export var v1: { new (): c1; };
export var v2: c1;
}
declare module "m2_M4_private" {
export function f1();
export class c1 {
}
export var v1: { new (): c1; };
export var v2: c1;
}
import m1_im1_private = m2_M1_public;
export var m1_im1_private_v1_public = m1_im1_private.c1;
export var m1_im1_private_v2_public = new m1_im1_private.c1();
export var m1_im1_private_v3_public = m1_im1_private.f1;
export var m1_im1_private_v4_public = m1_im1_private.f1();
var m1_im1_private_v1_private = m1_im1_private.c1;
var m1_im1_private_v2_private = new m1_im1_private.c1();
var m1_im1_private_v3_private = m1_im1_private.f1;
var m1_im1_private_v4_private = m1_im1_private.f1();
import m1_im2_private = m2_M2_private;
export var m1_im2_private_v1_public = m1_im2_private.c1;
export var m1_im2_private_v2_public = new m1_im2_private.c1();
export var m1_im2_private_v3_public = m1_im2_private.f1;
export var m1_im2_private_v4_public = m1_im2_private.f1();
var m1_im2_private_v1_private = m1_im2_private.c1;
var m1_im2_private_v2_private = new m1_im2_private.c1();
var m1_im2_private_v3_private = m1_im2_private.f1;
var m1_im2_private_v4_private = m1_im2_private.f1();
import m1_im3_private = require("m2_M3_public");
export var m1_im3_private_v1_public = m1_im3_private.c1;
export var m1_im3_private_v2_public = new m1_im3_private.c1();
export var m1_im3_private_v3_public = m1_im3_private.f1;
export var m1_im3_private_v4_public = m1_im3_private.f1();
var m1_im3_private_v1_private = m1_im3_private.c1;
var m1_im3_private_v2_private = new m1_im3_private.c1();
var m1_im3_private_v3_private = m1_im3_private.f1;
var m1_im3_private_v4_private = m1_im3_private.f1();
import m1_im4_private = require("m2_M4_private");
export var m1_im4_private_v1_public = m1_im4_private.c1;
export var m1_im4_private_v2_public = new m1_im4_private.c1();
export var m1_im4_private_v3_public = m1_im4_private.f1;
export var m1_im4_private_v4_public = m1_im4_private.f1();
var m1_im4_private_v1_private = m1_im4_private.c1;
var m1_im4_private_v2_private = new m1_im4_private.c1();
var m1_im4_private_v3_private = m1_im4_private.f1;
var m1_im4_private_v4_private = m1_im4_private.f1();
// Parse error to export module
export import m1_im1_public = m2_M1_public;
export import m1_im2_public = m2_M2_private;
export import m1_im3_public = require("m2_M3_public");
export import m1_im4_public = require("m2_M4_private");
}
export module glo_M1_public {
export class c1 {
}
export function f1() {
return new c1;
}
export var v1 = c1;
export var v2: c1;
}
export declare module "glo_M2_public" {
export function f1();
export class c1 {
}
export var v1: { new (): c1; };
export var v2: c1;
}
export module glo_M3_private {
export class c1 {
}
export function f1() {
return new c1;
}
export var v1 = c1;
export var v2: c1;
}
export declare module "glo_M4_private" {
export function f1();
export class c1 {
}
export var v1: { new (): c1; };
export var v2: c1;
}
import glo_im1_private = glo_M1_public;
export var glo_im1_private_v1_public = glo_im1_private.c1;
export var glo_im1_private_v2_public = new glo_im1_private.c1();
export var glo_im1_private_v3_public = glo_im1_private.f1;
export var glo_im1_private_v4_public = glo_im1_private.f1();
var glo_im1_private_v1_private = glo_im1_private.c1;
var glo_im1_private_v2_private = new glo_im1_private.c1();
var glo_im1_private_v3_private = glo_im1_private.f1;
var glo_im1_private_v4_private = glo_im1_private.f1();
import glo_im2_private = require("glo_M2_public");
export var glo_im2_private_v1_public = glo_im2_private.c1;
export var glo_im2_private_v2_public = new glo_im2_private.c1();
export var glo_im2_private_v3_public = glo_im2_private.f1;
export var glo_im2_private_v4_public = glo_im2_private.f1();
var glo_im2_private_v1_private = glo_im2_private.c1;
var glo_im2_private_v2_private = new glo_im2_private.c1();
var glo_im2_private_v3_private = glo_im2_private.f1;
var glo_im2_private_v4_private = glo_im2_private.f1();
import glo_im3_private = glo_M3_private;
export var glo_im3_private_v1_public = glo_im3_private.c1;
export var glo_im3_private_v2_public = new glo_im3_private.c1();
export var glo_im3_private_v3_public = glo_im3_private.f1;
export var glo_im3_private_v4_public = glo_im3_private.f1();
var glo_im3_private_v1_private = glo_im3_private.c1;
var glo_im3_private_v2_private = new glo_im3_private.c1();
var glo_im3_private_v3_private = glo_im3_private.f1;
var glo_im3_private_v4_private = glo_im3_private.f1();
import glo_im4_private = require("glo_M4_private");
export var glo_im4_private_v1_public = glo_im4_private.c1;
export var glo_im4_private_v2_public = new glo_im4_private.c1();
export var glo_im4_private_v3_public = glo_im4_private.f1;
export var glo_im4_private_v4_public = glo_im4_private.f1();
var glo_im4_private_v1_private = glo_im4_private.c1;
var glo_im4_private_v2_private = new glo_im4_private.c1();
var glo_im4_private_v3_private = glo_im4_private.f1;
var glo_im4_private_v4_private = glo_im4_private.f1();
// Parse error to export module
export import glo_im1_public = glo_M1_public;
export import glo_im2_public = glo_M3_private;
export import glo_im3_public = require("glo_M2_public");
export import glo_im4_public = require("glo_M4_private");
export declare module "use_glo_M1_public" {
import use_glo_M1_public = glo_M1_public;
export var use_glo_M1_public_v1_public: { new (): use_glo_M1_public.c1; };
export var use_glo_M1_public_v2_public: use_glo_M1_public;
export var use_glo_M1_public_v3_public: () => use_glo_M1_public.c1;
var use_glo_M1_public_v1_private: { new (): use_glo_M1_public.c1; };
var use_glo_M1_public_v2_private: use_glo_M1_public;
var use_glo_M1_public_v3_private: () => use_glo_M1_public.c1;
import use_glo_M2_public = require("glo_M2_public");
export var use_glo_M2_public_v1_public: { new (): use_glo_M2_public.c1; };
export var use_glo_M2_public_v2_public: use_glo_M2_public;
export var use_glo_M2_public_v3_public: () => use_glo_M2_public.c1;
var use_glo_M2_public_v1_private: { new (): use_glo_M2_public.c1; };
var use_glo_M2_public_v2_private: use_glo_M2_public;
var use_glo_M2_public_v3_private: () => use_glo_M2_public.c1;
module m2 {
import errorImport = require("glo_M2_public");
import nonerrorImport = glo_M1_public;
module m5 {
import m5_errorImport = require("glo_M2_public");
import m5_nonerrorImport = glo_M1_public;
}
}
}
declare module "use_glo_M3_private" {
import use_glo_M3_private = glo_M3_private;
export var use_glo_M3_private_v1_public: { new (): use_glo_M3_private.c1; };
export var use_glo_M3_private_v2_public: use_glo_M3_private;
export var use_glo_M3_private_v3_public: () => use_glo_M3_private.c1;
var use_glo_M3_private_v1_private: { new (): use_glo_M3_private.c1; };
var use_glo_M3_private_v2_private: use_glo_M3_private;
var use_glo_M3_private_v3_private: () => use_glo_M3_private.c1;
import use_glo_M4_private = require("glo_M4_private");
export var use_glo_M4_private_v1_public: { new (): use_glo_M4_private.c1; };
export var use_glo_M4_private_v2_public: use_glo_M4_private;
export var use_glo_M4_private_v3_public: () => use_glo_M4_private.c1;
var use_glo_M4_private_v1_private: { new (): use_glo_M4_private.c1; };
var use_glo_M4_private_v2_private: use_glo_M4_private;
var use_glo_M4_private_v3_private: () => use_glo_M4_private.c1;
module m2 {
import errorImport = require("glo_M4_private");
import nonerrorImport = glo_M3_private;
module m5 {
import m5_errorImport = require("glo_M4_private");
import m5_nonerrorImport = glo_M3_private;
}
}
}
declare module "anotherParseError" {
module m2 {
declare module "abc" {
}
}
module m2 {
module "abc2" {
}
}
module "abc3" {
}
}
declare export module "anotherParseError2" {
module m2 {
declare module "abc" {
}
}
module m2 {
module "abc2" {
}
}
module "abc3" {
}
}
module m2 {
import m3 = require("use_glo_M1_public");
module m4 {
var a = 10;
import m2 = require("use_glo_M1_public");
}
}
export module m3 {
import m3 = require("use_glo_M1_public");
module m4 {
var a = 10;
import m2 = require("use_glo_M1_public");
}
} | tests/cases/compiler/privacyImportParseErrors.ts | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.0001781523460522294,
0.0001748681825120002,
0.00017002876847982407,
0.0001753751712385565,
0.0000024916655547713162
]
|
{
"id": 2,
"code_window": [
"\n",
"// @Filename: emptyFile.ts\n",
"/////*0*/\n",
"\n",
"verify.noDocCommentTemplateAt(\"0\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"verify.emptyDocCommentTemplateAt(\"0\");"
],
"file_path": "tests/cases/fourslash/docCommentTemplateEmptyFile.ts",
"type": "replace",
"edit_start_line_idx": 5
} | /// <reference path='fourslash.ts' />
/////*top*/
////namespace n1.
//// /*n2*/ n2.
//// /*n3*/ n3 {
////}
verify.docCommentTemplateAt("top", /*indentation*/ 8,
`/**
*
*/`);
verify.noDocCommentTemplateAt("n2");
verify.noDocCommentTemplateAt("n3");
| tests/cases/fourslash/docCommentTemplateNamespacesAndModules02.ts | 1 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.0016341692535206676,
0.0010476334718987346,
0.0004610976902768016,
0.0010476334718987346,
0.000586535781621933
]
|
{
"id": 2,
"code_window": [
"\n",
"// @Filename: emptyFile.ts\n",
"/////*0*/\n",
"\n",
"verify.noDocCommentTemplateAt(\"0\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"verify.emptyDocCommentTemplateAt(\"0\");"
],
"file_path": "tests/cases/fourslash/docCommentTemplateEmptyFile.ts",
"type": "replace",
"edit_start_line_idx": 5
} | //@target: ES6
new Symbol(); | tests/cases/conformance/es6/Symbols/symbolType14.ts | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.00017420116637367755,
0.00017420116637367755,
0.00017420116637367755,
0.00017420116637367755,
0
]
|
{
"id": 2,
"code_window": [
"\n",
"// @Filename: emptyFile.ts\n",
"/////*0*/\n",
"\n",
"verify.noDocCommentTemplateAt(\"0\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"verify.emptyDocCommentTemplateAt(\"0\");"
],
"file_path": "tests/cases/fourslash/docCommentTemplateEmptyFile.ts",
"type": "replace",
"edit_start_line_idx": 5
} | === tests/cases/compiler/sourceMapValidationDestructuringVariableStatementObjectBindingPattern2.ts ===
var {x} = { x: 20 };
>x : number
>{ x: 20 } : { x: number; }
>x : number
>20 : 20
var { a, b } = { a: 30, b: 40 };
>a : number
>b : number
>{ a: 30, b: 40 } : { a: number; b: number; }
>a : number
>30 : 30
>b : number
>40 : 40
| tests/baselines/reference/sourceMapValidationDestructuringVariableStatementObjectBindingPattern2.types | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.00017262273468077183,
0.00017209534416906536,
0.00017156793910544366,
0.00017209534416906536,
5.273977876640856e-7
]
|
{
"id": 2,
"code_window": [
"\n",
"// @Filename: emptyFile.ts\n",
"/////*0*/\n",
"\n",
"verify.noDocCommentTemplateAt(\"0\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"verify.emptyDocCommentTemplateAt(\"0\");"
],
"file_path": "tests/cases/fourslash/docCommentTemplateEmptyFile.ts",
"type": "replace",
"edit_start_line_idx": 5
} | === tests/cases/compiler/captureThisInSuperCall.ts ===
class A {
>A : Symbol(A, Decl(captureThisInSuperCall.ts, 0, 0))
constructor(p:any) {}
>p : Symbol(p, Decl(captureThisInSuperCall.ts, 1, 16))
}
class B extends A {
>B : Symbol(B, Decl(captureThisInSuperCall.ts, 2, 1))
>A : Symbol(A, Decl(captureThisInSuperCall.ts, 0, 0))
constructor() { super({ test: () => this.someMethod()}); }
>super : Symbol(A, Decl(captureThisInSuperCall.ts, 0, 0))
>test : Symbol(test, Decl(captureThisInSuperCall.ts, 5, 27))
>this.someMethod : Symbol(B.someMethod, Decl(captureThisInSuperCall.ts, 5, 62))
>this : Symbol(B, Decl(captureThisInSuperCall.ts, 2, 1))
>someMethod : Symbol(B.someMethod, Decl(captureThisInSuperCall.ts, 5, 62))
someMethod() {}
>someMethod : Symbol(B.someMethod, Decl(captureThisInSuperCall.ts, 5, 62))
}
| tests/baselines/reference/captureThisInSuperCall.symbols | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.00017577188555151224,
0.0001730029034661129,
0.00016967100964393467,
0.00017356581520289183,
0.0000025222773274435895
]
|
{
"id": 3,
"code_window": [
"/// <reference path='fourslash.ts' />\n",
"\n",
"// @Filename: justAComment.ts\n",
"//// /* /*0*/ */\n",
"\n",
"verify.noDocCommentTemplateAt(\"0\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"verify.emptyDocCommentTemplateAt(\"0\");"
],
"file_path": "tests/cases/fourslash/docCommentTemplateInMultiLineComment.ts",
"type": "replace",
"edit_start_line_idx": 5
} | /// <reference path='fourslash.ts' />
// @Filename: justAComment.ts
//// /* /*0*/ */
verify.noDocCommentTemplateAt("0");
| tests/cases/fourslash/docCommentTemplateInMultiLineComment.ts | 1 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.9273794293403625,
0.9273794293403625,
0.9273794293403625,
0.9273794293403625,
0
]
|
{
"id": 3,
"code_window": [
"/// <reference path='fourslash.ts' />\n",
"\n",
"// @Filename: justAComment.ts\n",
"//// /* /*0*/ */\n",
"\n",
"verify.noDocCommentTemplateAt(\"0\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"verify.emptyDocCommentTemplateAt(\"0\");"
],
"file_path": "tests/cases/fourslash/docCommentTemplateInMultiLineComment.ts",
"type": "replace",
"edit_start_line_idx": 5
} | {"version":3,"file":"m1.js","sourceRoot":"","sources":["../../../ref/m1.ts"],"names":[],"mappings":";;;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"} | tests/baselines/reference/project/sourcemapModuleSubfolderSpecifyOutputDirectory/amd/outdir/simple/ref/m1.js.map | 0 | https://github.com/microsoft/TypeScript/commit/b566480aaaf92460b37eb0977b5c07c1c0729c85 | [
0.0001708372583379969,
0.0001708372583379969,
0.0001708372583379969,
0.0001708372583379969,
0
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.