Compare commits

...
Author SHA1 Message Date
Wahyu Kurniawan 8fd9ffe13b Merge branch 'andrehadianto/design-system-components' of https://github.com/snowball-tools/snowballtools-base into ayungavis/T-4866-switch 2024-02-22 17:38:17 +07:00
Wahyu Kurniawan d2ca4df35a [T-4864: feat] Radio component (#90)
* 🎨 style: make the cursor of the tab trigger wrapper to default

* ️ feat: create radio component

* 📝 docs: add radio component to the example page

* 🔧 chore: install `@radix-ui/react-radio-group`
2024-02-22 17:30:33 +07:00
Zachery 30bbe4d766 [T-4870] Tooltip component (#96)
* fix: button forwardRef

* feat: tooltip component
2024-02-22 18:25:04 +08:00
Wahyu Kurniawan 496404195c Merge branch 'main' of https://github.com/snowball-tools/snowballtools-base into andrehadianto/design-system-components 2024-02-22 12:45:17 +07:00
Wahyu Kurniawan 9dec48d67c ♻️ refactor: add disabled button example page 2024-02-22 12:24:25 +07:00
nabarunandneeraj e816c596ca Publish ApplicationRecord and ApplicationDeploymentRequest on creating new deployments (#89)
* Create application deployment request on new deployment

* Save application deployment request datas in deployment entity

* Add project as dependency

* Use project repo name as record app name

---------

Co-authored-by: neeraj <neeraj.rtly@gmail.com>
2024-02-22 10:04:33 +05:30
Wahyu Kurniawan 6bfbaf0ca0 Merge branch 'andrehadianto/design-system-components' of https://github.com/snowball-tools/snowballtools-base into ayungavis/T-4866-switch 2024-02-22 10:49:09 +07:00
Wahyu Kurniawan 6df094bf2e [T-4861: feat] Inline notification component (#86)
* ️ feat: create info square icon component

* ️ feat: create inline notification component

* 📝 docs: add js doc comment and add inline notification component to the example page

* 🐛 fix: use the right method of `useCallback
2024-02-22 10:45:19 +07:00
Wahyu Kurniawan 2820d040e1 🎨 style: addjust input outline when error and focus 2024-02-22 10:38:23 +07:00
Wahyu Kurniawan 43b76fcef8 Merge branch 'andrehadianto/design-system-components' of https://github.com/snowball-tools/snowballtools-base into ayungavis/T-4866-switch 2024-02-22 10:37:31 +07:00
Wahyu Kurniawan 020490da54 🎨 style: add inset shadow 2024-02-22 10:35:46 +07:00
Wahyu Kurniawan 95b9cf2e08 🔧 chore: install @radix-ui/react-switch 2024-02-22 10:35:25 +07:00
Wahyu Kurniawan c865e46367 📝 docs: add switch to the example page 2024-02-22 10:35:01 +07:00
Wahyu Kurniawan ab2d87fd09 ️ feat: create switch component 2024-02-22 10:34:36 +07:00
Andre Hadianto 2369f4498a Merge pull request #85 from snowball-tools/andrehadianto/T-4863-input-field
feat: input field
2024-02-22 10:18:59 +08:00
Wahyu Kurniawan eb6a727425 [T-4862: feat] Link component (#88) 2024-02-22 09:17:22 +07:00
Andre H da2f7ede42 🔧 chore: add dependency to usememo 2024-02-22 09:15:17 +07:00
telackey 4d0f2ca893 SO webapp-ify the frontend (#82)
* webapp-ify

* Tweak values

* Self-contained
2024-02-21 13:53:05 -06:00
Andre H 448d0ceb7c 🔧 chore: 1 classname per object 2024-02-21 17:10:45 +07:00
Andre H 195d957251 🔧 chore: restructure tailwind classnames 2024-02-21 17:08:33 +07:00
Andre H 807a4b1197 🔧 chore: lint 2024-02-21 17:08:14 +07:00
Andre H 5f6723fad6 ♻️ refactor: create new renderInput for component page 2024-02-21 17:07:59 +07:00
Andre H b663067035 🔧 chore: use absolute import 2024-02-21 17:07:30 +07:00
nabarunandneeraj 8ca55cd888 Implement polling for project deployment updates (#87)
* Populate organization and user if db is empty

* Use hardcoded user id from fixtures

* Implement polling for get deployments query

* Handle review changes

---------

Co-authored-by: neeraj <neeraj.rtly@gmail.com>
2024-02-21 15:34:33 +05:30
Andre Hadianto b3a99475af Merge branch 'andrehadianto/design-system-components' into andrehadianto/T-4863-input-field 2024-02-21 17:39:29 +08:00
Wahyu Kurniawan ea44efa0f2 [T-4867: feat] Horizontal and vertical tabs component (#84)
* ️ feat: create tabs component

* ♻️ refactor: avoid big conflict on the example page

* 🔧 chore: upgrade tailwindcss and install `@radix-ui/react-tabs`

* ️ feat: create globe icon component

* 🎨 style: adjust vertical tab theme

* 📝 docs: add vertical tabs to the example page
2024-02-21 16:13:16 +07:00
Andre H 7d5963d776 🔧 chore: add input to page/components 2024-02-21 15:44:21 +07:00
Andre H 33b6191539 ️ feat: implement Input Field component 2024-02-21 15:43:53 +07:00
Andre H 636f68d7a4 🔧 chore: add more icons 2024-02-21 15:43:32 +07:00
Andre H 237e9e5cb9 🔧 chore: implement classnames utils 2024-02-21 15:43:09 +07:00
Andre H e70bb34190 ⚒️ build: reorder packages 2024-02-21 15:42:35 +07:00
telackey fc240c93d8 SO deployable config for the backend. (#83)
* webapp-ify

* SO deployable config for the backend.

* Use process.env

* Detangle
2024-02-21 00:05:45 -06:00
Andre H b5eef95d15 Merge remote-tracking branch 'origin/main' 2024-02-21 11:00:14 +07:00
Zachery f0121605c4 feat: avatar component (#76) 2024-02-21 11:39:38 +08:00
Wahyu Kurniawan c8f1c58507 Merge pull request #81 from snowball-tools/ayungavis/T-4837-badge
[T-4837: feat] Badge component
2024-02-20 23:42:56 +07:00
Wahyu Kurniawan 83508cd81d Merge branch 'andrehadianto/design-system-components' of https://github.com/snowball-tools/snowballtools-base into ayungavis/T-4837-badge 2024-02-20 23:38:35 +07:00
Wahyu Kurniawan 76c59e2c58 Merge pull request #80 from snowball-tools/ayungavis/T-4838-checkbox
[T-4838: feat] Checkbox component
2024-02-20 23:37:30 +07:00
Wahyu Kurniawan a5bce0cda2 🎨 style: adjust disabled hover text color 2024-02-20 23:34:20 +07:00
Wahyu Kurniawan 3a085a79ae Merge branch 'andrehadianto/design-system-components' of https://github.com/snowball-tools/snowballtools-base into ayungavis/T-4838-checkbox 2024-02-20 23:29:18 +07:00
Wahyu Kurniawan abfe6a523c Merge pull request #79 from snowball-tools/ayungavis/T-4842-datepicker
[T-4842: feat] Calendar component
2024-02-20 23:26:38 +07:00
Wahyu Kurniawan f764bea6d1 📝 docs: add badge to the example page 2024-02-20 23:26:04 +07:00
Wahyu Kurniawan cc9c24cca1 🎨 style: add new font sizes 2024-02-20 23:26:04 +07:00
Wahyu Kurniawan e482f998a1 ️ feat: create badge comopnent 2024-02-20 23:26:04 +07:00
Wahyu Kurniawan b255078431 📝 docs: add checkbox to example component page 2024-02-20 23:25:19 +07:00
Wahyu Kurniawan 26260976fb ️ feat: create check icon for checkbox component 2024-02-20 23:25:19 +07:00
Wahyu Kurniawan 5e3a6ad2b5 ️ feat: create checkbox component 2024-02-20 23:25:19 +07:00
Wahyu Kurniawan f31ee7349f 🔧 chore: install @radix-ui/react-checkbox 2024-02-20 23:25:19 +07:00
Wahyu Kurniawan 5c5d759c10 ♻️ refactor: fix typo and change to readable name 2024-02-20 23:24:28 +07:00
Wahyu Kurniawan dc6bf3794a ️ feat: add interaction on the example page 2024-02-20 23:24:28 +07:00
Wahyu Kurniawan af0d28e654 🎨 style: add new shadows 2024-02-20 23:24:27 +07:00
Wahyu Kurniawan 4f7f9cf914 📝 docs: add calendar component to the example page 2024-02-20 23:24:27 +07:00
Wahyu Kurniawan ad7dd1920a ️ feat: create calendar component 2024-02-20 23:24:27 +07:00
Wahyu Kurniawan cc97ddff9d ️ feat: create chevron left, right, and grabbed horizontal component 2024-02-20 23:24:27 +07:00
Wahyu Kurniawan 0a5a1b8c55 🔧 chore: add vscode settings to enable tailwind variant intellisense 2024-02-20 23:24:27 +07:00
Wahyu Kurniawan 4f2944a974 🔧 chore: install date-fns and react-calendar 2024-02-20 23:24:26 +07:00
Wahyu Kurniawan 69198307fb Merge pull request #77 from snowball-tools/ayungavis/T-4834-button
[T-4834: feat] Button component
2024-02-20 23:23:38 +07:00
nabarunandneeraj a45fb4c617 Fix deployments visit URL and date filter (#78)
* Add method to update multiple deployments in single query

* Fix deployments URL visit and date filter

* Clean fixtures data

* Update fixtures data

---------

Co-authored-by: neeraj <neeraj.rtly@gmail.com>
2024-02-20 10:53:42 +05:30
nabarunandneeraj c3d1b4f3eb Use branches from GitHub API in edit domain dialog (#74)
* Use branches from GitHub API

* Disable git branch input if repo not found

* Disable git branch if branches is empty

* Use async select for accounts dropdown

* Log actual HTTP error in console

---------

Co-authored-by: neeraj <neeraj.rtly@gmail.com>
2024-02-19 16:55:07 +05:30
nabarunandneeraj ce55fe62d8 Check for ApplicationDeploymentRecord and update deployments (#73)
* Add skeleton and TODOs for polling deployment records

* Add method implementations for fetching deployment records

* Handle if deployment url is not set

* Add logs after getting ApplicationDeploymentRecord

* Add application deployment record to deployment entity

* Change type of application deployment record data

* Fetch delay to check deployment records from config

* Update isCurrent after deployment record received

---------

Co-authored-by: neeraj <neeraj.rtly@gmail.com>
2024-02-19 13:43:29 +05:30
nabarunandneeraj b007286f4a Add script to publish dummy ApplicationDeploymentRecord (#72)
* Add script to publish application deployment record

* Refactor publish deploy records script

* Assert if name doesn't exist in package.json

* Disable import environment variables button

---------

Co-authored-by: neeraj <neeraj.rtly@gmail.com>
2024-02-16 15:05:52 +05:30
121 changed files with 4623 additions and 839 deletions
+6
View File
@@ -0,0 +1,6 @@
{
// IntelliSense for taiwind variants
"tailwindCSS.experimental.classRegex": [
["tv\\((([^()]*|\\([^()]*\\))*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]
]
}
+2 -2
View File
@@ -31,7 +31,7 @@
- Load fixtures in database
```bash
yarn db:load:fixtures
yarn test:db:load:fixtures
```
- Set `gitHub.oAuth.clientId` and `gitHub.oAuth.clientSecret` in backend [config file](packages/backend/environments/local.toml)
@@ -66,7 +66,7 @@
- Run the script to create bond, reserve the authority and set authority bond
```bash
yarn registry:init
yarn test:registry:init
# snowball:initialize-registry bondId: 6af0ab81973b93d3511ae79841756fb5da3fd2f70ea1279e81fae7c9b19af6c4 +0ms
```
+26
View File
@@ -0,0 +1,26 @@
#!/bin/bash
PKG_DIR="./packages/frontend"
OUTPUT_DIR="${PKG_DIR}/build"
DEST_DIR=${1:-/data}
if [[ -d "$DEST_DIR" ]]; then
echo "${DEST_DIR} already exists." 1>&2
exit 1
fi
cat > $PKG_DIR/.env <<EOF
REACT_APP_GQL_SERVER_URL = 'LACONIC_HOSTED_CONFIG_app_gql_url'
REACT_APP_GITHUB_CLIENT_ID = 'LACONIC_HOSTED_CONFIG_app_github_clientid'
REACT_APP_GITHUB_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_app_github_templaterepo'
EOF
yarn || exit 1
yarn build || exit 1
if [[ ! -d "$OUTPUT_DIR" ]]; then
echo "Missing output directory: $OUTPUT_DIR" 1>&2
exit 1
fi
mv "$OUTPUT_DIR" "$DEST_DIR"
+4 -1
View File
@@ -25,6 +25,9 @@
"allowArgumentsExplicitlyTypedAsAny": true
}
],
"@typescript-eslint/no-unused-vars": ["error", { "ignoreRestSiblings": true }]
"@typescript-eslint/no-unused-vars": [
"error",
{ "ignoreRestSiblings": true }
]
}
}
+1
View File
@@ -13,6 +13,7 @@
clientSecret = ""
[registryConfig]
fetchDeploymentRecordDelay = 5000
restEndpoint = "http://localhost:1317"
gqlEndpoint = "http://localhost:9473/api"
chainId = "laconic_9000-1"
+4 -3
View File
@@ -36,9 +36,10 @@
"lint": "eslint .",
"format": "prettier --write .",
"format:check": "prettier --check .",
"registry:init": "DEBUG=snowball:* ts-node ./test/initialize-registry.ts",
"db:load:fixtures": "DEBUG=snowball:* ts-node ./test/initialize-db.ts",
"db:delete": "DEBUG=snowball:* ts-node ./test/delete-db.ts"
"test:registry:init": "DEBUG=snowball:* ts-node ./test/initialize-registry.ts",
"test:registry:publish-deploy-records": "DEBUG=snowball:* ts-node ./test/publish-deploy-records.ts",
"test:db:load:fixtures": "DEBUG=snowball:* ts-node ./test/initialize-db.ts",
"test:db:delete": "DEBUG=snowball:* ts-node ./test/delete-db.ts"
},
"devDependencies": {
"@types/fs-extra": "^11.0.4",
+3 -2
View File
@@ -13,7 +13,7 @@ export interface GitHubConfig {
oAuth: {
clientId: string;
clientSecret: string;
}
};
}
export interface RegistryConfig {
@@ -22,11 +22,12 @@ export interface RegistryConfig {
chainId: string;
privateKey: string;
bondId: string;
fetchDeploymentRecordDelay: number;
fee: {
amount: string;
denom: string;
gas: string;
}
};
}
export interface Config {
+9 -3
View File
@@ -1,8 +1,14 @@
export const DEFAULT_CONFIG_FILE_PATH = 'environments/local.toml';
import process from 'process';
export const DEFAULT_CONFIG_FILE_PATH =
process.env.SNOWBALL_BACKEND_CONFIG_FILE_PATH || 'environments/local.toml';
export const DEFAULT_GQL_PATH = '/graphql';
// Note: temporary hardcoded user, later to be derived from auth token
export const USER_ID = '59f4355d-9549-4aac-9b54-eeefceeabef0';
export const USER_ID =
process.env.SNOWBALL_BACKEND_USER_ID ||
'59f4355d-9549-4aac-9b54-eeefceeabef0';
export const PROJECT_DOMAIN = 'snowball.xyz';
export const PROJECT_DOMAIN =
process.env.SNOWBALL_BACKEND_PROJECT_DOMAIN || 'snowball.xyz';
+212 -53
View File
@@ -1,4 +1,10 @@
import { DataSource, DeepPartial, FindManyOptions, FindOneOptions, FindOptionsWhere } from 'typeorm';
import {
DataSource,
DeepPartial,
FindManyOptions,
FindOneOptions,
FindOptionsWhere
} from 'typeorm';
import path from 'path';
import debug from 'debug';
import assert from 'assert';
@@ -14,6 +20,12 @@ import { ProjectMember } from './entity/ProjectMember';
import { EnvironmentVariable } from './entity/EnvironmentVariable';
import { Domain } from './entity/Domain';
import { PROJECT_DOMAIN } from './constants';
import { getEntities, loadAndSaveData } from './utils';
import { UserOrganization } from './entity/UserOrganization';
const ORGANIZATION_DATA_PATH = '../test/fixtures/organizations.json';
const USER_DATA_PATH = '../test/fixtures/users.json';
const USER_ORGANIZATION_DATA_PATH = '../test/fixtures/user-organizations.json';
const log = debug('snowball:database');
@@ -36,6 +48,40 @@ export class Database {
async init (): Promise<void> {
await this.dataSource.initialize();
log('database initialized');
const organizations = await this.getOrganizations({});
if (!organizations.length) {
const orgEntities = await getEntities(
path.resolve(__dirname, ORGANIZATION_DATA_PATH)
);
const savedOrgs = await loadAndSaveData(Organization, this.dataSource, [
orgEntities[0]
]);
// TODO: Remove user once authenticated
const userEntities = await getEntities(
path.resolve(__dirname, USER_DATA_PATH)
);
const savedUsers = await loadAndSaveData(User, this.dataSource, [
userEntities[0]
]);
const userOrganizationRelations = {
member: savedUsers,
organization: savedOrgs
};
const userOrgEntities = await getEntities(
path.resolve(__dirname, USER_ORGANIZATION_DATA_PATH)
);
await loadAndSaveData(
UserOrganization,
this.dataSource,
[userOrgEntities[0]],
userOrganizationRelations
);
}
}
async getUser (options: FindOneOptions<User>): Promise<User | null> {
@@ -60,7 +106,18 @@ export class Database {
return updateResult.affected > 0;
}
async getOrganization (options: FindOneOptions<Organization>): Promise<Organization | null> {
async getOrganizations (
options: FindManyOptions<Organization>
): Promise<Organization[]> {
const organizationRepository = this.dataSource.getRepository(Organization);
const organizations = await organizationRepository.find(options);
return organizations;
}
async getOrganization (
options: FindOneOptions<Organization>
): Promise<Organization | null> {
const organizationRepository = this.dataSource.getRepository(Organization);
const organization = await organizationRepository.findOne(options);
@@ -95,7 +152,11 @@ export class Database {
const project = await projectRepository
.createQueryBuilder('project')
.leftJoinAndSelect('project.deployments', 'deployments', 'deployments.isCurrent = true')
.leftJoinAndSelect(
'project.deployments',
'deployments',
'deployments.isCurrent = true'
)
.leftJoinAndSelect('deployments.createdBy', 'user')
.leftJoinAndSelect('deployments.domain', 'domain')
.leftJoinAndSelect('project.owner', 'owner')
@@ -108,28 +169,48 @@ export class Database {
return project;
}
async getProjectsInOrganization (userId: string, organizationSlug: string): Promise<Project[]> {
async getProjectsInOrganization (
userId: string,
organizationSlug: string
): Promise<Project[]> {
const projectRepository = this.dataSource.getRepository(Project);
const projects = await projectRepository
.createQueryBuilder('project')
.leftJoinAndSelect('project.deployments', 'deployments', 'deployments.isCurrent = true')
.leftJoinAndSelect(
'project.deployments',
'deployments',
'deployments.isCurrent = true'
)
.leftJoinAndSelect('deployments.domain', 'domain')
.leftJoin('project.projectMembers', 'projectMembers')
.leftJoin('project.organization', 'organization')
.where('(project.ownerId = :userId OR projectMembers.userId = :userId) AND organization.slug = :organizationSlug', {
userId,
organizationSlug
})
.where(
'(project.ownerId = :userId OR projectMembers.userId = :userId) AND organization.slug = :organizationSlug',
{
userId,
organizationSlug
}
)
.getMany();
return projects;
}
async getDeploymentsByProjectId (projectId: string): Promise<Deployment[]> {
/**
* Get deployments with specified filter
*/
async getDeployments (
options: FindManyOptions<Deployment>
): Promise<Deployment[]> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployments = await deploymentRepository.find(options);
const deployments = await deploymentRepository.find({
return deployments;
}
async getDeploymentsByProjectId (projectId: string): Promise<Deployment[]> {
return this.getDeployments({
relations: {
project: true,
domain: true,
@@ -144,11 +225,11 @@ export class Database {
createdAt: 'DESC'
}
});
return deployments;
}
async getDeployment (options: FindOneOptions<Deployment>): Promise<Deployment | null> {
async getDeployment (
options: FindOneOptions<Deployment>
): Promise<Deployment | null> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployment = await deploymentRepository.findOne(options);
@@ -162,24 +243,25 @@ export class Database {
return domains;
}
async addDeployement (data: DeepPartial<Deployment>): Promise<Deployment> {
async addDeployment (data: DeepPartial<Deployment>): Promise<Deployment> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const id = nanoid();
const url = `${data.project!.name}-${id}.${PROJECT_DOMAIN}`;
const updatedData = {
...data,
id,
url
id
};
const deployment = await deploymentRepository.save(updatedData);
return deployment;
}
async getProjectMembersByProjectId (projectId: string): Promise<ProjectMember[]> {
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
async getProjectMembersByProjectId (
projectId: string
): Promise<ProjectMember[]> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
const projectMembers = await projectMemberRepository.find({
relations: {
@@ -196,8 +278,12 @@ export class Database {
return projectMembers;
}
async getEnvironmentVariablesByProjectId (projectId: string, filter?: FindOptionsWhere<EnvironmentVariable>): Promise<EnvironmentVariable[]> {
const environmentVariableRepository = this.dataSource.getRepository(EnvironmentVariable);
async getEnvironmentVariablesByProjectId (
projectId: string,
filter?: FindOptionsWhere<EnvironmentVariable>
): Promise<EnvironmentVariable[]> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
const environmentVariables = await environmentVariableRepository.find({
where: {
@@ -212,9 +298,12 @@ export class Database {
}
async removeProjectMemberById (projectMemberId: string): Promise<boolean> {
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
const deleteResult = await projectMemberRepository.delete({ id: projectMemberId });
const deleteResult = await projectMemberRepository.delete({
id: projectMemberId
});
if (deleteResult.affected) {
return deleteResult.affected > 0;
@@ -223,37 +312,63 @@ export class Database {
}
}
async updateProjectMemberById (projectMemberId: string, data: DeepPartial<ProjectMember>): Promise<boolean> {
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
const updateResult = await projectMemberRepository.update({ id: projectMemberId }, data);
async updateProjectMemberById (
projectMemberId: string,
data: DeepPartial<ProjectMember>
): Promise<boolean> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
const updateResult = await projectMemberRepository.update(
{ id: projectMemberId },
data
);
return Boolean(updateResult.affected);
}
async addProjectMember (data: DeepPartial<ProjectMember>): Promise<ProjectMember> {
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
async addProjectMember (
data: DeepPartial<ProjectMember>
): Promise<ProjectMember> {
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
const newProjectMember = await projectMemberRepository.save(data);
return newProjectMember;
}
async addEnvironmentVariables (data: DeepPartial<EnvironmentVariable>[]): Promise<EnvironmentVariable[]> {
const environmentVariableRepository = this.dataSource.getRepository(EnvironmentVariable);
const savedEnvironmentVariables = await environmentVariableRepository.save(data);
async addEnvironmentVariables (
data: DeepPartial<EnvironmentVariable>[]
): Promise<EnvironmentVariable[]> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
const savedEnvironmentVariables =
await environmentVariableRepository.save(data);
return savedEnvironmentVariables;
}
async updateEnvironmentVariable (environmentVariableId: string, data: DeepPartial<EnvironmentVariable>): Promise<boolean> {
const environmentVariableRepository = this.dataSource.getRepository(EnvironmentVariable);
const updateResult = await environmentVariableRepository.update({ id: environmentVariableId }, data);
async updateEnvironmentVariable (
environmentVariableId: string,
data: DeepPartial<EnvironmentVariable>
): Promise<boolean> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
const updateResult = await environmentVariableRepository.update(
{ id: environmentVariableId },
data
);
return Boolean(updateResult.affected);
}
async deleteEnvironmentVariable (environmentVariableId: string): Promise<boolean> {
const environmentVariableRepository = this.dataSource.getRepository(EnvironmentVariable);
const deleteResult = await environmentVariableRepository.delete({ id: environmentVariableId });
async deleteEnvironmentVariable (
environmentVariableId: string
): Promise<boolean> {
const environmentVariableRepository =
this.dataSource.getRepository(EnvironmentVariable);
const deleteResult = await environmentVariableRepository.delete({
id: environmentVariableId
});
if (deleteResult.affected) {
return deleteResult.affected > 0;
@@ -263,7 +378,8 @@ export class Database {
}
async getProjectMemberById (projectMemberId: string): Promise<ProjectMember> {
const projectMemberRepository = this.dataSource.getRepository(ProjectMember);
const projectMemberRepository =
this.dataSource.getRepository(ProjectMember);
const projectMemberWithProject = await projectMemberRepository.find({
relations: {
@@ -275,8 +391,7 @@ export class Database {
where: {
id: projectMemberId
}
}
);
});
if (projectMemberWithProject.length === 0) {
throw new Error('Member does not exist');
@@ -285,34 +400,66 @@ export class Database {
return projectMemberWithProject[0];
}
async getProjectsBySearchText (userId: string, searchText: string): Promise<Project[]> {
async getProjectsBySearchText (
userId: string,
searchText: string
): Promise<Project[]> {
const projectRepository = this.dataSource.getRepository(Project);
const projects = await projectRepository
.createQueryBuilder('project')
.leftJoinAndSelect('project.organization', 'organization')
.leftJoin('project.projectMembers', 'projectMembers')
.where('(project.owner = :userId OR projectMembers.member.id = :userId) AND project.name LIKE :searchText', {
userId,
searchText: `%${searchText}%`
})
.where(
'(project.owner = :userId OR projectMembers.member.id = :userId) AND project.name LIKE :searchText',
{
userId,
searchText: `%${searchText}%`
}
)
.getMany();
return projects;
}
async updateDeploymentById (deploymentId: string, data: DeepPartial<Deployment>): Promise<boolean> {
async updateDeploymentById (
deploymentId: string,
data: DeepPartial<Deployment>
): Promise<boolean> {
return this.updateDeployment({ id: deploymentId }, data);
}
async updateDeployment (criteria: FindOptionsWhere<Deployment>, data: DeepPartial<Deployment>): Promise<boolean> {
async updateDeployment (
criteria: FindOptionsWhere<Deployment>,
data: DeepPartial<Deployment>
): Promise<boolean> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const updateResult = await deploymentRepository.update(criteria, data);
return Boolean(updateResult.affected);
}
async addProject (userId: string, organizationId: string, data: DeepPartial<Project>): Promise<Project> {
async updateDeploymentsByProjectIds (
projectIds: string[],
data: DeepPartial<Deployment>
): Promise<boolean> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const updateResult = await deploymentRepository
.createQueryBuilder()
.update(Deployment)
.set(data)
.where('projectId IN (:...projectIds)', { projectIds })
.execute();
return Boolean(updateResult.affected);
}
async addProject (
userId: string,
organizationId: string,
data: DeepPartial<Project>
): Promise<Project> {
const projectRepository = this.dataSource.getRepository(Project);
// TODO: Check if organization exists
@@ -335,9 +482,15 @@ export class Database {
return projectRepository.save(newProject);
}
async updateProjectById (projectId: string, data: DeepPartial<Project>): Promise<boolean> {
async updateProjectById (
projectId: string,
data: DeepPartial<Project>
): Promise<boolean> {
const projectRepository = this.dataSource.getRepository(Project);
const updateResult = await projectRepository.update({ id: projectId }, data);
const updateResult = await projectRepository.update(
{ id: projectId },
data
);
return Boolean(updateResult.affected);
}
@@ -384,14 +537,20 @@ export class Database {
return domain;
}
async updateDomainById (domainId: string, data: DeepPartial<Domain>): Promise<boolean> {
async updateDomainById (
domainId: string,
data: DeepPartial<Domain>
): Promise<boolean> {
const domainRepository = this.dataSource.getRepository(Domain);
const updateResult = await domainRepository.update({ id: domainId }, data);
return Boolean(updateResult.affected);
}
async getDomainsByProjectId (projectId: string, filter?: FindOptionsWhere<Domain>): Promise<Domain[]> {
async getDomainsByProjectId (
projectId: string,
filter?: FindOptionsWhere<Domain>
): Promise<Domain[]> {
const domainRepository = this.dataSource.getRepository(Domain);
const domains = await domainRepository.find({
+39 -14
View File
@@ -12,6 +12,7 @@ import {
import { Project } from './Project';
import { Domain } from './Domain';
import { User } from './User';
import { AppDeploymentRecordAttributes } from '../types';
export enum Environment {
Production = 'Production',
@@ -25,18 +26,27 @@ export enum DeploymentStatus {
Error = 'Error',
}
export interface ApplicationDeploymentRequest {
type: string;
version: string;
name: string;
application: string;
config: string;
meta: string;
}
export interface ApplicationRecord {
type: string;
version:string
name?: string
description?: string
homepage?: string
license?: string
author?: string
repository?: string[],
app_version?: string
repository_ref: string
app_type: string
version: string;
name: string;
description?: string;
homepage?: string;
license?: string;
author?: string;
repository?: string[];
app_version?: string;
repository_ref: string;
app_type: string;
}
@Entity()
@@ -45,6 +55,9 @@ export class Deployment {
@PrimaryColumn('varchar')
id!: string;
@Column()
projectId!: string;
@ManyToOne(() => Project, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'projectId' })
project!: Project;
@@ -65,14 +78,26 @@ export class Deployment {
@Column('varchar')
commitMessage!: string;
@Column('varchar')
url!: string;
@Column('varchar', { nullable: true })
url!: string | null;
@Column('varchar')
registryRecordId!: string;
applicationRecordId!: string;
@Column('simple-json')
registryRecordData!: ApplicationRecord;
applicationRecordData!: ApplicationRecord;
@Column('varchar')
applicationDeploymentRequestId!: string;
@Column('simple-json')
applicationDeploymentRequestData!: ApplicationDeploymentRequest;
@Column('varchar', { nullable: true })
applicationDeploymentRecordId!: string | null;
@Column('simple-json', { nullable: true })
applicationDeploymentRecordData!: AppDeploymentRecordAttributes | null;
@Column({
enum: Environment
+1 -1
View File
@@ -39,7 +39,7 @@ export class Domain {
@ManyToOne(() => Domain)
@JoinColumn({ name: 'redirectToId' })
// eslint-disable-next-line no-use-before-define
// eslint-disable-next-line no-use-before-define
redirectTo!: Domain | null;
@Column({
+7 -3
View File
@@ -27,8 +27,12 @@ export class Organization {
@UpdateDateColumn()
updatedAt!: Date;
@OneToMany(() => UserOrganization, userOrganization => userOrganization.organization, {
cascade: ['soft-remove']
})
@OneToMany(
() => UserOrganization,
(userOrganization) => userOrganization.organization,
{
cascade: ['soft-remove']
}
)
userOrganizations!: UserOrganization[];
}
+1 -16
View File
@@ -15,15 +15,6 @@ import { Organization } from './Organization';
import { ProjectMember } from './ProjectMember';
import { Deployment } from './Deployment';
export interface ApplicationDeploymentRequest {
type: string
version: string
name: string
application: string
config: string,
meta: string
}
@Entity()
export class Project {
@PrimaryGeneratedColumn('uuid')
@@ -52,12 +43,6 @@ export class Project {
@Column('varchar', { length: 255, default: 'main' })
prodBranch!: string;
@Column('varchar', { nullable: true })
registryRecordId!: string | null;
@Column('simple-json', { nullable: true })
registryRecordData!: ApplicationDeploymentRequest | null;
@Column('text', { default: '' })
description!: string;
@@ -91,7 +76,7 @@ export class Project {
@OneToMany(() => Deployment, (deployment) => deployment.project)
deployments!: Deployment[];
@OneToMany(() => ProjectMember, projectMember => projectMember.project, {
@OneToMany(() => ProjectMember, (projectMember) => projectMember.project, {
cascade: ['soft-remove']
})
projectMembers!: ProjectMember[];
+1 -1
View File
@@ -15,7 +15,7 @@ import { User } from './User';
export enum Permission {
View = 'View',
Edit = 'Edit'
Edit = 'Edit',
}
@Entity()
+8 -4
View File
@@ -34,13 +34,17 @@ export class User {
@CreateDateColumn()
updatedAt!: Date;
@OneToMany(() => ProjectMember, projectMember => projectMember.project, {
@OneToMany(() => ProjectMember, (projectMember) => projectMember.project, {
cascade: ['soft-remove']
})
projectMembers!: ProjectMember[];
@OneToMany(() => UserOrganization, UserOrganization => UserOrganization.member, {
cascade: ['soft-remove']
})
@OneToMany(
() => UserOrganization,
(UserOrganization) => UserOrganization.member,
{
cascade: ['soft-remove']
}
)
userOrganizations!: UserOrganization[];
}
+12 -3
View File
@@ -19,7 +19,9 @@ const OAUTH_CLIENT_TYPE = 'oauth-app';
export const main = async (): Promise<void> => {
// TODO: get config path using cli
const { server, database, gitHub, registryConfig } = await getConfig<Config>(DEFAULT_CONFIG_FILE_PATH);
const { server, database, gitHub, registryConfig } = await getConfig<Config>(
DEFAULT_CONFIG_FILE_PATH
);
const app = new OAuthApp({
clientType: OAUTH_CLIENT_TYPE,
@@ -31,9 +33,16 @@ export const main = async (): Promise<void> => {
await db.init();
const registry = new Registry(registryConfig);
const service = new Service({ gitHubConfig: gitHub }, db, app, registry);
const service = new Service(
{ gitHubConfig: gitHub, registryConfig },
db,
app,
registry
);
const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.gql')).toString();
const typeDefs = fs
.readFileSync(path.join(__dirname, 'schema.gql'))
.toString();
const resolvers = await createResolvers(service);
await createAndStartServer(server, typeDefs, resolvers, service);
+115 -42
View File
@@ -6,48 +6,72 @@ import { DateTime } from 'luxon';
import { Registry as LaconicRegistry } from '@cerc-io/laconic-sdk';
import { RegistryConfig } from './config';
import { ApplicationDeploymentRequest } from './entity/Project';
import { ApplicationRecord } from './entity/Deployment';
import { PackageJSON } from './types';
import {
ApplicationRecord,
Deployment,
ApplicationDeploymentRequest
} from './entity/Deployment';
import { AppDeploymentRecord, PackageJSON } from './types';
const log = debug('snowball:registry');
const APP_RECORD_TYPE = 'ApplicationRecord';
const DEPLOYMENT_RECORD_TYPE = 'ApplicationDeploymentRequest';
const APP_DEPLOYMENT_REQUEST_TYPE = 'ApplicationDeploymentRequest';
const APP_DEPLOYMENT_RECORD_TYPE = 'ApplicationDeploymentRecord';
// TODO: Move registry code to laconic-sdk/watcher-ts
export class Registry {
private registry: LaconicRegistry;
private registryConfig: RegistryConfig;
constructor (registryConfig : RegistryConfig) {
constructor (registryConfig: RegistryConfig) {
this.registryConfig = registryConfig;
this.registry = new LaconicRegistry(registryConfig.gqlEndpoint, registryConfig.restEndpoint, registryConfig.chainId);
this.registry = new LaconicRegistry(
registryConfig.gqlEndpoint,
registryConfig.restEndpoint,
registryConfig.chainId
);
}
async createApplicationRecord ({
appName,
packageJSON,
commitHash,
appType,
repoUrl
}: {
packageJSON: PackageJSON
commitHash: string,
appType: string,
repoUrl: string
}): Promise<{registryRecordId: string, registryRecordData: ApplicationRecord}> {
appName: string;
packageJSON: PackageJSON;
commitHash: string;
appType: string;
repoUrl: string;
}): Promise<{
applicationRecordId: string;
applicationRecordData: ApplicationRecord;
}> {
// Use laconic-sdk to publish record
// Reference: https://git.vdb.to/cerc-io/test-progressive-web-app/src/branch/main/scripts/publish-app-record.sh
// Fetch previous records
const records = await this.registry.queryRecords({
type: APP_RECORD_TYPE,
name: packageJSON.name
}, true);
const records = await this.registry.queryRecords(
{
type: APP_RECORD_TYPE,
name: packageJSON.name
},
true
);
// Get next version of record
const bondRecords = records.filter((record: any) => record.bondId === this.registryConfig.bondId);
const [latestBondRecord] = bondRecords.sort((a: any, b: any) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime());
const nextVersion = semverInc(latestBondRecord?.attributes.version ?? '0.0.0', 'patch');
const bondRecords = records.filter(
(record: any) => record.bondId === this.registryConfig.bondId
);
const [latestBondRecord] = bondRecords.sort(
(a: any, b: any) =>
new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
);
const nextVersion = semverInc(
latestBondRecord?.attributes.version ?? '0.0.0',
'patch'
);
assert(nextVersion, 'Application record version not valid');
@@ -58,11 +82,16 @@ export class Registry {
repository_ref: commitHash,
repository: [repoUrl],
app_type: appType,
...(packageJSON.name && { name: packageJSON.name }),
name: appName,
...(packageJSON.description && { description: packageJSON.description }),
...(packageJSON.homepage && { homepage: packageJSON.homepage }),
...(packageJSON.license && { license: packageJSON.license }),
...(packageJSON.author && { author: typeof packageJSON.author === 'object' ? JSON.stringify(packageJSON.author) : packageJSON.author }),
...(packageJSON.author && {
author:
typeof packageJSON.author === 'object'
? JSON.stringify(packageJSON.author)
: packageJSON.author
}),
...(packageJSON.version && { app_version: packageJSON.version })
};
@@ -79,26 +108,45 @@ export class Registry {
log('Application record data:', applicationRecord);
// TODO: Discuss computation of CRN
const crn = this.getCrn(packageJSON.name ?? '');
const crn = this.getCrn(packageJSON.name, appName);
log(`Setting name: ${crn} for record ID: ${result.data.id}`);
await this.registry.setName({ cid: result.data.id, crn }, this.registryConfig.privateKey, this.registryConfig.fee);
await this.registry.setName({ cid: result.data.id, crn: `${crn}@${applicationRecord.app_version}` }, this.registryConfig.privateKey, this.registryConfig.fee);
await this.registry.setName({ cid: result.data.id, crn: `${crn}@${applicationRecord.repository_ref}` }, this.registryConfig.privateKey, this.registryConfig.fee);
await this.registry.setName(
{ cid: result.data.id, crn },
this.registryConfig.privateKey,
this.registryConfig.fee
);
await this.registry.setName(
{ cid: result.data.id, crn: `${crn}@${applicationRecord.app_version}` },
this.registryConfig.privateKey,
this.registryConfig.fee
);
await this.registry.setName(
{
cid: result.data.id,
crn: `${crn}@${applicationRecord.repository_ref}`
},
this.registryConfig.privateKey,
this.registryConfig.fee
);
return { registryRecordId: result.data.id, registryRecordData: applicationRecord };
return {
applicationRecordId: result.data.id,
applicationRecordData: applicationRecord
};
}
async createApplicationDeploymentRequest (data: {
appName: string,
commitHash: string,
repository: string,
environmentVariables: { [key: string]: string }
appName: string;
packageJsonName: string;
commitHash: string;
repository: string;
environmentVariables: { [key: string]: string };
}): Promise<{
registryRecordId: string,
registryRecordData: ApplicationDeploymentRequest
applicationDeploymentRequestId: string;
applicationDeploymentRequestData: ApplicationDeploymentRequest;
}> {
const crn = this.getCrn(data.appName);
const crn = this.getCrn(data.packageJsonName, data.appName);
const records = await this.registry.resolveNames([crn]);
const applicationRecord = records[0];
@@ -108,7 +156,7 @@ export class Registry {
// Create record of type ApplicationDeploymentRequest and publish
const applicationDeploymentRequest = {
type: DEPLOYMENT_RECORD_TYPE,
type: APP_DEPLOYMENT_REQUEST_TYPE,
version: '1.0.0',
name: `${applicationRecord.attributes.name}@${applicationRecord.attributes.app_version}`,
application: `${crn}@${applicationRecord.attributes.app_version}`,
@@ -122,7 +170,9 @@ export class Registry {
env: data.environmentVariables
}),
meta: JSON.stringify({
note: `Added by Snowball @ ${DateTime.utc().toFormat('EEE LLL dd HH:mm:ss \'UTC\' yyyy')}`,
note: `Added by Snowball @ ${DateTime.utc().toFormat(
"EEE LLL dd HH:mm:ss 'UTC' yyyy"
)}`,
repository: data.repository,
repository_ref: data.commitHash
})
@@ -140,17 +190,40 @@ export class Registry {
log(`Application deployment request record published: ${result.data.id}`);
log('Application deployment request data:', applicationDeploymentRequest);
return { registryRecordId: result.data.id, registryRecordData: applicationDeploymentRequest };
return {
applicationDeploymentRequestId: result.data.id,
applicationDeploymentRequestData: applicationDeploymentRequest
};
}
getCrn (packageJsonName: string): string {
const [arg1, arg2] = packageJsonName.split('/');
/**
* Fetch ApplicationDeploymentRecords for deployments
*/
async getDeploymentRecords (
deployments: Deployment[]
): Promise<AppDeploymentRecord[]> {
// Fetch ApplicationDeploymentRecords for corresponding ApplicationRecord set in deployments
// TODO: Implement Laconicd GQL query to filter records by multiple values for an attribute
const records = await this.registry.queryRecords(
{
type: APP_DEPLOYMENT_RECORD_TYPE
},
true
);
if (arg2) {
const authority = arg1.replace('@', '');
return `crn://${authority}/applications/${arg2}`;
}
// Filter records with ApplicationRecord ids
return records.filter((record: AppDeploymentRecord) =>
deployments.some(
(deployment) =>
deployment.applicationRecordId === record.attributes.application
)
);
}
return `crn://${arg1}/applications/${arg1}`;
getCrn (packageJsonName: string, appName: string): string {
const [arg1] = packageJsonName.split('/');
const authority = arg1.replace('@', '');
return `crn://${authority}/applications/${appName}`;
}
}
+148 -38
View File
@@ -17,7 +17,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
return service.getUser(context.userId);
},
organizations: async (_:any, __: any, context: any) => {
organizations: async (_: any, __: any, context: any) => {
return service.getOrganizationsByUserId(context.userId);
},
@@ -25,15 +25,25 @@ export const createResolvers = async (service: Service): Promise<any> => {
return service.getProjectById(projectId);
},
projectsInOrganization: async (_: any, { organizationSlug }: {organizationSlug: string }, context: any) => {
return service.getProjectsInOrganization(context.userId, organizationSlug);
projectsInOrganization: async (
_: any,
{ organizationSlug }: { organizationSlug: string },
context: any
) => {
return service.getProjectsInOrganization(
context.userId,
organizationSlug
);
},
deployments: async (_: any, { projectId }: { projectId: string }) => {
return service.getDeployementsByProjectId(projectId);
return service.getDeploymentsByProjectId(projectId);
},
environmentVariables: async (_: any, { projectId }: { projectId: string }) => {
environmentVariables: async (
_: any,
{ projectId }: { projectId: string }
) => {
return service.getEnvironmentVariablesByProjectId(projectId);
},
@@ -41,32 +51,55 @@ export const createResolvers = async (service: Service): Promise<any> => {
return service.getProjectMembersByProjectId(projectId);
},
searchProjects: async (_: any, { searchText }: { searchText: string }, context: any) => {
searchProjects: async (
_: any,
{ searchText }: { searchText: string },
context: any
) => {
return service.searchProjects(context.userId, searchText);
},
domains: async (_:any, { projectId, filter }: { projectId: string, filter?: FindOptionsWhere<Domain> }) => {
domains: async (
_: any,
{
projectId,
filter
}: { projectId: string; filter?: FindOptionsWhere<Domain> }
) => {
return service.getDomainsByProjectId(projectId, filter);
}
},
// TODO: Return error in GQL response
Mutation: {
removeProjectMember: async (_: any, { projectMemberId }: { projectMemberId: string }, context: any) => {
removeProjectMember: async (
_: any,
{ projectMemberId }: { projectMemberId: string },
context: any
) => {
try {
return await service.removeProjectMember(context.userId, projectMemberId);
return await service.removeProjectMember(
context.userId,
projectMemberId
);
} catch (err) {
log(err);
return false;
}
},
updateProjectMember: async (_: any, { projectMemberId, data }: {
projectMemberId: string,
data: {
permissions: Permission[]
updateProjectMember: async (
_: any,
{
projectMemberId,
data
}: {
projectMemberId: string;
data: {
permissions: Permission[];
};
}
}) => {
) => {
try {
return await service.updateProjectMember(projectMemberId, data);
} catch (err) {
@@ -75,13 +108,19 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
addProjectMember: async (_: any, { projectId, data }: {
projectId: string,
data: {
email: string,
permissions: Permission[]
addProjectMember: async (
_: any,
{
projectId,
data
}: {
projectId: string;
data: {
email: string;
permissions: Permission[];
};
}
}) => {
) => {
try {
return Boolean(await service.addProjectMember(projectId, data));
} catch (err) {
@@ -90,25 +129,51 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
addEnvironmentVariables: async (_: any, { projectId, data }: { projectId: string, data: { environments: string[], key: string, value: string}[] }) => {
addEnvironmentVariables: async (
_: any,
{
projectId,
data
}: {
projectId: string;
data: { environments: string[]; key: string; value: string }[];
}
) => {
try {
return Boolean(await service.addEnvironmentVariables(projectId, data));
return Boolean(
await service.addEnvironmentVariables(projectId, data)
);
} catch (err) {
log(err);
return false;
}
},
updateEnvironmentVariable: async (_: any, { environmentVariableId, data }: { environmentVariableId: string, data : DeepPartial<EnvironmentVariable>}) => {
updateEnvironmentVariable: async (
_: any,
{
environmentVariableId,
data
}: {
environmentVariableId: string;
data: DeepPartial<EnvironmentVariable>;
}
) => {
try {
return await service.updateEnvironmentVariable(environmentVariableId, data);
return await service.updateEnvironmentVariable(
environmentVariableId,
data
);
} catch (err) {
log(err);
return false;
}
},
removeEnvironmentVariable: async (_: any, { environmentVariableId }: { environmentVariableId: string}) => {
removeEnvironmentVariable: async (
_: any,
{ environmentVariableId }: { environmentVariableId: string }
) => {
try {
return await service.removeEnvironmentVariable(environmentVariableId);
} catch (err) {
@@ -117,25 +182,45 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
updateDeploymentToProd: async (_: any, { deploymentId }: { deploymentId: string }, context: any) => {
updateDeploymentToProd: async (
_: any,
{ deploymentId }: { deploymentId: string },
context: any
) => {
try {
return Boolean(await service.updateDeploymentToProd(context.userId, deploymentId));
return Boolean(
await service.updateDeploymentToProd(context.userId, deploymentId)
);
} catch (err) {
log(err);
return false;
}
},
addProject: async (_: any, { organizationSlug, data }: { organizationSlug: string, data: DeepPartial<Project> }, context: any) => {
addProject: async (
_: any,
{
organizationSlug,
data
}: { organizationSlug: string; data: DeepPartial<Project> },
context: any
) => {
try {
return await service.addProject(context.userId, organizationSlug, data);
return await service.addProject(
context.userId,
organizationSlug,
data
);
} catch (err) {
log(err);
throw err;
}
},
updateProject: async (_: any, { projectId, data }: { projectId: string, data: DeepPartial<Project> }) => {
updateProject: async (
_: any,
{ projectId, data }: { projectId: string; data: DeepPartial<Project> }
) => {
try {
return await service.updateProject(projectId, data);
} catch (err) {
@@ -144,9 +229,15 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
redeployToProd: async (_: any, { deploymentId }: { deploymentId: string }, context: any) => {
redeployToProd: async (
_: any,
{ deploymentId }: { deploymentId: string },
context: any
) => {
try {
return Boolean(await service.redeployToProd(context.userId, deploymentId));
return Boolean(
await service.redeployToProd(context.userId, deploymentId)
);
} catch (err) {
log(err);
return false;
@@ -157,7 +248,8 @@ export const createResolvers = async (service: Service): Promise<any> => {
try {
return await service.deleteProject(projectId);
} catch (err) {
log(err); return false;
log(err);
return false;
}
},
@@ -170,7 +262,13 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
rollbackDeployment: async (_: any, { projectId, deploymentId }: {deploymentId: string, projectId: string }) => {
rollbackDeployment: async (
_: any,
{
projectId,
deploymentId
}: { deploymentId: string; projectId: string }
) => {
try {
return await service.rollbackDeployment(projectId, deploymentId);
} catch (err) {
@@ -179,7 +277,10 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
addDomain: async (_: any, { projectId, data }: { projectId: string, data: { name: string } }) => {
addDomain: async (
_: any,
{ projectId, data }: { projectId: string; data: { name: string } }
) => {
try {
return Boolean(await service.addDomain(projectId, data));
} catch (err) {
@@ -188,7 +289,10 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
updateDomain: async (_: any, { domainId, data }: { domainId: string, data: DeepPartial<Domain>}) => {
updateDomain: async (
_: any,
{ domainId, data }: { domainId: string; data: DeepPartial<Domain> }
) => {
try {
return await service.updateDomain(domainId, data);
} catch (err) {
@@ -197,7 +301,11 @@ export const createResolvers = async (service: Service): Promise<any> => {
}
},
authenticateGitHub: async (_: any, { code }: { code: string }, context: any) => {
authenticateGitHub: async (
_: any,
{ code }: { code: string },
context: any
) => {
try {
return await service.authenticateGitHub(code, context.userId);
} catch (err) {
@@ -208,7 +316,9 @@ export const createResolvers = async (service: Service): Promise<any> => {
unauthenticateGitHub: async (_: any, __: object, context: any) => {
try {
return service.unauthenticateGitHub(context.userId, { gitHubToken: null });
return service.unauthenticateGitHub(context.userId, {
gitHubToken: null
});
} catch (err) {
log(err);
return false;
+13 -4
View File
@@ -91,7 +91,7 @@ type Deployment {
branch: String!
commitHash: String!
commitMessage: String!
url: String!
url: String
environment: Environment!
isCurrent: Boolean!
status: DeploymentStatus!
@@ -188,10 +188,19 @@ type Query {
type Mutation {
addProjectMember(projectId: String!, data: AddProjectMemberInput): Boolean!
updateProjectMember(projectMemberId: String!, data: UpdateProjectMemberInput): Boolean!
updateProjectMember(
projectMemberId: String!
data: UpdateProjectMemberInput
): Boolean!
removeProjectMember(projectMemberId: String!): Boolean!
addEnvironmentVariables(projectId: String!, data: [AddEnvironmentVariableInput!]): Boolean!
updateEnvironmentVariable(environmentVariableId: String!, data: UpdateEnvironmentVariableInput!): Boolean!
addEnvironmentVariables(
projectId: String!
data: [AddEnvironmentVariableInput!]
): Boolean!
updateEnvironmentVariable(
environmentVariableId: String!
data: UpdateEnvironmentVariableInput!
): Boolean!
removeEnvironmentVariable(environmentVariableId: String!): Boolean!
updateDeploymentToProd(deploymentId: String!): Boolean!
addProject(organizationSlug: String!, data: AddProjectInput): Project!
+367 -150
View File
@@ -14,14 +14,16 @@ import { Project } from './entity/Project';
import { Permission, ProjectMember } from './entity/ProjectMember';
import { User } from './entity/User';
import { Registry } from './registry';
import { GitHubConfig } from './config';
import { GitPushEventPayload } from './types';
import { GitHubConfig, RegistryConfig } from './config';
import { AppDeploymentRecord, GitPushEventPayload, PackageJSON } from './types';
const log = debug('snowball:service');
const GITHUB_UNIQUE_WEBHOOK_ERROR = 'Hook already exists on this repository';
interface Config {
gitHubConfig: GitHubConfig
gitHubConfig: GitHubConfig;
registryConfig: RegistryConfig;
}
export class Service {
@@ -30,11 +32,124 @@ export class Service {
private registry: Registry;
private config: Config;
private deployRecordCheckTimeout?: NodeJS.Timeout;
constructor (config: Config, db: Database, app: OAuthApp, registry: Registry) {
this.db = db;
this.oauthApp = app;
this.registry = registry;
this.config = config;
this.init();
}
/**
* Initialize services
*/
init (): void {
// Start check for ApplicationDeploymentRecords asynchronously
this.checkDeployRecordsAndUpdate();
}
/**
* Destroy services
*/
destroy (): void {
clearTimeout(this.deployRecordCheckTimeout);
}
/**
* Checks for ApplicationDeploymentRecord and update corresponding deployments
* Continues check in loop after a delay of DEPLOY_RECORD_CHECK_DELAY_MS
*/
async checkDeployRecordsAndUpdate (): Promise<void> {
// Fetch deployments in building state
const deployments = await this.db.getDeployments({
where: {
status: DeploymentStatus.Building
// TODO: Fetch and check records for recent deployments
}
});
if (deployments.length) {
log(
`Found ${deployments.length} deployments in ${DeploymentStatus.Building} state`
);
// Fetch ApplicationDeploymentRecord for deployments
const records = await this.registry.getDeploymentRecords(deployments);
log(`Found ${records.length} ApplicationDeploymentRecords`);
// Update deployments for which ApplicationDeploymentRecords were returned
if (records.length) {
await this.updateDeploymentsWithRecordData(records);
}
}
this.deployRecordCheckTimeout = setTimeout(() => {
this.checkDeployRecordsAndUpdate();
}, this.config.registryConfig.fetchDeploymentRecordDelay);
}
/**
* Update deployments with ApplicationDeploymentRecord data
*/
async updateDeploymentsWithRecordData (
records: AppDeploymentRecord[]
): Promise<void> {
// Get deployments for ApplicationDeploymentRecords
const deployments = await this.db.getDeployments({
where: records.map((record) => ({
applicationRecordId: record.attributes.application
})),
order: {
createdAt: 'DESC'
}
});
// Get project IDs of deployments that are in production environment
const productionDeploymentProjectIds = deployments.reduce(
(acc, deployment): Set<string> => {
if (deployment.environment === Environment.Production) {
acc.add(deployment.projectId);
}
return acc;
},
new Set<string>()
);
// Set old deployments isCurrent to false
await this.db.updateDeploymentsByProjectIds(
Array.from(productionDeploymentProjectIds),
{ isCurrent: false }
);
const recordToDeploymentsMap = deployments.reduce(
(acc: { [key: string]: Deployment }, deployment) => {
acc[deployment.applicationRecordId] = deployment;
return acc;
},
{}
);
// Update deployment data for ApplicationDeploymentRecords
const deploymentUpdatePromises = records.map(async (record) => {
const deployment = recordToDeploymentsMap[record.attributes.application];
await this.db.updateDeploymentById(deployment.id, {
applicationDeploymentRecordId: record.id,
applicationDeploymentRecordData: record.attributes,
url: record.attributes.url,
status: DeploymentStatus.Ready,
isCurrent: deployment.environment === Environment.Production
});
log(
`Updated deployment ${deployment.id} with URL ${record.attributes.url}`
);
});
await Promise.all(deploymentUpdatePromises);
}
async getUser (userId: string): Promise<User | null> {
@@ -47,7 +162,10 @@ export class Service {
async getOctokit (userId: string): Promise<Octokit> {
const user = await this.db.getUser({ where: { id: userId } });
assert(user && user.gitHubToken, 'User needs to be authenticated with GitHub token');
assert(
user && user.gitHubToken,
'User needs to be authenticated with GitHub token'
);
return new Octokit({ auth: user.gitHubToken });
}
@@ -62,45 +180,68 @@ export class Service {
return dbProject;
}
async getProjectsInOrganization (userId:string, organizationSlug: string): Promise<Project[]> {
const dbProjects = await this.db.getProjectsInOrganization(userId, organizationSlug);
async getProjectsInOrganization (
userId: string,
organizationSlug: string
): Promise<Project[]> {
const dbProjects = await this.db.getProjectsInOrganization(
userId,
organizationSlug
);
return dbProjects;
}
async getDeployementsByProjectId (projectId: string): Promise<Deployment[]> {
async getDeploymentsByProjectId (projectId: string): Promise<Deployment[]> {
const dbDeployments = await this.db.getDeploymentsByProjectId(projectId);
return dbDeployments;
}
async getEnvironmentVariablesByProjectId (projectId: string): Promise<EnvironmentVariable[]> {
const dbEnvironmentVariables = await this.db.getEnvironmentVariablesByProjectId(projectId);
async getEnvironmentVariablesByProjectId (
projectId: string
): Promise<EnvironmentVariable[]> {
const dbEnvironmentVariables =
await this.db.getEnvironmentVariablesByProjectId(projectId);
return dbEnvironmentVariables;
}
async getProjectMembersByProjectId (projectId: string): Promise<ProjectMember[]> {
const dbProjectMembers = await this.db.getProjectMembersByProjectId(projectId);
async getProjectMembersByProjectId (
projectId: string
): Promise<ProjectMember[]> {
const dbProjectMembers =
await this.db.getProjectMembersByProjectId(projectId);
return dbProjectMembers;
}
async searchProjects (userId: string, searchText: string): Promise<Project[]> {
const dbProjects = await this.db.getProjectsBySearchText(userId, searchText);
const dbProjects = await this.db.getProjectsBySearchText(
userId,
searchText
);
return dbProjects;
}
async getDomainsByProjectId (projectId: string, filter?: FindOptionsWhere<Domain>): Promise<Domain[]> {
async getDomainsByProjectId (
projectId: string,
filter?: FindOptionsWhere<Domain>
): Promise<Domain[]> {
const dbDomains = await this.db.getDomainsByProjectId(projectId, filter);
return dbDomains;
}
async updateProjectMember (projectMemberId: string, data: {permissions: Permission[]}): Promise<boolean> {
async updateProjectMember (
projectMemberId: string,
data: { permissions: Permission[] }
): Promise<boolean> {
return this.db.updateProjectMemberById(projectMemberId, data);
}
async addProjectMember (projectId: string,
async addProjectMember (
projectId: string,
data: {
email: string,
permissions: Permission[]
}): Promise<ProjectMember> {
email: string;
permissions: Permission[];
}
): Promise<ProjectMember> {
// TODO: Send invitation
let user = await this.db.getUser({
where: {
@@ -128,7 +269,10 @@ export class Service {
return newProjectMember;
}
async removeProjectMember (userId: string, projectMemberId: string): Promise<boolean> {
async removeProjectMember (
userId: string,
projectMemberId: string
): Promise<boolean> {
const member = await this.db.getProjectMemberById(projectMemberId);
if (String(member.member.id) === userId) {
@@ -145,33 +289,48 @@ export class Service {
}
}
async addEnvironmentVariables (projectId: string, data: { environments: string[], key: string, value: string}[]): Promise<EnvironmentVariable[]> {
const formattedEnvironmentVariables = data.map((environmentVariable) => {
return environmentVariable.environments.map((environment) => {
return ({
key: environmentVariable.key,
value: environmentVariable.value,
environment: environment as Environment,
project: Object.assign(new Project(), {
id: projectId
})
async addEnvironmentVariables (
projectId: string,
data: { environments: string[]; key: string; value: string }[]
): Promise<EnvironmentVariable[]> {
const formattedEnvironmentVariables = data
.map((environmentVariable) => {
return environmentVariable.environments.map((environment) => {
return {
key: environmentVariable.key,
value: environmentVariable.value,
environment: environment as Environment,
project: Object.assign(new Project(), {
id: projectId
})
};
});
});
}).flat();
})
.flat();
const savedEnvironmentVariables = await this.db.addEnvironmentVariables(formattedEnvironmentVariables);
const savedEnvironmentVariables = await this.db.addEnvironmentVariables(
formattedEnvironmentVariables
);
return savedEnvironmentVariables;
}
async updateEnvironmentVariable (environmentVariableId: string, data : DeepPartial<EnvironmentVariable>): Promise<boolean> {
async updateEnvironmentVariable (
environmentVariableId: string,
data: DeepPartial<EnvironmentVariable>
): Promise<boolean> {
return this.db.updateEnvironmentVariable(environmentVariableId, data);
}
async removeEnvironmentVariable (environmentVariableId: string): Promise<boolean> {
async removeEnvironmentVariable (
environmentVariableId: string
): Promise<boolean> {
return this.db.deleteEnvironmentVariable(environmentVariableId);
}
async updateDeploymentToProd (userId: string, deploymentId: string): Promise<Deployment> {
async updateDeploymentToProd (
userId: string,
deploymentId: string
): Promise<Deployment> {
const oldDeployment = await this.db.getDeployment({
where: { id: deploymentId },
relations: {
@@ -183,23 +342,23 @@ export class Service {
throw new Error('Deployment does not exist');
}
const prodBranchDomains = await this.db.getDomainsByProjectId(oldDeployment.project.id, { branch: oldDeployment.project.prodBranch });
const prodBranchDomains = await this.db.getDomainsByProjectId(
oldDeployment.project.id,
{ branch: oldDeployment.project.prodBranch }
);
const octokit = await this.getOctokit(userId);
const newDeployement = await this.createDeployment(userId,
octokit,
{
project: oldDeployment.project,
isCurrent: true,
branch: oldDeployment.branch,
environment: Environment.Production,
domain: prodBranchDomains[0],
commitHash: oldDeployment.commitHash,
commitMessage: oldDeployment.commitMessage
});
const newDeployment = await this.createDeployment(userId, octokit, {
project: oldDeployment.project,
branch: oldDeployment.branch,
environment: Environment.Production,
domain: prodBranchDomains[0],
commitHash: oldDeployment.commitHash,
commitMessage: oldDeployment.commitMessage
});
return newDeployement;
return newDeployment;
}
async createDeployment (
@@ -209,7 +368,9 @@ export class Service {
recordData: { repoUrl?: string } = {}
): Promise<Deployment> {
assert(data.project?.repository, 'Project repository not found');
log(`Creating deployment in project ${data.project.name} from branch ${data.branch}`);
log(
`Creating deployment in project ${data.project.name} from branch ${data.branch}`
);
const [owner, repo] = data.project.repository.split('/');
const { data: packageJSONData } = await octokit.rest.repos.getContent({
@@ -224,61 +385,90 @@ export class Service {
}
assert(!Array.isArray(packageJSONData) && packageJSONData.type === 'file');
const packageJSON = JSON.parse(atob(packageJSONData.content));
const packageJSON: PackageJSON = JSON.parse(atob(packageJSONData.content));
assert(packageJSON.name, "name field doesn't exist in package.json");
if (!recordData.repoUrl) {
const { data: repoDetails } = await octokit.rest.repos.get({ owner, repo });
const { data: repoDetails } = await octokit.rest.repos.get({
owner,
repo
});
recordData.repoUrl = repoDetails.html_url;
}
// TODO: Set environment variables for each deployment (environment variables can`t be set in application record)
const { registryRecordId, registryRecordData } = await this.registry.createApplicationRecord({
packageJSON,
appType: data.project!.template!,
commitHash: data.commitHash!,
repoUrl: recordData.repoUrl
});
const { applicationRecordId, applicationRecordData } =
await this.registry.createApplicationRecord({
appName: repo,
packageJSON,
appType: data.project!.template!,
commitHash: data.commitHash!,
repoUrl: recordData.repoUrl
});
// Check if new deployment is set to current
if (data.isCurrent) {
// Update previous current deployment
await this.db.updateDeployment({
project: {
id: data.project.id
},
isCurrent: true
}, { isCurrent: false });
}
const environmentVariables =
await this.db.getEnvironmentVariablesByProjectId(data.project.id!, {
environment: Environment.Production
});
const environmentVariablesObj = environmentVariables.reduce(
(acc, env) => {
acc[env.key] = env.value;
return acc;
},
{} as { [key: string]: string }
);
const { applicationDeploymentRequestId, applicationDeploymentRequestData } =
await this.registry.createApplicationDeploymentRequest({
appName: repo,
packageJsonName: packageJSON.name,
commitHash: data.commitHash!,
repository: recordData.repoUrl,
environmentVariables: environmentVariablesObj
});
// Update previous deployment with prod branch domain
// TODO: Fix unique constraint error for domain
await this.db.updateDeployment({
domainId: data.domain?.id
}, {
domain: null
});
await this.db.updateDeployment(
{
domainId: data.domain?.id
},
{
domain: null
}
);
const newDeployement = await this.db.addDeployement({
const newDeployment = await this.db.addDeployment({
project: data.project,
branch: data.branch,
commitHash: data.commitHash,
commitMessage: data.commitMessage,
environment: data.environment,
isCurrent: data.isCurrent,
status: DeploymentStatus.Building,
registryRecordId,
registryRecordData,
applicationRecordId,
applicationRecordData,
applicationDeploymentRequestId,
applicationDeploymentRequestData,
domain: data.domain,
createdBy: Object.assign(new User(), {
id: userId
})
});
log(`Created deployment ${newDeployement.id} and published application record ${registryRecordId}`);
return newDeployement;
log(
`Created deployment ${newDeployment.id} and published application record ${applicationRecordId}`
);
return newDeployment;
}
async addProject (userId: string, organizationSlug: string, data: DeepPartial<Project>): Promise<Project | undefined> {
async addProject (
userId: string,
organizationSlug: string,
data: DeepPartial<Project>
): Promise<Project | undefined> {
const organization = await this.db.getOrganization({
where: {
slug: organizationSlug
@@ -293,7 +483,9 @@ export class Service {
const octokit = await this.getOctokit(userId);
const [owner, repo] = project.repository.split('/');
const { data: [latestCommit] } = await octokit.rest.repos.listCommits({
const {
data: [latestCommit]
} = await octokit.rest.repos.listCommits({
owner,
repo,
sha: project.prodBranch,
@@ -303,11 +495,11 @@ export class Service {
const { data: repoDetails } = await octokit.rest.repos.get({ owner, repo });
// Create deployment with prod branch and latest commit
const newDeployment = await this.createDeployment(userId,
await this.createDeployment(
userId,
octokit,
{
project,
isCurrent: true,
branch: project.prodBranch,
environment: Environment.Production,
domain: null,
@@ -319,27 +511,6 @@ export class Service {
}
);
const environmentVariables = await this.db.getEnvironmentVariablesByProjectId(project.id, { environment: Environment.Production });
const environmentVariablesObj = environmentVariables.reduce((acc, env) => {
acc[env.key] = env.value;
return acc;
}, {} as { [key: string]: string });
const { registryRecordId, registryRecordData } = await this.registry.createApplicationDeploymentRequest(
{
appName: newDeployment.registryRecordData.name!,
commitHash: latestCommit.sha,
repository: repoDetails.html_url,
environmentVariables: environmentVariablesObj
});
await this.db.updateProjectById(project.id, {
registryRecordId,
registryRecordData
});
await this.createRepoHook(octokit, project);
return project;
@@ -352,7 +523,10 @@ export class Service {
owner,
repo,
config: {
url: new URL('api/github/webhook', this.config.gitHubConfig.webhookUrl).href,
url: new URL(
'api/github/webhook',
this.config.gitHubConfig.webhookUrl
).href,
content_type: 'json'
},
events: ['push']
@@ -360,9 +534,13 @@ export class Service {
} catch (err) {
// https://docs.github.com/en/rest/repos/webhooks?apiVersion=2022-11-28#create-a-repository-webhook--status-codes
if (
!(err instanceof RequestError &&
err.status === 422 &&
(err.response?.data as any).errors.some((err: any) => err.message === GITHUB_UNIQUE_WEBHOOK_ERROR))
!(
err instanceof RequestError &&
err.status === 422 &&
(err.response?.data as any).errors.some(
(err: any) => err.message === GITHUB_UNIQUE_WEBHOOK_ERROR
)
)
) {
throw err;
}
@@ -374,7 +552,9 @@ export class Service {
async handleGitHubPush (data: GitPushEventPayload): Promise<void> {
const { repository, ref, head_commit: headCommit } = data;
log(`Handling GitHub push event from repository: ${repository.full_name}`);
const projects = await this.db.getProjects({ where: { repository: repository.full_name } });
const projects = await this.db.getProjects({
where: { repository: repository.full_name }
});
if (!projects.length) {
log(`No projects found for repository ${repository.full_name}`);
@@ -386,24 +566,29 @@ export class Service {
for await (const project of projects) {
const octokit = await this.getOctokit(project.ownerId);
const [domain] = await this.db.getDomainsByProjectId(project.id, { branch });
const [domain] = await this.db.getDomainsByProjectId(project.id, {
branch
});
// Create deployment with branch and latest commit in GitHub data
await this.createDeployment(project.ownerId,
octokit,
{
project,
isCurrent: project.prodBranch === branch,
branch,
environment: project.prodBranch === branch ? Environment.Production : Environment.Preview,
domain,
commitHash: headCommit.id,
commitMessage: headCommit.message
});
await this.createDeployment(project.ownerId, octokit, {
project,
branch,
environment:
project.prodBranch === branch
? Environment.Production
: Environment.Preview,
domain,
commitHash: headCommit.id,
commitMessage: headCommit.message
});
}
}
async updateProject (projectId: string, data: DeepPartial<Project>): Promise<boolean> {
async updateProject (
projectId: string,
data: DeepPartial<Project>
): Promise<boolean> {
return this.db.updateProjectById(projectId, data);
}
@@ -420,13 +605,18 @@ export class Service {
});
if (domainsRedirectedFrom.length > 0) {
throw new Error('Cannot delete domain since it has redirects from other domains');
throw new Error(
'Cannot delete domain since it has redirects from other domains'
);
}
return this.db.deleteDomainById(domainId);
}
async redeployToProd (userId: string, deploymentId: string): Promise<Deployment> {
async redeployToProd (
userId: string,
deploymentId: string
): Promise<Deployment> {
const oldDeployment = await this.db.getDeployment({
relations: {
project: true,
@@ -444,23 +634,23 @@ export class Service {
const octokit = await this.getOctokit(userId);
const newDeployement = await this.createDeployment(userId,
octokit,
{
project: oldDeployment.project,
// TODO: Put isCurrent field in project
branch: oldDeployment.branch,
isCurrent: true,
environment: Environment.Production,
domain: oldDeployment.domain,
commitHash: oldDeployment.commitHash,
commitMessage: oldDeployment.commitMessage
});
const newDeployment = await this.createDeployment(userId, octokit, {
project: oldDeployment.project,
// TODO: Put isCurrent field in project
branch: oldDeployment.branch,
environment: Environment.Production,
domain: oldDeployment.domain,
commitHash: oldDeployment.commitHash,
commitMessage: oldDeployment.commitMessage
});
return newDeployement;
return newDeployment;
}
async rollbackDeployment (projectId: string, deploymentId: string): Promise<boolean> {
async rollbackDeployment (
projectId: string,
deploymentId: string
): Promise<boolean> {
// TODO: Implement transactions
const oldCurrentDeployment = await this.db.getDeployment({
relations: {
@@ -475,19 +665,28 @@ export class Service {
});
if (!oldCurrentDeployment) {
throw new Error('Current deployement doesnot exist');
throw new Error('Current deployment doesnot exist');
}
const oldCurrentDeploymentUpdate = await this.db.updateDeploymentById(oldCurrentDeployment.id, { isCurrent: false, domain: null });
const oldCurrentDeploymentUpdate = await this.db.updateDeploymentById(
oldCurrentDeployment.id,
{ isCurrent: false, domain: null }
);
const newCurrentDeploymentUpdate = await this.db.updateDeploymentById(deploymentId, { isCurrent: true, domain: oldCurrentDeployment?.domain });
const newCurrentDeploymentUpdate = await this.db.updateDeploymentById(
deploymentId,
{ isCurrent: true, domain: oldCurrentDeployment?.domain }
);
return newCurrentDeploymentUpdate && oldCurrentDeploymentUpdate;
}
async addDomain (projectId: string, data: { name: string }): Promise<{
primaryDomain: Domain,
redirectedDomain: Domain
async addDomain (
projectId: string,
data: { name: string }
): Promise<{
primaryDomain: Domain;
redirectedDomain: Domain;
}> {
const currentProject = await this.db.getProjectById(projectId);
@@ -512,12 +711,20 @@ export class Service {
redirectTo: savedPrimaryDomain
};
const savedRedirectedDomain = await this.db.addDomain(redirectedDomainDetails);
const savedRedirectedDomain = await this.db.addDomain(
redirectedDomainDetails
);
return { primaryDomain: savedPrimaryDomain, redirectedDomain: savedRedirectedDomain };
return {
primaryDomain: savedPrimaryDomain,
redirectedDomain: savedRedirectedDomain
};
}
async updateDomain (domainId: string, data: DeepPartial<Domain>): Promise<boolean> {
async updateDomain (
domainId: string,
data: DeepPartial<Domain>
): Promise<boolean> {
const domain = await this.db.getDomain({
where: {
id: domainId
@@ -558,7 +765,9 @@ export class Service {
}
if (redirectedDomain.redirectToId) {
throw new Error('Unable to redirect to the domain because it is already redirecting elsewhere. Redirects cannot be chained.');
throw new Error(
'Unable to redirect to the domain because it is already redirecting elsewhere. Redirects cannot be chained.'
);
}
newDomain.redirectTo = redirectedDomain;
@@ -569,8 +778,13 @@ export class Service {
return updateResult;
}
async authenticateGitHub (code:string, userId: string): Promise<{token: string}> {
const { authentication: { token } } = await this.oauthApp.createToken({
async authenticateGitHub (
code: string,
userId: string
): Promise<{ token: string }> {
const {
authentication: { token }
} = await this.oauthApp.createToken({
code
});
@@ -579,7 +793,10 @@ export class Service {
return { token };
}
async unauthenticateGitHub (userId: string, data: DeepPartial<User>): Promise<boolean> {
async unauthenticateGitHub (
userId: string,
data: DeepPartial<User>
): Promise<boolean> {
return this.db.updateUser(userId, data);
}
}
+26 -2
View File
@@ -1,6 +1,6 @@
export interface PackageJSON {
name?: string;
version?: string;
name: string;
version: string;
author?: string;
description?: string;
homepage?: string;
@@ -25,3 +25,27 @@ export interface GitPushEventPayload {
message: string;
};
}
export interface AppDeploymentRecordAttributes {
application: string;
dns: string;
meta: string;
name: string;
request: string;
type: string;
url: string;
version: string;
}
interface RegistryRecord {
id: string;
names: string[] | null;
owners: string[];
bondId: string;
createTime: string;
expiryTime: string;
}
export interface AppDeploymentRecord extends RegistryRecord {
attributes: AppDeploymentRecordAttributes;
}
+47
View File
@@ -2,6 +2,7 @@ import fs from 'fs-extra';
import path from 'path';
import toml from 'toml';
import debug from 'debug';
import { DataSource, DeepPartial, EntityTarget, ObjectLiteral } from 'typeorm';
const log = debug('snowball:utils');
@@ -19,3 +20,49 @@ export const getConfig = async <ConfigType>(
return config;
};
export const checkFileExists = async (filePath: string): Promise<boolean> => {
try {
await fs.access(filePath, fs.constants.F_OK);
return true;
} catch (err) {
log(err);
return false;
}
};
export const getEntities = async (filePath: string): Promise<any> => {
const entitiesData = await fs.readFile(filePath, 'utf-8');
const entities = JSON.parse(entitiesData);
return entities;
};
export const loadAndSaveData = async <Entity extends ObjectLiteral>(
entityType: EntityTarget<Entity>,
dataSource: DataSource,
entities: any,
relations?: any | undefined
): Promise<Entity[]> => {
const entityRepository = dataSource.getRepository(entityType);
const savedEntity: Entity[] = [];
for (const entityData of entities) {
let entity = entityRepository.create(entityData as DeepPartial<Entity>);
if (relations) {
for (const field in relations) {
const valueIndex = String(field + 'Index');
entity = {
...entity,
[field]: relations[field][entityData[valueIndex]]
};
}
}
const dbEntity = await entityRepository.save(entity);
savedEntity.push(dbEntity);
}
return savedEntity;
};
+1 -1
View File
@@ -18,4 +18,4 @@ const main = async () => {
deleteFile(config.database.dbPath);
};
main().catch(err => log(err));
main().catch((err) => log(err));
+71 -49
View File
@@ -1,14 +1,16 @@
[
{
"projectIndex": 0,
"domainIndex":0,
"domainIndex": 0,
"createdByIndex": 0,
"id":"ffhae3zq",
"status": "Building",
"id": "ffhae3zq",
"status": "Ready",
"environment": "Production",
"isCurrent": true,
"registryRecordId": "qbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"applicationRecordId": "qbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationRecordData": {},
"applicationDeploymentRequestId": "xqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "main",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -16,14 +18,16 @@
},
{
"projectIndex": 0,
"domainIndex":1,
"domainIndex": 1,
"createdByIndex": 0,
"id":"vehagei8",
"id": "vehagei8",
"status": "Ready",
"environment": "Preview",
"isCurrent": false,
"registryRecordId": "wbafyreihvzya6ovp4yfpkqnddkui2iw7thbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"applicationRecordId": "wbafyreihvzya6ovp4yfpkqnddkui2iw7thbhwq74lbqs7bhobvmfhrowoi",
"applicationRecordData": {},
"applicationDeploymentRequestId": "wqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "test",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -31,14 +35,16 @@
},
{
"projectIndex": 0,
"domainIndex":2,
"domainIndex": 2,
"createdByIndex": 0,
"id":"qmgekyte",
"status": "Error",
"id": "qmgekyte",
"status": "Ready",
"environment": "Development",
"isCurrent": false,
"registryRecordId": "ebafyreihvzya6ovp4yfpkqnddkui2iw7t6bhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"applicationRecordId": "ebafyreihvzya6ovp4yfpkqnddkui2iw7t6bhwq74lbqs7bhobvmfhrowoi",
"applicationRecordData": {},
"applicationDeploymentRequestId": "kqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "test",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -48,12 +54,14 @@
"projectIndex": 0,
"domainIndex": null,
"createdByIndex": 0,
"id":"f8wsyim6",
"id": "f8wsyim6",
"status": "Ready",
"environment": "Production",
"isCurrent": false,
"registryRecordId": "rbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhw74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"applicationRecordId": "rbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhw74lbqs7bhobvmfhrowoi",
"applicationRecordData": {},
"applicationDeploymentRequestId": "yqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "prod",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -61,14 +69,16 @@
},
{
"projectIndex": 1,
"domainIndex":3,
"domainIndex": 3,
"createdByIndex": 1,
"id":"eO8cckxk",
"status": "Building",
"id": "eO8cckxk",
"status": "Ready",
"environment": "Production",
"isCurrent": true,
"registryRecordId": "tbafyreihvzya6ovp4yfpqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"applicationRecordId": "tbafyreihvzya6ovp4yfpqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationRecordData": {},
"applicationDeploymentRequestId": "pqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "main",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -76,14 +86,16 @@
},
{
"projectIndex": 1,
"domainIndex":4,
"domainIndex": 4,
"createdByIndex": 1,
"id":"yaq0t5yw",
"id": "yaq0t5yw",
"status": "Ready",
"environment": "Preview",
"isCurrent": false,
"registryRecordId": "ybafyreihvzya6ovp4yfpkqnddkui2iw7t6bhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"applicationRecordId": "ybafyreihvzya6ovp4yfpkqnddkui2iw7t6bhwq74lbqs7bhobvmfhrowoi",
"applicationRecordData": {},
"applicationDeploymentRequestId": "tqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "test",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -91,14 +103,16 @@
},
{
"projectIndex": 1,
"domainIndex":5,
"domainIndex": 5,
"createdByIndex": 1,
"id":"hwwr6sbx",
"status": "Error",
"id": "hwwr6sbx",
"status": "Ready",
"environment": "Development",
"isCurrent": false,
"registryRecordId": "ubafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvfhrowoi",
"registryRecordData": {},
"applicationRecordId": "ubafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvfhrowoi",
"applicationRecordData": {},
"applicationDeploymentRequestId": "eqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "test",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -106,14 +120,16 @@
},
{
"projectIndex": 2,
"domainIndex":9,
"domainIndex": 9,
"createdByIndex": 2,
"id":"ndxje48a",
"status": "Building",
"id": "ndxje48a",
"status": "Ready",
"environment": "Production",
"isCurrent": true,
"registryRecordId": "ibayreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"applicationRecordId": "ibayreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationRecordData": {},
"applicationDeploymentRequestId": "dqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "main",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -121,14 +137,16 @@
},
{
"projectIndex": 2,
"domainIndex":7,
"domainIndex": 7,
"createdByIndex": 2,
"id":"gtgpgvei",
"id": "gtgpgvei",
"status": "Ready",
"environment": "Preview",
"isCurrent": false,
"registryRecordId": "obafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"applicationRecordId": "obafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationRecordData": {},
"applicationDeploymentRequestId": "aqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "test",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -136,14 +154,16 @@
},
{
"projectIndex": 2,
"domainIndex":8,
"domainIndex": 8,
"createdByIndex": 2,
"id":"b4bpthjr",
"status": "Error",
"id": "b4bpthjr",
"status": "Ready",
"environment": "Development",
"isCurrent": false,
"registryRecordId": "pbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowo",
"registryRecordData": {},
"applicationRecordId": "pbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowo",
"applicationRecordData": {},
"applicationDeploymentRequestId": "uqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "test",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
@@ -153,12 +173,14 @@
"projectIndex": 3,
"domainIndex": 6,
"createdByIndex": 2,
"id":"b4bpthjr",
"status": "Building",
"id": "b4bpthjr",
"status": "Ready",
"environment": "Production",
"isCurrent": true,
"registryRecordId": "pbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowo",
"registryRecordData": {},
"applicationRecordId": "pbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowo",
"applicationRecordData": {},
"applicationDeploymentRequestId": "pqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"applicationDeploymentRequestData": {},
"branch": "test",
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
"commitMessage": "subscription added",
+2 -2
View File
@@ -6,7 +6,7 @@
},
{
"id": "7eb9b3eb-eb74-4b53-b59a-69884c82a7fb",
"name": "AirFoil",
"slug": "airfoil-2"
"name": "Laconic",
"slug": "laconic-2"
}
]
+6 -6
View File
@@ -1,37 +1,37 @@
[
{
"projectIndex": 0,
"name": "randomurl.snowballtools.xyz",
"name": "example.snowballtools.xyz",
"status": "Live",
"branch": "main"
},
{
"projectIndex": 0,
"name": "saugatt.com",
"name": "example.org",
"status": "Pending",
"branch": "test"
},
{
"projectIndex": 1,
"name": "randomurl.snowballtools.xyz",
"name": "example.snowballtools.xyz",
"status": "Live",
"branch": "main"
},
{
"projectIndex": 1,
"name": "saugatt.com",
"name": "example.org",
"status": "Pending",
"branch": "test"
},
{
"projectIndex": 2,
"name": "randomurl.snowballtools.xyz",
"name": "example.snowballtools.xyz",
"status": "Live",
"branch": "main"
},
{
"projectIndex": 2,
"name": "saugatt.com",
"name": "example.org",
"status": "Pending",
"branch": "test"
},
+9 -31
View File
@@ -2,77 +2,55 @@
{
"memberIndex": 1,
"projectIndex": 0,
"permissions": [
"View"
],
"permissions": ["View"],
"isPending": false
},
{
"memberIndex": 2,
"projectIndex": 0,
"permissions": [
"View",
"Edit"
],
"permissions": ["View", "Edit"],
"isPending": false
},
{
"memberIndex": 2,
"projectIndex": 1,
"permissions": [
"View"
],
"permissions": ["View"],
"isPending": false
},
{
"memberIndex": 0,
"projectIndex": 2,
"permissions": [
"View"
],
"permissions": ["View"],
"isPending": false
},
{
"memberIndex": 1,
"projectIndex": 2,
"permissions": [
"View",
"Edit"
],
"permissions": ["View", "Edit"],
"isPending": false
},
{
"memberIndex": 0,
"projectIndex": 3,
"permissions": [
"View"
],
"permissions": ["View"],
"isPending": false
},
{
"memberIndex": 2,
"projectIndex": 3,
"permissions": [
"View",
"Edit"
],
"permissions": ["View", "Edit"],
"isPending": false
},
{
"memberIndex": 1,
"projectIndex": 4,
"permissions": [
"View"
],
"permissions": ["View"],
"isPending": false
},
{
"memberIndex": 2,
"projectIndex": 4,
"permissions": [
"View",
"Edit"
],
"permissions": ["View", "Edit"],
"isPending": false
}
]
-10
View File
@@ -10,8 +10,6 @@
"framework": "test",
"webhooks": [],
"icon": "",
"registryRecordId": "hbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"subDomain": "testProject.snowball.xyz"
},
{
@@ -25,8 +23,6 @@
"framework": "test-2",
"webhooks": [],
"icon": "",
"registryRecordId": "gbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"subDomain": "testProject-2.snowball.xyz"
},
{
@@ -40,8 +36,6 @@
"framework": "test-3",
"webhooks": [],
"icon": "",
"registryRecordId": "ebafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"subDomain": "iglootools.snowball.xyz"
},
{
@@ -55,8 +49,6 @@
"framework": "test-4",
"webhooks": [],
"icon": "",
"registryRecordId": "qbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"subDomain": "iglootools-2.snowball.xyz"
},
{
@@ -70,8 +62,6 @@
"framework": "test-5",
"webhooks": [],
"icon": "",
"registryRecordId": "xbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
"registryRecordData": {},
"subDomain": "snowball-2.snowball.xyz"
}
]
+3 -3
View File
@@ -1,21 +1,21 @@
[
{
"projectIndex": 0,
"name": "www.saugatt.com",
"name": "www.example.org",
"status": "Pending",
"redirectToIndex": 1,
"branch": "test"
},
{
"projectIndex": 1,
"name": "www.saugatt.com",
"name": "www.example.org",
"status": "Pending",
"redirectToIndex": 3,
"branch": "test"
},
{
"projectIndex": 2,
"name": "www.saugatt.com",
"name": "www.example.org",
"status": "Pending",
"redirectToIndex": 5,
"branch": "test"
+6 -6
View File
@@ -1,20 +1,20 @@
[
{
"id": "59f4355d-9549-4aac-9b54-eeefceeabef0",
"name": "Saugat Yadav",
"email": "saugaty@airfoil.studio",
"name": "Snowball",
"email": "snowball@snowballtools.xyz",
"isVerified": true
},
{
"id": "e505b212-8da6-48b2-9614-098225dab34b",
"name": "Gideon Low",
"email": "gideonl@airfoil.studio",
"name": "Alice Anderson",
"email": "alice@snowballtools.xyz",
"isVerified": true
},
{
"id": "cd892fad-9138-4aa2-a62c-414a32776ea7",
"name": "Sushan Yadav",
"email": "sushany@airfoil.studio",
"name": "Bob Banner",
"email": "bob@snowballtools.xyz",
"isVerified": true
}
]
+84 -50
View File
@@ -1,5 +1,4 @@
import { DataSource, DeepPartial, EntityTarget, ObjectLiteral } from 'typeorm';
import * as fs from 'fs/promises';
import { DataSource } from 'typeorm';
import debug from 'debug';
import path from 'path';
@@ -11,7 +10,12 @@ import { EnvironmentVariable } from '../src/entity/EnvironmentVariable';
import { Domain } from '../src/entity/Domain';
import { ProjectMember } from '../src/entity/ProjectMember';
import { Deployment } from '../src/entity/Deployment';
import { getConfig } from '../src/utils';
import {
checkFileExists,
getConfig,
getEntities,
loadAndSaveData
} from '../src/utils';
import { Config } from '../src/config';
import { DEFAULT_CONFIG_FILE_PATH } from '../src/constants';
@@ -20,50 +24,42 @@ const log = debug('snowball:initialize-database');
const USER_DATA_PATH = './fixtures/users.json';
const PROJECT_DATA_PATH = './fixtures/projects.json';
const ORGANIZATION_DATA_PATH = './fixtures/organizations.json';
const USER_ORGANIZATION_DATA_PATH = './fixtures/user-orgnizations.json';
const USER_ORGANIZATION_DATA_PATH = './fixtures/user-organizations.json';
const PROJECT_MEMBER_DATA_PATH = './fixtures/project-members.json';
const PRIMARY_DOMAIN_DATA_PATH = './fixtures/primary-domains.json';
const DEPLOYMENT_DATA_PATH = './fixtures/deployments.json';
const ENVIRONMENT_VARIABLE_DATA_PATH = './fixtures/environment-variables.json';
const REDIRECTED_DOMAIN_DATA_PATH = './fixtures/redirected-domains.json';
const loadAndSaveData = async <Entity extends ObjectLiteral>(entityType: EntityTarget<Entity>, dataSource: DataSource, filePath: string, relations?: any | undefined) => {
const entitiesData = await fs.readFile(filePath, 'utf-8');
const entities = JSON.parse(entitiesData);
const entityRepository = dataSource.getRepository(entityType);
const savedEntity:Entity[] = [];
for (const entityData of entities) {
let entity = entityRepository.create(entityData as DeepPartial<Entity>);
if (relations) {
for (const field in relations) {
const valueIndex = String(field + 'Index');
entity = {
...entity,
[field]: relations[field][entityData[valueIndex]]
};
}
}
const dbEntity = await entityRepository.save(entity);
savedEntity.push(dbEntity);
}
return savedEntity;
};
const generateTestData = async (dataSource: DataSource) => {
const savedUsers = await loadAndSaveData(User, dataSource, path.resolve(__dirname, USER_DATA_PATH));
const savedOrgs = await loadAndSaveData(Organization, dataSource, path.resolve(__dirname, ORGANIZATION_DATA_PATH));
const userEntities = await getEntities(
path.resolve(__dirname, USER_DATA_PATH)
);
const savedUsers = await loadAndSaveData(User, dataSource, userEntities);
const orgEntities = await getEntities(
path.resolve(__dirname, ORGANIZATION_DATA_PATH)
);
const savedOrgs = await loadAndSaveData(
Organization,
dataSource,
orgEntities
);
const projectRelations = {
owner: savedUsers,
organization: savedOrgs
};
const savedProjects = await loadAndSaveData(Project, dataSource, path.resolve(__dirname, PROJECT_DATA_PATH), projectRelations);
const projectEntities = await getEntities(
path.resolve(__dirname, PROJECT_DATA_PATH)
);
const savedProjects = await loadAndSaveData(
Project,
dataSource,
projectEntities,
projectRelations
);
const domainRepository = dataSource.getRepository(Domain);
@@ -71,14 +67,30 @@ const generateTestData = async (dataSource: DataSource) => {
project: savedProjects
};
const savedPrimaryDomains = await loadAndSaveData(Domain, dataSource, path.resolve(__dirname, PRIMARY_DOMAIN_DATA_PATH), domainPrimaryRelations);
const primaryDomainsEntities = await getEntities(
path.resolve(__dirname, PRIMARY_DOMAIN_DATA_PATH)
);
const savedPrimaryDomains = await loadAndSaveData(
Domain,
dataSource,
primaryDomainsEntities,
domainPrimaryRelations
);
const domainRedirectedRelations = {
project: savedProjects,
redirectTo: savedPrimaryDomains
};
await loadAndSaveData(Domain, dataSource, path.resolve(__dirname, REDIRECTED_DOMAIN_DATA_PATH), domainRedirectedRelations);
const redirectDomainsEntities = await getEntities(
path.resolve(__dirname, REDIRECTED_DOMAIN_DATA_PATH)
);
await loadAndSaveData(
Domain,
dataSource,
redirectDomainsEntities,
domainRedirectedRelations
);
const savedDomains = await domainRepository.find();
@@ -87,14 +99,30 @@ const generateTestData = async (dataSource: DataSource) => {
organization: savedOrgs
};
await loadAndSaveData(UserOrganization, dataSource, path.resolve(__dirname, USER_ORGANIZATION_DATA_PATH), userOrganizationRelations);
const userOrganizationsEntities = await getEntities(
path.resolve(__dirname, USER_ORGANIZATION_DATA_PATH)
);
await loadAndSaveData(
UserOrganization,
dataSource,
userOrganizationsEntities,
userOrganizationRelations
);
const projectMemberRelations = {
member: savedUsers,
project: savedProjects
};
await loadAndSaveData(ProjectMember, dataSource, path.resolve(__dirname, PROJECT_MEMBER_DATA_PATH), projectMemberRelations);
const projectMembersEntities = await getEntities(
path.resolve(__dirname, PROJECT_MEMBER_DATA_PATH)
);
await loadAndSaveData(
ProjectMember,
dataSource,
projectMembersEntities,
projectMemberRelations
);
const deploymentRelations = {
project: savedProjects,
@@ -102,23 +130,29 @@ const generateTestData = async (dataSource: DataSource) => {
createdBy: savedUsers
};
await loadAndSaveData(Deployment, dataSource, path.resolve(__dirname, DEPLOYMENT_DATA_PATH), deploymentRelations);
const deploymentsEntities = await getEntities(
path.resolve(__dirname, DEPLOYMENT_DATA_PATH)
);
await loadAndSaveData(
Deployment,
dataSource,
deploymentsEntities,
deploymentRelations
);
const environmentVariableRelations = {
project: savedProjects
};
await loadAndSaveData(EnvironmentVariable, dataSource, path.resolve(__dirname, ENVIRONMENT_VARIABLE_DATA_PATH), environmentVariableRelations);
};
const checkFileExists = async (filePath: string) => {
try {
await fs.access(filePath, fs.constants.F_OK);
return true;
} catch (err) {
log(err);
return false;
}
const environmentVariablesEntities = await getEntities(
path.resolve(__dirname, ENVIRONMENT_VARIABLE_DATA_PATH)
);
await loadAndSaveData(
EnvironmentVariable,
dataSource,
environmentVariablesEntities,
environmentVariableRelations
);
};
const main = async () => {
+20 -4
View File
@@ -17,16 +17,32 @@ const AUTHORITY_NAMES = ['snowballtools', 'cerc-io'];
async function main () {
const { registryConfig } = await getConfig<Config>(DEFAULT_CONFIG_FILE_PATH);
const registry = new Registry(registryConfig.gqlEndpoint, registryConfig.restEndpoint, registryConfig.chainId);
const registry = new Registry(
registryConfig.gqlEndpoint,
registryConfig.restEndpoint,
registryConfig.chainId
);
const bondId = await registry.getNextBondId(registryConfig.privateKey);
log('bondId:', bondId);
await registry.createBond({ denom: DENOM, amount: BOND_AMOUNT }, registryConfig.privateKey, registryConfig.fee);
await registry.createBond(
{ denom: DENOM, amount: BOND_AMOUNT },
registryConfig.privateKey,
registryConfig.fee
);
for await (const name of AUTHORITY_NAMES) {
await registry.reserveAuthority({ name }, registryConfig.privateKey, registryConfig.fee);
await registry.reserveAuthority(
{ name },
registryConfig.privateKey,
registryConfig.fee
);
log('Reserved authority name:', name);
await registry.setAuthorityBond({ name, bondId }, registryConfig.privateKey, registryConfig.fee);
await registry.setAuthorityBond(
{ name, bondId },
registryConfig.privateKey,
registryConfig.fee
);
log(`Bond ${bondId} set for authority ${name}`);
}
}
@@ -0,0 +1,83 @@
import debug from 'debug';
import { DataSource } from 'typeorm';
import path from 'path';
import { Registry } from '@cerc-io/laconic-sdk';
import { Config } from '../src/config';
import { DEFAULT_CONFIG_FILE_PATH, PROJECT_DOMAIN } from '../src/constants';
import { getConfig } from '../src/utils';
import { Deployment, DeploymentStatus } from '../src/entity/Deployment';
const log = debug('snowball:publish-deploy-records');
async function main () {
const { registryConfig, database } = await getConfig<Config>(
DEFAULT_CONFIG_FILE_PATH
);
const registry = new Registry(
registryConfig.gqlEndpoint,
registryConfig.restEndpoint,
registryConfig.chainId
);
const dataSource = new DataSource({
type: 'better-sqlite3',
database: database.dbPath,
synchronize: true,
entities: [path.join(__dirname, '../src/entity/*')]
});
await dataSource.initialize();
const deploymentRepository = dataSource.getRepository(Deployment);
const deployments = await deploymentRepository.find({
relations: {
project: true
},
where: {
status: DeploymentStatus.Building
}
});
for await (const deployment of deployments) {
const url = `${deployment.project.name}-${deployment.id}.${PROJECT_DOMAIN}`;
const applicationDeploymentRecord = {
type: 'ApplicationDeploymentRecord',
version: '0.0.1',
name: deployment.applicationRecordData.name,
application: deployment.applicationRecordId,
// TODO: Create DNS record
dns: 'bafyreihlymqggsgqiqawvehkpr2imt4l3u6q7um7xzjrux5rhsvwnuyewm',
// Using dummy values
meta: JSON.stringify({
config: 'da39a3ee5e6b4b0d3255bfef95601890afd80709',
so: '66fcfa49a1664d4cb4ce4f72c1c0e151'
}),
request: deployment.applicationDeploymentRequestId,
url
};
const result = await registry.setRecord(
{
privateKey: registryConfig.privateKey,
record: applicationDeploymentRecord,
bondId: registryConfig.bondId
},
'',
registryConfig.fee
);
log('Application deployment record data:', applicationDeploymentRecord);
log(`Application deployment record published: ${result.data.id}`);
}
}
main().catch((err) => {
log(err);
});
+10 -2
View File
@@ -5,6 +5,12 @@
"dependencies": {
"@fontsource/inter": "^5.0.16",
"@material-tailwind/react": "^2.1.7",
"@radix-ui/react-avatar": "^1.0.4",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-radio-group": "^1.1.3",
"@radix-ui/react-tabs": "^1.0.4",
"@radix-ui/react-tooltip": "^1.0.7",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
@@ -13,13 +19,15 @@
"@types/react": "^18.2.42",
"@types/react-dom": "^18.2.17",
"assert": "^2.1.0",
"date-fns": "^3.0.1",
"clsx": "^2.1.0",
"date-fns": "^3.3.1",
"downshift": "^8.2.3",
"eslint-config-react-app": "^7.0.1",
"gql-client": "^1.0.0",
"luxon": "^3.4.4",
"octokit": "^3.1.2",
"react": "^18.2.0",
"react-calendar": "^4.8.0",
"react-code-blocks": "^0.1.6",
"react-day-picker": "^8.9.1",
"react-dom": "^18.2.0",
@@ -73,6 +81,6 @@
"eslint-plugin-prettier": "^5.0.1",
"eslint-plugin-react": "^7.33.2",
"prettier": "^3.1.0",
"tailwindcss": "^3.3.6"
"tailwindcss": "^3.4.1"
}
}
+3 -3
View File
@@ -2,7 +2,7 @@
{
"id": 1,
"projectid": 1,
"name": "randomurl.snowballtools.xyz",
"name": "example.snowballtools.xyz",
"status": "live",
"record": null,
"isRedirectedto": false
@@ -10,7 +10,7 @@
{
"id": 2,
"projectid": 1,
"name": "saugatt.com",
"name": "example.org",
"status": "pending",
"record": {
"type": "A",
@@ -22,7 +22,7 @@
{
"id": 3,
"projectid": 1,
"name": "www.saugatt.com",
"name": "www.example.org",
"status": "pending",
"record": {
"type": "CNAME",
-17
View File
@@ -1,17 +0,0 @@
[
{
"name": "Saugat Yadav",
"email": "saugaty@airfoil.studio",
"id": 1
},
{
"name": "Gideon Low",
"email": "gideonl@airfoil.studio",
"id": 2
},
{
"name": "Sushan Yadav",
"email": "sushany@airfoil.studio",
"id": 3
}
]
@@ -1,6 +1,6 @@
[
"[20:50:03.502] Running build in Washington, D.C., USA (East) iad1",
"[20:50:03.641] Cloning github.com/saugatyadav11/nextjs2 (Branch: main, Commit: 4a5f47f)",
"[20:50:03.641] Cloning github.com/cerc-io/nextjs2 (Branch: main, Commit: 4a5f47f)",
"[20:50:04.004] Previous build cache not available",
"[20:50:04.118] Cloning completed: 480.574ms",
"[20:50:04.382] Running 'vercel build'",
-190
View File
@@ -1,190 +0,0 @@
[
{
"id": 1,
"icon": "^",
"name": "iglootools",
"title": "Iglootools",
"domain": null,
"organization": "Airfoil",
"url": "iglootools.co",
"createdAt": "2023-12-07T04:20:00",
"createdBy": "Alice",
"deployment": "iglootools.snowballtools.co",
"source": "feature/add-remote-control",
"latestCommit": {
"message": "subscription added",
"createdAt": "2023-12-11T04:20:00",
"branch": "main"
},
"repositoryId": 1,
"members": [
{
"id": 1,
"permissions": []
},
{
"id": 2,
"permissions": ["view", "edit"]
},
{
"id": 3,
"permissions": ["view"]
}
],
"ownerId": 1
},
{
"id": 2,
"icon": "^",
"name": "snowball-starter-kit",
"title": "Snowball Starter Kit",
"domain": null,
"organization": "Snowball",
"url": "starterkit.snowballtools.com",
"createdAt": "2023-12-04T04:20:00",
"createdBy": "Bob",
"deployment": "deploy.snowballtools.com",
"source": "prod/add-docker-compose",
"latestCommit": {
"message": "component updates",
"createdAt": "2023-12-11T04:20:00",
"branch": "staging"
},
"repositoryId": 1,
"members": [
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": ["view"]
}
],
"ownerId": 2
},
{
"id": 3,
"icon": "^",
"name": "web3-android",
"title": "Web3 Android",
"domain": null,
"organization": "Personal",
"url": "web3fordroids.com",
"createdAt": "2023-12-01T04:20:00",
"createdBy": "Charlie",
"deployment": "deploy.web3fordroids.com",
"source": "dev/style-page",
"latestCommit": {
"message": "No repo connected",
"createdAt": "2023-12-01T04:20:00",
"branch": "main"
},
"repositoryId": 1,
"members": [
{
"id": 1,
"permissions": []
},
{
"id": 2,
"permissions": ["view", "edit"]
},
{
"id": 3,
"permissions": ["view"]
}
],
"ownerId": 1
},
{
"id": 4,
"icon": "^",
"name": "passkeys-demo",
"title": "Passkeys Demo",
"domain": null,
"organization": "Airfoil",
"url": "passkeys.iglootools.xyz",
"createdAt": "2023-12-01T04:20:00",
"createdBy": "David",
"deployment": "demo.passkeys.xyz",
"source": "dev/style-page",
"latestCommit": {
"message": "hello world",
"createdAt": "2023-12-01T04:20:00",
"branch": "main"
},
"repositoryId": 1,
"members": [
{
"id": 1,
"permissions": []
},
{
"id": 2,
"permissions": ["view", "edit"]
},
{
"id": 3,
"permissions": ["view"]
}
],
"ownerId": 1
},
{
"id": 5,
"icon": "^",
"name": "iglootools",
"title": "Iglootools",
"domain": null,
"organization": "Airfoil",
"url": "iglootools.xyz",
"createdAt": "2023-12-11T04:20:00",
"createdBy": "Erin",
"deployment": "staging.snowballtools.com",
"source": "prod/fix-error",
"latestCommit": {
"message": "404 added",
"createdAt": "2023-12-09T04:20:00",
"branch": "main"
},
"repositoryId": 1,
"members": [
{
"id": 3,
"permissions": []
}
],
"ownerId": 3
},
{
"id": 6,
"icon": "^",
"name": "iglootools",
"title": "Iglootools",
"domain": null,
"organization": "Airfoil",
"url": "iglootools.xyz",
"createdAt": "2023-12-11T04:20:00",
"createdBy": "Frank",
"deployment": "iglootools.snowballtools.com",
"source": "prod/fix-error",
"latestCommit": {
"message": "design system integrated",
"createdAt": "2023-12-09T04:20:00",
"branch": "prod"
},
"repositoryId": 1,
"members": [
{
"id": 2,
"permissions": []
},
{
"id": 3,
"permissions": ["view"]
}
],
"ownerId": 2
}
]
@@ -3,11 +3,12 @@ import { Octokit } from 'octokit';
import assert from 'assert';
import { useDebounce } from 'usehooks-ts';
import { Button, Typography, Option, Select } from '@material-tailwind/react';
import { Button, Typography, Option } from '@material-tailwind/react';
import SearchBar from '../../SearchBar';
import ProjectRepoCard from './ProjectRepoCard';
import { GitOrgDetails, GitRepositoryDetails } from '../../../types';
import AsyncSelect from '../../shared/AsyncSelect';
const DEFAULT_SEARCHED_REPO = '';
const REPOS_PER_PAGE = 5;
@@ -109,8 +110,7 @@ const RepositoryList = ({ octokit }: RepositoryListProps) => {
<div className="p-4">
<div className="flex gap-2 mb-2">
<div className="basis-1/3">
{/* TODO: Fix selection of Git user at start */}
<Select
<AsyncSelect
value={selectedAccount}
onChange={(value) => setSelectedAccount(value!)}
>
@@ -119,7 +119,7 @@ const RepositoryList = ({ octokit }: RepositoryListProps) => {
^ {account.login}
</Option>
))}
</Select>
</AsyncSelect>
</div>
<div className="basis-2/3">
<SearchBar
@@ -90,7 +90,9 @@ const DeploymentDetailsCard = ({
<div className="grid grid-cols-4 gap-2 border-b border-gray-300 p-3 my-2">
<div className="col-span-2">
<div className="flex">
<Typography className=" basis-3/4">{deployment.url}</Typography>
{deployment.url && (
<Typography className=" basis-3/4">{deployment.url}</Typography>
)}
<Chip
value={deployment.status}
color={STATUS_COLORS[deployment.status] ?? 'gray'}
@@ -120,12 +122,8 @@ const DeploymentDetailsCard = ({
<button className="self-start">...</button>
</MenuHandler>
<MenuList>
<a
href={'https://' + deployment.url}
target="_blank"
rel="noreferrer"
>
<MenuItem>^ Visit</MenuItem>
<a href={deployment.url} target="_blank" rel="noreferrer">
<MenuItem disabled={!Boolean(deployment.url)}>^ Visit</MenuItem>
</a>
<MenuItem
onClick={() => setAssignDomainDialog(!assignDomainDialog)}
@@ -28,9 +28,11 @@ const DeploymentDialogBodyCard = ({
color={chip.color}
/>
)}
<Typography variant="small" className="text-black">
{deployment.url}
</Typography>
{deployment.url && (
<Typography variant="small" className="text-black">
{deployment.url}
</Typography>
)}
<Typography variant="small">
^ {deployment.branch} ^{' '}
{deployment.commitHash.substring(0, SHORT_COMMIT_HASH_LENGTH)}{' '}
@@ -12,7 +12,6 @@ import {
Card,
} from '@material-tailwind/react';
import { RepositoryDetails } from '../../../../types';
import ConfirmDialog from '../../../shared/ConfirmDialog';
import EditDomainDialog from './EditDomainDialog';
import { useGQLClient } from '../../../../context/GQLClientContext';
@@ -27,7 +26,7 @@ enum RefreshStatus {
interface DomainCardProps {
domains: Domain[];
domain: Domain;
repo: RepositoryDetails;
branches: string[];
project: Project;
onUpdate: () => Promise<void>;
}
@@ -44,7 +43,7 @@ const DOMAIN_RECORD = {
const DomainCard = ({
domains,
domain,
repo,
branches,
project,
onUpdate,
}: DomainCardProps) => {
@@ -188,7 +187,7 @@ const DomainCard = ({
domains={domains}
open={editDialogOpen}
domain={domain}
repo={repo}
branches={branches}
onUpdate={onUpdate}
/>
</>
@@ -15,7 +15,6 @@ import {
Option,
} from '@material-tailwind/react';
import { RepositoryDetails } from '../../../../types';
import { useGQLClient } from '../../../../context/GQLClientContext';
const DEFAULT_REDIRECT_OPTIONS = ['none'];
@@ -25,7 +24,7 @@ interface EditDomainDialogProp {
open: boolean;
handleOpen: () => void;
domain: Domain;
repo: RepositoryDetails;
branches: string[];
onUpdate: () => Promise<void>;
}
@@ -40,7 +39,7 @@ const EditDomainDialog = ({
open,
handleOpen,
domain,
repo,
branches,
onUpdate,
}: EditDomainDialogProp) => {
const client = useGQLClient();
@@ -120,7 +119,7 @@ const EditDomainDialog = ({
branch: domain.branch,
redirectedTo: getRedirectUrl(domain),
});
}, [domain, repo]);
}, [domain]);
return (
<Dialog open={open} handler={handleOpen}>
@@ -166,9 +165,13 @@ const EditDomainDialog = ({
<Input
crossOrigin={undefined}
{...register('branch', {
validate: (value) => repo.branch.includes(value),
validate: (value) =>
Boolean(branches.length) ? branches.includes(value) : true,
})}
disabled={watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0]}
disabled={
!Boolean(branches.length) ||
watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0]
}
/>
{!isValid && (
<Typography variant="small" className="text-red-500">
@@ -0,0 +1,71 @@
import { tv, type VariantProps } from 'tailwind-variants';
export const avatarTheme = tv(
{
base: ['relative', 'block', 'rounded-full', 'overflow-hidden'],
slots: {
image: [
'h-full',
'w-full',
'rounded-[inherit]',
'object-cover',
'object-center',
],
fallback: [
'grid',
'select-none',
'place-content-center',
'h-full',
'w-full',
'rounded-[inherit]',
'font-medium',
],
},
variants: {
type: {
gray: {
fallback: ['text-elements-highEm', 'bg-base-bg-emphasized'],
},
orange: {
fallback: ['text-elements-warning', 'bg-base-bg-emphasized-warning'],
},
blue: {
fallback: ['text-elements-info', 'bg-base-bg-emphasized-info'],
},
},
size: {
18: {
base: ['rounded-md', 'h-[18px]', 'w-[18px]', 'text-[0.625rem]'],
},
20: {
base: ['rounded-md', 'h-5', 'w-5', 'text-[0.625rem]'],
},
24: {
base: ['rounded-md', 'h-6', 'w-6', 'text-[0.625rem]'],
},
28: {
base: ['rounded-lg', 'h-[28px]', 'w-[28px]', 'text-[0.625rem]'],
},
32: {
base: ['rounded-lg', 'h-8', 'w-8', 'text-xs'],
},
36: {
base: ['rounded-xl', 'h-[36px]', 'w-[36px]', 'text-xs'],
},
40: {
base: ['rounded-xl', 'h-10', 'w-10', 'text-sm'],
},
44: {
base: ['rounded-xl', 'h-[44px]', 'w-[44px]', 'text-sm'],
},
},
},
defaultVariants: {
size: 24,
type: 'gray',
},
},
{ responsiveVariants: true },
);
export type AvatarVariants = VariantProps<typeof avatarTheme>;
@@ -0,0 +1,40 @@
import React from 'react';
import { type ComponentPropsWithoutRef, type ComponentProps } from 'react';
import { avatarTheme, type AvatarVariants } from './Avatar.theme';
import * as PrimitiveAvatar from '@radix-ui/react-avatar';
export type AvatarProps = ComponentPropsWithoutRef<'div'> & {
imageSrc?: string | null;
initials?: string;
imageProps?: ComponentProps<typeof PrimitiveAvatar.Image>;
fallbackProps?: ComponentProps<typeof PrimitiveAvatar.Fallback>;
} & AvatarVariants;
export const Avatar = ({
className,
size,
type,
imageSrc,
imageProps,
fallbackProps,
initials,
}: AvatarProps) => {
const { base, image, fallback } = avatarTheme({ size, type });
return (
<PrimitiveAvatar.Root className={base({ className })}>
{imageSrc && (
<PrimitiveAvatar.Image
{...imageProps}
className={image({ className: imageProps?.className })}
src={imageSrc}
/>
)}
<PrimitiveAvatar.Fallback asChild {...fallbackProps}>
<div className={fallback({ className: fallbackProps?.className })}>
{initials}
</div>
</PrimitiveAvatar.Fallback>
</PrimitiveAvatar.Root>
);
};
@@ -0,0 +1,2 @@
export * from './Avatar';
export * from './Avatar.theme';
@@ -0,0 +1,43 @@
import { VariantProps, tv } from 'tailwind-variants';
export const badgeTheme = tv({
slots: {
wrapper: ['rounded-full', 'grid', 'place-content-center'],
},
variants: {
variant: {
primary: {
wrapper: ['bg-controls-primary', 'text-elements-on-primary'],
},
secondary: {
wrapper: ['bg-controls-secondary', 'text-elements-on-secondary'],
},
tertiary: {
wrapper: [
'bg-controls-tertiary',
'border',
'border-border-interactive/10',
'text-elements-high-em',
'shadow-button',
],
},
inset: {
wrapper: ['bg-controls-inset', 'text-elements-high-em'],
},
},
size: {
sm: {
wrapper: ['h-5', 'w-5', 'text-xs'],
},
xs: {
wrapper: ['h-4', 'w-4', 'text-2xs', 'font-medium'],
},
},
},
defaultVariants: {
variant: 'primary',
size: 'sm',
},
});
export type BadgeTheme = VariantProps<typeof badgeTheme>;
@@ -0,0 +1,33 @@
import React from 'react';
import { ComponentPropsWithoutRef } from 'react';
import { BadgeTheme, badgeTheme } from './Badge.theme';
export interface BadgeProps
extends ComponentPropsWithoutRef<'div'>,
BadgeTheme {}
/**
* A badge is a small status descriptor for UI elements.
* It can be used to indicate a status, a count, or a category.
* It is typically used in lists, tables, or navigation elements.
*
* @example
* ```tsx
* <Badge variant="primary" size="sm">1</Badge
* ```
*/
export const Badge = ({
className,
children,
variant,
size,
...props
}: BadgeProps) => {
const { wrapper } = badgeTheme();
return (
<div {...props} className={wrapper({ className, variant, size })}>
{children}
</div>
);
};
@@ -0,0 +1 @@
export * from './Badge';
@@ -118,6 +118,29 @@ export const buttonTheme = tv(
'disabled:border-transparent',
'disabled:shadow-none',
],
link: [
'p-0',
'gap-1.5',
'text-elements-link',
'rounded',
'focus-ring',
'hover:underline',
'hover:text-elements-link-hovered',
'disabled:text-controls-disabled',
'disabled:hover:no-underline',
],
'link-emphasized': [
'p-0',
'gap-1.5',
'text-elements-high-em',
'rounded',
'underline',
'focus-ring',
'hover:text-elements-link-hovered',
'disabled:text-controls-disabled',
'disabled:hover:no-underline',
'dark:text-elements-on-high-contrast',
],
unstyled: [],
},
},
@@ -98,19 +98,29 @@ const Button = forwardRef<
href,
...baseLinkProps,
};
return <a {...externalLinkProps}>{_children}</a>;
return (
// @ts-expect-error - ref
<a ref={ref} {...externalLinkProps}>
{_children}
</a>
);
}
// Internal link
return (
<Link {...baseLinkProps} to={href}>
// @ts-expect-error - ref
<Link ref={ref} {...baseLinkProps} to={href}>
{_children}
</Link>
);
} else {
const { ...buttonProps } = _props;
// @ts-expect-error - as prop is not a valid prop for button elements
return <button {...buttonProps}>{_children}</button>;
return (
// @ts-expect-error - as prop is not a valid prop for button elements
<button ref={ref} {...buttonProps}>
{_children}
</button>
);
}
},
[],
@@ -161,8 +171,6 @@ const Button = forwardRef<
return (
<Component
{...props}
// @ts-expect-error - ref is not a valid prop for button elements
ref={ref}
className={buttonTheme({ ...styleProps, class: className })}
>
{cloneIcon(leftIcon, { ...iconSize })}
@@ -0,0 +1,128 @@
/* React Calendar */
.react-calendar {
@apply border-none font-sans;
}
/* Weekdays -- START */
.react-calendar__month-view__weekdays {
@apply p-0 flex items-center justify-center;
}
.react-calendar__month-view__weekdays__weekday {
@apply h-8 w-12 flex items-center justify-center p-0 font-medium text-xs text-elements-disabled mb-2;
}
abbr[title] {
text-decoration: none;
}
/* Weekdays -- END */
/* Days -- START */
.react-calendar__month-view__days {
@apply p-0 gap-0;
}
.react-calendar__month-view__days__day--neighboringMonth {
@apply !text-elements-disabled;
}
.react-calendar__month-view__days__day--neighboringMonth:hover {
@apply !text-elements-disabled !bg-transparent;
}
.react-calendar__month-view__days__day--neighboringMonth {
@apply !text-elements-disabled !bg-transparent;
}
/* For weekend days */
.react-calendar__month-view__days__day--weekend {
/* color: ${colors.grey[950]} !important; */
}
.react-calendar__tile {
@apply h-12 w-12 text-elements-high-em;
}
.react-calendar__tile:hover {
@apply bg-base-bg-emphasized rounded-lg;
}
.react-calendar__tile:focus-visible {
@apply bg-base-bg-emphasized rounded-lg focus-ring z-10;
}
.react-calendar__tile--now {
@apply bg-base-bg-emphasized text-elements-high-em rounded-lg;
}
.react-calendar__tile--now:hover {
@apply bg-base-bg-emphasized text-elements-high-em rounded-lg;
}
.react-calendar__tile--now:focus-visible {
@apply bg-base-bg-emphasized text-elements-high-em rounded-lg focus-ring;
}
.react-calendar__tile--active {
@apply bg-controls-primary text-elements-on-primary rounded-lg;
}
.react-calendar__tile--active:hover {
@apply bg-controls-primary-hovered;
}
.react-calendar__tile--active:focus-visible {
@apply bg-controls-primary-hovered focus-ring;
}
/* Range -- START */
.react-calendar__tile--range {
@apply bg-controls-secondary text-elements-on-secondary rounded-none;
}
.react-calendar__tile--range:hover {
@apply bg-controls-secondary-hovered text-elements-on-secondary rounded-none;
}
.react-calendar__tile--range:focus-visible {
@apply bg-controls-secondary-hovered text-elements-on-secondary rounded-lg;
}
.react-calendar__tile--rangeStart {
@apply bg-controls-primary text-elements-on-primary rounded-lg;
}
.react-calendar__tile--rangeStart:hover {
@apply bg-controls-primary-hovered text-elements-on-primary rounded-lg;
}
.react-calendar__tile--rangeStart:focus-visible {
@apply bg-controls-primary-hovered text-elements-on-primary rounded-lg focus-ring;
}
.react-calendar__tile--rangeEnd {
@apply bg-controls-primary text-elements-on-primary rounded-lg;
}
.react-calendar__tile--rangeEnd:hover {
@apply bg-controls-primary-hovered text-elements-on-primary rounded-lg;
}
.react-calendar__tile--rangeEnd:focus-visible {
@apply bg-controls-primary-hovered text-elements-on-primary rounded-lg focus-ring;
}
/* Range -- END */
/* Days -- END */
/* Months -- START */
.react-calendar__tile--hasActive {
@apply bg-controls-primary text-elements-on-primary rounded-lg;
}
.react-calendar__tile--hasActive:hover {
@apply bg-controls-primary-hovered text-elements-on-primary rounded-lg;
}
.react-calendar__tile--hasActive:focus-visible {
@apply bg-controls-primary-hovered text-elements-on-primary rounded-lg focus-ring;
}
@@ -0,0 +1,49 @@
import { VariantProps, tv } from 'tailwind-variants';
export const calendarTheme = tv({
slots: {
wrapper: [
'max-w-[352px]',
'bg-surface-floating',
'shadow-calendar',
'rounded-xl',
],
calendar: ['flex', 'flex-col', 'py-2', 'px-2', 'gap-2'],
navigation: [
'flex',
'items-center',
'justify-between',
'gap-3',
'py-2.5',
'px-1',
],
actions: ['flex', 'items-center', 'justify-center', 'gap-1.5', 'flex-1'],
button: [
'flex',
'items-center',
'gap-2',
'px-2',
'py-2',
'rounded-lg',
'border',
'border-border-interactive',
'text-elements-high-em',
'shadow-field',
'bg-white',
'hover:bg-base-bg-alternate',
'focus-visible:bg-base-bg-alternate',
],
footer: [
'flex',
'items-center',
'justify-end',
'py-3',
'px-2',
'gap-3',
'border-t',
'border-border-separator',
],
},
});
export type CalendarTheme = VariantProps<typeof calendarTheme>;
@@ -0,0 +1,298 @@
import React, {
ComponentPropsWithRef,
MouseEvent,
ReactNode,
useCallback,
useState,
} from 'react';
import {
Calendar as ReactCalendar,
CalendarProps as ReactCalendarProps,
} from 'react-calendar';
import { Value } from 'react-calendar/dist/cjs/shared/types';
import { CalendarTheme, calendarTheme } from './Calendar.theme';
import { Button } from 'components/shared/Button';
import {
ChevronGrabberHorizontal,
ChevronLeft,
ChevronRight,
} from 'components/shared/CustomIcon';
import './Calendar.css';
import { format } from 'date-fns';
const CALENDAR_VIEW = ['month', 'year', 'decade'] as const;
export type CalendarView = (typeof CALENDAR_VIEW)[number];
/**
* Defines a custom set of props for a React calendar component by excluding specific props
* from the original ReactCalendarProps type.
* @type {CustomReactCalendarProps}
*/
type CustomReactCalendarProps = Omit<
ReactCalendarProps,
'view' | 'showNavigation' | 'onClickMonth' | 'onClickYear'
>;
export interface CalendarProps extends CustomReactCalendarProps, CalendarTheme {
/**
* Optional props for wrapping a component with a div element.
*/
wrapperProps?: ComponentPropsWithRef<'div'>;
/**
* Props for the calendar wrapper component.
*/
calendarWrapperProps?: ComponentPropsWithRef<'div'>;
/**
* Optional props for the footer component.
*/
footerProps?: ComponentPropsWithRef<'div'>;
/**
* Optional custom actions to be rendered.
*/
actions?: ReactNode;
/**
* Optional callback function that is called when a value is selected.
* @param {Value} value - The selected value
* @returns None
*/
onSelect?: (value: Value) => void;
/**
* Optional callback function that is called when a cancel action is triggered.
* @returns None
*/
onCancel?: () => void;
}
/**
* Calendar component that allows users to select dates and navigate through months and years.
* @param {Object} CalendarProps - Props for the Calendar component.
* @returns {JSX.Element} A calendar component with navigation, date selection, and actions.
*/
export const Calendar = ({
selectRange,
activeStartDate: activeStartDateProp,
value: valueProp,
wrapperProps,
calendarWrapperProps,
footerProps,
actions,
onSelect,
onCancel,
onChange: onChangeProp,
...props
}: CalendarProps): JSX.Element => {
const {
wrapper,
calendar,
navigation,
actions: actionsClass,
button,
footer,
} = calendarTheme();
const today = new Date();
const currentMonth = format(today, 'MMM');
const currentYear = format(today, 'yyyy');
const [view, setView] = useState<CalendarView>('month');
const [activeDate, setActiveDate] = useState<Date>(
activeStartDateProp ?? today,
);
const [value, setValue] = useState<Value>(valueProp as Value);
const [month, setMonth] = useState(currentMonth);
const [year, setYear] = useState(currentYear);
/**
* Update the navigation label based on the active date
*/
const changeNavigationLabel = useCallback(
(date: Date) => {
setMonth(format(date, 'MMM'));
setYear(format(date, 'yyyy'));
},
[setMonth, setYear],
);
/**
* Change the active date base on the action and range
*/
const handleNavigate = useCallback(
(action: 'previous' | 'next', view: CalendarView) => {
setActiveDate((date) => {
const newDate = new Date(date);
switch (view) {
case 'month':
newDate.setMonth(
action === 'previous' ? date.getMonth() - 1 : date.getMonth() + 1,
);
break;
case 'year':
newDate.setFullYear(
action === 'previous'
? date.getFullYear() - 1
: date.getFullYear() + 1,
);
break;
case 'decade':
newDate.setFullYear(
action === 'previous'
? date.getFullYear() - 10
: date.getFullYear() + 10,
);
break;
}
changeNavigationLabel(newDate);
return newDate;
});
},
[setActiveDate, changeNavigationLabel],
);
/**
* Change the view of the calendar
*/
const handleChangeView = useCallback(
(view: CalendarView) => {
setView(view);
},
[setView],
);
/**
* Change the active date and set the view to the selected type
* and also update the navigation label
*/
const handleChangeNavigation = useCallback(
(view: 'month' | 'year', date: Date) => {
setActiveDate(date);
changeNavigationLabel(date);
setView(view);
},
[setActiveDate, changeNavigationLabel, setView],
);
const handlePrevious = useCallback(() => {
switch (view) {
case 'month':
return handleNavigate('previous', 'month');
case 'year':
return handleNavigate('previous', 'year');
case 'decade':
return handleNavigate('previous', 'decade');
}
}, [view]);
const handleNext = useCallback(() => {
switch (view) {
case 'month':
return handleNavigate('next', 'month');
case 'year':
return handleNavigate('next', 'year');
case 'decade':
return handleNavigate('next', 'decade');
}
}, [view]);
const handleChange = useCallback(
(newValue: Value, event: MouseEvent<HTMLButtonElement>) => {
setValue(newValue);
// Call the onChange prop if it exists
onChangeProp?.(newValue, event);
/**
* Update the active date and navigation label
*
* NOTE:
* For range selection, the active date is not updated
* The user only can select multiple dates within the same month
*/
if (!selectRange) {
setActiveDate(newValue as Date);
changeNavigationLabel(newValue as Date);
}
},
[setValue, setActiveDate, changeNavigationLabel, selectRange],
);
return (
<div
{...wrapperProps}
className={wrapper({ className: wrapperProps?.className })}
>
{/* Calendar wrapper */}
<div
{...calendarWrapperProps}
className={calendar({ className: calendarWrapperProps?.className })}
>
{/* Navigation */}
<div className={navigation()}>
<Button iconOnly size="sm" variant="ghost" onClick={handlePrevious}>
<ChevronLeft />
</Button>
<div className={actionsClass()}>
<Button
variant="unstyled"
className={button()}
rightIcon={
<ChevronGrabberHorizontal className="text-elements-low-em" />
}
onClick={() => handleChangeView('year')}
>
{month}
</Button>
<Button
variant="unstyled"
className={button()}
rightIcon={
<ChevronGrabberHorizontal className="text-elements-low-em" />
}
onClick={() => handleChangeView('decade')}
>
{year}
</Button>
</div>
<Button iconOnly size="sm" variant="ghost" onClick={handleNext}>
<ChevronRight />
</Button>
</div>
{/* Calendar */}
<ReactCalendar
{...props}
activeStartDate={activeDate}
view={view}
value={value}
showNavigation={false}
selectRange={selectRange}
onChange={handleChange}
onClickMonth={(date) => handleChangeNavigation('month', date)}
onClickYear={(date) => handleChangeNavigation('year', date)}
/>
</div>
{/* Footer or CTA */}
<div
{...footerProps}
className={footer({ className: footerProps?.className })}
>
{actions ? (
actions
) : (
<>
<Button variant="tertiary" onClick={onCancel}>
Cancel
</Button>
<Button
disabled={!value}
onClick={() => (value ? onSelect?.(value) : null)}
>
Select
</Button>
</>
)}
</div>
</div>
);
};
@@ -0,0 +1 @@
export * from './Calendar';
@@ -0,0 +1,68 @@
import { tv, type VariantProps } from 'tailwind-variants';
export const getCheckboxVariant = tv({
slots: {
wrapper: ['group', 'flex', 'gap-3'],
indicator: [
'grid',
'place-content-center',
'text-transparent',
'group-hover:text-controls-disabled',
'focus-visible:text-controls-disabled',
'group-focus-visible:text-controls-disabled',
'data-[state=checked]:text-elements-on-primary',
'data-[state=checked]:group-focus-visible:text-elements-on-primary',
'data-[state=indeterminate]:text-elements-on-primary',
'data-[state=checked]:data-[disabled]:text-elements-on-disabled-active',
],
icon: ['w-3', 'h-3', 'stroke-current', 'text-current'],
input: [
'h-5',
'w-5',
'group',
'border',
'border-border-interactive/10',
'bg-controls-tertiary',
'rounded-md',
'transition-all',
'duration-150',
'focus-ring',
'shadow-button',
'group-hover:border-border-interactive/[0.14]',
'group-hover:bg-controls-tertiary',
'data-[state=checked]:bg-controls-primary',
'data-[state=checked]:hover:bg-controls-primary-hovered',
'data-[state=checked]:focus-visible:bg-controls-primary-hovered',
'data-[disabled]:bg-controls-disabled',
'data-[disabled]:shadow-none',
'data-[disabled]:hover:border-border-interactive/10',
'data-[disabled]:cursor-not-allowed',
'data-[state=checked]:data-[disabled]:bg-controls-disabled-active',
],
label: [
'text-sm',
'tracking-[-0.006em]',
'text-elements-high-em',
'flex',
'flex-col',
'gap-1',
'px-1',
],
description: ['text-xs', 'text-elements-low-em'],
},
variants: {
disabled: {
true: {
wrapper: ['cursor-not-allowed'],
indicator: ['group-hover:text-transparent'],
input: [
'group-hover:border-border-interactive/[0.14]',
'group-hover:bg-controls-disabled',
],
label: ['cursor-not-allowed'],
},
},
},
});
export type CheckboxVariants = VariantProps<typeof getCheckboxVariant>;
@@ -0,0 +1,76 @@
import React from 'react';
import * as CheckboxRadix from '@radix-ui/react-checkbox';
import { type CheckboxProps as CheckboxRadixProps } from '@radix-ui/react-checkbox';
import { getCheckboxVariant, type CheckboxVariants } from './Checkbox.theme';
import { CheckIcon } from 'components/shared/CustomIcon';
interface CheckBoxProps extends CheckboxRadixProps, CheckboxVariants {
/**
* The label of the checkbox.
*/
label?: string;
/**
* The description of the checkbox.
*/
description?: string;
}
/**
* Checkbox component is used to allow users to select one or more items from a set.
* It is a wrapper around the `@radix-ui/react-checkbox` component.
*
* It accepts all the props from `@radix-ui/react-checkbox` component and the variants from the theme.
*
* It also accepts `label` and `description` props to display the label and description of the checkbox.
*
* @example
* ```tsx
* <Checkbox
* id="checkbox"
* label="Checkbox"
* description="This is a checkbox"
* />
* ```
*/
export const Checkbox = ({
id,
className,
label,
description,
onCheckedChange,
...props
}: CheckBoxProps) => {
const {
wrapper: wrapperStyle,
indicator: indicatorStyle,
icon: iconStyle,
input: inputStyle,
label: labelStyle,
description: descriptionStyle,
} = getCheckboxVariant({
disabled: props?.disabled,
});
return (
<div className={wrapperStyle()}>
<CheckboxRadix.Root
{...props}
className={inputStyle({ className })}
id={id}
onCheckedChange={onCheckedChange}
>
<CheckboxRadix.Indicator forceMount className={indicatorStyle()}>
<CheckIcon className={iconStyle()} />
</CheckboxRadix.Indicator>
</CheckboxRadix.Root>
{label && (
<label className={labelStyle()} htmlFor={id}>
{label}
{description && (
<span className={descriptionStyle()}>{description}</span>
)}
</label>
)}
</div>
);
};
@@ -0,0 +1 @@
export * from './Checkbox';
@@ -0,0 +1,22 @@
import React from 'react';
import { CustomIcon, CustomIconProps } from './CustomIcon';
export const CheckIcon = (props: CustomIconProps) => {
return (
<CustomIcon
width="12"
height="12"
viewBox="0 0 12 12"
fill="none"
{...props}
>
<path
d="M1.5 7.5L4.64706 10L10.5 2"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</CustomIcon>
);
};
@@ -0,0 +1,20 @@
import React from 'react';
import { CustomIcon, CustomIconProps } from './CustomIcon';
export const ChevronGrabberHorizontal = (props: CustomIconProps) => {
return (
<CustomIcon
width="20"
height="20"
viewBox="0 0 20 20"
fill="none"
{...props}
>
<path
d="M6.66666 12.5L9.99999 15.8333L13.3333 12.5M6.66666 7.5L9.99999 4.16666L13.3333 7.5"
stroke="currentColor"
strokeLinecap="square"
/>
</CustomIcon>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
import { CustomIcon, CustomIconProps } from './CustomIcon';
export const ChevronLeft = (props: CustomIconProps) => {
return (
<CustomIcon
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
{...props}
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M10.7071 2.66666L5.37378 8.00001L10.7071 13.3333L10 14.0404L3.95956 8.00001L10 1.95956L10.7071 2.66666Z"
fill="currentColor"
/>
</CustomIcon>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
import { CustomIcon, CustomIconProps } from './CustomIcon';
export const ChevronRight = (props: CustomIconProps) => {
return (
<CustomIcon
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
{...props}
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M6.00001 1.95956L12.0405 7.99998L6.00001 14.0404L5.29291 13.3333L10.6262 7.99999L5.29291 2.66666L6.00001 1.95956Z"
fill="currentColor"
/>
</CustomIcon>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
import { CustomIcon, CustomIconProps } from './CustomIcon';
export const CrossIcon = (props: CustomIconProps) => {
return (
<CustomIcon
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
{...props}
>
<path
d="M5 5L19 19M19 5L5 19"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</CustomIcon>
);
};
@@ -0,0 +1,20 @@
import React from 'react';
import { CustomIcon, CustomIconProps } from './CustomIcon';
export const GlobeIcon = (props: CustomIconProps) => {
return (
<CustomIcon
width="20"
height="20"
viewBox="0 0 20 20"
fill="none"
{...props}
>
<path
d="M10 17.9167C14.3723 17.9167 17.9167 14.3723 17.9167 10C17.9167 5.62776 14.3723 2.08334 10 2.08334M10 17.9167C5.62776 17.9167 2.08334 14.3723 2.08334 10C2.08334 5.62776 5.62776 2.08334 10 2.08334M10 17.9167C8.15906 17.9167 6.66668 14.3723 6.66668 10C6.66668 5.62776 8.15906 2.08334 10 2.08334M10 17.9167C11.841 17.9167 13.3333 14.3723 13.3333 10C13.3333 5.62776 11.841 2.08334 10 2.08334M17.5 10H2.50001"
stroke="currentColor"
strokeLinecap="square"
/>
</CustomIcon>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
import { CustomIcon, CustomIconProps } from './CustomIcon';
export const InfoSquareIcon = (props: CustomIconProps) => {
return (
<CustomIcon
width="20"
height="20"
viewBox="0 0 20 20"
fill="none"
{...props}
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M5.96786 2.5C5.52858 2.49999 5.14962 2.49997 4.83748 2.52548C4.50802 2.55239 4.18034 2.61182 3.86503 2.77249C3.39462 3.01217 3.01217 3.39462 2.77249 3.86503C2.61182 4.18034 2.55239 4.50802 2.52548 4.83748C2.49997 5.14962 2.49999 5.52857 2.5 5.96785V14.0321C2.49999 14.4714 2.49997 14.8504 2.52548 15.1625C2.55239 15.492 2.61182 15.8197 2.77249 16.135C3.01217 16.6054 3.39462 16.9878 3.86503 17.2275C4.18034 17.3882 4.50802 17.4476 4.83748 17.4745C5.14962 17.5 5.52858 17.5 5.96786 17.5H14.0321C14.4714 17.5 14.8504 17.5 15.1625 17.4745C15.492 17.4476 15.8197 17.3882 16.135 17.2275C16.6054 16.9878 16.9878 16.6054 17.2275 16.135C17.3882 15.8197 17.4476 15.492 17.4745 15.1625C17.5 14.8504 17.5 14.4714 17.5 14.0321V5.96786C17.5 5.52858 17.5 5.14962 17.4745 4.83748C17.4476 4.50802 17.3882 4.18034 17.2275 3.86503C16.9878 3.39462 16.6054 3.01217 16.135 2.77249C15.8197 2.61182 15.492 2.55239 15.1625 2.52548C14.8504 2.49997 14.4714 2.49999 14.0322 2.5H5.96786ZM8.33333 9.16667C8.33333 8.70643 8.70643 8.33333 9.16667 8.33333H10C10.4602 8.33333 10.8333 8.70643 10.8333 9.16667V13.3333C10.8333 13.7936 10.4602 14.1667 10 14.1667C9.53976 14.1667 9.16667 13.7936 9.16667 13.3333V10C8.70643 10 8.33333 9.6269 8.33333 9.16667ZM10 5.83333C9.53976 5.83333 9.16667 6.20643 9.16667 6.66667C9.16667 7.1269 9.53976 7.5 10 7.5C10.4602 7.5 10.8333 7.1269 10.8333 6.66667C10.8333 6.20643 10.4602 5.83333 10 5.83333Z"
fill="currentColor"
/>
</CustomIcon>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
import { CustomIcon, CustomIconProps } from './CustomIcon';
export const SearchIcon = (props: CustomIconProps) => {
return (
<CustomIcon
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
{...props}
>
<path
d="M20 20L16.05 16.05M18 11C18 14.866 14.866 18 11 18C7.13401 18 4 14.866 4 11C4 7.13401 7.13401 4 11 4C14.866 4 18 7.13401 18 11Z"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</CustomIcon>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
import { CustomIcon, CustomIconProps } from './CustomIcon';
export const WarningIcon = (props: CustomIconProps) => {
return (
<CustomIcon
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
{...props}
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M10.4902 2.84406C11.1661 1.69 12.8343 1.69 13.5103 2.84406L22.0156 17.3654C22.699 18.5321 21.8576 19.9999 20.5056 19.9999H3.49483C2.14281 19.9999 1.30147 18.5321 1.98479 17.3654L10.4902 2.84406ZM12 9C12.4142 9 12.75 9.33579 12.75 9.75V13.25C12.75 13.6642 12.4142 14 12 14C11.5858 14 11.25 13.6642 11.25 13.25V9.75C11.25 9.33579 11.5858 9 12 9ZM13 15.75C13 16.3023 12.5523 16.75 12 16.75C11.4477 16.75 11 16.3023 11 15.75C11 15.1977 11.4477 14.75 12 14.75C12.5523 14.75 13 15.1977 13 15.75Z"
fill="currentColor"
/>
</CustomIcon>
);
};
@@ -1,2 +1,11 @@
export * from './PlusIcon';
export * from './CustomIcon';
export * from './CheckIcon';
export * from './ChevronGrabberHorizontal';
export * from './ChevronLeft';
export * from './ChevronRight';
export * from './InfoSquareIcon';
export * from './WarningIcon';
export * from './SearchIcon';
export * from './CrossIcon';
export * from './GlobeIcon';
@@ -0,0 +1,78 @@
import { VariantProps, tv } from 'tailwind-variants';
export const inlineNotificationTheme = tv({
slots: {
wrapper: ['rounded-xl', 'flex', 'gap-2', 'items-start', 'w-full', 'border'],
content: ['flex', 'flex-col', 'gap-1'],
title: [],
description: [],
icon: ['flex', 'items-start'],
},
variants: {
variant: {
info: {
wrapper: ['border-border-info-light', 'bg-base-bg-emphasized-info'],
title: ['text-elements-on-emphasized-info'],
description: ['text-elements-on-emphasized-info'],
icon: ['text-elements-info'],
},
danger: {
wrapper: ['border-border-danger-light', 'bg-base-bg-emphasized-danger'],
title: ['text-elements-on-emphasized-danger'],
description: ['text-elements-on-emphasized-danger'],
icon: ['text-elements-danger'],
},
warning: {
wrapper: [
'border-border-warning-light',
'bg-base-bg-emphasized-warning',
],
title: ['text-elements-on-emphasized-warning'],
description: ['text-elements-on-emphasized-warning'],
icon: ['text-elements-warning'],
},
success: {
wrapper: [
'border-border-success-light',
'bg-base-bg-emphasized-success',
],
title: ['text-elements-on-emphasized-success'],
description: ['text-elements-on-emphasized-success'],
icon: ['text-elements-success'],
},
generic: {
wrapper: ['border-border-separator', 'bg-base-bg-emphasized'],
title: ['text-elements-high-em'],
description: ['text-elements-on-emphasized-info'],
icon: ['text-elements-high-em'],
},
},
size: {
sm: {
wrapper: ['px-2', 'py-2'],
title: ['leading-4', 'text-xs'],
description: ['leading-4', 'text-xs'],
icon: ['h-4', 'w-4'],
},
md: {
wrapper: ['px-3', 'py-3'],
title: ['leading-5', 'tracking-[-0.006em]', 'text-sm'],
description: ['leading-5', 'tracking-[-0.006em]', 'text-sm'],
icon: ['h-5', 'w-5'],
},
},
hasDescription: {
true: {
title: ['font-medium'],
},
},
},
defaultVariants: {
variant: 'generic',
size: 'md',
},
});
export type InlineNotificationTheme = VariantProps<
typeof inlineNotificationTheme
>;
@@ -0,0 +1,68 @@
import React, { ReactNode, useCallback } from 'react';
import { ComponentPropsWithoutRef } from 'react';
import {
InlineNotificationTheme,
inlineNotificationTheme,
} from './InlineNotification.theme';
import { InfoSquareIcon } from 'components/shared/CustomIcon';
import { cloneIcon } from 'utils/cloneIcon';
export interface InlineNotificationProps
extends ComponentPropsWithoutRef<'div'>,
InlineNotificationTheme {
/**
* The title of the notification
*/
title: string;
/**
* The description of the notification
*/
description?: string;
/**
* The icon to display in the notification
* @default <InfoSquareIcon />
*/
icon?: ReactNode;
}
/**
* A notification that is displayed inline with the content
*
* @example
* ```tsx
* <InlineNotification title="Notification title goes here" />
* ```
*/
export const InlineNotification = ({
className,
title,
description,
size,
variant,
icon,
...props
}: InlineNotificationProps) => {
const {
wrapper,
content,
title: titleClass,
description: descriptionClass,
icon: iconClass,
} = inlineNotificationTheme({ size, variant, hasDescription: !!description });
// Render custom icon or default icon
const renderIcon = useCallback(() => {
if (!icon) return <InfoSquareIcon className={iconClass()} />;
return cloneIcon(icon, { className: iconClass() });
}, [icon]);
return (
<div {...props} className={wrapper({ className })}>
{renderIcon()}
<div className={content()}>
<p className={titleClass()}>{title}</p>
{description && <p className={descriptionClass()}>{description}</p>}
</div>
</div>
);
};
@@ -0,0 +1 @@
export * from './InlineNotification';
@@ -0,0 +1,85 @@
import { VariantProps, tv } from 'tailwind-variants';
export const inputTheme = tv(
{
slots: {
container: [
'flex',
'items-center',
'rounded-lg',
'relative',
'placeholder:text-elements-disabled',
'disabled:cursor-not-allowed',
'disabled:bg-controls-disabled',
],
label: ['text-sm', 'text-elements-high-em'],
description: ['text-xs', 'text-elements-low-em'],
input: [
'focus-ring',
'block',
'w-full',
'h-full',
'rounded-lg',
'text-elements-mid-em',
'shadow-sm',
'border',
'border-border-interactive',
'disabled:shadow-none',
'disabled:border-none',
],
icon: ['text-elements-mid-em'],
iconContainer: [
'absolute',
'inset-y-0',
'flex',
'items-center',
'z-10',
'cursor-pointer',
],
helperIcon: [],
helperText: ['flex', 'gap-2', 'items-center', 'text-elements-danger'],
},
variants: {
state: {
default: {
input: '',
},
error: {
input: [
'outline',
'outline-offset-0',
'outline-border-danger',
'shadow-none',
'focus:outline-border-danger',
],
helperText: 'text-elements-danger',
},
},
size: {
md: {
container: 'h-11',
input: ['text-sm pl-4 pr-4'],
icon: ['h-[18px] w-[18px]'],
helperText: 'text-sm',
helperIcon: ['h-5 w-5'],
},
sm: {
container: 'h-8',
input: ['text-xs pl-3 pr-3'],
icon: ['h-4 w-4'],
helperText: 'text-xs',
helperIcon: ['h-4 w-4'],
},
},
},
defaultVariants: {
size: 'md',
state: 'default',
},
},
{
responsiveVariants: true,
},
);
export type InputTheme = VariantProps<typeof inputTheme>;
@@ -0,0 +1,100 @@
import React, { ReactNode, useMemo } from 'react';
import { ComponentPropsWithoutRef } from 'react';
import { InputTheme, inputTheme } from './Input.theme';
import { WarningIcon } from 'components/shared/CustomIcon';
import { cloneIcon } from 'utils/cloneIcon';
import { cn } from 'utils/classnames';
export interface InputProps
extends InputTheme,
Omit<ComponentPropsWithoutRef<'input'>, 'size'> {
label?: string;
description?: string;
leftIcon?: ReactNode;
rightIcon?: ReactNode;
helperText?: string;
}
export const Input = ({
className,
label,
description,
leftIcon,
rightIcon,
helperText,
size,
state,
...props
}: InputProps) => {
const styleProps = (({ size = 'md', state }) => ({
size,
state,
}))({ size, state });
const {
container: containerCls,
label: labelCls,
description: descriptionCls,
input: inputCls,
icon: iconCls,
iconContainer: iconContainerCls,
helperText: helperTextCls,
helperIcon: helperIconCls,
} = inputTheme({ ...styleProps });
const renderLabels = useMemo(
() => (
<div className="space-y-1">
<p className={labelCls()}>{label}</p>
<p className={descriptionCls()}>{description}</p>
</div>
),
[labelCls, descriptionCls, label, description],
);
const renderLeftIcon = useMemo(() => {
return (
<div className={iconContainerCls({ class: 'left-0 pl-4' })}>
{cloneIcon(leftIcon, { className: iconCls(), ariaHidden: true })}
</div>
);
}, [cloneIcon, iconCls, iconContainerCls, leftIcon]);
const renderRightIcon = useMemo(() => {
return (
<div className={iconContainerCls({ class: 'pr-4 right-0' })}>
{cloneIcon(rightIcon, { className: iconCls(), ariaHidden: true })}
</div>
);
}, [cloneIcon, iconCls, iconContainerCls, rightIcon]);
const renderHelperText = useMemo(
() => (
<div className={helperTextCls()}>
{state &&
cloneIcon(<WarningIcon className={helperIconCls()} />, {
ariaHidden: true,
})}
<p>{helperText}</p>
</div>
),
[cloneIcon, state, helperIconCls, helperText, helperTextCls],
);
return (
<div className="space-y-2">
{renderLabels}
<div className={containerCls({ class: className })}>
{leftIcon && renderLeftIcon}
<input
className={cn(inputCls({ class: 'w-80' }), {
'pl-10': leftIcon,
})}
{...props}
/>
{rightIcon && renderRightIcon}
</div>
{renderHelperText}
</div>
);
};
@@ -0,0 +1,2 @@
export * from './Input';
export * from './Input.theme';
@@ -0,0 +1,54 @@
import { VariantProps, tv } from 'tailwind-variants';
export const radioTheme = tv({
slots: {
root: ['flex', 'gap-3', 'flex-wrap'],
wrapper: ['flex', 'items-center', 'gap-2', 'group'],
label: ['text-sm', 'tracking-[-0.006em]', 'text-elements-high-em'],
radio: [
'w-5',
'h-5',
'rounded-full',
'border',
'group',
'border-border-interactive/10',
'shadow-button',
'group-hover:border-border-interactive/[0.14]',
'focus-ring',
// Checked
'data-[state=checked]:bg-controls-primary',
'data-[state=checked]:group-hover:bg-controls-primary-hovered',
],
indicator: [
'flex',
'items-center',
'justify-center',
'relative',
'w-full',
'h-full',
'after:content-[""]',
'after:block',
'after:w-2.5',
'after:h-2.5',
'after:rounded-full',
'after:bg-transparent',
'after:group-hover:bg-controls-disabled',
'after:group-focus-visible:bg-controls-disabled',
// Checked
'after:data-[state=checked]:bg-elements-on-primary',
'after:data-[state=checked]:group-hover:bg-elements-on-primary',
'after:data-[state=checked]:group-focus-visible:bg-elements-on-primary',
],
},
variants: {
orientation: {
vertical: { root: ['flex-col'] },
horizontal: { root: ['flex-row'] },
},
},
defaultVariants: {
orientation: 'vertical',
},
});
export type RadioTheme = VariantProps<typeof radioTheme>;
@@ -0,0 +1,63 @@
import React from 'react';
import {
Root as RadixRoot,
RadioGroupProps,
} from '@radix-ui/react-radio-group';
import { RadioTheme, radioTheme } from './Radio.theme';
import { RadioItem, RadioItemProps } from './RadioItem';
export interface RadioOption extends RadioItemProps {
/**
* The label of the radio option.
*/
label: string;
/**
* The value of the radio option.
*/
value: string;
}
export interface RadioProps extends RadioGroupProps, RadioTheme {
/**
* The options of the radio.
* @default []
* @example
* ```tsx
* const options = [
* {
* label: 'Label 1',
* value: '1',
* },
* {
* label: 'Label 2',
* value: '2',
* },
* {
* label: 'Label 3',
* value: '3',
* },
* ];
* ```
*/
options: RadioOption[];
}
/**
* The Radio component is used to select one option from a list of options.
*/
export const Radio = ({
className,
options,
orientation,
...props
}: RadioProps) => {
const { root } = radioTheme({ orientation });
return (
<RadixRoot {...props} className={root({ className })}>
{options.map((option) => (
<RadioItem key={option.value} {...option} />
))}
</RadixRoot>
);
};
@@ -0,0 +1,74 @@
import React, { ComponentPropsWithoutRef } from 'react';
import {
Item as RadixRadio,
Indicator as RadixIndicator,
RadioGroupItemProps,
RadioGroupIndicatorProps,
} from '@radix-ui/react-radio-group';
import { radioTheme } from './Radio.theme';
export interface RadioItemProps extends RadioGroupItemProps {
/**
* The wrapper props of the radio item.
* You can use this prop to customize the wrapper props.
*/
wrapperProps?: ComponentPropsWithoutRef<'div'>;
/**
* The label props of the radio item.
* You can use this prop to customize the label props.
*/
labelProps?: ComponentPropsWithoutRef<'label'>;
/**
* The indicator props of the radio item.
* You can use this prop to customize the indicator props.
*/
indicatorProps?: RadioGroupIndicatorProps;
/**
* The id of the radio item.
*/
id?: string;
/**
* The label of the radio item.
*/
label?: string;
}
/**
* The RadioItem component is used to render a radio item.
*/
export const RadioItem = ({
className,
wrapperProps,
labelProps,
indicatorProps,
label,
id,
...props
}: RadioItemProps) => {
const { wrapper, label: labelClass, radio, indicator } = radioTheme();
// Generate a unique id for the radio item from the label if the id is not provided
const kebabCaseLabel = label?.toLowerCase().replace(/\s+/g, '-');
const componentId = id ?? kebabCaseLabel;
return (
<div className={wrapper({ className: wrapperProps?.className })}>
<RadixRadio {...props} className={radio({ className })} id={componentId}>
<RadixIndicator
forceMount
{...indicatorProps}
className={indicator({ className: indicatorProps?.className })}
/>
</RadixRadio>
{label && (
<label
{...labelProps}
className={labelClass({ className: labelProps?.className })}
htmlFor={componentId}
>
{label}
</label>
)}
</div>
);
};
@@ -0,0 +1,2 @@
export * from './Radio';
export * from './RadioItem';
@@ -0,0 +1,84 @@
import { tv, type VariantProps } from 'tailwind-variants';
export const switchTheme = tv({
slots: {
wrapper: ['flex', 'items-start', 'gap-4', 'w-[375px]'],
switch: [
'h-6',
'w-12',
'rounded-full',
'transition-all',
'duration-500',
'relative',
'cursor-default',
'shadow-inset',
'focus-ring',
'outline-none',
],
thumb: [
'block',
'h-4',
'w-4',
'translate-x-1',
'transition-transform',
'duration-100',
'will-change-transform',
'rounded-full',
'shadow-button',
'data-[state=checked]:translate-x-7',
'bg-controls-elevated',
],
label: [
'flex',
'flex-1',
'flex-col',
'px-1',
'gap-1',
'text-sm',
'text-elements-high-em',
'tracking-[-0.006em]',
],
description: ['text-xs', 'text-elements-low-em'],
},
variants: {
checked: {
true: {
switch: [
'bg-controls-primary',
'hover:bg-controls-primary-hovered',
'focus-visible:bg-controls-primary-hovered',
],
},
false: {
switch: [
'bg-controls-inset',
'hover:bg-controls-inset-hovered',
'focus-visible:bg-controls-inset-hovered',
],
},
},
disabled: {
true: {
switch: ['bg-controls-disabled', 'cursor-not-allowed'],
thumb: ['bg-elements-on-disabled'],
},
},
fullWidth: {
true: {
wrapper: ['w-full', 'justify-between'],
},
},
},
compoundVariants: [
{
checked: true,
disabled: true,
class: {
switch: ['bg-controls-disabled-active'],
thumb: ['bg-snowball-900'],
},
},
],
});
export type SwitchVariants = VariantProps<typeof switchTheme>;
@@ -0,0 +1,85 @@
import React, { type ComponentPropsWithoutRef } from 'react';
import { type SwitchProps as SwitchRadixProps } from '@radix-ui/react-switch';
import * as SwitchRadix from '@radix-ui/react-switch';
import { switchTheme, type SwitchVariants } from './Switch.theme';
interface SwitchProps
extends Omit<SwitchRadixProps, 'checked'>,
SwitchVariants {
/**
* The label of the switch.
*/
label?: string;
/**
* The description of the switch.
*/
description?: string;
/**
* Custom wrapper props for the switch.
*/
wrapperProps?: ComponentPropsWithoutRef<'div'>;
/**
* Function that is called when the checked state of the switch changes.
* @param checked The new checked state of the switch.
*/
onCheckedChange?(checked: boolean): void;
}
/**
* A switch is a component used for toggling between two states.
*/
export const Switch = ({
className,
checked,
label,
description,
disabled,
name,
wrapperProps,
fullWidth,
...props
}: SwitchProps) => {
const {
wrapper,
switch: switchClass,
thumb,
label: labelClass,
description: descriptionClass,
} = switchTheme({
checked,
disabled,
fullWidth,
});
const switchComponent = (
<SwitchRadix.Root
{...props}
checked={checked}
disabled={disabled}
className={switchClass({ className })}
>
<SwitchRadix.Thumb className={thumb()} />
</SwitchRadix.Root>
);
// If a label is provided, wrap the switch in a label element.
if (label) {
return (
<div
{...wrapperProps}
className={wrapper({ className: wrapperProps?.className })}
>
<label className={labelClass()} htmlFor={name}>
{label}
{description && (
<span className={descriptionClass()}>{description}</span>
)}
</label>
{switchComponent}
</div>
);
}
return switchComponent;
};
@@ -0,0 +1 @@
export * from './Switch';
@@ -0,0 +1,82 @@
import { tv, type VariantProps } from 'tailwind-variants';
export type TabsVariants = VariantProps<typeof tabsTheme>;
export const tabsTheme = tv({
slots: {
root: ['flex', 'data-[orientation=horizontal]:w-full'],
triggerWrapper: [
// Horizontal default
'px-1',
'pb-5',
'cursor-default',
'select-none',
'text-elements-low-em',
'border-b-2',
'border-transparent',
'hover:border-border-interactive/10',
'hover:text-elements-mid-em',
'focus-within:border-border-interactive/10',
'data-[state=active]:font-medium',
'data-[state=active]:text-elements-high-em',
'data-[state=active]:border-elements-high-em',
// Vertical
'data-[orientation=vertical]:px-3',
'data-[orientation=vertical]:py-3',
'data-[orientation=vertical]:min-w-[240px]',
'data-[orientation=vertical]:focus-ring',
'data-[orientation=vertical]:rounded-xl',
'data-[orientation=vertical]:border-transparent',
'data-[orientation=vertical]:hover:bg-base-bg-emphasized',
'data-[orientation=vertical]:hover:text-elements-mid-em',
'data-[orientation=vertical]:hover:border-transparent',
'data-[orientation=vertical]:focus-visible:border-transparent',
'data-[orientation=vertical]:focus-visible:bg-base-bg-emphasized',
'data-[orientation=vertical]:focus-visible:text-elements-mid-em',
'data-[orientation=vertical]:data-[state=active]:font-normal',
'data-[orientation=vertical]:data-[state=active]:bg-base-bg-emphasized',
'data-[orientation=vertical]:data-[state=active]:border-transparent',
'data-[orientation=vertical]:data-[state=active]:hover:text-elements-high-em',
'data-[orientation=vertical]:data-[state=active]:focus-visible:text-elements-high-em',
],
trigger: [
'flex',
'gap-1.5',
'cursor-default',
'select-none',
'items-center',
'justify-center',
'outline-none',
'leading-none',
'tracking-[-0.006em]',
'rounded-md',
// Horizontal default
'data-[orientation=horizontal]:focus-ring',
// Vertical
'data-[orientation=vertical]:gap-2',
],
triggerList: [
'flex',
'shrink-0',
'gap-5',
'border-b',
'border-transparent',
// Horizontal default
'data-[orientation=horizontal]:border-border-interactive/10',
// Vertical
'data-[orientation=vertical]:flex-col',
'data-[orientation=vertical]:gap-0.5',
],
content: ['text-elements-high-em', 'grow', 'outline-none', 'tab-content'],
},
variants: {
fillWidth: {
true: {
trigger: ['flex-1'],
},
},
},
defaultVariants: {
fillWidth: false,
},
});
@@ -0,0 +1,51 @@
import React, { type ComponentPropsWithoutRef } from 'react';
import { Root as TabsRoot } from '@radix-ui/react-tabs';
import { tabsTheme } from './Tabs.theme';
import TabsContent from './TabsContent';
import TabsList from './TabsList';
import TabsTrigger from './TabsTrigger';
import TabsProvider, { TabsProviderProps } from './TabsProvider';
export interface TabsProps extends ComponentPropsWithoutRef<typeof TabsRoot> {
/**
* The configuration for the tabs component.
*/
config?: TabsProviderProps;
}
/**
* A component that allows users to switch between different tabs.
* @returns JSX element representing the tabs component.
*/
export const Tabs = ({
config,
className,
orientation = 'horizontal',
...props
}: TabsProps) => {
const { root } = tabsTheme(config);
return (
<TabsProvider {...config} orientation={orientation}>
<TabsRoot
{...props}
orientation={orientation}
className={root({ className })}
/>
</TabsProvider>
);
};
/**
* Assigns the TabsTrigger class to the Trigger property of the Tabs object.
*/
Tabs.Trigger = TabsTrigger;
/**
* Assigns the TabsList object to the List property of the Tabs object.
*/
Tabs.List = TabsList;
/**
* Assigns the TabsContent component to the Content property of the Tabs component.
*/
Tabs.Content = TabsContent;
@@ -0,0 +1,26 @@
import React, {
forwardRef,
type ComponentPropsWithoutRef,
type ElementRef,
} from 'react';
import { Content } from '@radix-ui/react-tabs';
import { tabsTheme } from '../Tabs.theme';
export interface TabsContentProps
extends ComponentPropsWithoutRef<typeof Content> {}
/**
* A component that represents the content of the tabs component.
*/
const TabsContent = forwardRef<ElementRef<typeof Content>, TabsContentProps>(
({ className, ...props }, ref) => {
const { content } = tabsTheme();
return <Content ref={ref} className={content({ className })} {...props} />;
},
);
// Assigns the display name to the TabsContent component.
TabsContent.displayName = 'TabsContent';
export { TabsContent };
@@ -0,0 +1,3 @@
import { TabsContent } from './TabsContent';
export default TabsContent;
@@ -0,0 +1,25 @@
import React, {
forwardRef,
type ComponentPropsWithoutRef,
type ElementRef,
} from 'react';
import { List } from '@radix-ui/react-tabs';
import { tabsTheme } from 'components/shared/Tabs/Tabs.theme';
export interface TabsListProps extends ComponentPropsWithoutRef<typeof List> {}
/**
* A component that represents the list of tabs.
*/
const TabsList = forwardRef<ElementRef<typeof List>, TabsListProps>(
({ className, ...props }, ref) => {
const { triggerList } = tabsTheme({ className });
return <List ref={ref} className={triggerList({ className })} {...props} />;
},
);
// Assigns the display name to the TabsList component.
TabsList.displayName = 'TabsList';
export { TabsList };
@@ -0,0 +1,3 @@
import { TabsList } from './TabsList';
export default TabsList;
@@ -0,0 +1,47 @@
import React, {
createContext,
useContext,
type PropsWithChildren,
ComponentPropsWithoutRef,
} from 'react';
import { TabsVariants } from './Tabs.theme';
import { Root as TabsRoot } from '@radix-ui/react-tabs';
export interface TabsProviderProps
extends Partial<TabsVariants>,
ComponentPropsWithoutRef<typeof TabsRoot> {}
type TabsProviderContext = ReturnType<typeof useTabsValues>;
const TabsContext = createContext<Partial<TabsProviderContext>>({});
// For inferring return type
const useTabsValues = (props: TabsProviderProps) => {
return props;
};
/**
* A provider component that allows users to switch between different tabs.
* @returns JSX element representing the tabs provider component.
*/
export const TabsProvider = ({
children,
...props
}: PropsWithChildren<TabsProviderProps>): JSX.Element => {
const values = useTabsValues(props);
return <TabsContext.Provider value={values}>{children}</TabsContext.Provider>;
};
/**
* A hook that returns the context of the tabs provider.
* @returns The context of the tabs provider.
*/
export const useTabs = () => {
const context = useContext(TabsContext);
if (context === undefined) {
throw new Error('useTabs was used outside of its Provider');
}
return context;
};
export default TabsProvider;
@@ -0,0 +1,59 @@
import React, {
forwardRef,
type ComponentPropsWithoutRef,
type ElementRef,
type PropsWithChildren,
type ReactNode,
} from 'react';
import { Trigger } from '@radix-ui/react-tabs';
import { tabsTheme } from 'components/shared/Tabs/Tabs.theme';
import { useTabs } from 'components/shared/Tabs/TabsProvider';
export interface TabsTriggerProps
extends ComponentPropsWithoutRef<typeof Trigger> {
/**
* The icon to display in the trigger.
*/
icon?: ReactNode;
}
/**
* A component that represents the trigger for the tabs component.
*/
const TabsTrigger = forwardRef<
ElementRef<typeof Trigger>,
PropsWithChildren<TabsTriggerProps>
>(({ className, icon, children, ...props }, ref) => {
const config = useTabs();
const { triggerWrapper, trigger } = tabsTheme(config);
const orientation = config.orientation;
return (
<Trigger
ref={ref}
// Disabled focus state for horizontal tabs
tabIndex={orientation === 'horizontal' ? -1 : undefined}
className={triggerWrapper({ className })}
{...props}
>
{/* Need to add button in the trigger children because there's focus state inside the children */}
<button
data-orientation={orientation}
// Disabled focus state for vertical tabs
tabIndex={orientation === 'vertical' ? -1 : undefined}
className={trigger()}
>
{/* Put the icon on the left of the text for veritcal tab */}
{orientation === 'vertical' && icon}
{children}
{/* Put the icon on the right of the text for horizontal tab */}
{orientation === 'horizontal' && icon}
</button>
</Trigger>
);
});
TabsTrigger.displayName = 'TabsTrigger';
export { TabsTrigger };
@@ -0,0 +1,3 @@
import { TabsTrigger } from './TabsTrigger';
export default TabsTrigger;
@@ -0,0 +1 @@
export * from './Tabs';
@@ -0,0 +1,14 @@
import { tv } from 'tailwind-variants';
export const tooltipTheme = tv({
slots: {
content: [
'z-tooltip',
'rounded-md',
'bg-surface-high-contrast',
'p-2',
'text-elements-on-high-contrast',
],
arrow: ['fill-surface-high-contrast'],
},
});
@@ -0,0 +1,47 @@
import React from 'react';
import type {
TooltipContentProps,
TooltipTriggerProps,
} from '@radix-ui/react-tooltip';
import { ReactNode, useState } from 'react';
import { TooltipBase, type TooltipBaseProps } from './TooltipBase';
export interface TooltipProps extends TooltipBaseProps {
triggerProps?: TooltipTriggerProps;
contentProps?: TooltipContentProps;
content?: ReactNode;
}
// https://github.com/radix-ui/primitives/issues/955#issuecomment-1798201143
// Wrap on top of Tooltip base to make tooltip open on mobile via click
export const Tooltip = ({
children,
triggerProps,
contentProps,
content,
...props
}: TooltipProps) => {
const [isTooltipVisible, setIsTooltipVisible] = useState(false);
return (
<TooltipBase
open={isTooltipVisible}
onOpenChange={setIsTooltipVisible}
{...props}
>
<TooltipBase.Trigger
asChild
onBlur={() => setIsTooltipVisible(false)}
onClick={() => setIsTooltipVisible((prevOpen) => !prevOpen)}
onFocus={() => setTimeout(() => setIsTooltipVisible(true), 0)}
{...triggerProps}
>
{triggerProps?.children ?? children}
</TooltipBase.Trigger>
<TooltipBase.Content {...contentProps}>
{content ?? contentProps?.children ?? 'Coming soon'}
</TooltipBase.Content>
</TooltipBase>
);
};
@@ -0,0 +1,38 @@
import React from 'react';
import {
Provider,
TooltipProps as RadixTooltipProps,
Root,
type TooltipProviderProps,
} from '@radix-ui/react-tooltip';
import { useState, type PropsWithChildren } from 'react';
import { TooltipContent } from './TooltipContent';
import { TooltipTrigger } from './TooltipTrigger';
export interface TooltipBaseProps extends RadixTooltipProps {
providerProps?: TooltipProviderProps;
}
export const TooltipBase = ({
children,
providerProps,
...props
}: PropsWithChildren<TooltipBaseProps>) => {
const [isTooltipVisible, setIsTooltipVisible] = useState(false);
return (
<Provider {...providerProps}>
<Root
open={isTooltipVisible}
onOpenChange={setIsTooltipVisible}
{...props}
>
{children}
</Root>
</Provider>
);
};
TooltipBase.Trigger = TooltipTrigger;
TooltipBase.Content = TooltipContent;
@@ -0,0 +1,46 @@
import React from 'react';
import {
Arrow,
Content,
Portal,
type TooltipArrowProps,
type TooltipContentProps,
} from '@radix-ui/react-tooltip';
import { tooltipTheme } from '../Tooltip.theme';
export interface ContentProps extends TooltipContentProps {
hasArrow?: boolean;
arrowProps?: TooltipArrowProps;
}
export const TooltipContent = ({
children,
arrowProps,
className,
hasArrow = true,
...props
}: ContentProps) => {
const { content, arrow } = tooltipTheme();
return (
<Portal>
<Content
className={content({
className,
})}
sideOffset={5}
{...props}
>
{hasArrow && (
<Arrow
className={arrow({
className: arrowProps?.className,
})}
{...arrowProps}
/>
)}
{children}
</Content>
</Portal>
);
};
@@ -0,0 +1 @@
export * from './TooltipContent';
@@ -0,0 +1,12 @@
import React from 'react';
import { Trigger, type TooltipTriggerProps } from '@radix-ui/react-tooltip';
export type TriggerProps = TooltipTriggerProps;
export const TooltipTrigger = ({ children, ...props }: TriggerProps) => {
return (
<Trigger asChild {...props}>
{children}
</Trigger>
);
};
@@ -0,0 +1 @@
export * from './TooltipTrigger';
@@ -0,0 +1,2 @@
export * from './Tooltip';
export * from './TooltipBase';

Some files were not shown because too many files have changed in this diff Show More