Merge branch 'billing' of github.com:appwrite/console into refactor/create-file-wizard

This commit is contained in:
Arman committed 2023-12-12 12:39:46 +01:00
commit 6948485a0e
786 files changed
+47683 -9883

No files matched your search

+4 -2
View File
@@ -1,4 +1,6 @@
VITE_APPWRITE_ENDPOINT=
VITE_APPWRITE_ENDPOINT=http://localhost/v1
VITE_APPWRITE_GROWTH_ENDPOINT=
VITE_GA_PROJECT=
VITE_CONSOLE_MODE=self-hosted
VITE_CONSOLE_MODE=self-hosted
VITE_STRIPE_PUBLIC_KEY=
VITE_CONSOLE_MODE=self-hosted
+26 -11
View File
@@ -1,28 +1,43 @@
module.exports = {
root: true,
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:svelte/recommended',
'prettier'
],
parser: '@typescript-eslint/parser',
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
plugins: ['svelte3', '@typescript-eslint'],
parserOptions: {
extraFileExtensions: ['.svelte'], // This is a required setting in `@typescript-eslint/parser` v4.24.0.
sourceType: 'module',
ecmaVersion: 2020
},
ignorePatterns: ['*.cjs'],
overrides: [
{
files: ['*.svelte'],
processor: 'svelte3/svelte3',
rules: {
'no-redeclare': 'off'
parser: 'svelte-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser' //This is required to parse TypeScript inside Svelte files.
}
}
],
settings: {
'svelte3/typescript': () => require('typescript')
},
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020
rules: {
'no-redeclare': 'off',
'@typescript-eslint/no-duplicate-enum-values': 'off',
'svelte/no-at-html-tags': 'off',
'no-unused-vars': 'off', // This rule is handled by `@typescript-eslint/no-unused-vars` so it needs to be disabled to avoid conflicts.
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^(_|\\$\\$)' } // Ignore unused variables starting with `_` or `$$`.
]
},
env: {
browser: true,
es2017: true,
node: true
},
globals: {
globalThis: false // false means it is not writeable
}
};
+2 -2
View File
@@ -22,11 +22,11 @@ jobs:
# run: npm audit --audit-level low
- name: Install dependencies
run: npm ci
- name: Build Console
run: npm run build
- name: Svelte Diagnostics
run: npm run check
- name: Linter
run: npm run lint
- name: Unit Tests
run: npm test
- name: Build Console
run: npm run build
+133
View File
@@ -1,4 +1,6 @@
.DS_Store
.envrc
.vscode
node_modules
/build
/.svelte-kit
@@ -13,3 +15,134 @@ node_modules
node_modules/
dist/
.vercel
*.swp
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
.env.production
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
### Node Patch ###
# Serverless Webpack directories
.webpack/
# Optional stylelint cache
.stylelintcache
# SvelteKit build / generate output
.svelte-kit
+9
View File
@@ -0,0 +1,9 @@
# This configuration file was automatically generated by Gitpod.
# Please adjust to your needs (see https://www.gitpod.io/docs/introduction/learn-gitpod/gitpod-yaml)
# and commit this file to your remote git repository to share the goodness with others.
# Learn more from ready-to-use templates: https://www.gitpod.io/docs/introduction/getting-started/quickstart
tasks:
- init: npm install && npm run build
command: npm run dev
+1 -1
View File
@@ -5,5 +5,5 @@
"trailingComma": "none",
"printWidth": 100,
"bracketSameLine": true,
"svelteSortOrder": "scripts-options-markup-styles"
"plugins": ["prettier-plugin-svelte"]
}
+36 -23
View File
@@ -4,31 +4,36 @@ We would ❤️ for you to contribute to Appwrite and help make it better! We wa
## How to Start?
If you are worried about or don’t know where to start, check out the next section that explains what kind of help is needed and how you can get involved. You can reach out with any questions on our [Discord](https://appwrite.io/discord) server. You can also submit an issue and a maintainer can guide you!
If you are worried about or don't know where to start, check out the next section that explains what kind of help is needed and how you can get involved. You can reach out with any questions on our [Discord](https://appwrite.io/discord) server. You can also submit an issue and a maintainer can guide you!
## Repo Structure
```
├── src
│ ├── lib // All non-route components, accessible over "import ... from '$lib'"
│ │ ├── components // Re-usable components
│ │ ├── elements // Re-usable elements
│ │ ├── layout // Global components for the layout (Nav/Content/Container)
│ │ └── stores // Global stores (state management)
│ └─── routes
│ ├── console // Routes that need authentication
│ │ ├──[project]
│ │ │ ├── database // Database Service
│ │ │ │ ├── [collection] // Nested Route for the collection "/console/[PROJECT_ID]/database/[COLLECTION_ID]"
│ │ │ │ ├── _create.svelte // Component to Create collections
│ │ │ │ └── index.svelte // Entrypoint for "/console/[PROJECT_ID]/database"
│ │ │ ├── storage // Storage Service "/console/[PROJECT]/storage"
│ │ │ └── auth // Users Service "/console/[PROJECT]/auth"
│ │ └──...
│ ├── login.svelte // Component for Login "/console/login"
│ └── register.svelte // Component for Register "/console/register"
├── build // Compiled application
└── static // Static assets
│ ├── lib // Reusable logic (accessible with '$lib')
│ │ ├── actions // Svelte actions
│ │ ├── charts // Chart components
│ │ ├── components // Re-usable components
│ │ ├── elements // Re-usable elements
│ │ ├── helpers // Small functions used through out the console
│ │ ├── images // Images used in the console
│ │ ├── layout // Global components for the layout (Nav/Content/Container)
│ │ ├── mock // Mock components used for testing
│ │ └── stores // Global stores (state management)
│ └── routes
│ └── console // Routes that need authentication
│ │ └── project-[project]
│ │ │ └── database // Database Service
│ │ │ │ ├── +layout.svelte // Layout head and other logic like realtime events is set here
│ │ │ │ ├── +layout.ts // Layout data is set here (Header, Breadcrumbs, ...)
│ │ │ │ ├── +page.svelte // Page displayed on "/console/project-[PROJECT_ID]/database"
│ │ │ │ ├── +page.ts // Necessary data for the page is fetched here
│ │ │ │ └── create.svelte // Component to create databases
│ │ │ └── ... // Other services
│ │ └── ...
│ └── ... // Routes that don't need authentication
├── build // Compiled application
└── static // Static assets
```
## Development
@@ -41,11 +46,19 @@ git clone https://github.com/appwrite/console.git appwrite-console
### 2. Install dependencies with npm
Navigate to the Appwrite Console repository and install dependencies.
```bash
npm install
cd appwrite-console && npm install
```
### 3. Setup environment variables
### 3. Install and run Appwrite locally
When you run the Appwrite Console locally, it needs to point to a backend as well. The easiest way to do this is to run an Appwrite instance locally.
Follow the [install instructions](https://appwrite.io/docs/advanced/self-hosting) in the Appwrite docs.
### 4. Setup environment variables
Add a `.env` file by copying the `.env.example` file as a template in the project's root directory.
@@ -229,7 +242,7 @@ When blogging, speaking about, or creating tutorials about one of Appwrite's man
### Presenting at Meetups
Presenting at meetups and conferences about your Appwrite projects is another excellent way to get the word out about Appwrite. Your unique challenges and successes in building things with Appwrite can provide great speaking material. We’d love to review your talk abstract/CFP, so get in touch with us if you’d like some help!
Presenting at meetups and conferences about your Appwrite projects is another excellent way to get the word out about Appwrite. Your unique challenges and successes in building things with Appwrite can provide great speaking material. We'd love to review your talk abstract/CFP, so get in touch with us if you'd like some help!
### Sending Feedback & Reporting Bugs
+1 -1
View File
@@ -31,7 +31,7 @@ Console 2.0 is designed to be accessible, from design to code. Console 2.0 is al
### Scalability and Collaboration
The new console is more maintainable and welcoming to community contributions. Console 2.0 is built using Svelte instead of our own library. It’s better documented and well-known, making it easier for developers to contribute to Appwrite.
The new console is more maintainable and welcoming to community contributions. Console 2.0 is built using Svelte instead of our own library. It's better documented and well-known, making it easier for developers to contribute to Appwrite.
## Contributing
-1
View File
@@ -26,7 +26,6 @@ async function main() {
logEnv('CONSOLE MODE', env?.VITE_CONSOLE_MODE);
logEnv('APPWRITE ENDPOINT', env?.VITE_APPWRITE_ENDPOINT, 'relative');
logEnv('GROWTH ENDPOINT', env?.VITE_APPWRITE_GROWTH_ENDPOINT);
logEnv('GOOGLE ANALYTICS', env?.VITE_GA_PROJECT);
log();
logDelimiter();
await build();
+2540 -1993
View File
File diff suppressed because it is too large. Load diff
+46 -39
View File
@@ -10,62 +10,69 @@
"sync": "svelte-kit sync",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings --threshold warning",
"check:watch": "svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --ignore-path .gitignore --check --plugin-search-dir=. . && eslint .",
"format": "prettier --ignore-path .gitignore --write --plugin-search-dir=. .",
"lint": "prettier --ignore-path .gitignore --check --plugin prettier-plugin-svelte . && eslint .",
"format": "prettier --ignore-path .gitignore --write --plugin prettier-plugin-svelte .",
"test": "vitest run",
"test:ui": "vitest --ui",
"test:watch": "vitest watch",
"e2e": "playwright test tests/e2e"
},
"dependencies": {
"@analytics/google-analytics": "^1.0.5",
"@appwrite.io/console": "0.1.0",
"@appwrite.io/pink": "^0.0.6-rc.10",
"@popperjs/core": "^2.11.6",
"@sentry/svelte": "^7.44.2",
"@sentry/tracing": "^7.44.2",
"analytics": "^0.8.1",
"dotenv": "^16.0.3",
"echarts": "^5.4.1",
"logrocket": "^3.0.1",
"pretty-bytes": "^6.1.0",
"@appwrite.io/console": "^0.4.1",
"@appwrite.io/pink": "0.2.0",
"@appwrite.io/pink-icons": "0.2.0",
"@popperjs/core": "^2.11.8",
"@sentry/svelte": "^7.66.0",
"@sentry/tracing": "^7.66.0",
"@stripe/stripe-js": "^2.2.0",
"ai": "^2.2.11",
"analytics": "^0.8.9",
"dayjs": "^1.11.9",
"deep-equal": "^2.2.2",
"dotenv": "^16.3.1",
"echarts": "^5.4.3",
"logrocket": "^5.0.1",
"nanoid": "^4.0.2",
"plausible-tracker": "^0.3.8",
"pretty-bytes": "^6.1.1",
"prismjs": "^1.29.0",
"svelte-confetti": "^1.3.0",
"tippy.js": "^6.3.7",
"web-vitals": "^3.1.1"
"web-vitals": "^3.4.0"
},
"devDependencies": {
"@playwright/test": "^1.31.2",
"@sveltejs/adapter-static": "^2.0.2",
"@sveltejs/kit": "^1.15.4",
"@sveltejs/vite-plugin-svelte": "^2.0.4",
"@melt-ui/pp": "^0.1.4",
"@melt-ui/svelte": "^0.61.2",
"@playwright/test": "^1.37.1",
"@sveltejs/adapter-static": "^2.0.3",
"@sveltejs/kit": "^1.24.0",
"@sveltejs/vite-plugin-svelte": "^2.4.5",
"@testing-library/dom": "^9.0.1",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/svelte": "^3.2.2",
"@testing-library/svelte": "^4.0.3",
"@testing-library/user-event": "^14.4.3",
"@types/deep-equal": "^1.0.1",
"@types/prismjs": "^1.26.0",
"@typescript-eslint/eslint-plugin": "^5.56.0",
"@typescript-eslint/parser": "^5.56.0",
"@typescript-eslint/eslint-plugin": "^6.5.0",
"@typescript-eslint/parser": "^6.5.0",
"@vitest/ui": "^0.29.7",
"eslint": "^8.36.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-svelte3": "^4.0.0",
"jsdom": "^21.1.1",
"eslint": "^8.48.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-svelte": "^2.33.0",
"jsdom": "^22.1.0",
"kleur": "^4.1.5",
"pre-commit": "^1.2.2",
"prettier": "^2.8.6",
"prettier-plugin-svelte": "^2.9.0",
"sass": "^1.59.3",
"svelte": "^3.57.0",
"svelte-check": "^3.1.4",
"prettier": "^3.0.3",
"prettier-plugin-svelte": "^3.0.3",
"sass": "^1.66.1",
"svelte": "^4.2.0",
"svelte-check": "^3.5.1",
"svelte-jester": "^2.3.2",
"svelte-preprocess": "^5.0.3",
"tslib": "^2.5.0",
"typescript": "^5.0.2",
"vite": "^4.2.1",
"svelte-preprocess": "^5.0.4",
"svelte-sequential-preprocessor": "^2.0.1",
"tslib": "^2.6.2",
"typescript": "^5.2.2",
"vite": "^4.4.9",
"vitest": "^0.29.7"
},
"type": "module",
"pre-commit": [
"lint"
]
"type": "module"
}
+7647
View File
File diff suppressed because it is too large. Load diff
+89 -3
View File
@@ -1,9 +1,9 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="" />
<link rel="icon" href="/favicon.png" />
<link rel="icon" type="image/svg+xml" href="/logos/appwrite-icon.svg" />
<link
rel="preload"
href="/fonts/inter/inter-v8-latin-600.woff2"
@@ -40,12 +40,98 @@
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-Air.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-AirItalic.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-Thin.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-ThinItalic.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-Light.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-LightItalic.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-Regular.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-RegularItalic.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-Medium.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-MediumItalic.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-Bold.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-BoldItalic.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-Black.woff2"
as="font"
type="font/woff2"
crossorigin />
<link
rel="preload"
href="https://fonts.appwrite.io/aeonik-pro/AeonikPro-BlackItalic.woff2"
as="font"
type="font/woff2"
crossorigin />
<link rel="preload" as="style" type="text/css" href="/fonts/main.css" />
<link rel="stylesheet" href="/fonts/main.css" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- {{CLOUD_OG}} -->
%sveltekit.head%
</head>
<body>
<body data-sveltekit-preload-data="hover">
<div id="svelte">%sveltekit.body%</div>
</body>
</html>
+87 -10
View File
@@ -1,18 +1,53 @@
import Analytics, { type AnalyticsPlugin } from 'analytics';
import Plausible from 'plausible-tracker';
import { get } from 'svelte/store';
import { page } from '$app/stores';
import { user } from '$lib/stores/user';
import { ENV, MODE, VARS } from '$lib/system';
import googleAnalytics from '@analytics/google-analytics';
import { ENV, MODE, VARS, isCloud } from '$lib/system';
import { AppwriteException } from '@appwrite.io/console';
import Analytics from 'analytics';
import { get } from 'svelte/store';
import { browser } from '$app/environment';
function plausible(domain: string): AnalyticsPlugin {
if (!browser) return { name: 'analytics-plugin-plausible' };
const instance = Plausible({
domain
});
return {
name: 'analytics-plugin-plausible',
page: ({ payload }) => {
instance.trackPageview({
url: payload.properties.path,
referrer: payload.properties.referrer,
deviceWidth: payload.properties.width
});
},
track: ({ payload }) => {
instance.trackEvent(
payload.event,
{
props: payload.properties
},
{
url: payload.properties.path,
deviceWidth: payload.properties.width
}
);
},
loaded: () => true
};
}
const PLAUSIBLE_DOMAINS = {
CLOUD: 'cloud.appwrite.io',
GLOBAL: 'console.appwrite',
SELF_HOSTED: 'self-hosted.appwrite'
};
const analytics = Analytics({
app: 'appwrite',
plugins: [
googleAnalytics({
measurementIds: [VARS.GOOGLE_ANALYTICS || 'G-R4YJ9JN8L4']
})
]
plugins: [plausible(isCloud ? PLAUSIBLE_DOMAINS.CLOUD : PLAUSIBLE_DOMAINS.SELF_HOSTED)]
});
export function trackEvent(name: string, data: object = null): void {
@@ -118,6 +153,7 @@ export enum Submit {
UserCreate = 'submit_user_create',
UserDelete = 'submit_user_delete',
UserUpdateEmail = 'submit_user_update_email',
UserUpdateLabels = 'submit_user_update_labels',
UserUpdateName = 'submit_user_update_name',
UserUpdatePassword = 'submit_user_update_password',
UserUpdatePhone = 'submit_user_update_phone',
@@ -131,7 +167,9 @@ export enum Submit {
ProjectCreate = 'submit_project_create',
ProjectDelete = 'submit_project_delete',
ProjectUpdateName = 'submit_project_update_name',
ProjectUpdateTeam = 'submit_project_update_team',
ProjectService = 'submit_project_service',
ProjectUpdateSMTP = 'submit_project_update_smtp',
MemberCreate = 'submit_member_create',
MemberDelete = 'submit_member_delete',
MembershipUpdateStatus = 'submit_membership_update_status',
@@ -143,6 +181,7 @@ export enum Submit {
AuthStatusUpdate = 'submit_auth_status_update',
AuthPasswordHistoryUpdate = 'submit_auth_password_history_limit_update',
AuthPasswordDictionaryUpdate = 'submit_auth_password_dictionary_update',
AuthPersonalDataCheckUpdate = 'submit_auth_personal_data_check_update',
SessionsLengthUpdate = 'submit_sessions_length_update',
SessionsLimitUpdate = 'submit_sessions_limit_update',
SessionDelete = 'submit_session_delete',
@@ -171,8 +210,13 @@ export enum Submit {
FunctionUpdateName = 'submit_function_update_name',
FunctionUpdatePermissions = 'submit_function_update_permissions',
FunctionUpdateSchedule = 'submit_function_update_schedule',
FunctionUpdateConfiguration = 'submit_function_update_configuration',
FunctionUpdateLogging = 'submit_function_update_logging',
FunctionUpdateTimeout = 'submit_function_update_timeout',
FunctionUpdateEvents = 'submit_function_update_events',
FunctionConnectRepo = 'submit_function_connect_repo',
FunctionDisconnectRepo = 'submit_function_disconnect_repo',
FunctionRedeploy = 'submit_function_redeploy',
DeploymentCreate = 'submit_deployment_create',
DeploymentDelete = 'submit_deployment_delete',
DeploymentUpdate = 'submit_deployment_update',
@@ -180,6 +224,7 @@ export enum Submit {
VariableCreate = 'submit_variable_create',
VariableDelete = 'submit_variable_delete',
VariableUpdate = 'submit_variable_update',
VariableEditor = 'submit_variable_editor',
KeyCreate = 'submit_key_create',
KeyDelete = 'submit_key_delete',
KeyUpdateName = 'submit_key_update_name',
@@ -210,5 +255,37 @@ export enum Submit {
BucketUpdateExtensions = 'submit_bucket_update_extensions',
FileCreate = 'submit_file_create',
FileDelete = 'submit_file_delete',
FileUpdatePermissions = 'submit_file_update_permissions'
FileUpdatePermissions = 'submit_file_update_permissions',
BudgetCapUpdate = 'submit_budget_cap_update',
BudgetAlertsUpdate = 'submit_budget_alert_conditions_update',
CreditRedeem = 'submit_credit_redeem',
PaymentMethodCreate = 'submit_payment_method_create',
PaymentMethodUpdate = 'submit_payment_method_update',
PaymentMethodDelete = 'submit_payment_method_delete',
BillingAddressCreate = 'submit_billing_address_create',
BillingAddressUpdate = 'submit_billing_address_update',
BillingAddressDelete = 'submit_billing_address_delete',
OrganizationPaymentUpdate = 'submit_organization_payment_update',
OrganizationPaymentDelete = 'submit_organization_payment_delete',
OrganizationBackupPaymentUpdate = 'submit_organization_backup_payment_update',
OrganizationBackupPaymentDelete = 'submit_organization_backup_payment_delete',
OrganizationBillingAddressUpdate = 'submit_organization_billing_address_update',
OrganizationBillingAddressDelete = 'submit_organization_billing_address_delete',
OrganizationUpgrade = 'submit_organization_upgrade',
OrganizationDowngrade = 'submit_organization_downgrade',
OrganizationBillingTaxIdUpdate = 'submit_organization_billing_tax_id_update',
SupportTicket = 'submit_support_ticket',
InstallationCreate = 'submit_installation_create',
InstallationDelete = 'submit_installation_delete',
EmailChangeLocale = 'submit_email_change_locale',
EmailResetTemplate = 'submit_email_reset_template',
EmailUpdateInviteTemplate = 'submit_email_update_invite_template',
EmailUpdateMagicUrlTemplate = 'submit_email_update_magic_url_template',
EmailUpdateRecoveryTemplate = 'submit_email_update_recovery_template',
EmailUpdateVerificationTemplate = 'submit_email_update_verification_template',
SmsChangeLocale = 'submit_sms_change_locale',
SmsResetTemplate = 'submit_sms_reset_template',
SmsUpdateInviteTemplate = 'submit_sms_update_invite_template',
SmsUpdateLoginTemplate = 'submit_sms_update_login_template',
SmsUpdateVerificationTemplate = 'submit_sms_update_verification_template'
}
+22
View File
@@ -0,0 +1,22 @@
import type { Action } from 'svelte/action';
export type MultiActionArray = Array<
(node: HTMLElement) => ReturnType<Action<HTMLElement, unknown>>
>;
export function multiAction(node: HTMLElement, arr: MultiActionArray) {
const destroyFns = arr.map((fn) => {
const actionReturn = fn(node);
return actionReturn
? actionReturn.destroy
: () => {
/* noop */
};
});
return {
destroy() {
destroyFns.forEach((fn) => fn());
}
};
}
+42
View File
@@ -0,0 +1,42 @@
import { tick } from 'svelte';
import type { Action } from 'svelte/action';
export type PortalConfig = string | HTMLElement | undefined;
export const portal: Action<HTMLElement, PortalConfig> = (el, target = 'body') => {
let targetEl;
async function update(newTarget: PortalConfig) {
target = newTarget;
if (typeof target === 'string') {
targetEl = document.querySelector(target);
if (targetEl === null) {
await tick();
targetEl = document.querySelector(target);
}
if (targetEl === null) {
throw new Error(`No element found matching css selector: "${target}"`);
}
} else if (target instanceof HTMLElement) {
targetEl = target;
} else {
throw new TypeError(
`Unknown portal target type: ${
target === null ? 'null' : typeof target
}. Allowed types: string (CSS selector) or HTMLElement.`
);
}
targetEl.appendChild(el);
el.hidden = false;
}
function destroy() {
el.remove();
}
update(target);
return {
update,
destroy
};
};
+158
View File
@@ -0,0 +1,158 @@
<script lang="ts" context="module">
type Context = Readable<{
isInitialPanel: boolean;
open: boolean;
}>;
type ReadableValue<T> = T extends Readable<infer U> ? U : never;
const contextKey = 'command-center';
export const getCommandCenterCtx = () => getContext<Context>(contextKey);
const setCommandCenterCtx = (value: ReadableValue<Context>) => {
const store = writable(value);
setContext(contextKey, store);
return store;
};
export const toggleCommandCenter = () => {
if (get(subPanels).length > 0) {
clearSubPanels();
} else {
addSubPanel(RootPanel);
}
};
</script>
<script lang="ts">
import { dev } from '$app/environment';
import { portal } from '$lib/actions/portal';
import { last } from '$lib/helpers/array';
import { debounce } from '$lib/helpers/debounce';
import { getContext, setContext } from 'svelte';
import { get, writable, type Readable } from 'svelte/store';
import { fade } from 'svelte/transition';
import { commandCenterKeyDownHandler, disableCommands, registerCommands } from './commands';
import { RootPanel } from './panels';
import { addSubPanel, clearSubPanels, subPanels } from './subPanels';
import { addNotification } from '$lib/stores/notifications';
let debugOverlayEnabled = false;
$: $registerCommands([
{
callback: toggleCommandCenter,
keys: ['k'],
ctrl: true,
forceEnable: true
},
{
label: 'Toggle debug overlay',
callback: () => {
debugOverlayEnabled = !debugOverlayEnabled;
addNotification({
title: 'Debug overlay',
message: debugOverlayEnabled ? 'Enabled' : 'Disabled',
type: 'info'
});
},
keys: ['d', 'o'],
group: 'misc',
disabled: !dev
}
]);
$: openSubPanel = last($subPanels) ?? null;
$: $disableCommands(!!openSubPanel);
$: if (openSubPanel) {
document.documentElement.classList.add('u-overflow-hidden');
} else {
document.documentElement.classList.remove('u-overflow-hidden');
}
let dialog: HTMLDivElement;
function handleBlur(event: MouseEvent) {
if (event.target === dialog) {
clearSubPanels();
}
}
const ctx = setCommandCenterCtx({
isInitialPanel: true,
open: false
});
$: if (!openSubPanel) {
$ctx.isInitialPanel = true;
}
$: $subPanels.length > 1 && ($ctx.isInitialPanel = false);
$: $ctx.open = !!openSubPanel;
let keys: string[] = [];
const resetKeys = debounce(() => {
keys = [];
}, 1000);
function isInputEvent(event: KeyboardEvent) {
return ['INPUT', 'TEXTAREA', 'SELECT'].includes((event.target as HTMLElement).tagName);
}
const handleKeydown = (e) => {
if (!$subPanels.length) {
if (isInputEvent(e)) return;
keys = [...keys, e.key].slice(-10);
resetKeys();
}
$commandCenterKeyDownHandler(e);
};
</script>
<svelte:window on:mousedown={handleBlur} on:keydown={handleKeydown} />
{#if openSubPanel}
<div class="dialog" bind:this={dialog} transition:fade|global={{ duration: 100 }}>
<svelte:component this={openSubPanel.component} />
</div>
{/if}
{#if dev && debugOverlayEnabled}
<div class="debug-keys" use:portal>
{#each keys as key, i (i)}
<kbd class="kbd" transition:fade={{ duration: 150 }}>
{key.length === 1 ? key.toUpperCase() : key}
</kbd>
{/each}
</div>
{/if}
<style lang="scss">
.dialog {
padding: 0.5rem;
position: fixed;
inset: 0;
background-color: hsl(var(--color-neutral-500) / 0.5);
z-index: 9999;
}
.debug-keys {
position: fixed;
bottom: 10%;
left: 50%;
transform: translateX(-50%);
padding: 0.5rem;
z-index: 9999;
display: flex;
gap: 1rem;
font-size: 2rem;
.kbd {
padding-inline: 0.5rem;
padding-block: 1.5rem;
}
}
</style>
+354
View File
@@ -0,0 +1,354 @@
import { debounce } from '$lib/helpers/debounce';
import { isMac } from '$lib/helpers/platform';
import { wizard } from '$lib/stores/wizard';
import { onMount } from 'svelte';
import { derived, writable } from 'svelte/store';
import { nanoid } from 'nanoid/non-secure';
import { trackEvent } from '$lib/actions/analytics';
const groups = [
'ungrouped',
'navigation',
'projects',
'organizations',
'auth',
'help',
'account',
'platforms',
'databases',
'functions',
'storage',
'domains',
'webhooks',
'integrations',
'migrations',
'users',
'collections',
'attributes',
'indexes',
'documents',
'teams',
'security',
'buckets',
'files',
'misc',
'settings'
] as const;
export type CommandGroup = (typeof groups)[number];
type BaseCommand = {
callback: () => void;
label?: string;
disabled?: boolean;
forceEnable?: boolean;
group?: CommandGroup;
icon?: string;
rank?: number;
nested?: boolean;
keepOpen?: boolean;
};
type KeyedCommand = BaseCommand & {
keys: string[];
/* Ctrl on Windows/Linux, Meta on Mac */
ctrl?: boolean;
shift?: boolean;
/* Alt on Windows/Linux, Option on Mac */
alt?: boolean;
};
export function isKeyedCommand(command: Command): command is KeyedCommand {
return 'keys' in command && Array.isArray((command as KeyedCommand).keys);
}
export type Command = KeyedCommand | BaseCommand;
export const commandMap = writable<Map<string, Command[]>>(new Map());
export const disabledMap = writable<Map<string, boolean>>(new Map());
// Derived stores
export const commands = derived(commandMap, ($commandMap) => {
return Array.from($commandMap.values()).flat();
});
const commandsEnabled = derived(disabledMap, ($disabledMap) => {
// If there's an item on the disabledMap that's true, then disable the command center
return Array.from($disabledMap.values()).every((disabled) => !disabled);
});
function isInputEvent(event: KeyboardEvent) {
return ['INPUT', 'TEXTAREA', 'SELECT'].includes((event.target as HTMLElement).tagName);
}
function getCommandRank(command: KeyedCommand) {
const { keys, ctrl: meta, shift, alt } = command;
const modifiers = [meta, shift, alt].filter(Boolean).length;
return (keys?.length || 0) + modifiers * 10;
}
function hasDisputing(command: KeyedCommand, allCommands: Command[]) {
return allCommands.some((otherCommand) => {
if (command === otherCommand) {
return false;
}
if (!isKeyedCommand(otherCommand)) {
return false;
}
const keysString = command.keys.join('+');
const otherKeysString = otherCommand?.keys?.join('+');
const cmdRank = getCommandRank(command);
const otherCmdRank = getCommandRank(otherCommand);
return (
(keysString.includes(otherKeysString) || otherKeysString.includes(keysString)) &&
cmdRank <= otherCmdRank
);
});
}
export const commandCenterKeyDownHandler = derived(
[commandMap, commandsEnabled, wizard],
([$commandMap, enabled, $wizard]) => {
const commandsArr = Array.from($commandMap.values()).flat();
let recentKeyCodes: number[] = [];
let validCommands: KeyedCommand[] = [];
const reset = debounce(() => {
recentKeyCodes = [];
validCommands = [];
}, 1000);
const getHighestPriorityCommand = () => {
if (!validCommands.length) return;
if (validCommands.length === 1) {
return validCommands[0];
}
// Rank commands by how many keys and modifiers they have.
// Each key is worth 1 point, each modifier is worth 10 points.
// The command with the highest score wins.
const rankedCommands = validCommands.map((command) => {
return { command, score: getCommandRank(command) };
});
const highestScore = Math.max(...rankedCommands.map(({ score }) => score));
const highestScoreCommands = rankedCommands.filter(
({ score }) => score === highestScore
);
if (highestScoreCommands.length === 1) {
return highestScoreCommands[0].command;
}
// If there's still a tie, the command with the most modifiers wins.
// And if even that's a tie, the first command wins.
const mostModifiers = Math.max(
...highestScoreCommands.map(({ command }) => {
const { ctrl: meta, shift, alt } = command;
return [meta, shift, alt].filter(Boolean).length;
})
);
const mostModifiersCommands = highestScoreCommands.filter(({ command }) => {
const { ctrl: meta, shift, alt } = command;
return [meta, shift, alt].filter(Boolean).length === mostModifiers;
});
return mostModifiersCommands[0]?.command;
};
const rankAndExecute = debounce(() => {
const command = getHighestPriorityCommand();
command?.callback();
reset.immediate();
}, 200);
const execute = (command: KeyedCommand) => {
if (hasDisputing(command, commandsArr)) {
validCommands.push(command);
rankAndExecute();
} else {
command.callback();
reset.immediate();
}
};
return (event: KeyboardEvent) => {
recentKeyCodes.push(event.keyCode);
reset();
for (const command of commandsArr) {
if (!isKeyedCommand(command)) continue;
if (!command.forceEnable) {
if (command.disabled || !enabled || isInputEvent(event) || $wizard.show) {
continue;
}
}
const { keys, ctrl: meta, shift, alt } = command;
const isMetaPressed = meta
? isMac()
? event.metaKey
: event.ctrlKey
: !(isMac() ? event.metaKey : event.ctrlKey);
const isShiftPressed = shift ? event.shiftKey : !event.shiftKey;
const isAltPressed = alt ? event.altKey : !event.altKey;
const commandKeyCodes = keys?.map((key) => key.toUpperCase().charCodeAt(0));
const allKeysPressed = commandKeyCodes
? recentKeyCodes.join(',').includes(commandKeyCodes.join(','))
: false;
if (allKeysPressed && isMetaPressed && isShiftPressed && isAltPressed) {
event.preventDefault();
execute(command);
}
}
};
}
);
// Methods
export const registerCommands = {
subscribe(runner: (cb: (newCommands: Command[]) => void) => void) {
const uuid = nanoid();
runner((newCommands: Command[]) => {
commandMap.update((curr) => {
const commandsWithTracking = newCommands.map((command) => {
const trackingCallback = () => {
if (command.label) {
trackEvent('command', { label: command.label, group: command.group });
}
command.callback();
};
return { ...command, callback: trackingCallback };
});
curr.set(uuid, commandsWithTracking);
return curr;
});
});
return () => {
commandMap.update((curr) => {
curr.delete(uuid);
return curr;
});
};
}
};
export const disableCommands = {
subscribe(runner: (cb: (disabled: boolean) => void) => void) {
const uuid = nanoid();
runner((disabled: boolean) => {
disabledMap.update((curr) => {
curr.set(uuid, disabled);
return curr;
});
});
return () => {
disabledMap.update((curr) => {
curr.delete(uuid);
return curr;
});
};
}
};
type CommandGroupRanks = Partial<Record<CommandGroup, number>>;
type GroupRanksMap = Map<string, CommandGroupRanks>;
const groupRanksMap = writable<GroupRanksMap>(new Map());
export const updateCommandGroupRanks = {
subscribe(runner: (cb: (updater: CommandGroupRanks) => void) => void) {
const uuid = nanoid();
runner((groupRank: CommandGroupRanks) => {
groupRanksMap.update((curr) => {
curr.set(uuid, groupRank);
return curr;
});
});
return () => {
groupRanksMap.update((curr) => {
curr.delete(uuid);
return curr;
});
};
}
};
export const commandGroupRanks = derived(groupRanksMap, ($groupRankTransformations) => {
const initialRanks = {
...Object.fromEntries(groups.map((group) => [group, 0])),
ungrouped: 9999,
databases: 50,
users: 40,
teams: 30,
projects: 20,
organizations: 10,
navigation: 0,
help: -20,
misc: -30
} as CommandGroupRanks;
const transformations = Array.from($groupRankTransformations.values());
return transformations.reduce((prev, curr) => ({ ...prev, ...curr }), initialRanks);
});
export type Searcher = (query: string) => Promise<Command[]>;
const searchersMap = writable<Map<string, Searcher[]>>(new Map());
export const registerSearchers = {
subscribe(runner: (cb: (...searchers: Searcher[]) => void) => void) {
const uuid = nanoid();
runner((...searchers: Searcher[]) => {
searchersMap.update((curr) => {
curr.set(uuid, [...searchers]);
return curr;
});
});
return () => {
searchersMap.update((curr) => {
curr.delete(uuid);
return curr;
});
};
}
};
export const searchers = derived(searchersMap, ($searchersMap) => {
return Array.from($searchersMap.values()).flat();
});
export const initSearcher = (searcher: Searcher) => {
const search = writable('');
const results = writable<Command[]>([]);
const searcherDebounced = debounce(async (query: string) => {
results.set(await searcher(query));
}, 500);
onMount(() => {
searcherDebounced.immediate('');
return search.subscribe((query) => {
searcherDebounced(query);
});
});
return {
search,
results
};
};
+4
View File
@@ -0,0 +1,4 @@
export * from './commands';
export * from './subPanels';
import CommandCenter from './commandCenter.svelte';
export { CommandCenter };
+318
View File
@@ -0,0 +1,318 @@
<script lang="ts">
import Template from './template.svelte';
import { Alert, AvatarInitials, Code, LoadingDots, SvgIcon } from '$lib/components';
import { user } from '$lib/stores/user';
import { useCompletion } from 'ai/svelte';
import { subPanels } from '../subPanels';
import { isLanguage, type Language } from '$lib/components/code.svelte';
import { preferences } from '$lib/stores/preferences';
import { VARS } from '$lib/system';
const endpoint = VARS.APPWRITE_ENDPOINT ?? `${globalThis?.location?.origin}/v1`;
const { input, handleSubmit, completion, isLoading, complete, error } = useCompletion({
api: endpoint + '/console/assistant',
headers: {
'content-type': 'application/json',
'x-appwrite-project': 'console'
},
credentials: 'include'
});
let question = $input;
const examples = [
'How to add platform in the console?',
'How can I manage users, permissions, and access control in Appwrite?',
'How can I set up database collections and documents in Appwrite?',
'How do I configure and manage server-side functions in Appwrite?',
'How to add custom domain in the console?'
];
type Answer = Array<
| {
type: 'code';
language: Language;
value: string;
}
| {
type: 'text';
value: string;
}
>;
function parseCompletion(c: string): Answer | null {
if (!c) return null;
const answer: Answer = [];
// get all code matches
const codeMatches = Array.from(c.matchAll(/```([a-z]*)(.*?)(```|$)/gs));
let i = 0;
let codeIdx = 0;
while (i < c.length) {
const nextCodeMatch = codeMatches[codeIdx] ?? null;
if (!nextCodeMatch) {
answer.push({
type: 'text',
value: c.slice(i)
});
break;
} else if (i >= nextCodeMatch.index) {
let language = nextCodeMatch[1];
if (language === 'javascript') language = 'js';
answer.push({
type: 'code',
value: nextCodeMatch[2].startsWith('\n')
? nextCodeMatch[2].slice(1)
: nextCodeMatch[2],
language: isLanguage(language) ? language : 'js'
});
i = nextCodeMatch.index + nextCodeMatch[0].length;
codeIdx++;
} else {
answer.push({
type: 'text',
value: c.slice(i, nextCodeMatch.index)
});
i = nextCodeMatch.index;
}
}
return answer;
}
$: answer = parseCompletion($completion);
function getInitials(name: string) {
const [first, last] = name.split(' ');
return `${first?.[0] ?? ''}${last?.[0] ?? ''}`;
}
</script>
<Template
options={$isLoading || answer
? undefined
: examples.map((e) => {
return {
label: e,
callback: () => {
$input = e;
complete($input);
},
group: 'Examples'
};
})}
clearOnCallback={false}
on:keydown={(e) => {
if (e.detail.key !== 'Escape') {
e.detail.cancel();
}
}}
--min-height="40rem"
--max-height="52.5rem">
<div slot="search">
<span class="experimental border-gradient">EXPERIMENTAL</span>
</div>
<div slot="option" let:option class="u-flex u-cross-center u-gap-8">
<i class="icon-question-mark-circle" />
<span>{option.label}</span>
</div>
{#if !$preferences.hideAiDisclaimer}
<div style="padding: 1rem; padding-block-end: 0;">
<Alert
type="default"
dismissible
on:dismiss={() => {
$preferences.hideAiDisclaimer = true;
}}>
<span slot="title">
We collect user responses to refine our experimental AI feature.
</span>
</Alert>
</div>
{/if}
{#if $isLoading || answer}
<div class="content">
<div class="u-flex u-gap-8 u-cross-center">
<div class="avatar is-size-x-small">{getInitials($user.name)}</div>
<p class="u-opacity-75">{question}</p>
</div>
<div class="u-flex u-gap-8 u-margin-block-start-24">
<div class="logo">
<SvgIcon name="sparkles" type="color" />
</div>
<div class="answer">
{#if $isLoading && !$completion}
<LoadingDots />
{:else}
{#each answer as part}
{#if part.type === 'text'}
<p>{part.value.trimStart()}</p>
{:else if part.type === 'code'}
{#key part.value}
<div
class="u-margin-block-start-8"
style="margin-block-end: 1rem;">
<Code
label={part.language}
language={part.language}
code={part.value}
noMargin
noBoxPadding
withCopy />
</div>
{/key}
{/if}
{/each}
{/if}
</div>
</div>
</div>
{/if}
{#if $error}
<div style="padding: 1rem; padding-block-end: 0;">
<Alert type="error">
<span slot="title">Something went wrong</span>
<p>
An unexpected error occurred while handling your request. Please try again
later.
</p>
</Alert>
</div>
{/if}
<div class="footer" slot="footer">
<div class="u-flex u-cross-center u-gap-4">
<AvatarInitials size={32} name={$user.name} />
<form
class="input-text-wrapper u-width-full-line"
style="--amount-of-buttons: 1;"
on:submit|preventDefault={(e) => {
question = $input;
handleSubmit(e);
}}>
<!-- svelte-ignore a11y-autofocus -->
<input
type="text"
class="input-text"
placeholder="Ask a question..."
autofocus
bind:value={$input}
disabled={$isLoading} />
<div class="options-list">
<button
class="options-list-button"
aria-label="ask AI"
type="submit"
disabled={!$input.trim() || $isLoading}>
<span class="icon-arrow-sm-right" aria-hidden="true" />
</button>
</div>
</form>
</div>
<div class="u-flex u-main-end u-cross-center u-gap-16 u-margin-block-start-16">
<div class="u-flex u-cross-center u-gap-4">
<kbd class="kbd">Enter</kbd>
<span>to search</span>
</div>
<div class="sep" />
<div class="u-flex u-cross-center u-gap-4">
<kbd class="kbd">Esc</kbd>
<span>to {$subPanels.length === 1 ? 'close' : 'go back'}</span>
</div>
</div>
</div>
</Template>
<style lang="scss">
:global(.theme-dark) .content {
--logo-bg: #282a3b;
}
:global(.theme-light) .content {
--logo-bg: #f2f2f8;
}
:global(.theme-dark) .footer {
--sep-clr: hsl(var(--color-neutral-150));
}
:global(.theme-light) .footer {
--sep-clr: hsl(var(--color-neutral-30));
}
.content {
overflow: auto;
padding: 1rem;
.logo {
display: flex;
width: 1.5rem;
height: 1.5rem;
justify-content: center;
align-items: center;
flex-shrink: 0;
border-radius: 0.25rem;
background: var(--logo-bg);
}
.answer {
overflow: hidden;
p {
white-space: pre-wrap;
}
}
}
.footer {
.sep {
width: 1px;
height: 1.5rem;
background-color: var(--sep-clr);
}
}
.experimental {
display: flex;
padding: 0.09375rem 0.25rem;
align-items: center;
color: var(--light-neutrals-30, #e8e9f0);
text-align: center;
font-family: Inter;
font-size: 0.625rem;
font-style: normal;
font-weight: 500;
line-height: 150%; /* 0.9375rem */
letter-spacing: 0.075rem;
text-transform: uppercase;
background: rgba(240, 46, 101, 0.24);
--border-gradient: linear-gradient(
to bottom,
rgba(240, 46, 101, 0.48) 0%,
rgba(240, 46, 101, 0) 150%
)
border-box;
--border-size: 0.03rem;
--border-radius: 0.25rem;
border-radius: var(--border-radius);
}
:global(.theme-light) .experimental {
color: rgba(240, 46, 101, 1);
}
</style>
@@ -0,0 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { bucketSearcher } from '../searchers';
import Template from './template.svelte';
const { search, results } = initSearcher(bucketSearcher);
</script>
<Template options={$results} bind:search={$search} />
@@ -0,0 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { collectionsSearcher } from '../searchers';
import Template from './template.svelte';
const { search, results } = initSearcher(collectionsSearcher);
</script>
<Template options={$results} bind:search={$search} />
@@ -0,0 +1,28 @@
<script lang="ts">
import { initCreateAttribute } from '$routes/console/project-[project]/databases/database-[database]/collection-[collection]/+layout.svelte';
import { attributeOptions } from '$routes/console/project-[project]/databases/database-[database]/collection-[collection]/attributes/store';
import Template from './template.svelte';
let search = '';
let options = attributeOptions.map((option) => {
return {
label: option.name,
icon: option.icon,
callback() {
initCreateAttribute(option.name);
}
};
});
$: filteredOptions = options.filter((option) => {
return option.label.toLowerCase().includes(search.toLowerCase());
});
</script>
<Template options={filteredOptions} bind:search>
<div class="u-flex u-cross-center u-gap-8" slot="option" let:option>
<i class="icon-{option.icon}" />
<span>{option.label}</span>
</div>
</Template>
@@ -0,0 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { dbSearcher } from '../searchers';
import Template from './template.svelte';
const { search, results } = initSearcher(dbSearcher);
</script>
<Template options={$results} bind:search={$search} />
@@ -0,0 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { fileSearcher } from '../searchers';
import Template from './template.svelte';
const { search, results } = initSearcher(fileSearcher);
</script>
<Template options={$results} bind:search={$search} />
@@ -0,0 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { functionsSearcher } from '../searchers';
import Template from './template.svelte';
const { search, results } = initSearcher(functionsSearcher);
</script>
<Template options={$results} bind:search={$search} />
+80
View File
@@ -0,0 +1,80 @@
import type { SubPanel } from '../subPanels';
export { default as Template } from './template.svelte';
import Root from './root.svelte';
export const RootPanel: SubPanel = {
name: 'root',
component: Root
};
import AI from './ai.svelte';
export const AIPanel: SubPanel = {
name: 'Ask the AI',
component: AI
};
import Projects from './projects.svelte';
export const ProjectsPanel: SubPanel = {
name: 'Projects',
component: Projects
};
import Organizations from './organizations.svelte';
export const OrganizationsPanel: SubPanel = {
name: 'Organizations',
component: Organizations
};
import Platforms from './platforms.svelte';
export const PlatformsPanel: SubPanel = {
name: 'Platforms',
component: Platforms
};
import Databases from './databases.svelte';
export const DatabasesPanel: SubPanel = {
name: 'Databases',
component: Databases
};
import Collections from './collections.svelte';
export const CollectionsPanel: SubPanel = {
name: 'Collections',
component: Collections
};
import CreateAttribute from './createAttribute.svelte';
export const CreateAttributePanel: SubPanel = {
name: 'Create Attribute',
component: CreateAttribute
};
import Users from './users.svelte';
export const UsersPanel: SubPanel = {
name: 'Users',
component: Users
};
import Teams from './teams.svelte';
export const TeamsPanel: SubPanel = {
name: 'Teams',
component: Teams
};
import Functions from './functions.svelte';
export const FunctionsPanel: SubPanel = {
name: 'Functions',
component: Functions
};
import Buckets from './buckets.svelte';
export const BucketsPanel: SubPanel = {
name: 'Buckets',
component: Buckets
};
import Files from './files.svelte';
export const FilesPanel: SubPanel = {
name: 'Files',
component: Files
};
@@ -0,0 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { orgSearcher } from '../searchers';
import Template from './template.svelte';
const { results, search } = initSearcher(orgSearcher);
</script>
<Template options={$results} bind:search={$search} />
@@ -0,0 +1,55 @@
<script lang="ts">
import {
Platform,
addPlatform
} from '$routes/console/project-[project]/overview/platforms/+page.svelte';
import Template from './template.svelte';
let search = '';
let platforms = [
{
label: 'Web',
icon: 'code',
group: 'platforms',
callback: () => {
addPlatform(Platform.Web);
}
},
{
label: 'Flutter',
icon: 'flutter',
group: 'platforms',
callback: () => {
addPlatform(Platform.Flutter);
}
},
{
label: 'Android',
icon: 'android',
group: 'platforms',
callback: () => {
addPlatform(Platform.Android);
}
},
{
label: 'Apple',
icon: 'apple',
group: 'platforms',
callback: () => {
addPlatform(Platform.Apple);
}
}
] as const;
$: filteredPlatforms = platforms.filter((platform) => {
return platform.label.toLowerCase().includes(search.toLowerCase());
});
</script>
<Template options={filteredPlatforms} bind:search>
<div class="u-flex u-cross-center u-gap-8" slot="option" let:option>
<i class="icon-{option.icon}" />
<span>{option.label}</span>
</div>
</Template>
@@ -0,0 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { projectsSearcher } from '../searchers';
import Template from './template.svelte';
const { search, results } = initSearcher(projectsSearcher);
</script>
<Template options={$results} bind:search={$search} />
+87
View File
@@ -0,0 +1,87 @@
<!--
This is the root command panel. It precedes all other command panels.
-->
<script lang="ts">
import { debounce } from '$lib/helpers/debounce';
import { isMac } from '$lib/helpers/platform';
import { commands, searchers, type Command, isKeyedCommand } from '../commands';
import Template from './template.svelte';
let search = '';
let searchResults: Omit<Command, 'keys'>[] = [];
const executeSearch = debounce(async (s: string) => {
$searchers.forEach(async (searcher) => {
const results = await searcher(s);
searchResults = [...searchResults, ...results];
});
}, 500);
$: {
if (search) {
searchResults = [];
executeSearch(search);
} else {
searchResults = [];
executeSearch.cancel();
}
}
$: results = [
...$commands.filter((command) => {
return (
!command.disabled &&
command.label &&
command.label.toLowerCase().includes(search.toLowerCase())
);
}),
...searchResults
] as Array<Command | Omit<Command, 'keys'>>;
const hasCtrl = (command: Command) => {
return 'ctrl' in command && command.ctrl;
};
const hasShift = (command: Command) => {
return 'shift' in command && command.shift;
};
const hasAlt = (command: Command) => {
return 'alt' in command && command.alt;
};
</script>
<Template options={results} bind:search searchPlaceholder="Search for commands or content...">
<div slot="option" class="u-flex u-main-space-between content" let:option={command}>
<div class="u-flex u-gap-8 u-cross-center">
<i class="icon-{command.icon ?? 'arrow-sm-right'}" />
<span>
{command.label}
</span>
</div>
<div class="u-flex u-gap-4 u-cross-center">
{#if hasCtrl(command)}
<kbd class="kbd"> {isMac() ? '⌘' : 'Ctrl'} </kbd>
{/if}
{#if hasShift(command)}
<kbd class="kbd"> {isMac() ? '⇧' : 'Shift'} </kbd>
{/if}
{#if hasAlt(command)}
<kbd class="kbd"> {isMac() ? '⌥' : 'Alt'} </kbd>
{/if}
{#if isKeyedCommand(command)}
{#each command.keys as key, i}
{@const hasNext = command.keys.length - 1 !== i}
<kbd class="kbd">
{key.toUpperCase()}
</kbd>
{#if hasNext}
<span class="u-margin-inline-4" style:opacity={0.5}>then</span>
{/if}
{/each}
{/if}
</div>
</div>
<svelte:fragment slot="no-options">No commands found</svelte:fragment>
</Template>
@@ -0,0 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { teamSearcher } from '../searchers';
import Template from './template.svelte';
const { search, results } = initSearcher(teamSearcher);
</script>
<Template options={$results} bind:search={$search} />
@@ -0,0 +1,577 @@
<script lang="ts">
import { commandGroupRanks, type Command, type CommandGroup } from '../commands';
// This is the template for all panels used in the command center.
// Use this component when you want to create a new panel.
import { createEventDispatcher, tick } from 'svelte';
import { getCommandCenterCtx } from '../commandCenter.svelte';
import { clearSubPanels, popSubPanel, subPanels } from '../subPanels';
/* eslint no-undef: "off" */
type Option = $$Generic<Omit<Command, 'group'> & { group?: string }>;
export let options: Option[] | null = null;
export let search = '';
export let searchPlaceholder = 'Search...';
export let fullheight = false;
export let clearOnCallback = true;
let selected = 0;
let usingKeyboard = false;
let contentEl: HTMLElement;
async function triggerOption(option: Option) {
const prevPanels = $subPanels.length;
option.callback();
if (prevPanels === $subPanels.length && clearOnCallback && !option.keepOpen) {
clearSubPanels();
}
}
const dispatch = createEventDispatcher<{
keydown: {
originalEvent: KeyboardEvent;
cancel: () => void;
key: string;
};
}>();
function handleKeyDown(event: KeyboardEvent) {
if (!open) return;
usingKeyboard = true;
let canceled = false;
dispatch('keydown', {
originalEvent: event,
cancel: () => (canceled = true),
key: event.key
});
if (canceled) return;
if (options) {
if (event.key === 'ArrowDown') {
event.preventDefault();
if (event.metaKey) {
selected = options.length - 1;
} else {
selected = selected === options.length - 1 ? options.length - 1 : selected + 1;
}
} else if (event.key === 'ArrowUp') {
event.preventDefault();
if (event.metaKey) {
selected = 0;
} else {
selected = selected === 0 ? 0 : selected - 1;
}
} else if (event.key === 'Enter') {
const option = groupsAndOptions.find(
(item) => 'index' in item && item.index === selected
) as IndexedOption;
if (!option) return;
event.preventDefault();
triggerOption(option);
} else if (event.key === 'Home') {
event.preventDefault();
selected = 0;
} else if (event.key === 'End') {
event.preventDefault();
selected = options.length - 1;
}
tick().then(() => {
if (!cardEl) return;
const selectedEl = contentEl.querySelector('[data-selected]');
if (selectedEl) {
selectedEl.scrollIntoView({
block: 'nearest'
});
}
});
}
if (event.key === 'Escape') {
event.preventDefault();
popSubPanel();
}
}
$: if (selected > options?.length - 1) {
selected = options?.length - 1;
} else if (usingKeyboard && selected < 0 && options?.length) {
selected = 0;
}
const commandCenterCtx = getCommandCenterCtx();
let cardEl: HTMLElement;
type Group = { type: 'group'; name: string };
type IndexedOption = Option & { index: number };
function isGroup(item: Option | Group): item is Group {
return !!item && 'type' in item && item.type === 'group';
}
const getGroupsAndOptions = (options: Option[]) => {
if (!options) return null;
const groupedOptions = new Map<string, Option[]>();
groupedOptions.set('ungrouped', []);
for (const option of options) {
if (!option.group) {
groupedOptions.set('ungrouped', [...groupedOptions.get('ungrouped'), option]);
} else {
groupedOptions.set(option.group, [
...(groupedOptions.get(option.group) || []),
option
]);
}
}
// Organize groups
const sortedOptions = [...groupedOptions.entries()]
.sort(([a], [b]) => {
const aRank = $commandGroupRanks[a] || 0;
const bRank = $commandGroupRanks[b] || 0;
if (aRank < bRank) {
return 1;
} else if (aRank > bRank) {
return -1;
} else {
return 0;
}
})
.map(([groupName, options]) => {
return [
groupName,
options.sort((a, b) => {
const aRank = a.rank || 0;
const bRank = b.rank || 0;
if (aRank < bRank) {
return 1;
} else if (aRank > bRank) {
return -1;
} else {
return 0;
}
})
] as [CommandGroup, Option[]];
});
// return a flat array of groups and indexed options
let optionIndex = 0;
const groupsAndOptions: (Group | IndexedOption)[] = [];
for (const [groupName, options] of sortedOptions) {
if (groupName !== 'ungrouped') {
groupsAndOptions.push({ type: 'group', name: groupName });
}
for (const option of options) {
groupsAndOptions.push({ ...option, index: optionIndex++ });
}
}
return groupsAndOptions;
};
$: groupsAndOptions = getGroupsAndOptions(options);
const getOptionClickHandler = (option: IndexedOption) => () => {
triggerOption(option);
};
const getOptionFocusHandler =
(option: IndexedOption, hover = false) =>
() => {
selected = option.index;
usingKeyboard = hover ? false : usingKeyboard;
};
const getOptionBlurHandler = () => () => {
selected = -1;
usingKeyboard = false;
};
const castOption = (option: IndexedOption) => option as Option;
function getBreadcrumbs(subPanels: typeof $subPanels) {
return subPanels.filter((panel) => panel.name !== 'root').map((panel) => panel.name);
}
let breadcrumbs = getBreadcrumbs($subPanels);
// Avoid clearing subpanels before the closing transition is finished
$: if ($subPanels.length) {
breadcrumbs = getBreadcrumbs($subPanels);
}
const handleCrumbClick = (index: number) => {
if (index === breadcrumbs.length - 1) {
popSubPanel();
} else {
const numCrumbsToPop = breadcrumbs.length - index - 1;
for (let i = 0; i < numCrumbsToPop; i++) {
popSubPanel();
}
}
};
const isFirstNested = (index: number) => {
const prevItem = groupsAndOptions[index - 1];
const item = groupsAndOptions[index];
if (isGroup(item)) return false;
if (!item.nested) return false;
return !isGroup(prevItem) && !prevItem?.nested;
};
const isLastNested = (index: number) => {
const nextItem = groupsAndOptions[index + 1];
const item = groupsAndOptions[index];
if (isGroup(item)) return false;
if (!item.nested) return false;
return isGroup(nextItem) || !nextItem?.nested;
};
</script>
<svelte:window on:keydown={handleKeyDown} />
<div
class="card"
class:fullheight
bind:this={cardEl}
class:press={!$commandCenterCtx.isInitialPanel}
class:scale-up={$commandCenterCtx.isInitialPanel && $commandCenterCtx.open}>
<div class="search-wrapper">
{#each breadcrumbs as crumb, i}
{@const isLast = i === breadcrumbs.length - 1}
<button class="crumb" on:click={() => handleCrumbClick(i)}>
<span>{crumb}</span>
<i class="icon-x" />
</button>
{#if !isLast}
<span style="opacity: 50%">/</span>
{/if}
{/each}
<slot name="search">
<div class="u-flex default-search u-width-full-line">
<!-- svelte-ignore a11y-autofocus -->
<input type="text" placeholder={searchPlaceholder} autofocus bind:value={search} />
</div>
</slot>
</div>
<div class="content" bind:this={contentEl}>
<slot />
{#if groupsAndOptions}
<ul class="options">
{#each groupsAndOptions as item, i}
{@const isSelected = !isGroup(item) && item.index === selected}
{#if isGroup(item)}
<li class="group eyebrow-heading-3">
{item.name}
</li>
{:else}
<li
class="result"
data-selected={isSelected ? true : undefined}
class:nested={item.nested}
class:first-nested={isFirstNested(i)}
class:last-nested={isLastNested(i)}>
{#if isSelected}
<div class="bg" />
{/if}
<button
class="option"
on:click={getOptionClickHandler(item)}
on:mouseover={getOptionFocusHandler(item, true)}
on:mouseleave={getOptionBlurHandler()}
on:focus={getOptionFocusHandler(item)}>
<slot name="option" option={castOption(item)}>
<div class="u-flex u-gap-8 u-cross-center">
<i class="icon-{item.icon ?? 'arrow-sm-right'}" />
<span>
{item.label}
</span>
</div>
</slot>
</button>
</li>
{/if}
{:else}
<li class="result">
<slot name="no-options">
<span class="text">No options found</span>
</slot>
</li>
{/each}
</ul>
{/if}
</div>
<div class="footer">
<slot name="footer">
<div class=" u-flex u-flex u-cross-center u-main-space-between">
<div class="u-flex u-cross-center u-gap-4">
<kbd class="kbd">Enter</kbd> <span>to select</span>
</div>
<div class="u-flex u-cross-center u-gap-4">
<kbd class="kbd">Esc</kbd>
<span>to {$subPanels.length > 1 ? 'go back' : 'close'}</span>
</div>
</div>
</slot>
</div>
</div>
<style lang="scss">
// Animations
@keyframes press {
0% {
scale: 1;
}
30% {
scale: 0.985;
}
100% {
scale: 1;
}
}
.press {
animation: press 250ms ease;
}
@keyframes scale-up {
0% {
scale: 0.95;
}
100% {
scale: 1;
}
}
.scale-up {
animation: scale-up 150ms cubic-bezier(0.5, 1, 0.89, 1);
}
// Theme
:global(.theme-light) .card {
--cmd-center-bg: hsl(var(--color-neutral-0));
--cmd-center-border: hsl(var(--color-neutral-10));
--cmd-center-shadow: 0px 16px 32px 0px rgba(55, 59, 77, 0.04);
--kbd-bg: hsl(var(--color-neutral-15));
--kbd-color: hsl(var(--color-neutral-60));
--crumb-bg: hsl(var(--color-neutral-10));
--crumb-color: hsl(var(--color-neutral-100));
--result-bg: hsl(var(--color-neutral-10));
--footer-bg: linear-gradient(180deg, #fff 0%, #e8e9f0 100%);
--icon-color: hsl(var(--color-neutral-50));
--label-color: hsl(var(--color-neutral-60));
}
:global(.theme-dark) .card {
--cmd-center-bg: hsl(var(--color-neutral-90));
--cmd-center-border: hsl(var(--color-neutral-80));
--cmd-center-shadow: 0px 16px 32px 0px #14141f;
--kbd-bg: hsl(var(--color-neutral-80));
--kbd-color: hsl(var(--color-neutral-15));
--crumb-bg: hsl(var(--color-neutral-150));
--crumb-color: hsl(var(--color-neutral-30));
--result-bg: hsl(var(--color-neutral-85));
--footer-bg: linear-gradient(
180deg,
hsl(var(--color-neutral-100)) 0%,
hsl(var(--color-neutral-85)) 100%
);
--icon-color: hsl(var(--color-neutral-70));
--label-color: hsl(var(--color-neutral-15));
}
// Elements
.card {
position: absolute;
--top: clamp(64px, 10vh, 400px);
top: var(--top);
left: 50%;
translate: -50%;
display: flex;
flex-direction: column;
width: var(--width, 42.5rem);
max-width: 100%;
min-height: var(--min-height);
max-height: min(calc(100vh - var(--top) - 4rem), var(--max-height, 32rem));
overflow: hidden;
padding: 0;
border-radius: 0.5rem;
border: 1px solid var(--cmd-center-border);
background: var(--cmd-center-bg);
box-shadow: var(--cmd-center-shadow);
backdrop-filter: blur(6px);
&.fullheight {
height: var(--max-height, 32rem);
}
:global(.kbd) {
color: var(--kbd-color);
background-color: var(--kbd-bg);
padding-inline: 0.25rem;
}
}
.search-wrapper {
display: flex;
gap: 0.25rem;
align-items: center;
width: 100%;
border-bottom: 1px solid hsl(var(--color-border));
font-size: 16px;
padding: 1rem;
.default-search {
input {
margin: -1rem;
padding: 1rem;
border: none;
background-color: transparent;
}
}
}
.crumb {
display: flex;
padding: 0.09375rem 0.25rem;
align-items: center;
gap: 0.25rem;
border-radius: 0.25rem;
background: var(--crumb-bg);
color: var(--crumb-color);
text-align: center;
font-family: Inter;
font-size: 0.75rem;
font-style: normal;
font-weight: 400;
line-height: normal;
white-space: nowrap;
&:hover {
opacity: 0.75;
}
i {
font-size: 10px;
}
}
.content {
overflow-y: auto;
flex-grow: 1;
.options {
padding: 1rem;
.group {
color: hsl(var(--color-neutral-70));
margin-inline-start: 0.25rem;
margin-block-end: 0.25rem;
position: relative;
z-index: 10;
font-size: 10px !important;
&:not(:first-child) {
margin-block-start: 1rem;
}
}
.result {
position: relative;
scroll-margin-block: 0.5rem;
.bg {
position: absolute;
inset: 0;
background-color: var(--result-bg);
border-radius: 0.5rem;
translate: 0 -1px;
}
.option {
padding: 0.5rem 9.5px;
font-size: 14px;
position: relative;
z-index: 10;
width: 100%;
box-shadow: none !important;
color: var(--label-color);
:global(i[class^='icon-']) {
font-size: 1rem !important;
width: 1rem !important;
height: 1rem !important;
color: var(--icon-color);
position: relative;
}
:global(i[class^='icon-']::before) {
position: absolute;
top: 50%;
left: 50%;
translate: -50% -50%;
}
}
&.nested {
margin-left: 30px;
&.first-nested::before {
top: 8px;
}
&.last-nested::before {
height: calc(100% - 8px);
}
&::before {
content: '';
position: absolute;
left: -8px;
border-left: 1px solid hsl(var(--color-border));
height: 100%;
}
}
}
}
}
.footer {
background: var(--footer-bg);
border-top: 1px solid hsl(var(--color-border));
padding: 0.5rem 1rem;
}
</style>
@@ -0,0 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { userSearcher } from '../searchers';
import Template from './template.svelte';
const { search, results } = initSearcher(userSearcher);
</script>
<Template options={$results} bind:search={$search} />
@@ -0,0 +1,81 @@
import { goto } from '$app/navigation';
import { sdk } from '$lib/stores/sdk';
import { project } from '$routes/console/project-[project]/store';
import { Query, type Models } from '@appwrite.io/console';
import { get } from 'svelte/store';
import type { Command, Searcher } from '../commands';
import { addSubPanel } from '../subPanels';
import { FilesPanel } from '../panels';
const getBucketCommand = (bucket: Models.Bucket, projectId: string) => {
return {
label: `${bucket.name}`,
callback() {
goto(`/console/project-${projectId}/storage/bucket-${bucket.$id}`);
},
group: 'buckets',
icon: 'folder'
} satisfies Command;
};
export const bucketSearcher = (async (query: string) => {
const { buckets } = await sdk.forProject.storage.listBuckets([Query.orderDesc('$createdAt')]);
const $project = get(project);
const filtered = buckets.filter((bucket) => bucket.name.includes(query));
if (filtered.length === 1) {
const bucket = filtered[0];
return [
getBucketCommand(bucket, $project.$id),
{
label: 'Find files',
async callback() {
await goto(`/console/project-${$project.$id}/storage/bucket-${bucket.$id}`);
addSubPanel(FilesPanel);
},
group: 'buckets',
nested: true,
icon: 'search',
keepOpen: true
},
{
label: 'Permissions',
async callback() {
await goto(
`/console/project-${$project.$id}/storage/bucket-${bucket.$id}/settings#permissions`
);
scrollBy({ top: -100 });
},
group: 'buckets',
nested: true,
icon: 'key'
},
{
label: 'Extensions',
async callback() {
await goto(
`/console/project-${$project.$id}/storage/bucket-${bucket.$id}/settings#extensions`
);
},
group: 'buckets',
nested: true,
icon: 'puzzle'
},
{
label: 'File Security',
async callback() {
await goto(
`/console/project-${$project.$id}/storage/bucket-${bucket.$id}/settings#file-security`
);
scrollBy({ top: -100 });
},
group: 'buckets',
nested: true,
icon: 'lock-closed'
}
];
}
return filtered.map((bucket) => getBucketCommand(bucket, $project.$id));
}) satisfies Searcher;
@@ -0,0 +1,27 @@
import { goto } from '$app/navigation';
import { database } from '$routes/console/project-[project]/databases/database-[database]/store';
import { project } from '$routes/console/project-[project]/store';
import { get } from 'svelte/store';
import type { Searcher } from '../commands';
import { sdk } from '$lib/stores/sdk';
export const collectionsSearcher = (async (query: string) => {
const databaseId = get(database).$id;
const { collections } = await sdk.forProject.databases.listCollections(databaseId);
const projectId = get(project).$id;
return collections
.filter((col) => col.name.toLowerCase().includes(query.toLowerCase()))
.map(
(col) =>
({
group: 'collections',
label: col.name,
callback: () => {
goto(
`/console/project-${projectId}/databases/database-${databaseId}/collection-${col.$id}`
);
}
}) as const
);
}) satisfies Searcher;
@@ -0,0 +1,23 @@
import { goto } from '$app/navigation';
import { project } from '$routes/console/project-[project]/store';
import { get } from 'svelte/store';
import type { Searcher } from '../commands';
import { sdk } from '$lib/stores/sdk';
export const dbSearcher = (async (query: string) => {
const { databases } = await sdk.forProject.databases.list();
return databases
.filter((db) => db.name.toLowerCase().includes(query.toLowerCase()))
.map(
(db) =>
({
group: 'databases',
label: db.name,
callback: () => {
goto(`/console/project-${get(project).$id}/databases/database-${db.$id}`);
},
icon: 'database'
}) as const
);
}) satisfies Searcher;
+27
View File
@@ -0,0 +1,27 @@
import { sdk } from '$lib/stores/sdk';
import { get } from 'svelte/store';
import type { Searcher } from '../commands';
import { bucket } from '$routes/console/project-[project]/storage/bucket-[bucket]/store';
import { Query } from '@appwrite.io/console';
import { goto } from '$app/navigation';
import { project } from '$routes/console/project-[project]/store';
export const fileSearcher = (async (query: string) => {
const $bucket = get(bucket);
const $project = get(project);
const { files } = await sdk.forProject.storage.listFiles(
$bucket.$id,
[Query.orderDesc('')],
query || undefined
);
return files.map((file) => ({
label: file.name,
callback: () => {
goto(`/console/project-${$project.$id}/storage/bucket-${$bucket.$id}/file-${file.$id}`);
},
icon: 'document',
group: 'files'
}));
}) satisfies Searcher;
@@ -0,0 +1,81 @@
import { goto } from '$app/navigation';
import { sdk } from '$lib/stores/sdk';
import { project } from '$routes/console/project-[project]/store';
import { get } from 'svelte/store';
import type { Searcher } from '../commands';
import type { Models } from '@appwrite.io/console';
import { page } from '$app/stores';
import { showCreateDeployment } from '$routes/console/project-[project]/functions/function-[function]/store';
const getFunctionCommand = (fn: Models.Function, projectId: string) => {
return {
label: fn.name,
callback: () => {
goto(`/console/project-${projectId}/functions/function-${fn.$id}`);
},
group: 'functions',
icon: 'lightning-bolt'
} as const;
};
export const functionsSearcher = (async (query: string) => {
const { functions } = await sdk.forProject.functions.list();
const projectId = get(project).$id;
const filtered = functions.filter((fn) => fn.name.toLowerCase().includes(query.toLowerCase()));
if (filtered.length === 1) {
const func = filtered[0];
return [
getFunctionCommand(func, projectId),
{
label: 'Create deployment',
nested: true,
async callback() {
const $page = get(page);
if (!$page.url.pathname.endsWith(func.$id)) {
await goto(`/console/project-${projectId}/functions/function-${func.$id}`);
}
showCreateDeployment.set(true);
},
group: 'functions',
icon: 'plus'
},
{
label: 'Go to deployments',
nested: true,
callback() {
goto(`/console/project-${projectId}/functions/function-${func.$id}`);
},
group: 'functions'
},
{
label: 'Go to usage',
nested: true,
callback() {
goto(`/console/project-${projectId}/functions/function-${func.$id}/usage`);
},
group: 'functions'
},
{
label: 'Go to executions',
nested: true,
callback() {
goto(`/console/project-${projectId}/functions/function-${func.$id}/executions`);
},
group: 'functions'
},
{
label: 'Go to settings',
nested: true,
callback() {
goto(`/console/project-${projectId}/functions/function-${func.$id}/settings`);
},
group: 'functions'
}
];
}
return filtered.map((fn) => getFunctionCommand(fn, projectId));
}) satisfies Searcher;
+9
View File
@@ -0,0 +1,9 @@
export * from './databases';
export * from './users';
export * from './organizations';
export * from './collections';
export * from './projects';
export * from './teams';
export * from './functions';
export * from './buckets';
export * from './files';
@@ -0,0 +1,18 @@
import { goto } from '$app/navigation';
import { sdk } from '$lib/stores/sdk';
import type { Searcher } from '../commands';
export const orgSearcher = (async (query: string) => {
const { teams } = await sdk.forConsole.teams.list();
return teams
.filter((organization) => organization.name.toLowerCase().includes(query.toLowerCase()))
.map((organization) => {
return {
label: organization.name,
callback: () => {
goto(`/console/organization-${organization.$id}`);
},
group: 'organizations'
} as const;
});
}) satisfies Searcher;
@@ -0,0 +1,25 @@
import { goto } from '$app/navigation';
import { organization } from '$lib/stores/organization';
import { sdk } from '$lib/stores/sdk';
import { Query } from '@appwrite.io/console';
import { get } from 'svelte/store';
import type { Searcher } from '../commands';
export const projectsSearcher = (async (query: string) => {
const { projects } = await sdk.forConsole.projects.list([
Query.equal('teamId', get(organization).$id),
Query.orderDesc('')
]);
return projects
.filter((project) => project.name.toLowerCase().includes(query.toLowerCase()))
.map((project) => {
return {
label: project.name,
callback: () => {
goto(`/console/project-${project.$id}`);
},
group: 'projects'
} as const;
});
}) satisfies Searcher;
+45
View File
@@ -0,0 +1,45 @@
import { goto } from '$app/navigation';
import { sdk } from '$lib/stores/sdk';
import { project } from '$routes/console/project-[project]/store';
import { get } from 'svelte/store';
import type { Command, Searcher } from '../commands';
import type { Models } from '@appwrite.io/console';
const getTeamCommand = (team: Models.Team<Models.Preferences>, projectId: string) =>
({
label: team.name,
callback: () => {
goto(`/console/project-${projectId}/auth/teams/team-${team.$id}`);
},
group: 'teams',
icon: 'user-circle'
}) satisfies Command;
export const teamSearcher = (async (query: string) => {
const { teams } = await sdk.forProject.teams.list([], query);
const projectId = get(project).$id;
if (teams.length === 1) {
return [
getTeamCommand(teams[0], projectId),
{
label: 'Go to members',
callback: () => {
goto(`/console/project-${projectId}/auth/teams/team-${teams[0].$id}/members`);
},
group: 'teams',
nested: true
},
{
label: 'Go to activity',
callback: () => {
goto(`/console/project-${projectId}/auth/teams/team-${teams[0].$id}/activity`);
},
group: 'teams',
nested: true
}
];
}
return teams.map((team) => getTeamCommand(team, projectId));
}) satisfies Searcher;
+62
View File
@@ -0,0 +1,62 @@
import { goto } from '$app/navigation';
import { sdk } from '$lib/stores/sdk';
import { project } from '$routes/console/project-[project]/store';
import { get } from 'svelte/store';
import type { Command, Searcher } from '../commands';
import type { Models } from '@appwrite.io/console';
import { promptDeleteUser } from '$routes/console/project-[project]/auth/user-[user]/dangerZone.svelte';
const getUserCommand = (user: Models.User<Models.Preferences>, projectId: string) =>
({
label: user.name,
callback: () => {
goto(`/console/project-${projectId}/auth/user-${user.$id}`);
},
group: 'users',
icon: 'user-circle'
}) satisfies Command;
export const userSearcher = (async (query: string) => {
const { users } = await sdk.forProject.users.list([], query || undefined);
const projectId = get(project).$id;
if (users.length === 1) {
return [
getUserCommand(users[0], projectId),
{
label: 'Delete user',
callback: () => {
promptDeleteUser(users[0].$id);
},
group: 'users',
nested: true,
icon: 'trash'
},
{
label: 'Go to activity',
callback: () => {
goto(`/console/project-${projectId}/auth/user-${users[0].$id}/activity`);
},
group: 'users',
nested: true
},
{
label: 'Go to sessions',
callback: () => {
goto(`/console/project-${projectId}/auth/user-${users[0].$id}/sessions`);
},
group: 'users',
nested: true
},
{
label: 'Go to memberships',
callback: () => {
goto(`/console/project-${projectId}/auth/user-${users[0].$id}/memberships`);
},
group: 'users',
nested: true
}
];
}
return users.map((user) => getUserCommand(user, projectId));
}) satisfies Searcher;
+31
View File
@@ -0,0 +1,31 @@
import type { SvelteComponent } from 'svelte';
import { writable } from 'svelte/store';
export type SubPanel = {
name: string;
component: typeof SvelteComponent<unknown>;
};
type CastSubPanel = Omit<SubPanel, 'component'> & {
component: unknown;
};
export const subPanels = writable<Array<SubPanel>>([]);
export function addSubPanel(subPanel: CastSubPanel) {
subPanels.update((curr) => {
curr.push(subPanel as SubPanel);
return curr;
});
}
export function popSubPanel() {
subPanels.update((curr) => {
curr = curr.slice(0, -1);
return curr;
});
}
export function clearSubPanels() {
subPanels.set([]);
}
+35 -10
View File
@@ -1,16 +1,23 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import type { Buttons } from '../stores/notifications';
import { Button } from '$lib/elements/forms';
export let dismissible = false;
export let type: 'info' | 'success' | 'warning' | 'error' = 'info';
export let type: 'info' | 'success' | 'warning' | 'error' | 'default' = 'info';
export let buttons: Buttons[] = [];
export let isAction = false;
export let isStandalone = false;
let classes = '';
export { classes as class };
const dispatch = createEventDispatcher();
</script>
<section
class="alert"
class="alert {classes}"
class:is-action={isAction}
class:is-standalone={isStandalone}
class:is-success={type === 'success'}
class:is-warning={type === 'warning'}
class:is-danger={type === 'error'}
@@ -27,7 +34,7 @@
</button>
{/if}
<span
class:icon-info={type === 'info'}
class:icon-info={type === 'info' || type === 'default'}
class:icon-check-circle={type === 'success'}
class:icon-exclamation={type === 'warning'}
class:icon-exclamation-circle={type === 'error'}
@@ -38,16 +45,34 @@
<slot name="title" />
</h6>
{/if}
<p class="alert-message"><slot /></p>
{#if buttons?.length}
<div class="alert-buttons u-flex">
{#if $$slots.default}
<p class="alert-message"><slot /></p>
{/if}
<slot name="action">
{#if ($$slots.buttons || buttons?.length) && !isAction}
<div class="alert-buttons u-flex">
<slot name="buttons">
{#each buttons as button}
<Button text on:click={button.method}>
<span class="text">{button.name}</span>
</Button>
{/each}
</slot>
</div>
{/if}
</slot>
</div>
{#if ($$slots.buttons || buttons?.length) && isAction}
<div class="alert-buttons u-flex u-gap-16 u-cross-child-center">
<slot name="buttons">
{#each buttons as button}
<button class="button is-text" on:click={button.method}>
<button type="button" class="button is-text" on:click={button.method}>
<span class="text">{button.name}</span>
</button>
{/each}
</div>
{/if}
</div>
</slot>
</div>
{/if}
</div>
</section>
+21
View File
@@ -0,0 +1,21 @@
<script lang="ts">
export let direction: 'up' | 'down' | 'left' | 'right' = 'right';
$: angle = {
down: 0,
left: 90,
up: 180,
right: 270
}[direction];
</script>
<svg
width="16"
height="17"
viewBox="0 0 16 17"
fill="none"
xmlns="http://www.w3.org/2000/svg"
style:transform="rotate({angle}deg)">
<path
d="M7.64645 15.8622C7.84171 16.0574 8.15829 16.0574 8.35355 15.8622L11.5355 12.6802C11.7308 12.4849 11.7308 12.1683 11.5355 11.9731C11.3403 11.7778 11.0237 11.7778 10.8284 11.9731L8 14.8015L5.17157 11.9731C4.97631 11.7778 4.65973 11.7778 4.46447 11.9731C4.2692 12.1683 4.2692 12.4849 4.46447 12.6802L7.64645 15.8622ZM7.5 1V15.5086H8.5V1H7.5Z"
fill="#C4C6D7" />
</svg>
+2 -1
View File
@@ -2,13 +2,14 @@
export let size: number;
export let src: string;
export let name: string;
export let color = 'transparent';
</script>
<img
width={size}
height={size}
class="avatar"
style="--size: {size / 16}rem"
style="--size: {size / 16}rem; background-color: {color};"
{src}
title={name}
alt={name} />
+21 -2
View File
@@ -2,11 +2,23 @@
import AvatarInitials from './avatarInitials.svelte';
export let avatars: string[] = [];
export let icons: string[] = [];
export let total = avatars.length;
export let size = 40;
export let avatarSize: keyof typeof Sizes = 'medium';
export let bordered = false;
export let color = '';
enum Sizes {
xsmall = 'is-size-x-small',
small = 'is-size-small',
medium = '',
large = 'is-size-large',
xlarge = 'is-size-x-large'
}
</script>
<ul class="avatars-group">
<ul class="avatars-group" class:is-with-border={bordered}>
{#each avatars as name, index}
{#if index < 2}
<li class="avatars-group-item">
@@ -14,9 +26,16 @@
</li>
{/if}
{/each}
{#each icons as icon}
<li class="avatars-group-item">
<span class="avatar {Sizes[avatarSize]} {color}"><span class={`icon-${icon}`} /></span>
</li>
{/each}
{#if total > 2}
<li class="avatars-group-item">
<div class="avatar">+{total - 2}</div>
<div class="avatar {Sizes[avatarSize]} {color}">+{total - 2}</div>
</li>
{/if}
</ul>
+4 -2
View File
@@ -4,8 +4,10 @@
export let name: string;
export let size: number;
export let background: string | undefined = undefined;
export let color = 'black';
$: src = sdk.forConsole.avatars.getInitials(name, size * 2, size * 2).toString();
$: src = sdk.forConsole.avatars.getInitials(name, size * 2, size * 2, background).toString();
</script>
<Avatar {name} {size} {src} />
<Avatar {name} {size} {src} {color} />
@@ -0,0 +1,14 @@
<script lang="ts">
import { page } from '$app/stores';
import { HeaderAlert } from '$lib/layout';
import { organization } from '$lib/stores/organization';
</script>
{#if $organization?.markedForDeletion && !$page.url.pathname.includes('/console/account')}
<HeaderAlert title="Organization flagged for deletion">
<svelte:fragment>
All existing projects in the {$organization.name} organization have been paused. This organization
will be deleted once your upcoming invoice is processed successfully.
</svelte:fragment>
</HeaderAlert>
{/if}
@@ -0,0 +1,29 @@
<script lang="ts">
import { page } from '$app/stores';
import { Button } from '$lib/elements/forms';
import { HeaderAlert } from '$lib/layout';
import { actionRequiredInvoices } from '$lib/stores/billing';
import { organization } from '$lib/stores/organization';
import { VARS } from '$lib/system';
const endpoint = VARS.APPWRITE_ENDPOINT ?? `${$page.url.origin}/v1`;
</script>
{#if $actionRequiredInvoices && $actionRequiredInvoices.total && !$page.url.pathname.includes('/console/account')}
<HeaderAlert title="Authorization required">
Please authorize your upcoming payment for {$organization.name}. Your bank requires this
security measure to proceed with payment.
<svelte:fragment slot="buttons">
<Button
text
href={`${endpoint}/organizations/${$organization.$id}/invoices/${$actionRequiredInvoices.invoices[0].$id}/view`}>
View invoice
</Button>
<Button
secondary
href={`/console/organization-${$organization.$id}/billing?type=confirmation&invoice=${$actionRequiredInvoices.invoices[0].$id}`}>
Authorize payment
</Button>
</svelte:fragment>
</HeaderAlert>
{/if}
@@ -0,0 +1,32 @@
<script lang="ts">
import { base } from '$app/paths';
import { page } from '$app/stores';
import { Button } from '$lib/elements/forms';
import { diffDays, toLocaleDate } from '$lib/helpers/date';
import { HeaderAlert } from '$lib/layout';
import { failedInvoice } from '$lib/stores/billing';
</script>
{#if $failedInvoice && !$page.url.pathname.includes('/console/account')}
{@const daysPassed = diffDays(new Date($failedInvoice.dueAt), new Date())}
<HeaderAlert title="Your projects are at risk">
<svelte:fragment>
{#if daysPassed > 30}
Your scheduled payment on <b>{toLocaleDate($failedInvoice?.dueAt)}</b> failed. To resume
write access of your organization, please update your billing details.
{:else}
Your scheduled payment on <b>{toLocaleDate($failedInvoice?.dueAt)}</b> failed. Access
to paid projects within this organization will be disabled if no action is taken within
30 days.
{/if}
</svelte:fragment>
<svelte:fragment slot="buttons">
<Button
href={`${base}/console/organization-${$failedInvoice?.teamId}/billing#paymentMethods`}
secondary
fullWidthMobile>
<span class="text">Update billing details</span>
</Button>
</svelte:fragment>
</HeaderAlert>
{/if}
@@ -0,0 +1,21 @@
<script lang="ts">
// import { base } from '$app/paths';
// import { Button } from '$lib/elements/forms';
import { HeaderAlert } from '$lib/layout';
import { failedInvoice } from '$lib/stores/billing';
</script>
{#if $failedInvoice}
<HeaderAlert title="You are limited to one free organization per account">
All but one organization will be automatically upgraded to a Pro plan on <b>01 Feb 2024</b>.
You can add a payment method or transfer projects from your settings.
<!-- <svelte:fragment slot="buttons">
<Button
href={`${base}/console/organization-${$failedInvoice?.teamId}/billing#paymentMethods`}
secondary
fullWidthMobile>
<span class="text">Update billing details</span>
</Button>
</svelte:fragment> -->
</HeaderAlert>
{/if}
@@ -0,0 +1,75 @@
<script lang="ts">
import { Button, FormList, InputText } from '$lib/elements/forms';
import type { Coupon } from '$lib/sdk/billing';
import { sdk } from '$lib/stores/sdk';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let required = false;
export let coupon: string = '';
export let couponData: Partial<Coupon> = {
code: null,
status: null,
credits: null
};
async function addCoupon() {
try {
const response = await sdk.forConsole.billing.getCoupon(coupon);
couponData = response;
dispatch('validation', couponData);
coupon = null;
} catch (error) {
console.log(error);
couponData.code = coupon;
couponData.status = 'error';
}
}
function removeCoupon() {
couponData = {
code: null,
status: null,
credits: null
};
}
</script>
<FormList gap={8}>
<InputText
placeholder="Coupon code"
id="code"
label="Add credits"
{required}
hideRequired
disabled={couponData?.status === 'active'}
bind:value={coupon}>
<Button
secondary
disabled={couponData?.status === 'active' || !coupon}
on:click={addCoupon}>
Apply
</Button>
</InputText>
{#if couponData?.status === 'error'}
<div>
<span class="icon-exclamation-circle u-color-text-danger" />
<span>
{couponData.code} is not a valid promo code
</span>
</div>
{:else if couponData?.status === 'active'}
<div class="u-flex u-main-space-between u-cross-center">
<div>
<span class="icon-tag u-color-text-success" />
<slot data={couponData}>
<span>
{couponData.code} applied (-${couponData.credits})
</span>
</slot>
</div>
<Button text on:click={removeCoupon}>Remove</Button>
</div>
{/if}
</FormList>
+2
View File
@@ -0,0 +1,2 @@
export { default as PaymentBoxes } from './paymentBoxes.svelte';
export { default as CouponInput } from './couponInput.svelte';
@@ -0,0 +1,73 @@
<script lang="ts">
import { FormList, InputText } from '$lib/elements/forms';
import { onDestroy, onMount } from 'svelte';
import { CreditCardBrandImage, RadioBoxes } from '..';
export let methods: Record<string, unknown>[];
export let group: string;
export let name: string;
let element: HTMLDivElement;
let loader: HTMLDivElement;
let observer: MutationObserver;
onMount(() => {
observer = new MutationObserver((mutationsList) => {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
if (mutation.addedNodes.length > 0) {
for (let node of Array.from(mutation.addedNodes)) {
if (
node instanceof Element &&
node.className.toLowerCase().includes('__privatestripeelement')
) {
loader.style.display = 'none';
}
}
}
}
}
});
observer.observe(element, { childList: true });
});
onDestroy(() => {
observer.disconnect();
});
</script>
<RadioBoxes elements={methods} total={methods?.length} variableName="$id" name="payment" bind:group>
<svelte:fragment slot="element" let:element>
<slot {element}>
<span class="u-flex u-cross-center u-gap-8" style="padding-inline:0.25rem">
<span>
<span class="u-capitalize">{element.brand}</span> ending in {element.last4}</span>
<CreditCardBrandImage brand={element.brand?.toString()} />
</span>
</slot>
</svelte:fragment>
<svelte:fragment slot="new">
<span style="padding-inline:0.25rem">Add new payment method</span>
</svelte:fragment>
<FormList class="u-margin-block-start-8" gap={16}>
<InputText
id="name"
label="Cardholder name"
placeholder="Cardholder name"
bind:value={name}
required
autofocus={true} />
<div class="aw-stripe-container">
<div class="loader-container" bind:this={loader}>
<div class="loader"></div>
</div>
<div id="payment-element" bind:this={element}>
<!-- Elements will create form elements here -->
</div>
</div>
</FormList>
</RadioBoxes>
+19 -8
View File
@@ -1,9 +1,20 @@
<div class="box">
<div class="u-flex u-gap-16">
<slot name="image" />
<div class="u-cross-child-center u-line-height-1-5">
<slot name="title" />
<slot />
</div>
</div>
<script lang="ts">
export let radius: keyof typeof radiuses = 'small';
export let padding = 24;
let classes = '';
export { classes as class };
enum radiuses {
xsmall = '--border-radius-xsmall',
small = '--border-radius-small',
medium = '--border-radius-medium',
large = '--border-radius-large'
}
</script>
<div
class="box {classes}"
style:--box-border-radius={`var(${radiuses[radius]})`}
style:--box-padding={`${padding / 16}rem`}>
<slot />
</div>
+13
View File
@@ -0,0 +1,13 @@
<script lang="ts">
import { Box } from '.';
</script>
<Box>
<div class="u-flex u-gap-16">
<slot name="image" />
<div class="u-cross-child-center u-line-height-1-5">
<slot name="title" />
<slot />
</div>
</div>
</Box>
+1
View File
@@ -46,6 +46,7 @@
class:is-allowed-focus={href}
on:click
on:keyup={clickOnEnter}
role={href || isButton ? 'button' : 'generic'}
{href}>
<slot />
</svelte:element>
+14 -3
View File
@@ -2,11 +2,18 @@
import { page } from '$app/stores';
import { Empty } from '$lib/components';
import { CARD_LIMIT } from '$lib/constants';
import { getServiceLimit, type PlanServices } from '$lib/stores/billing';
import { preferences } from '$lib/stores/preferences';
import { isCloud } from '$lib/system';
import CardPlanLimit from './cardPlanLimit.svelte';
export let offset = 0;
export let total = 0;
export let event: string = null;
export let service = '';
export let serviceId: PlanServices = service as PlanServices;
$: planLimit = getServiceLimit(serviceId) || Infinity;
$: limit = preferences.get($page.route)?.limit ?? CARD_LIMIT;
</script>
@@ -18,8 +25,12 @@
<slot />
{#if total > 3 ? total < limit + offset : total % 2 !== 0}
<Empty on:click target={event}>
<slot name="empty" />
</Empty>
{#if isCloud && serviceId && total >= planLimit}
<CardPlanLimit {service} />
{:else}
<Empty on:click target={event}>
<slot name="empty" />
</Empty>
{/if}
{/if}
</ul>
+11 -3
View File
@@ -1,15 +1,16 @@
<script>
<script lang="ts">
import { Card } from './';
export let danger = false;
export let hideOverflow = false;
</script>
<Card {danger}>
<div class="common-section grid-1-2">
<div class="common-section grid-1-2" class:hideOverflow>
<div class="grid-1-2-col-1 u-flex u-flex-vertical u-gap-16">
<slot />
</div>
<div class="grid-1-2-col-2 u-flex u-flex-vertical u-gap-24">
<div class="grid-1-2-col-2 u-flex u-flex-vertical u-gap-16">
<slot name="aside" />
</div>
</div>
@@ -19,3 +20,10 @@
</div>
{/if}
</Card>
<style lang="scss">
.hideOverflow > * {
width: 100%;
overflow: hidden;
}
</style>
+16
View File
@@ -0,0 +1,16 @@
<script lang="ts">
import { Button } from '$lib/elements/forms';
import { wizard } from '$lib/stores/wizard';
import ChangeOrganizationTierCloud from '$routes/console/changeOrganizationTierCloud.svelte';
export let service = '';
</script>
<article class="card u-grid u-cross-center u-width-full-line">
<div class="u-flex u-flex-vertical u-gap-24 u-main-center u-cross-center">
<p class="text u-text-center">Upgrade your plan to add more {service}</p>
<Button secondary on:click={() => wizard.start(ChangeOrganizationTierCloud)}>
Change plan
</Button>
</div>
</article>
+10 -6
View File
@@ -4,11 +4,15 @@
<li class="clickable-list-item">
<a {href} class="clickable-list-button" on:click>
<h5 class="clickable-list-title u-trim-1">
<slot />
</h5>
<div class="clickable-list-desc">
<p class="text u-margin-block-start-8"><slot name="desc" /></p>
</div>
{#if $$slots.default}
<h5 class="clickable-list-title u-trim-1">
<slot />
</h5>
{/if}
{#if $$slots.desc}
<div class="clickable-list-desc">
<p class="text u-margin-block-start-8"><slot name="desc" /></p>
</div>
{/if}
</a>
</li>
+33 -6
View File
@@ -1,3 +1,12 @@
<script lang="ts" context="module">
const langArr = ['js', 'html', 'dart', 'kotlin', 'json', 'sh', 'yml', 'swift'] as const;
export type Language = (typeof langArr)[number];
export function isLanguage(str: string): str is Language {
return langArr.includes(str as Language);
}
</script>
<script lang="ts">
import { Pill } from '$lib/elements';
import Prism from 'prismjs';
@@ -20,6 +29,8 @@
export let withLineNumbers = false;
export let withCopy = false;
export let noMargin = false;
export let noBoxPadding = false;
export let allowScroll = false;
Prism.plugins.customClass.prefix('prism-');
@@ -28,7 +39,7 @@
});
</script>
<section class="box u-overflow-hidden" class:common-section={!noMargin}>
<section class="box u-overflow-hidden" class:common-section={!noMargin} class:noBoxPadding>
<div
class="controls u-position-absolute u-inset-inline-end-8 u-inset-block-start-8 u-flex u-gap-8">
{#if label}
@@ -47,11 +58,13 @@
</Copy>
{/if}
</div>
<pre class={`language-${language}`} class:line-numbers={withLineNumbers}><code
>{code}</code></pre>
<pre
class:with-scroll={allowScroll}
class={`language-${language}`}
class:line-numbers={withLineNumbers}><code>{code}</code></pre>
</section>
<!-- svelte-ignore css-unused-selector -->
<style lang="scss" global>
@import 'prismjs/themes/prism.css';
@import 'prismjs/plugins/line-numbers/prism-line-numbers.css';
@@ -68,6 +81,15 @@
}
}
.noBoxPadding {
padding: 0 !important;
}
.with-scroll {
height: 100%;
overflow: auto;
}
code,
pre {
&[class*='language-'] {
@@ -100,7 +122,7 @@
:not(pre) > code[class*='language-'],
pre[class*='language-'] {
background: hsl(var(--p-box-background-color));
padding: 0;
margin: 0;
}
.prism-token {
@@ -168,7 +190,6 @@
color: #62aed2;
}
}
&.prism-regex,
&.prism-important,
&.prism-variable {
color: #a1c4ff;
@@ -176,5 +197,11 @@
color: #62aed2;
}
}
&.prism-regex {
color: #a1c4ff;
body.theme-light & {
color: #62aed2;
}
}
}
</style>
+12 -2
View File
@@ -1,15 +1,25 @@
<script lang="ts">
import { clickOnEnter } from '$lib/helpers/a11y';
export let withIndentation = false;
export let open = false;
</script>
<li class="collapsible-item">
<details class="collapsible-wrapper" {open}>
<summary class="collapsible-button">
<!-- svelte-ignore a11y-no-redundant-roles -->
<summary
class="collapsible-button"
on:keyup={clickOnEnter}
on:click
role="button"
tabindex="0">
<slot name="beforetitle" />
<div>
<span class="text"><slot name="title" /></span>
<span class="collapsible-button-optional"><slot name="subtitle" /></span>
{#if $$slots.subtitle}
<span class="collapsible-button-optional"><slot name="subtitle" /></span>
{/if}
</div>
<div class="icon">
<span class="icon-cheveron-down" aria-hidden="true" />
+2
View File
@@ -34,6 +34,8 @@
<span
data-private
role="button"
tabindex="0"
style:cursor="pointer"
on:click|preventDefault={handleClick}
on:keyup={clickOnEnter}
@@ -0,0 +1,14 @@
<script lang="ts">
import { sdk } from '$lib/stores/sdk';
export let brand: string;
export let width = 23;
export let height = 16;
function getCreditCardImage(brand: string, width = 46, height = 32) {
if (!brand) return '';
return sdk.forConsole.avatars.getCreditCard(brand, width, height).toString();
}
</script>
<img style="border-radius: 2.5px" {width} {height} src={getCreditCardImage(brand)} alt={brand} />
+36
View File
@@ -0,0 +1,36 @@
<script lang="ts">
import type { PaymentMethodData } from '$lib/sdk/billing';
import { Alert } from '.';
import CreditCardBrandImage from './creditCardBrandImage.svelte';
export let isBox = false;
export let paymentMethod: PaymentMethodData;
</script>
<div class:box={isBox}>
<div class="u-flex u-main-space-between u-cross-start">
<div class="u-line-height-1-5 u-flex u-flex-vertical u-gap-2">
<span class="u-flex u-cross-center u-gap-8">
<p class="text u-bold">
<span class="u-capitalize">{paymentMethod?.brand}</span> ending in {paymentMethod?.last4}
</p>
<CreditCardBrandImage brand={paymentMethod?.brand} />
</span>
<p class="text">
Expires {paymentMethod?.expiryMonth}/{paymentMethod?.expiryYear}
</p>
{#if paymentMethod?.name}
<p class="text">
{paymentMethod.name}
</p>
{/if}
</div>
<slot />
</div>
{#if paymentMethod?.expired}
<Alert type="error" class="u-margin-block-start-16 u-width-full-line">
<svelte:fragment slot="title">This payment method has expired</svelte:fragment>
</Alert>
{/if}
</div>
+9 -4
View File
@@ -2,12 +2,13 @@
import { trackEvent } from '$lib/actions/analytics';
import { InnerModal } from '$lib/components';
import { InputId } from '$lib/elements/forms';
import { InputProjectId } from '$lib/elements/forms';
export let show = false;
export let name: string;
export let id: string;
export let autofocus = true;
export let fullWidth = false;
export let isProject = false;
$: if (!show) {
id = null;
}
@@ -21,14 +22,18 @@
}
</script>
<InnerModal bind:show>
<InnerModal bind:show {fullWidth}>
<svelte:fragment slot="title">{name} ID</svelte:fragment>
<svelte:fragment slot="subtitle">
Enter a custom {name} ID. Leave blank for a randomly generated one.
</svelte:fragment>
<svelte:fragment slot="content">
<div class="form">
<InputId bind:value={id} {autofocus} />
{#if isProject}
<InputProjectId bind:value={id} {autofocus} />
{:else}
<InputId bind:value={id} {autofocus} />
{/if}
</div>
</svelte:fragment>
</InnerModal>
+17 -4
View File
@@ -14,7 +14,9 @@
export let fullWidth = false;
export let fixed = false;
const dispatch = createEventDispatcher();
const dispatch = createEventDispatcher<{
blur: undefined;
}>();
let element: HTMLDivElement;
let tooltip: HTMLDivElement;
@@ -77,16 +79,26 @@
event.target === element ||
element.contains(event.target as Node) ||
event.target === tooltip ||
tooltip.contains(event.target as Node)
tooltip.contains(event.target as Node) ||
// Avoid deleted elements triggering blur
!document.body.contains(event.target as Node)
)
) {
show = false;
dispatch('blur');
}
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape' && show) {
event.preventDefault();
show = false;
dispatch('blur');
}
};
</script>
<svelte:window on:click={onBlur} />
<svelte:window on:click={onBlur} on:keydown={onKeyDown} />
<div class:drop-wrapper={!noStyle} class:u-cross-child-start={childStart} bind:this={element}>
<slot />
@@ -103,6 +115,7 @@
{/if}
</div>
<!-- svelte-ignore css-unused-selector -->
<style global lang="scss">
.drop-tooltip[data-popper-placement^='top'] > .drop-arrow {
bottom: -4px;
@@ -130,7 +143,7 @@
.drop-arrow::before {
content: '';
transform: rotate(45deg);
background: hsl(var(--color-neutral-200));
background: hsl(var(--color-neutral-85));
body.theme-light & {
background: hsl(var(--color-neutral-10));
+9 -1
View File
@@ -4,6 +4,7 @@
export let disabled = false;
export let icon: string = null;
export let event: string = null;
export let loading = false;
function track() {
if (!event) {
@@ -17,10 +18,17 @@
</script>
<li class="drop-list-item">
<button class="drop-button" on:click={track} on:click|preventDefault {disabled}>
<button
class="drop-button u-flex u-cross-center u-main-space-between"
on:click={track}
on:click|preventDefault
{disabled}>
<span class="text"><slot /></span>
{#if icon}
<span class={`icon-${icon}`} aria-hidden="true" />
{/if}
{#if loading}
<span class="loader is-small u-line-height-1-5" aria-hidden="true" />
{/if}
</button>
</li>
+22 -3
View File
@@ -1,13 +1,32 @@
<script lang="ts">
import { clickOnEnter } from '$lib/helpers/a11y';
import { trackEvent } from '$lib/actions/analytics';
export let href: string;
export let icon: string = null;
export let disabled = false;
export let external = false;
export let event: string = null;
function track() {
if (!event) {
return;
}
trackEvent(`click_${event}`, {
from: 'drop-list-link'
});
}
</script>
<li class="drop-list-item" on:click on:keyup={clickOnEnter}>
<a {href} class="drop-button" class:is-disabled={disabled}>
<li class="drop-list-item">
<a
on:click
on:click={track}
{href}
class="drop-button"
class:is-disabled={disabled}
target={external ? '_blank' : ''}
rel={external ? 'noopener noreferrer' : ''}>
<span class="text"><slot /></span>
{#if icon}
<span class={`icon-${icon}`} aria-hidden="true" />
+25 -22
View File
@@ -7,8 +7,10 @@
import { trackEvent } from '$lib/actions/analytics';
export let single = false;
export let noMedia = false;
export let target: string = null;
export let href: string = null;
export let marginTop = false;
function track() {
if (target) {
@@ -21,37 +23,37 @@
{#if single}
<article class="card u-grid u-cross-center u-width-full-line common-section">
<div class="u-flex u-flex-vertical u-cross-center u-gap-24">
<button
type="button"
on:click|preventDefault
on:click={track}
aria-label={`create {target}`}>
{#if $app.themeInUse === 'dark'}
<img src={EmptyDark} alt="create" aria-hidden="true" height="124" width="215" />
{:else}
<img
src={EmptyLight}
alt="create"
aria-hidden="true"
height="124"
width="215" />
{/if}
</button>
<div
class="u-flex u-flex-vertical u-cross-center u-gap-24 u-width-full-line u-overflow-hidden">
{#if !noMedia}
<button
type="button"
on:click|preventDefault
on:click={track}
aria-label="create {target}">
{#if $app.themeInUse === 'dark'}
<img src={EmptyDark} alt="create" aria-hidden="true" width="376" />
{:else}
<img src={EmptyLight} alt="create" aria-hidden="true" width="376" />
{/if}
</button>
{/if}
<slot>
<div class="u-text-center">
<Heading size="7" tag="h2">Create your first {target} to get started.</Heading>
<Heading size="7" tag="h2" trimmed={false}>
Create a {target} to get started.
</Heading>
<p class="body-text-2 u-bold u-margin-block-start-4">
Need a hand? Check out our documentation.
Need a hand? Learn more in our documentation.
</p>
</div>
<div class="u-flex u-gap-16 u-main-center">
<div class="u-flex u-flex-wrap u-gap-16 u-main-center">
<Button
external
{href}
text
event="empty_documentation"
ariaLabel={`create {target}`}>Documentation</Button>
ariaLabel="create {target}">Documentation</Button>
<Button secondary on:click on:click={track}>
Create {target}
</Button>
@@ -65,7 +67,8 @@
on:click={track}
aria-label="create"
type="button"
class="card u-grid u-cross-center u-width-full-line dashed">
class="card u-grid u-cross-center u-width-full-line dashed"
class:common-section={marginTop}>
<div class="u-flex u-cross-center u-flex-vertical u-main-center u-flex">
<div class="common-section">
<div class="button is-secondary is-only-icon">
+8 -5
View File
@@ -4,11 +4,12 @@
import Dark from '$lib/images/search-dark.svg';
import PaginationInline from './paginationInline.svelte';
export let hidePagination = false;
export let hidePages = false;
</script>
<article class="card u-grid u-cross-center u-width-full-line common-section">
<div class="u-flex u-flex-vertical u-cross-center u-gap-24">
<div class="u-flex u-flex-vertical u-cross-center u-gap-24 u-overflow-hidden">
{#if $app.themeInUse === 'dark'}
<img src={Dark} alt="create" aria-hidden="true" />
{:else}
@@ -18,7 +19,9 @@
</div>
</article>
<div class="u-flex u-margin-block-start-32 u-main-space-between">
<p class="text">Total results: 0</p>
<PaginationInline limit={1} offset={0} sum={0} {hidePages} />
</div>
{#if !hidePagination}
<div class="u-flex u-margin-block-start-32 u-main-space-between u-cross-center">
<p class="text">Total results: 0</p>
<PaginationInline limit={1} offset={0} sum={0} {hidePages} />
</div>
{/if}
+2 -2
View File
@@ -245,8 +245,7 @@
}
</script>
<Modal bind:show onSubmit={create} size="big">
<svelte:fragment slot="header">Create Event</svelte:fragment>
<Modal title="Create event" bind:show onSubmit={create} size="big">
<slot />
<div>
<p class="u-text">Choose a service</p>
@@ -340,6 +339,7 @@
<div {...{ type: 'text' }} style="min-height: 2.5rem;">
{#each eventString as route, i}
<span
role="tooltip"
class:u-opacity-0-5={helper !== route.description}
on:mouseenter={() => (helper = route.description)}
on:mouseleave={() => (helper = null)}>
+21
View File
@@ -0,0 +1,21 @@
<script lang="ts">
type NumSize = 1 | 2 | 3;
type Size = NumSize | `${NumSize}`;
export let tag: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
export let size: Size;
export let trimmed = true;
export let id: string = null;
export let style: string = undefined;
let classes: string = undefined;
export { classes as class };
</script>
<svelte:element
this={tag}
class="eyebrow-heading-{size} {classes}"
class:u-trim-1={trimmed}
{id}
{style}>
<slot />
</svelte:element>
+151
View File
@@ -0,0 +1,151 @@
<script lang="ts">
import { Alert } from '$lib/components';
import { onMount } from 'svelte';
import Form from '$lib/elements/forms/form.svelte';
import { trackEvent } from '$lib/actions/analytics';
import { clickOnEnter } from '$lib/helpers/a11y';
export let show = false;
export let size: 'small' | 'big' = 'big';
export let icon: string = null;
export let state: 'success' | 'warning' | 'error' | 'info' = null;
export let error: string = null;
export let closable = true;
export let headerDivider = true;
export let onSubmit: (e: SubmitEvent) => Promise<void> | void = function () {
return;
};
export let title = '';
let backdrop: HTMLDivElement;
onMount(async () => {
document.body.appendChild(backdrop);
});
function handleBLur(event: MouseEvent) {
if (event.target === backdrop) {
trackEvent('click_close_modal', {
from: 'backdrop'
});
closeModal();
}
}
function closeModal() {
if (show) {
show = false;
document.documentElement.classList.remove('u-overflow-hidden');
}
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
event.preventDefault();
trackEvent('click_close_modal', {
from: 'escape'
});
closeModal();
}
}
$: if (show) {
document.documentElement.classList.add('u-overflow-hidden');
} else {
closeModal();
error = null;
}
</script>
<svelte:window on:keydown={handleKeydown} />
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div
class="payment-modal-backdrop"
on:keyup={clickOnEnter}
on:click={handleBLur}
bind:this={backdrop}>
<div
class="modal payment-modal"
class:is-small={size === 'small'}
class:is-big={size === 'big'}
class:is-separate-header={headerDivider}>
<Form isModal {onSubmit}>
<header class="modal-header">
<div class="u-flex u-main-space-between u-cross-center u-gap-16">
<div class="u-flex u-cross-center u-gap-16">
{#if icon}
<div
class="avatar is-medium"
class:is-success={state === 'success'}
class:is-warning={state === 'warning'}
class:is-danger={state === 'error'}
class:is-info={state === 'info'}>
<span class={`icon-${icon}`} aria-hidden="true" />
</div>
{/if}
<h4 class="modal-title heading-level-5">
<slot name="title">
{title}
</slot>
</h4>
</div>
{#if closable}
<button
type="button"
class="button is-text is-only-icon"
style="--button-size:1.5rem;"
aria-label="Close Modal"
title="Close Modal"
on:click={() =>
trackEvent('click_close_modal', {
from: 'button'
})}
on:click={closeModal}>
<span class="icon-x" aria-hidden="true" />
</button>
{/if}
</div>
</header>
<div class="modal-content">
{#if error}
<Alert
dismissible
type="warning"
on:dismiss={() => {
error = null;
}}>
{error}
</Alert>
{/if}
<slot />
</div>
{#if $$slots.footer}
<div class="modal-footer">
<div class="u-flex u-main-end u-gap-16">
<slot name="footer" />
</div>
</div>
{/if}
</Form>
</div>
</div>
<style lang="scss">
.payment-modal-backdrop {
position: fixed;
top: 0;
left: 0;
z-index: 100000;
width: 100%;
height: 100%;
background-color: hsl(240 22% 10% / 0.3);
display: flex;
align-items: center;
justify-content: center;
:global() {
background-color: hsl(240 5% 8% / 0.6);
}
}
</style>
@@ -1,6 +1,4 @@
<script lang="ts">
import { clickOnEnter } from '$lib/helpers/a11y';
export let value: number = null;
</script>
@@ -9,9 +7,10 @@
<slot />
</legend>
<ul class="u-flex u-main-space-between u-margin-block-start-16">
{#each Array(10) as _, i}
<li on:keyup={clickOnEnter} on:click={() => (value = i)}>
{#each Array(11) as _, i}
<li>
<input
on:click={() => (value = i)}
type="radio"
name="recommend"
class="radio-button"
@@ -1,40 +1,41 @@
<script lang="ts">
import { Button, Form } from '$lib/elements/forms';
import {
Form,
FormList,
InputTextarea,
Button,
InputText,
InputEmail
} from '$lib/elements/forms';
import { feedback } from '$lib/stores/app';
feedback,
selectedFeedback,
feedbackOptions,
feedbackData
} from '$lib/stores/feedback';
import { addNotification } from '$lib/stores/notifications';
let message: string;
let name: string;
let email: string;
async function handleSubmit() {
try {
await feedback.submitFeedback('feedback-general', message, name, email);
$: $selectedFeedback = feedbackOptions.find((option) => option.type === $feedback.type);
async function submit() {
try {
await feedback.submitFeedback(
`feedback-${$feedback.type}`,
$feedbackData.message,
$feedbackData.name,
$feedbackData.email
);
addNotification({
type: 'success',
message: 'Feedback submitted successfully'
});
feedback.toggleFeedback();
feedbackData.reset();
} catch (error) {
addNotification({
type: 'error',
message: error.message
});
} finally {
feedback.toggleFeedback();
}
}
</script>
<section class="drop-section">
<header class="u-flex u-main-space-between u-gap-16">
<h4 class="body-text-1 u-bold">How can we improve?</h4>
<h4 class="body-text-1 u-bold">{$selectedFeedback.title}</h4>
<button
type="button"
class="button is-text is-only-icon u-margin-inline-start-auto"
@@ -46,21 +47,11 @@
</button>
</header>
<div class="u-margin-block-start-8 u-line-height-1-5">
Your feedback is important to us. Please be honest and tell us what you think.
{$selectedFeedback.desc}
</div>
<Form onSubmit={handleSubmit}>
<FormList>
<InputText label="Name" id="name" bind:value={name} placeholder="Enter name" />
<InputEmail label="Email" id="email" bind:value={email} placeholder="Enter email" />
<InputTextarea
id="feedback"
placeholder="Your message here"
label="Message"
required
bind:value={message} />
</FormList>
<Form onSubmit={submit}>
<svelte:component this={$selectedFeedback.component} />
<div class="u-flex u-main-end u-gap-16 u-margin-block-start-24">
<Button text on:click={() => feedback.toggleFeedback()}>Cancel</Button>
<Button secondary submit>Submit</Button>
@@ -0,0 +1,19 @@
<script lang="ts">
import { FormList, InputTextarea, InputText, InputEmail } from '$lib/elements/forms';
import { feedbackData } from '$lib/stores/feedback';
</script>
<FormList>
<InputText label="Name" id="name" bind:value={$feedbackData.name} placeholder="Enter name" />
<InputEmail
label="Email"
id="email"
bind:value={$feedbackData.email}
placeholder="Enter email" />
<InputTextarea
id="feedback"
placeholder="Your message here"
label="Message"
required
bind:value={$feedbackData.message} />
</FormList>
@@ -0,0 +1,30 @@
<script lang="ts">
import { FormList, InputTextarea, InputText, InputEmail } from '$lib/elements/forms';
import { feedbackData } from '$lib/stores/feedback';
import Evaluation from './evaluation.svelte';
</script>
<Evaluation bind:value={$feedbackData.value}>
How likely are you to recommend Appwrite to a friend or colleague?
</Evaluation>
{#if $feedbackData.value}
<FormList>
<InputTextarea
id="feedback"
placeholder="Your message here"
label="Message"
required
bind:value={$feedbackData.message}
showLabel={false} />
<InputText
label="Name"
id="name"
bind:value={$feedbackData.name}
placeholder="Enter name" />
<InputEmail
label="Email"
id="email"
bind:value={$feedbackData.email}
placeholder="Enter email" />
</FormList>
{/if}
+3
View File
@@ -0,0 +1,3 @@
export { default as Feedback } from './feedback.svelte';
export { default as FeedbackGeneral } from './feedbackGeneral.svelte';
export { default as FeedbackNPS } from './feedbackNPS.svelte';
-78
View File
@@ -1,78 +0,0 @@
<script lang="ts">
import {
Form,
FormList,
InputTextarea,
Button,
InputText,
InputEmail
} from '$lib/elements/forms';
import { feedback } from '$lib/stores/app';
import { addNotification } from '$lib/stores/notifications';
import Evaluation from './evaluation.svelte';
let value: number = null;
let message: string;
let email: string;
let name: string;
async function handleSubmit() {
try {
await feedback.submitFeedback('feedback-nps', message, name, email, value);
feedback.switchType('general');
addNotification({
type: 'success',
message: 'Thank you for your feedback!'
});
} catch (error) {
feedback.switchType('general');
addNotification({
type: 'error',
message: error.message
});
} finally {
feedback.toggleFeedback();
}
}
</script>
<section class="drop-section">
<header class="u-flex u-main-space-between u-gap-16">
<h4 class="body-text-1 u-bold">How are we doing?</h4>
<button
type="button"
class="button is-text is-only-icon u-margin-inline-start-auto"
style="--button-size:1.5rem;"
aria-label="Close Modal"
title="Close Modal"
on:click={() => feedback.toggleFeedback()}>
<span class="icon-x" aria-hidden="true" />
</button>
</header>
<div class="u-margin-block-start-8 u-line-height-1-5">
At Appwrite, we value the feedback of our users. That means you! We'd love to hear what you
think.
</div>
<Form onSubmit={handleSubmit}>
<Evaluation bind:value>
How likely are you to recommend Appwrite to a friend or colleague?
</Evaluation>
{#if value}
<FormList>
<InputTextarea
id="feedback"
placeholder="Your message here"
label="Message"
required
bind:value={message}
showLabel={false} />
<InputText label="Name" id="name" bind:value={name} placeholder="Enter name" />
<InputEmail label="Email" id="email" bind:value={email} placeholder="Enter email" />
</FormList>
{/if}
<div class="u-flex u-main-end u-gap-16 u-margin-block-start-24">
<Button text on:click={() => feedback.toggleFeedback()}>No thanks</Button>
<Button disabled={!value} secondary submit>Submit</Button>
</div>
</Form>
</section>
+187
View File
@@ -0,0 +1,187 @@
<script lang="ts">
import { Button, InputNumber } from '$lib/elements/forms';
import InputSelect from '$lib/elements/forms/inputSelect.svelte';
import InputText from '$lib/elements/forms/inputText.svelte';
import { Query } from '@appwrite.io/console';
import { createEventDispatcher } from 'svelte';
import { tags, type Operator, queries } from './store';
import type { Column } from '$lib/helpers/types';
import type { Writable } from 'svelte/store';
export let columns: Writable<Column[]>;
const dispatch = createEventDispatcher<{
clear: void;
apply: { applied: number };
}>();
let columnId: string | null = null;
$: column = $columns.find((c) => c.id === columnId) as Column;
dispatch('apply', { applied: $tags.length });
const operators: Record<string, Operator> = {
'starts with': {
toQuery: Query.startsWith,
toTag: (attribute, input) => `**${attribute}** starts with **${input}**`,
types: ['string']
},
'ends with': {
toQuery: Query.endsWith,
toTag: (attribute, input) => `**${attribute}** ends with **${input}**`,
types: ['string']
},
'greater than': {
toQuery: (attr, input) => Query.greaterThan(attr, Number(input)),
toTag: (attribute, input) => `**${attribute}** greater than **${input}**`,
types: ['integer', 'double', 'datetime']
},
'greater than or equal to': {
toQuery: (attr, input) => Query.greaterThanEqual(attr, Number(input)),
toTag: (attribute, input) => `**${attribute}** greater than or equal to **${input}**`,
types: ['integer', 'double', 'datetime']
},
'less than': {
toQuery: Query.lessThan,
toTag: (attribute, input) => `**${attribute}** less than **${input}**`,
types: ['integer', 'double', 'datetime']
},
'less than or equal to': {
toQuery: Query.lessThanEqual,
toTag: (attribute, input) => `**${attribute}** less than or equal to **${input}**`,
types: ['integer', 'double', 'datetime']
},
equal: {
toQuery: Query.equal,
toTag: (attribute, input) => `**${attribute}** equal to **${input}**`,
types: ['string', 'integer', 'double', 'boolean']
},
'not equal to': {
toQuery: Query.notEqual,
toTag: (attribute, input) => `**${attribute}** not equal to **${input}**`,
types: ['string', 'integer', 'double', 'boolean']
},
'not null': {
toQuery: Query.isNotNull,
toTag: (attribute) => `**${attribute}** is not null`,
types: ['string', 'integer', 'double', 'boolean', 'datetime', 'relationship'],
hideInput: true
},
null: {
toQuery: Query.isNull,
toTag: (attribute) => `**${attribute}** is null`,
types: ['string', 'integer', 'double', 'boolean', 'datetime', 'relationship'],
hideInput: true
}
};
$: operatorsForColumn = Object.entries(operators)
.filter(([, v]) => v.types.includes(column?.type))
.map(([k]) => ({
label: k,
value: k
}));
let operatorKey: string | null = null;
$: operator = operatorKey ? operators[operatorKey] : null;
$: {
columnId;
operatorKey = null;
}
// We cast to any to not cause type errors in the input components
/* eslint @typescript-eslint/no-explicit-any: 'off' */
let value: any = null;
$: {
columnId;
value = null;
}
// This Map is keyed by tags, and has a query as the value
function addFilter() {
if (!column || !operator) return;
queries.addFilter({ column, operator, value: value ?? '' });
value = null;
}
function tagFormat(node: HTMLElement) {
node.innerHTML = node.innerHTML.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>');
}
$: isDisabled = !operator;
</script>
<div>
<form on:submit|preventDefault={addFilter}>
<div class="selects u-flex u-gap-8 u-margin-block-start-16">
<InputSelect
id="column"
options={$columns.map((c) => ({
label: c.title,
value: c.id
}))}
placeholder="Select column"
bind:value={columnId} />
<InputSelect
id="operator"
disabled={!column}
options={operatorsForColumn}
placeholder="Select operator"
bind:value={operatorKey} />
</div>
{#if column && operator && !operator?.hideInput}
<div class="u-margin-block-start-8">
{#if column.type === 'integer' || column.type === 'double'}
<InputNumber id="value" bind:value placeholder="Enter value" />
{:else if column.type === 'boolean'}
<InputSelect
id="value"
placeholder="Select a value"
required={true}
options={[
{ label: 'True', value: true },
{ label: 'False', value: false }
].filter(Boolean)}
bind:value />
{:else}
<InputText id="value" bind:value placeholder="Enter value" />
{/if}
</div>
{/if}
<Button text disabled={isDisabled} class="u-margin-block-start-4" submit>
<i class="icon-plus" />
Add filter
</Button>
</form>
<ul class="u-flex u-flex-wrap u-cross-center u-gap-8 u-margin-block-start-16 tags">
{#each $tags as tag (tag)}
<button
class="tag"
on:click={() => {
queries.removeFilter(tag);
}}>
<span class="text" use:tagFormat>
{tag}
</span>
<i class="icon-x" />
</button>
{/each}
</ul>
</div>
<style lang="scss">
.selects {
:global(> *) {
flex: 1;
}
}
.tags {
:global(b) {
font-weight: bold;
}
}
</style>
+103
View File
@@ -0,0 +1,103 @@
<script lang="ts">
import { beforeNavigate } from '$app/navigation';
import { Drop, Modal } from '$lib/components';
import { Button } from '$lib/elements/forms';
import type { Column } from '$lib/helpers/types';
import type { Writable } from 'svelte/store';
import Content from './content.svelte';
import { queries, queriesAreDirty, queryParamToMap, tags } from './store';
export let query = '[]';
export let columns: Writable<Column[]>;
const parsedQueries = queryParamToMap(query);
queries.set(parsedQueries);
// We need to separate them so we don't trigger Drop's handlers
let showFiltersDesktop = false;
let showFiltersMobile = false;
let applied = $tags.length;
beforeNavigate(() => {
applied = $tags.length;
showFiltersDesktop = false;
showFiltersMobile = false;
});
</script>
<div class="is-not-mobile">
<Drop bind:show={showFiltersDesktop} noArrow>
<Button secondary on:click={() => (showFiltersDesktop = !showFiltersDesktop)}>
<i class="icon-filter u-opacity-50" />
Filters
{#if applied > 0}
<span class="inline-tag">
{applied}
</span>
{/if}
</Button>
<svelte:fragment slot="list">
<div class="dropped card">
<p>Apply filter rules to refine the table view</p>
<Content
{columns}
on:apply={(e) => (applied = e.detail.applied)}
on:clear={() => (applied = 0)} />
<hr />
<div class="u-flex u-margin-block-start-16 u-main-end u-gap-8">
<Button text on:click={queries.clearAll}>Clear all</Button>
<Button on:click={queries.apply} disabled={!$queriesAreDirty}>Apply</Button>
</div>
</div>
</svelte:fragment>
</Drop>
</div>
<div class="is-only-mobile">
<Button secondary on:click={() => (showFiltersMobile = !showFiltersMobile)}>
<i class="icon-filter u-opacity-50" />
Filters
{#if applied > 0}
<span class="inline-tag">
{applied}
</span>
{/if}
</Button>
<Modal
title="Filters"
description="Apply filter rules to refine the table view"
bind:show={showFiltersMobile}
size="big">
<Content
{columns}
on:apply={(e) => (applied = e.detail.applied)}
on:clear={() => (applied = 0)} />
<svelte:fragment slot="footer">
<Button text on:click={queries.clearAll}>Clear all</Button>
<Button on:click={queries.apply} disabled={!$queriesAreDirty}>Apply</Button
></svelte:fragment>
</Modal>
</div>
<style lang="scss">
.dropped {
border-radius: 0.5rem;
box-shadow: 0px 16px 32px 0px rgba(55, 59, 77, 0.04);
padding: 1rem;
margin-top: 0.5rem;
width: 37.5rem;
hr {
height: 1px;
width: calc(100% + 2rem);
background-color: hsl(var(--color-border));
margin-block-start: 1rem;
margin-inline: -1rem;
}
}
</style>
+1
View File
@@ -0,0 +1 @@
export { default as filters } from './filters.svelte';
+81
View File
@@ -0,0 +1,81 @@
import { goto } from '$app/navigation';
import { derived, get, writable } from 'svelte/store';
import { page } from '$app/stores';
import deepEqual from 'deep-equal';
import type { Column, ColumnType } from '$lib/helpers/types';
export type Operator = {
toTag: (attribute: string, input?: string | number) => string;
toQuery: (attribute: string, input?: string | number) => string;
types: ColumnType[];
hideInput?: boolean;
};
export function mapToQueryParams(map: Map<string, string>) {
return encodeURIComponent(JSON.stringify(Array.from(map.entries())));
}
export function queryParamToMap(queryParam: string) {
const decodedQueryParam = decodeURIComponent(queryParam);
const queries = JSON.parse(decodedQueryParam) as [string, string][];
return new Map(queries);
}
function initQueries(initialValue = new Map<string, string>()) {
const queries = writable(initialValue);
type AddFilterArgs = {
operator: Operator;
column: Column;
value: string | number;
};
function addFilter({ column, operator, value }: AddFilterArgs) {
queries.update((map) => {
map.set(operator.toTag(column.id, value), operator.toQuery(column.id, value));
return map;
});
}
function removeFilter(tag: string) {
queries.update((map) => {
map.delete(tag);
return map;
});
}
function clearAll() {
queries.set(new Map());
}
function apply() {
const queryParam = mapToQueryParams(get(queries));
const currentLocation = window.location.pathname;
goto(`${currentLocation}?query=${queryParam}`);
}
return {
...queries,
addFilter,
removeFilter,
clearAll,
apply
};
}
export const queries = initQueries();
export const queriesAreDirty = derived([queries, page], ([$queries, $page]) => {
const paramQueries = $page.url.searchParams.get('query');
const parsedQueries = queryParamToMap(paramQueries || '[]');
return !deepEqual($queries, parsedQueries);
});
export const hasPageQueries = derived(page, ($page) => {
const paramQueries = $page.url.searchParams.get('query');
const parsedQueries = queryParamToMap(paramQueries || '[]');
return parsedQueries.size > 0;
});
export const tags = derived(queries, ($queries) => Array.from($queries.keys()));
@@ -0,0 +1,39 @@
<script lang="ts">
import { portal } from '$lib/actions/portal';
import { fly } from 'svelte/transition';
export let show = false;
</script>
{#if show}
<div class="floating-action-bar" transition:fly={{ y: '6rem' }} use:portal>
<slot />
</div>
{/if}
<style lang="scss">
.floating-action-bar {
position: fixed;
bottom: 2rem;
left: 50%;
transform: translateX(-50%);
z-index: 100;
border-radius: 0.5rem;
padding: 0.75rem 1rem;
width: clamp(0px, calc(100vw - 4rem), 32.5rem);
}
:global(.theme-dark) .floating-action-bar {
border: 1px solid hsl(var(--color-neutral-200));
background: hsl(var(--color-neutral-300));
box-shadow: 0px 6px 16px 8px #14141f;
}
:global(.theme-light) .floating-action-bar {
border: 1px solid hsl(var(--color-neutral-30));
background: hsl(var(--color-neutral-0));
box-shadow: 0px 6px 16px 0px rgba(55, 59, 77, 0.14);
}
</style>
+1 -1
View File
@@ -7,7 +7,7 @@
<div class="grid-item-1">
<div class="grid-item-1-start-start">
<div class="eyebrow-heading-3"><slot name="eyebrow" /></div>
<Heading tag="h2" size="6"><slot name="title" /></Heading>
<Heading tag="h2" size="7"><slot name="title" /></Heading>
</div>
<div class="grid-item-1-start-end">
<slot name="status" />
+4 -1
View File
@@ -1,6 +1,9 @@
<script lang="ts">
type NumSize = 1 | 2 | 3 | 4 | 5 | 6 | 7;
type Size = NumSize | `${NumSize}`;
export let tag: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
export let size: '1' | '2' | '3' | '4' | '5' | '6' | '7';
export let size: Size;
export let trimmed = true;
export let id: string = null;
</script>
+18 -16
View File
@@ -3,6 +3,7 @@
export let value: string;
export let event: string = null;
export let centered = true;
function truncateText(node: HTMLElement) {
const MAX_TRIES = 100;
@@ -31,7 +32,7 @@
}
}
}
checkOverflow();
requestAnimationFrame(checkOverflow);
window.addEventListener('resize', checkOverflow);
return {
@@ -46,22 +47,23 @@
}
</script>
<div
class="interactive-text-output is-buttons-on-top"
style:min-inline-size="0"
style:display="inline-flex">
<span
style:white-space="nowrap"
class="text u-line-height-1-5"
style:overflow="hidden"
use:truncateText>
<slot />
</span>
<div class="interactive-text-output-buttons">
<Copy {value} {event}>
<Copy {value} {event}>
<div
class="interactive-text-output is-buttons-on-top"
class:u-text-center={centered}
style:min-inline-size="0"
style:display="inline-flex">
<span
style:white-space="nowrap"
class="text u-line-height-1-5"
style:overflow="hidden"
use:truncateText>
<slot />
</span>
<div class="interactive-text-output-buttons">
<button class="interactive-text-output-button is-hidden" aria-label="copy text">
<span class="icon-duplicate" aria-hidden="true" />
</button>
</Copy>
</div>
</div>
</div>
</Copy>
+20 -3
View File
@@ -1,3 +1,4 @@
export { default as Arrow } from './arrow.svelte';
export { default as Modal } from './modal.svelte';
export { default as Pagination } from './pagination.svelte';
export { default as PaginationInline } from './paginationInline.svelte';
@@ -28,12 +29,10 @@ export { default as AvatarInitials } from './avatarInitials.svelte';
export { default as AvatarGroup } from './avatarGroup.svelte';
export { default as Alert } from './alert.svelte';
export { default as Box } from './box.svelte';
export { default as BoxAvatar } from './boxAvatar.svelte';
export { default as Search } from './search.svelte';
export { default as SearchQuery } from './searchQuery.svelte';
export { default as GridItem1 } from './gridItem1.svelte';
export { default as FeedbackGeneral } from './feedbackGeneral.svelte';
export { default as FeedbackNPS } from './feedbackNPS.svelte';
export { default as Evaluation } from './evaluation.svelte';
export { default as Steps } from './steps.svelte';
export { default as Step } from './step.svelte';
export { default as Code } from './code.svelte';
@@ -47,10 +46,28 @@ export { default as EventModal } from './eventModal.svelte';
export { default as Status } from './status.svelte';
export { default as Heading } from './heading.svelte';
export { default as Output } from './output.svelte';
export { default as Support } from './support.svelte';
export { default as ViewSelector } from './viewSelector.svelte';
export { default as LabelCard } from './labelCard.svelte';
export { default as RegionCard } from './regionCard.svelte';
export { default as Limit } from './limit.svelte';
export { default as PaginationWithLimit } from './paginationWithLimit.svelte';
export { default as ClickableList } from './clickableList.svelte';
export { default as ClickableListItem } from './clickableListItem.svelte';
export { default as Id } from './id.svelte';
export { default as ProgressBar } from './progressBar.svelte';
export { default as ProgressBarBig } from './progressBarBig.svelte';
export { default as CreditCardInfo } from './creditCardInfo.svelte';
export { default as CreditCardBrandImage } from './creditCardBrandImage.svelte';
export { default as CardPlanLimit } from './cardPlanLimit.svelte';
export { default as NumericList } from './numericList.svelte';
export { default as NumericListItem } from './numericListItem.svelte';
export { default as EyebrowHeading } from './eyebrowHeading.svelte';
export { default as SvgIcon } from './svgIcon.svelte';
export { default as MigrationBox } from './migrationBox.svelte';
export { default as FloatingActionBar } from './floatingActionBar.svelte';
export { default as LoadingDots } from './loadingDots.svelte';
export { default as FakeModal } from './fakeModal.svelte';
export { default as RadioBoxes } from './radioBoxes.svelte';
export { default as ModalWrapper } from './modalWrapper.svelte';
export { default as ModalSideCol } from './modalSideCol.svelte';
+2 -1
View File
@@ -3,11 +3,12 @@
export let show = false;
export let closable = true;
export let fullWidth = false;
</script>
{#if show}
<FormItem>
<section class="modal is-inner-modal">
<section class="modal is-inner-modal" class:u-width-full-line={fullWidth}>
<div class="modal-form">
<header class="modal-header">
<div class="u-flex u-main-space-between u-cross-center u-gap-16">
+30 -11
View File
@@ -1,4 +1,6 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip';
export let name: string;
export let group: string;
export let value: string | number | boolean;
@@ -7,6 +9,10 @@
export let icon: string = null;
export let fullHeight = true;
export let borderRadius: 'xsmall' | 'small' | 'medium' | 'large' = 'small';
export let backgroundColor: string = null;
export let backgroundColorHover: string = null;
export let tooltipText: string = null;
export let showTooltip = false;
enum Radius {
xsmall = '--border-radius-xsmall',
@@ -17,11 +23,16 @@
</script>
<label
class="card is-allow-focus u-cursor-pointer"
class="card u-cursor-pointer"
class:is-allow-focus={!disabled}
class:is-disabled={disabled}
class:u-height-100-percent={fullHeight}
style:--card-padding={`${padding}rem`}
style:--card-border-radius={`var(${Radius[borderRadius]})`}>
<div class="u-flex u-gap-16">
style:--card-border-radius={`var(${Radius[borderRadius]})`}
style:--p-card-bg-color-default={backgroundColor}
style:--p-card-bg-color-hover={backgroundColorHover}
use:tooltip={{ content: tooltipText, disabled: !tooltipText || !showTooltip }}>
<div class="u-flex u-gap-8">
<input
class="is-small u-margin-block-start-2"
type="radio"
@@ -30,14 +41,22 @@
{value}
bind:group
on:click />
<div class="u-flex u-flex-vertical u-gap-4">
<h4 class="body-text-2 u-bold"><slot name="title" /></h4>
<p class="u-color-text-gray u-small">
<slot />
</p>
</div>
{#if icon}
<span class={`icon-${icon} u-margin-inline-start-auto`} aria-hidden="true" />
{#if $$slots.custom}
<slot name="custom" {disabled} />
{:else}
<div class="u-flex u-flex-vertical u-gap-4" class:u-opacity-50={disabled}>
{#if $$slots.title}
<h4 class="body-text-2 u-bold"><slot name="title" /></h4>
{/if}
{#if $$slots.default}
<p class="u-color-text-gray u-small">
<slot />
</p>
{/if}
</div>
{#if icon}
<span class={`icon-${icon} u-margin-inline-start-auto`} aria-hidden="true" />
{/if}
{/if}
</div>
</label>
+2 -1
View File
@@ -34,11 +34,12 @@
<div class="u-flex u-gap-12 u-cross-center">
<InputSelect
wrapperTag="div"
id="rows"
label="Rows per page"
showLabel={false}
{options}
bind:value={limit}
on:change={limitChange} />
<p class="text">{name} per page. Total results: {sum}</p>
<p class="text">{name} per page. Total results: {sum >= 5000 ? `${sum}+` : sum}</p>
</div>
+2 -1
View File
@@ -1,3 +1,4 @@
<ul class="sessions">
<!-- TODO: remove inline styling -->
<ul class="list" style:gap="0.25rem">
<slot />
</ul>
+4 -12
View File
@@ -1,16 +1,8 @@
<script lang="ts">
export let avatar: string;
export let icon: string = null;
</script>
<li class="sessions-item">
<article class="card">
<img class="sessions-item-image avatar" src={avatar} alt="" />
<header class="sessions-item-header">
<slot name="header" />
</header>
<p class="sessions-item-info">
<slot name="info" />
</p>
<slot name="action" />
</article>
<li class="list-item">
<span class={icon ? `icon-${icon}` : 'icon-check-circle'} aria-hidden="true" />
<slot />
</li>
+56
View File
@@ -0,0 +1,56 @@
<!-- Loading dots -->
<script>
let className = '';
export { className as class };
</script>
<div class="loading-dots {className}">
<div class="dot" />
<div class="dot" />
<div class="dot" />
</div>
<style>
.loading-dots {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
gap: 0.25rem;
padding-inline: 0.5rem;
}
.dot {
width: 0.25rem;
height: 0.25rem;
border-radius: 50%;
background-color: hsl(var(--p-body-text-color));
animation: loading-dots 1s infinite ease-in-out;
}
.dot:nth-child(1) {
animation-delay: 0.1s;
}
.dot:nth-child(2) {
animation-delay: 0.2s;
}
.dot:nth-child(3) {
animation-delay: 0.3s;
}
@keyframes loading-dots {
0% {
transform: translateY(0.25rem);
}
25% {
transform: translateY(0rem);
}
50%,
100% {
transform: translateY(0.25rem);
}
}
</style>
+101
View File
@@ -0,0 +1,101 @@
<script lang="ts" context="module">
import { last } from '$lib/helpers/array';
import { debounce } from '$lib/helpers/debounce';
import { parseIfString } from '$lib/helpers/object';
import { sdk } from '$lib/stores/sdk';
import type { Models } from '@appwrite.io/console';
import { onMount } from 'svelte';
import { writable } from 'svelte/store';
export const showMigrationBox = writable(false);
</script>
<script lang="ts">
let migration: Models.Migration;
type Counter = {
pending: number;
error: number;
success: number;
processing: number;
skip: number;
warning: number;
};
type TotalCounter = {
done: number;
processing: number;
};
$: percentage = (function getPercentage() {
if (!migration) return 0;
if (migration.status === 'failed') return 100;
if (migration.status === 'completed') return 100;
const statusCounters = parseIfString(migration.statusCounters) as Record<string, Counter>;
const totalCounter: TotalCounter = Object.values(statusCounters).reduce(
(curr, acc) => {
return {
done: curr.done + acc.success + acc.error + acc.skip + acc.warning,
processing: curr.processing + acc.processing + acc.pending
};
},
{ done: 0, processing: 0 } as TotalCounter
);
const res = Math.round(
(totalCounter.done / (totalCounter.done + totalCounter.processing)) * 100
);
return Number.isNaN(res) ? 0 : res;
})();
const fetchMigrations = debounce(async () => {
const { migrations } = await sdk.forProject.migrations.list();
migration = last(migrations);
}, 1000);
fetchMigrations();
onMount(async () => {
sdk.forConsole.client.subscribe(['project', 'console'], async (response) => {
if (response.events.includes('migrations.*')) {
fetchMigrations();
}
});
});
</script>
{#if $showMigrationBox && migration}
<section class="upload-box is-float">
<header class="upload-box-header">
<h4 class="upload-box-title">
<span class="text">Importing Data</span>
</h4>
<button
class="upload-box-button"
aria-label="close migration box"
on:click={() => ($showMigrationBox = false)}>
<span class="icon-x" aria-hidden="true" />
</button>
</header>
<div class="upload-box-content is-open">
<section class="progress-bar">
<div class="progress-bar-top-line u-flex u-gap-8 u-main-space-between">
<span>{percentage}%</span>
</div>
<div
class="progress-bar-container"
class:is-danger={migration.status === 'failed'}
style="--graph-size:{percentage}%" />
</section>
</div>
</section>
{/if}
<style>
.upload-box-content {
padding: 1.5rem;
min-width: 400px;
max-width: 100vw;
}
</style>
Loaded 100 of 786 files, more files were not shown because too many files have changed in this diff. Show more