Compare commits

...

91 Commits

Author SHA1 Message Date
Andrew Bastin
0d78e6d209 Merge pull request #2243 from RishabhAgarwal-2001/2087-openapi 2022-06-29 22:14:42 +05:30
Andrew Bastin
172e459872 Merge branch 'orphan-pr/2243' into 2087-openapi 2022-06-29 22:14:14 +05:30
Andrew Bastin
cfdab014c7 refactor: allow smart tabs to render inactive tabs as an option 2022-06-28 16:37:43 +05:30
liyasthomas
ed6e1c0f94 chore: update package lock file 2022-06-28 15:19:45 +05:30
Anwarul Islam
07a8a37739 feat: realtime tabs as subpages (#2450)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-06-28 15:12:47 +05:30
Akash K
ca553b9d3c fix: empty string exported when exporting team collections (#2460) 2022-06-27 22:24:38 +05:30
Jitendra Nirnejak
69aaeaf42a fix: environment variables overflowing issue on test results - fix (#2473) 2022-06-27 15:52:32 +05:30
Andrew Bastin
015393d98f fix: allow volar to function properly on gitpod 2022-06-23 14:56:09 +05:30
Nivedin
c8dec56b96 fix: remove confirm change popup and add ability to overwrite request in saveas popup (#2433) 2022-06-22 15:21:35 +05:30
liyasthomas
8fefd37862 fix: make scrollbars visible, fixed #2437, #2411 2022-06-18 18:14:02 +05:30
kyteinsky
c1cc1ce295 fix: curl parser json detection issues (#2370)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-06-18 14:09:16 +05:30
Chun-Hao Lien
16be7c38f3 fix: typo in getEnvironment (#2434) 2022-06-18 07:37:32 +05:30
Vaugen Wake
82b6ad935a fix: resolve removing body parameters in requests (#2390) (#2428)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-06-16 19:47:46 +05:30
Nivedin
185dc3f2c9 fix: Copy and download filtered response body (#2426) 2022-06-16 06:09:43 +05:30
liyasthomas
51138fa42d chore: updated i18n translations 2022-06-16 06:02:57 +05:30
Andrew Bastin
7f08a4bd81 chore: hoppscotch-cli version 0.2.1 2022-06-15 23:58:34 +05:30
Deepanshu Dhruw
0244b941b3 feat: added support for passing env.json file to test cmd (#2373) 2022-06-15 23:53:24 +05:30
Moritz Mock
2d0bd48e00 feat: checks only if not default param (#2410)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-06-14 22:21:03 +05:30
Andrew Bastin
15e433b114 fix: broken volar inference on templates 2022-06-14 17:29:31 +05:30
nicognaW
97ff089110 feat: display response size with a bigger unit in tooltip (#2425)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-06-14 15:40:33 +05:30
Andrew Bastin
a6b5295df5 chore: revert indented line wrap due to issues with mobile (fixes hoppscotch/internal-issues#9) 2022-06-13 23:05:23 +05:30
Nivedin
6b1ca1dce1 feat: filter json body response (#2404) 2022-06-10 18:12:40 +05:30
Andrew Bastin
04a9c4dc52 fix: improve graphql syntax highlighting 2022-06-10 01:26:42 +05:30
liyasthomas
e5e44b889f ci: use pnpm/action-setup in actions 2022-06-08 12:34:03 +05:30
Andrew Bastin
c46bc40bcb chore: add staging backend env vars to nuxt config 2022-06-08 12:21:17 +05:30
Andrew Bastin
a91a8ba575 chore: use pnpm/action-setup instead of manual pnpm install 2022-06-08 12:19:47 +05:30
Andrew Bastin
1f536eeedd fix: volar complaining about jsx 2022-06-07 15:58:14 +05:30
liyasthomas
25253c4bdf chore: improve ui consistency in realtime pages 2022-06-07 14:34:00 +05:30
Andrew Bastin
043c49541f chore: add backend urls to staging env 2022-06-07 02:11:40 +05:30
Andrew Bastin
a78462fbe3 chore: move backend urls to env variables 2022-06-07 01:57:48 +05:30
Andrew Bastin
52c25e497f chore: introduce staging deploy workflow 2022-06-07 01:03:29 +05:30
Andrew Bastin
4f539c9781 fix: remove staging push from deploy-netlify workflow 2022-06-07 01:00:45 +05:30
Andrew Bastin
ba468bb835 chore: allow system env vars to be available during build time 2022-06-07 00:59:10 +05:30
liyasthomas
93faa8d5ff ci: activate staging deployment 2022-06-03 15:32:58 +05:30
Liyas Thomas
cf90d16f8a refactor: use refAutoReset instead of settimeout (#2385)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-06-01 16:54:37 +05:30
Nivedin
39f72f8458 feat: segmented content-type dropdown UI (#2382)
Co-authored-by: liyasthomas <liyascthomas@gmail.com>
2022-05-31 17:04:05 +05:30
liyasthomas
eb6c4f1a05 feat: add copy to clipboard button in response headers entry 2022-05-28 15:39:17 +05:30
liyasthomas
b132077cdd chore: improve ui consistency 2022-05-28 15:19:04 +05:30
Anwarul Islam
f6950bac0f refactor: real-time system (#2228)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
Co-authored-by: liyasthomas <liyascthomas@gmail.com>
2022-05-28 15:05:41 +05:30
kyteinsky
83bdd03f43 fix: curl parser url sanitisation (#2366) 2022-05-27 14:48:33 +05:30
liyasthomas
b1a2c9e9d5 fix: text overflow in table layout 2022-05-25 17:42:48 +05:30
liyasthomas
346ac8bde9 chore: improve ui consistency on table layout 2022-05-24 18:48:45 +05:30
Nivedin
cfa89a6ded feat: UI of shortcode actions (#2347)
Co-authored-by: liyasthomas <liyascthomas@gmail.com>
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-05-24 17:58:49 +05:30
Akash K
184914ba4f feat: extension identification improvements (#2332)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-05-19 13:41:05 +05:30
Rishabh Agarwal
5233c36904 refactor: comments address 2022-05-17 15:24:36 +05:30
Rishabh Agarwal
6417ece710 Merge branch '2087-openapi' of https://github.com/RishabhAgarwal-2001/hoppscotch into 2087-openapi 2022-05-17 14:42:02 +05:30
Deepanshu Dhruw
432337b801 chore: tests for hoppscotch-cli (#2300)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-05-11 15:44:19 +05:30
Andrew Bastin
d04520698d refactor: isolate computed header calculation on effective requests (#2313)
Co-authored-by: liyasthomas <liyascthomas@gmail.com>
2022-05-11 14:53:06 +05:30
liyasthomas
450af983e2 fix: overflow on log entry 2022-05-10 19:34:37 +05:30
Balázs Úr
c36e421d13 chore(i18n): updated Hungarian translation (#2331) 2022-05-10 11:42:54 +05:30
Joel Jacob Stephen
fb1da491d8 refactor: realtime log entry revamp (#2240)
Co-authored-by: liyasthomas <liyascthomas@gmail.com>
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-05-10 02:05:24 +05:30
Andrew Bastin
127bd7318f fix: improve indentation on GQL editors 2022-05-07 23:33:48 +05:30
Nivedin
c3b784c680 fix : save request popup bug (#2324) 2022-05-05 20:46:28 +05:30
Andrew Bastin
df55807fa4 fix: rest session not updating when the request is renamed from the sidebar (fixes #2297) 2022-05-05 20:07:13 +05:30
Andrew Bastin
a3d92c862c refactor: rename to prettyPrintJSON and add jsdoc 2022-05-03 18:05:39 +05:30
Rishabh Agarwal
f84b67ec39 feat: handle oneof and anyof 2022-05-03 18:04:34 +05:30
Rishabh Agarwal
3afd2c1cf2 refactor: address comments 2022-05-03 18:04:34 +05:30
Rishabh Agarwal
ed49c0b72c refactor: examplev2 created and lintfix 2022-05-03 18:04:33 +05:30
Rishabh Agarwal
bc2f81ff25 feat: v3 requests example working 2022-05-03 18:04:33 +05:30
Rishabh Agarwal
721a201e7a refactor: removed unecessary const 2022-05-03 18:04:33 +05:30
Rishabh Agarwal
b0071e6859 feat: oasv2 example generation complete 2022-05-03 18:04:33 +05:30
Akash K
4ef2844a22 feat: import collections from URL (#2262)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-05-03 17:54:47 +05:30
Andrew Bastin
c20339d222 fix: deprecated pnpx usage migrated to pnpm exec 2022-05-03 12:39:56 +05:30
liyasthomas
514210e167 fix: proper scrollbar width - resolved #2301 2022-04-30 19:53:23 +05:30
Anwarul Islam
50744136d0 fix: same key params are not overwritten to the last defined (#2299)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-04-30 19:23:43 +05:30
liyasthomas
07735994e1 refactor: update echo server URLs 2022-04-29 06:40:38 +05:30
Rishabh Agarwal
3a41d79c2f feat: handle oneof and anyof 2022-04-27 23:48:26 +05:30
liyasthomas
00acf06700 chore(i18n): updated translations 2022-04-26 12:48:56 +05:30
Andrew Bastin
9486279b02 fix: first env edit not being applied (thanks @17307) 2022-04-23 00:16:39 +05:30
Andrew Bastin
021908c8d1 fix: regressions in environment details modal 2022-04-22 11:58:29 +05:30
liyasthomas
bf97d8811c fix: proper toast for actions on environments - resolved #2279 2022-04-22 11:40:47 +05:30
kyteinsky
2452b1be4b feat: loading states for modal buttons (#2268) 2022-04-20 23:48:25 +05:30
liyasthomas
7bf76a5812 fix: remove newline in smart inputs - resolved #2277 2022-04-19 23:54:04 +05:30
Andrew Bastin
d1b339df5d chore: hoppscotch-cli release 0.1.14 2022-04-18 22:49:34 +05:30
Deepanshu Dhruw
06937fe9e8 feat: added execution duration and updated collection-metrics (#2257) 2022-04-18 22:43:43 +05:30
Andrew Bastin
62a5beb52f chore: update 'post' method usages to be uppercased as per HTTP spec 2022-04-18 21:37:15 +05:30
Rishabh Agarwal
2fd9eb0767 refactor: address comments 2022-04-18 19:29:45 +05:30
Rishabh Agarwal
2aef9c5691 refactor: examplev2 created and lintfix 2022-04-18 15:45:52 +05:30
Kane Sweet
100e562dcc fix: add aria labels to forms (#2270) 2022-04-18 10:01:04 +05:30
liyasthomas
09af858fbc chore(deps): bump 2022-04-17 22:41:00 +05:30
Nivedin
01acbc8db6 refactor : migrate components to script setup on ts (#2267)
* refactor: migrate buttons to script setup on ts

* refactor: migrate env components to script setup on ts

* fix: reference sharing when requests are opened from the sidebar

* ci: deploy to prod from actions

* chore: type updation

* chore: update

* refactor: update types

Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
Co-authored-by: liyasthomas <liyascthomas@gmail.com>
2022-04-17 22:29:32 +05:30
liyasthomas
f1c42f28de ci: deploy to prod from actions 2022-04-15 14:58:07 +05:30
Rishabh Agarwal
14e9d19ae6 feat: v3 requests example working 2022-04-15 12:06:51 +05:30
Andrew Bastin
c99b224829 fix: reference sharing when requests are opened from the sidebar 2022-04-15 00:20:35 +05:30
Andrew Bastin
ede27e0600 refactor: implement updated equality heuristics for hopprestrequest struct 2022-04-14 20:28:59 +05:30
Nivedin
99148a0a0e feat: unsaved change popup (#2239)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
Co-authored-by: liyasthomas <liyascthomas@gmail.com>
2022-04-14 20:28:58 +05:30
liyasthomas
9232aad184 refactor: improve ui consistency 2022-04-14 19:00:04 +05:30
liyasthomas
f7ca3f8bd1 feat: add essential keymaps to codemirror input box - resolved #2264 2022-04-14 18:37:25 +05:30
kyteinsky
ff51b7e5df feat: add New Request button for folder and collection (#2241)
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
2022-04-14 17:09:02 +05:30
Rishabh Agarwal
a04b634089 refactor: removed unecessary const 2022-04-08 11:15:39 +05:30
Rishabh Agarwal
2244d38439 feat: oasv2 example generation complete 2022-04-08 11:06:25 +05:30
251 changed files with 13315 additions and 5768 deletions

34
.github/workflows/deploy-netlify.yml vendored Normal file
View File

@@ -0,0 +1,34 @@
name: Deploy to Netlify
on:
push:
branches: [main]
jobs:
build:
name: Push build files to Netlify
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v2
- name: Setup and run pnpm install
uses: pnpm/action-setup@v2.2.2
with:
version: 7
run_install: true
- name: Setup Environment
run: mv packages/hoppscotch-app/.env.example packages/hoppscotch-app/.env
- name: Build Site
run: pnpm run generate
# Deploy the production site with netlify-cli
- name: Deploy to Netlify (production)
uses: netlify/actions/cli@master
env:
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_PRODUCTION_SITE_ID }}
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
with:
args: deploy --dir=packages/hoppscotch-app/dist --prod

View File

@@ -0,0 +1,45 @@
name: Deploy to Staging Netlify
on:
push:
# TODO: Migrate to staging branch only
branches: [main]
jobs:
build:
name: Push build files to Netlify
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v2
- name: Setup and run pnpm install
uses: pnpm/action-setup@v2.2.2
with:
version: 7
run_install: true
- name: Build Site
env:
GA_ID: ${{ secrets.STAGING_GA_ID }}
GTM_ID: ${{ secrets.STAGING_GTM_ID }}
API_KEY: ${{ secrets.STAGING_FB_API_KEY }}
AUTH_DOMAIN: ${{ secrets.STAGING_FB_AUTH_DOMAIN }}
DATABASE_URL: ${{ secrets.STAGING_FB_DATABASE_URL }}
PROJECT_ID: ${{ secrets.STAGING_FB_PROJECT_ID }}
STORAGE_BUCKET: ${{ secrets.STAGING_FB_STORAGE_BUCKET }}
MESSAGING_SENDER_ID: ${{ secrets.STAGING_FB_MESSAGING_SENDER_ID }}
APP_ID: ${{ secrets.STAGING_FB_APP_ID }}
BASE_URL: ${{ secrets.STAGING_BASE_URL }}
BACKEND_GQL_URL: ${{ secrets.STAGING_BACKEND_GQL_URL }}
BACKEND_WS_URL: ${{ secrets.STAGING_BACKEND_WS_URL }}
run: pnpm run generate
# Deploy the staging site with netlify-cli
- name: Deploy to Netlify (staging)
uses: netlify/actions/cli@master
env:
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_STAGING_SITE_ID }}
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
with:
args: deploy --dir=packages/hoppscotch-app/dist --prod

View File

@@ -17,12 +17,15 @@ jobs:
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- name: Install pnpm
run: curl -f https://get.pnpm.io/v6.14.js | node - add --global pnpm@6
- name: Setup and run pnpm install
uses: pnpm/action-setup@v2.2.2
with:
version: 7
run_install: true
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
cache: pnpm
- name: Run tests
run: pnpm i && pnpm -r test
run: pnpm test

View File

@@ -22,11 +22,11 @@
],
"dependencies": {
"husky": "^7.0.4",
"lint-staged": "^12.3.7"
"lint-staged": "^12.3.8"
},
"devDependencies": {
"@commitlint/cli": "^16.2.3",
"@commitlint/config-conventional": "^16.2.1",
"@types/node": "^17.0.23"
"@types/node": "^17.0.24"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@hoppscotch/codemirror-lang-graphql",
"version": "0.1.0",
"version": "0.2.0",
"description": "GraphQL language support for CodeMirror",
"author": "Hoppscotch (support@hoppscotch.io)",
"license": "MIT",
@@ -24,9 +24,9 @@
"devDependencies": {
"@lezer/generator": "^0.15.4",
"mocha": "^9.2.2",
"rollup": "^2.70.1",
"rollup": "^2.70.2",
"rollup-plugin-dts": "^4.2.1",
"rollup-plugin-ts": "^2.0.5",
"rollup-plugin-ts": "^2.0.7",
"typescript": "^4.6.3"
}
}

View File

@@ -27,16 +27,22 @@ export const GQLLanguage = LRLanguage.define({
},
}),
styleTags({
Name: t.definition(t.variableName),
"OperationDefinition/Name": t.definition(t.function(t.variableName)),
OperationType: t.keyword,
BooleanValue: t.bool,
StringValue: t.string,
IntValue: t.number,
FloatValue: t.number,
NullValue: t.null,
ObjectValue: t.brace,
Comment: t.lineComment,
Name: t.propertyName,
StringValue: t.string,
IntValue: t.integer,
FloatValue: t.float,
NullValue: t.null,
BooleanValue: t.bool,
Comma: t.separator,
"OperationDefinition/Name": t.definition(t.function(t.variableName)),
"OperationType TypeKeyword SchemaKeyword FragmentKeyword OnKeyword DirectiveKeyword RepeatableKeyword SchemaKeyword ExtendKeyword ScalarKeyword InterfaceKeyword UnionKeyword EnumKeyword InputKeyword ImplementsKeyword": t.keyword,
"ExecutableDirectiveLocation TypeSystemDirectiveLocation": t.atom,
"DirectiveName!": t.annotation,
"\"{\" \"}\"": t.brace,
"\"(\" \")\"": t.paren,
"\"[\" \"]\"": t.squareBracket,
"Type! NamedType": t.typeName,
}),
],
}),

View File

@@ -33,16 +33,24 @@ TypeSystemExtension {
TypeExtension
}
SchemaKeyword {
@specialize<Name, "schema">
}
SchemaDefinition {
Description? @specialize<Name, "schema"> Directives? RootTypeDef
Description? SchemaKeyword Directives? RootTypeDef
}
RootTypeDef {
"{" RootOperationTypeDefinition+ "}"
}
ExtendKeyword {
@specialize<Name, "extend">
}
SchemaExtension {
@specialize<Name, "extend"> @specialize<Name, "schema"> Directives? RootTypeDef
ExtendKeyword SchemaKeyword Directives? RootTypeDef
}
TypeExtension {
@@ -54,33 +62,53 @@ TypeExtension {
InputObjectTypeExtension
}
ScalarKeyword {
@specialize<Name, "scalar">
}
ScalarTypeExtension {
@specialize<Name, "extend"> @specialize<Name, "scalar"> Name Directives
ExtendKeyword ScalarKeyword Name Directives
}
ObjectTypeExtension /* precedence: right 0 */ {
@specialize<Name, "extend"> @specialize<Name, "type"> Name ImplementsInterfaces? Directives? !typeDef FieldsDefinition |
@specialize<Name, "extend"> @specialize<Name, "type"> Name ImplementsInterfaces? Directives?
ExtendKeyword TypeKeyword Name ImplementsInterfaces? Directives? !typeDef FieldsDefinition |
ExtendKeyword TypeKeyword Name ImplementsInterfaces? Directives?
}
InterfaceKeyword {
@specialize<Name, "interface">
}
InterfaceTypeExtension /* precedence: right 0 */ {
@specialize<Name, "extend"> @specialize<Name, "interface"> Name ImplementsInterfaces? Directives? FieldsDefinition |
@specialize<Name, "extend"> @specialize<Name, "interface"> Name ImplementsInterfaces? Directives?
ExtendKeyword InterfaceKeyword Name ImplementsInterfaces? Directives? FieldsDefinition |
ExtendKeyword InterfaceKeyword Name ImplementsInterfaces? Directives?
}
UnionKeyword {
@specialize<Name, "union">
}
UnionTypeExtension /* precedence: right 0 */ {
@specialize<Name, "extend"> @specialize<Name, "union"> Name Directives? UnionMemberTypes |
@specialize<Name, "extend"> @specialize<Name, "union"> Name Directives?
ExtendKeyword UnionKeyword Name Directives? UnionMemberTypes |
ExtendKeyword UnionKeyword Name Directives?
}
EnumKeyword {
@specialize<Name, "enum">
}
EnumTypeExtension /* precedence: right 0 */ {
@specialize<Name, "extend"> @specialize<Name, "enum"> Name Directives? !typeDef EnumValuesDefinition |
@specialize<Name, "extend"> @specialize<Name, "enum"> Name Directives?
ExtendKeyword EnumKeyword Name Directives? !typeDef EnumValuesDefinition |
ExtendKeyword EnumKeyword Name Directives?
}
InputKeyword {
@specialize<Name, "input">
}
InputObjectTypeExtension /* precedence: right 0 */ {
@specialize<Name, "extend"> @specialize<Name, "input"> Name Directives? InputFieldsDefinition+ |
@specialize<Name, "extend"> @specialize<Name, "input"> Name Directives?
ExtendKeyword InputKeyword Name Directives? InputFieldsDefinition+ |
ExtendKeyword InputKeyword Name Directives?
}
InputFieldsDefinition {
@@ -95,9 +123,13 @@ EnumValueDefinition {
Description? EnumValue Directives?
}
ImplementsKeyword {
@specialize<Name, "implements">
}
ImplementsInterfaces {
ImplementsInterfaces "&" NamedType |
@specialize<Name, "implements"> "&"? NamedType
ImplementsKeyword "&"? NamedType
}
FieldsDefinition {
@@ -144,27 +176,31 @@ TypeDefinition {
}
ScalarTypeDefinition /* precedence: right 0 */ {
Description? @specialize<Name, "scalar"> Name Directives?
Description? ScalarKeyword Name Directives?
}
TypeKeyword {
@specialize<Name, "type">
}
ObjectTypeDefinition /* precedence: right 0 */ {
Description? @specialize<Name, "type"> Name ImplementsInterfaces? Directives? FieldsDefinition?
Description? TypeKeyword Name ImplementsInterfaces? Directives? FieldsDefinition?
}
InterfaceTypeDefinition /* precedence: right 0 */ {
Description? @specialize<Name, "interface"> Name ImplementsInterfaces? Directives? FieldsDefinition?
Description? InterfaceKeyword Name ImplementsInterfaces? Directives? FieldsDefinition?
}
UnionTypeDefinition /* precedence: right 0 */ {
Description? @specialize<Name, "union"> Name Directives? UnionMemberTypes?
Description? UnionKeyword Name Directives? UnionMemberTypes?
}
EnumTypeDefinition /* precedence: right 0 */ {
Description? @specialize<Name, "enum"> Name Directives? !typeDef EnumValuesDefinition?
Description? EnumKeyword Name Directives? !typeDef EnumValuesDefinition?
}
InputObjectTypeDefinition /* precedence: right 0 */ {
Description? @specialize<Name, "input"> Name Directives? !typeDef InputFieldsDefinition?
Description? InputKeyword Name Directives? !typeDef InputFieldsDefinition?
}
VariableDefinitions {
@@ -237,8 +273,12 @@ FragmentSpread {
"..." FragmentName Directives?
}
FragmentKeyword {
@specialize<Name, "fragment">
}
FragmentDefinition {
@specialize<Name, "fragment"> FragmentName TypeCondition Directives? SelectionSet
FragmentKeyword FragmentName TypeCondition Directives? SelectionSet
}
FragmentName {
@@ -249,20 +289,36 @@ InlineFragment {
"..." TypeCondition? Directives? SelectionSet
}
OnKeyword {
@specialize<Name, "on">
}
TypeCondition {
@specialize<Name, "on"> NamedType
OnKeyword NamedType
}
Directives {
Directive+
}
DirectiveName {
"@" Name
}
Directive {
"@" Name Arguments?
DirectiveName Arguments?
}
DirectiveKeyword {
@specialize<Name, "directive">
}
RepeatableKeyword {
@specialize<Name, "repeatable">
}
DirectiveDefinition /* precedence: right 1 */ {
Description? @specialize<Name, "directive"> "@" Name ArgumentsDefinition? @specialize<Name, "repeatable"> ? @specialize<Name, "on"> DirectiveLocations
Description? DirectiveKeyword "@" Name ArgumentsDefinition? RepeatableKeyword ? OnKeyword DirectiveLocations
}
DirectiveLocations {
@@ -299,8 +355,8 @@ Description {
}
OperationType {
@specialize<Name, "query">
| @specialize<Name, "mutation">
@specialize<Name, "query">
| @specialize<Name, "mutation">
| @specialize<Name, "subscription">
}
@@ -317,7 +373,7 @@ ExecutableDirectiveLocation {
@specialize<Name, "QUERY">
| @specialize<Name, "MUTATION">
| @specialize<Name, "SUBSCRIPTION">
| @specialize<Name, "FIELD">
| @specialize<Name, "FIELD">
| @specialize<Name, "FRAGMENT_DEFINITION">
| @specialize<Name, "FRAGMENT_SPREAD">
| @specialize<Name, "INLINE_FRAGMENT">
@@ -338,10 +394,9 @@ TypeSystemDirectiveLocation {
| @specialize<Name, "INPUT_FIELD_DEFINITION">
}
@skip { Whitespace | Comment }
@tokens {
Whitespace {
whitespace {
std.whitespace+
}
StringValue {
@@ -353,7 +408,7 @@ TypeSystemDirectiveLocation {
}
FloatValue {
IntValue ("." std.digit+ | ("e" | "E") IntValue+)
IntValue ("." std.digit+ | ("e" | "E") IntValue+)
}
@precedence { IntValue, FloatValue }
@@ -361,12 +416,19 @@ TypeSystemDirectiveLocation {
Name {
$[_A-Za-z] $[_0-9A-Za-z]*
}
Comment {
"#" ![\n]*
}
Comma {
","
}
Comment {
"#" ![\n]*
}
"{" "}"
}
@detectDelim
@skip { whitespace | Comment }
@detectDelim

View File

@@ -16,3 +16,7 @@ MEASUREMENT_ID=G-BBJ3R80PJT
# Base URL
BASE_URL=https://hoppscotch.io
# Backend URLs
BACKEND_GQL_URL=https://api.hoppscotch.io/graphql
BACKEND_WS_URL=wss://api.hoppscotch.io/graphql

View File

@@ -115,4 +115,4 @@ shims-volar.d.ts
helpers/backend/backend-schema.json
# GraphQL Type Generation
helpers/backend/graphql.ts
helpers/backend/graphql.ts

View File

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="17" y1="7" x2="7" y2="17"></line>
<polyline points="17 17 7 17 7 7"></polyline>
</svg>

After

Width:  |  Height:  |  Size: 283 B

View File

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19"></line>
<polyline points="19 12 12 19 5 12"></polyline>
</svg>

After

Width:  |  Height:  |  Size: 285 B

View File

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="7" y1="17" x2="17" y2="7"></line>
<polyline points="7 7 17 7 17 17"></polyline>
</svg>

After

Width:  |  Height:  |  Size: 283 B

View File

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="19" x2="12" y2="5"></line>
<polyline points="5 12 12 5 19 12"></polyline>
</svg>

After

Width:  |  Height:  |  Size: 284 B

View File

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="7 13 12 18 17 13"></polyline>
<polyline points="7 6 12 11 17 6"></polyline>
</svg>

After

Width:  |  Height:  |  Size: 286 B

View File

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="17 11 12 6 7 11"></polyline>
<polyline points="17 18 12 13 7 18"></polyline>
</svg>

After

Width:  |  Height:  |  Size: 287 B

View File

@@ -0,0 +1,13 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"></polygon>
</svg>

After

Width:  |  Height:  |  Size: 283 B

View File

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="16" x2="12" y2="12"></line>
<line x1="12" y1="8" x2="12.01" y2="8"></line>
</svg>

After

Width:  |  Height:  |  Size: 329 B

View File

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="16" x2="12" y2="12"></line>
<line x1="12" y1="8" x2="12.01" y2="8"></line>
</svg>

After

Width:  |  Height:  |  Size: 329 B

View File

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="22" y1="2" x2="11" y2="13"></line>
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
</svg>

After

Width:  |  Height:  |  Size: 292 B

View File

@@ -15,6 +15,7 @@
::-webkit-scrollbar-track {
@apply bg-transparent;
@apply border-solid border-l border-t-0 border-b-0 border-r-0 border-dividerLight;
}
::-webkit-scrollbar-thumb {
@@ -27,17 +28,17 @@
::-webkit-scrollbar {
@apply w-4;
@apply h-4;
@apply h-0;
}
.hide-scrollbar {
-ms-overflow-style: none;
scrollbar-width: none;
}
// .hide-scrollbar {
// -ms-overflow-style: none;
// scrollbar-width: none;
// }
.hide-scrollbar::-webkit-scrollbar {
@apply hidden;
}
// .hide-scrollbar::-webkit-scrollbar {
// @apply hidden;
// }
input::placeholder,
textarea::placeholder,

View File

@@ -255,6 +255,7 @@
--upper-mobile-raw-tertiary-sticky-fold: 8.188rem;
--lower-primary-sticky-fold: 3rem;
--lower-secondary-sticky-fold: 5rem;
--lower-tertiary-sticky-fold: 7.05rem;
--sidebar-primary-sticky-fold: 2rem;
}
@@ -270,6 +271,7 @@
--upper-mobile-raw-tertiary-sticky-fold: 8.938rem;
--lower-primary-sticky-fold: 3.25rem;
--lower-secondary-sticky-fold: 5.5rem;
--lower-tertiary-sticky-fold: 7.8rem;
--sidebar-primary-sticky-fold: 2.25rem;
}
@@ -285,6 +287,7 @@
--upper-mobile-raw-tertiary-sticky-fold: 9.688rem;
--lower-primary-sticky-fold: 3.5rem;
--lower-secondary-sticky-fold: 6rem;
--lower-tertiary-sticky-fold: 8.55rem;
--sidebar-primary-sticky-fold: 2.5rem;
}

View File

@@ -22,7 +22,7 @@
</template>
<script setup lang="ts">
import { ref } from "@nuxtjs/composition-api"
import { refAutoReset } from "@vueuse/core"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import {
useI18n,
@@ -45,7 +45,7 @@ const emit = defineEmits<{
(e: "hide-modal"): void
}>()
const copyIcon = ref("copy")
const copyIcon = refAutoReset<"copy" | "check">("copy", 1000)
// Copy user auth token to clipboard
const copyUserAuthToken = () => {
@@ -53,7 +53,6 @@ const copyUserAuthToken = () => {
copyToClipboard(userAuthToken.value)
copyIcon.value = "check"
toast.success(`${t("state.copied_to_clipboard")}`)
setTimeout(() => (copyIcon.value = "copy"), 1000)
} else {
toast.error(`${t("error.something_went_wrong")}`)
}

View File

@@ -1,7 +1,7 @@
<template>
<div>
<header
class="flex items-center justify-between flex-1 px-2 py-2 space-x-2"
class="flex items-center justify-between flex-1 px-2 py-2 space-x-2 overflow-x-auto"
>
<div class="inline-flex items-center space-x-2">
<ButtonSecondary

View File

@@ -8,11 +8,7 @@
{{ t("settings.interceptor_description") }}
</p>
</div>
<SmartRadioGroup
:radios="interceptors"
:selected="interceptorSelection"
@change="toggleSettingKey"
/>
<SmartRadioGroup v-model="interceptorSelection" :radios="interceptors" />
<div
v-if="interceptorSelection == 'EXTENSIONS_ENABLED' && !extensionVersion"
class="flex space-x-2"
@@ -38,58 +34,29 @@
</template>
<script setup lang="ts">
import { computed, ref, watchEffect } from "@nuxtjs/composition-api"
import { KeysMatching } from "~/types/ts-utils"
import {
applySetting,
SettingsType,
toggleSetting,
useSetting,
} from "~/newstore/settings"
import { hasExtensionInstalled } from "~/helpers/strategies/ExtensionStrategy"
import { useI18n, usePolled } from "~/helpers/utils/composables"
import { computed } from "@nuxtjs/composition-api"
import { applySetting, toggleSetting, useSetting } from "~/newstore/settings"
import { useI18n, useReadonlyStream } from "~/helpers/utils/composables"
import { extensionStatus$ } from "~/newstore/HoppExtension"
const t = useI18n()
const PROXY_ENABLED = useSetting("PROXY_ENABLED")
const EXTENSIONS_ENABLED = useSetting("EXTENSIONS_ENABLED")
const toggleSettingKey = <
K extends KeysMatching<SettingsType | "BROWSER_ENABLED", boolean>
>(
key: K
) => {
interceptorSelection.value = key
if (key === "EXTENSIONS_ENABLED") {
applySetting("EXTENSIONS_ENABLED", true)
if (PROXY_ENABLED.value) toggleSetting("PROXY_ENABLED")
}
if (key === "PROXY_ENABLED") {
applySetting("PROXY_ENABLED", true)
if (EXTENSIONS_ENABLED.value) toggleSetting("EXTENSIONS_ENABLED")
}
if (key === "BROWSER_ENABLED") {
applySetting("PROXY_ENABLED", false)
applySetting("EXTENSIONS_ENABLED", false)
}
}
const currentExtensionStatus = useReadonlyStream(extensionStatus$, null)
const extensionVersion = usePolled(5000, (stopPolling) => {
const result = hasExtensionInstalled()
? window.__POSTWOMAN_EXTENSION_HOOK__.getVersion()
const extensionVersion = computed(() => {
return currentExtensionStatus.value === "available"
? window.__POSTWOMAN_EXTENSION_HOOK__?.getVersion() ?? null
: null
// We don't need to poll anymore after we get value
if (result) stopPolling()
return result
})
const interceptors = computed(() => [
{ value: "BROWSER_ENABLED", label: t("state.none") },
{ value: "PROXY_ENABLED", label: t("settings.proxy") },
{ value: "BROWSER_ENABLED" as const, label: t("state.none") },
{ value: "PROXY_ENABLED" as const, label: t("settings.proxy") },
{
value: "EXTENSIONS_ENABLED",
value: "EXTENSIONS_ENABLED" as const,
label:
`${t("settings.extensions")}: ` +
(extensionVersion.value !== null
@@ -98,15 +65,27 @@ const interceptors = computed(() => [
},
])
const interceptorSelection = ref("")
type InterceptorMode = typeof interceptors["value"][number]["value"]
watchEffect(() => {
if (PROXY_ENABLED.value) {
interceptorSelection.value = "PROXY_ENABLED"
} else if (EXTENSIONS_ENABLED.value) {
interceptorSelection.value = "EXTENSIONS_ENABLED"
} else {
interceptorSelection.value = "BROWSER_ENABLED"
}
const interceptorSelection = computed<InterceptorMode>({
get() {
if (PROXY_ENABLED.value) return "PROXY_ENABLED"
if (EXTENSIONS_ENABLED.value) return "EXTENSIONS_ENABLED"
return "BROWSER_ENABLED"
},
set(val) {
if (val === "EXTENSIONS_ENABLED") {
applySetting("EXTENSIONS_ENABLED", true)
if (PROXY_ENABLED.value) toggleSetting("PROXY_ENABLED")
}
if (val === "PROXY_ENABLED") {
applySetting("PROXY_ENABLED", true)
if (EXTENSIONS_ENABLED.value) toggleSetting("EXTENSIONS_ENABLED")
}
if (val === "BROWSER_ENABLED") {
applySetting("PROXY_ENABLED", false)
applySetting("EXTENSIONS_ENABLED", false)
}
},
})
</script>

View File

@@ -28,7 +28,7 @@
</Splitpanes>
</Pane>
<Pane
v-if="SIDEBAR"
v-if="SIDEBAR && hasSidebar"
size="25"
min-size="20"
class="hide-scrollbar !overflow-auto flex flex-col"
@@ -42,6 +42,7 @@
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import { breakpointsTailwind, useBreakpoints } from "@vueuse/core"
import { computed, useSlots } from "@nuxtjs/composition-api"
import { useSetting } from "~/newstore/settings"
const SIDEBAR_ON_LEFT = useSetting("SIDEBAR_ON_LEFT")
@@ -52,4 +53,8 @@ const mdAndLarger = breakpoints.greater("md")
const COLUMN_LAYOUT = useSetting("COLUMN_LAYOUT")
const SIDEBAR = useSetting("SIDEBAR")
const slots = useSlots()
const hasSidebar = computed(() => !!slots.sidebar)
</script>

View File

@@ -36,7 +36,7 @@
</template>
<script setup lang="ts">
import { ref } from "@nuxtjs/composition-api"
import { refAutoReset } from "@vueuse/core"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import { useI18n, useToast } from "~/helpers/utils/composables"
@@ -60,7 +60,8 @@ const subject = "Checkout Hoppscotch - an open source API development ecosystem"
const summary = `Hi there!%0D%0A%0D%0AI thought you'll like this new platform that I joined called Hoppscotch - https://hoppscotch.io.%0D%0AIt is a simple and intuitive interface for creating and managing your APIs. You can build, test, document, and share your APIs.%0D%0A%0D%0AThe best part about Hoppscotch is that it is open source and free to get started.%0D%0A%0D%0A`
const twitter = "hoppscotch_io"
const copyIcon = ref("copy")
const copyIcon = refAutoReset<"copy" | "check">("copy", 1000)
const platforms = [
{
name: "Email",
@@ -93,7 +94,6 @@ const copyAppLink = () => {
copyToClipboard(url)
copyIcon.value = "check"
toast.success(`${t("state.copied_to_clipboard")}`)
setTimeout(() => (copyIcon.value = "copy"), 1000)
}
const hideModal = () => {

View File

@@ -7,6 +7,7 @@
:to="localePath(navigation.target)"
class="nav-link"
tabindex="0"
:exact="navigation.exact"
>
<div v-if="navigation.svg">
<SmartIcon :name="navigation.svg" class="svg-icons" />
@@ -40,26 +41,31 @@ const primaryNavigation = [
target: "index",
svg: "link-2",
title: t("navigation.rest"),
exact: true,
},
{
target: "graphql",
svg: "graphql",
title: t("navigation.graphql"),
exact: false,
},
{
target: "realtime",
svg: "globe",
title: t("navigation.realtime"),
exact: false,
},
{
target: "documentation",
svg: "book-open",
title: t("navigation.doc"),
exact: false,
},
{
target: "settings",
svg: "settings",
title: t("navigation.settings"),
exact: false,
},
]
</script>
@@ -105,6 +111,20 @@ const primaryNavigation = [
@apply text-tiny;
}
&.active-link {
@apply text-secondaryDark;
@apply bg-primaryLight;
@apply hover:text-secondaryDark;
.material-icons,
.svg-icons {
@apply opacity-100;
}
&::after {
@apply bg-accent;
}
}
&.exact-active-link {
@apply text-secondaryDark;
@apply bg-primaryLight;

View File

@@ -25,7 +25,6 @@
]"
:disabled="disabled"
:tabindex="loading ? '-1' : '0'"
:type="type"
role="button"
>
<span
@@ -67,79 +66,41 @@
</SmartLink>
</template>
<script lang="ts">
import { defineComponent } from "@nuxtjs/composition-api"
export default defineComponent({
props: {
to: {
type: String,
default: "",
},
exact: {
type: Boolean,
default: true,
},
blank: {
type: Boolean,
default: false,
},
label: {
type: String,
default: "",
},
icon: {
type: String,
default: "",
},
svg: {
type: String,
default: "",
},
color: {
type: String,
default: "",
},
disabled: {
type: Boolean,
default: false,
},
loading: {
type: Boolean,
default: false,
},
large: {
type: Boolean,
default: false,
},
shadow: {
type: Boolean,
default: false,
},
reverse: {
type: Boolean,
default: false,
},
rounded: {
type: Boolean,
default: false,
},
gradient: {
type: Boolean,
default: false,
},
outline: {
type: Boolean,
default: false,
},
shortcut: {
type: Array,
default: () => [],
},
type: {
type: String,
default: "button",
},
},
<script setup lang="ts">
interface Props {
to: string
exact: boolean
blank: boolean
label: string
icon: string
svg: string
color: string
disabled: boolean
loading: boolean
large: boolean
shadow: boolean
reverse: boolean
rounded: boolean
gradient: boolean
outline: boolean
shortcut: string[]
}
withDefaults(defineProps<Props>(), {
to: "",
exact: true,
blank: false,
label: "",
icon: "",
svg: "",
color: "",
disabled: false,
loading: false,
large: false,
shadow: false,
reverse: false,
rounded: false,
gradient: false,
outline: false,
shortcut: () => [],
})
</script>

View File

@@ -66,71 +66,39 @@
</SmartLink>
</template>
<script lang="ts">
import { defineComponent } from "@nuxtjs/composition-api"
export default defineComponent({
props: {
to: {
type: String,
default: "",
},
exact: {
type: Boolean,
default: true,
},
blank: {
type: Boolean,
default: false,
},
label: {
type: String,
default: "",
},
icon: {
type: String,
default: "",
},
svg: {
type: String,
default: "",
},
color: {
type: String,
default: "",
},
disabled: {
type: Boolean,
default: false,
},
loading: {
type: Boolean,
default: false,
},
reverse: {
type: Boolean,
default: false,
},
rounded: {
type: Boolean,
default: false,
},
large: {
type: Boolean,
default: false,
},
outline: {
type: Boolean,
default: false,
},
shortcut: {
type: Array,
default: () => [],
},
filled: {
type: Boolean,
default: false,
},
},
<script setup lang="ts">
interface Props {
to: string
exact: boolean
blank: boolean
label: string
icon: string
svg: string
color: string
disabled: boolean
loading: boolean
reverse: boolean
rounded: boolean
large: boolean
outline: boolean
shortcut: string[]
filled: boolean
}
withDefaults(defineProps<Props>(), {
to: "",
exact: true,
blank: false,
label: "",
icon: "",
svg: "",
color: "",
disabled: false,
loading: false,
reverse: false,
rounded: false,
large: false,
outline: false,
shortcut: () => [],
filled: false,
})
</script>

View File

@@ -26,6 +26,7 @@
<span>
<ButtonPrimary
:label="$t('action.save')"
:loading="loadingState"
@click.native="addNewCollection"
/>
<ButtonSecondary
@@ -43,6 +44,7 @@ import { defineComponent } from "@nuxtjs/composition-api"
export default defineComponent({
props: {
show: Boolean,
loadingState: Boolean,
},
data() {
return {
@@ -56,7 +58,6 @@ export default defineComponent({
return
}
this.$emit("submit", this.name)
this.hideModal()
},
hideModal() {
this.name = null

View File

@@ -24,7 +24,11 @@
</template>
<template #footer>
<span>
<ButtonPrimary :label="$t('action.save')" @click.native="addFolder" />
<ButtonPrimary
:label="$t('action.save')"
:loading="loadingState"
@click.native="addFolder"
/>
<ButtonSecondary
:label="$t('action.cancel')"
@click.native="hideModal"
@@ -43,6 +47,7 @@ export default defineComponent({
folder: { type: Object, default: () => {} },
folderPath: { type: String, default: null },
collectionIndex: { type: Number, default: null },
loadingState: Boolean,
},
data() {
return {
@@ -60,7 +65,6 @@ export default defineComponent({
folder: this.folder,
path: this.folderPath || `${this.collectionIndex}`,
})
this.hideModal()
},
hideModal() {
this.name = null

View File

@@ -0,0 +1,92 @@
<template>
<SmartModal
v-if="show"
dialog
:title="$t('request.new')"
@close="$emit('hide-modal')"
>
<template #body>
<div class="flex flex-col px-2">
<input
id="selectLabelAddRequest"
v-model="name"
v-focus
class="input floating-input"
placeholder=" "
type="text"
autocomplete="off"
@keyup.enter="addRequest"
/>
<label for="selectLabelAddRequest">{{ $t("action.label") }}</label>
</div>
</template>
<template #footer>
<span>
<ButtonPrimary
:label="$t('action.save')"
:loading="loadingState"
@click.native="addRequest"
/>
<ButtonSecondary
:label="$t('action.cancel')"
@click.native="hideModal"
/>
</span>
</template>
</SmartModal>
</template>
<script setup lang="ts">
import { ref, watch } from "@nuxtjs/composition-api"
import { useI18n, useToast } from "~/helpers/utils/composables"
import { getRESTRequest } from "~/newstore/RESTSession"
const toast = useToast()
const t = useI18n()
const props = defineProps<{
show: boolean
loadingState: boolean
folder?: object
folderPath?: string
}>()
const emit = defineEmits<{
(e: "hide-modal"): void
(
e: "add-request",
v: {
name: string
folder: object | undefined
path: string | undefined
}
): void
}>()
const name = ref("")
watch(
() => props.show,
(show) => {
if (show) {
name.value = getRESTRequest().name
}
}
)
const addRequest = () => {
if (!name.value) {
toast.error(`${t("error.empty_req_name")}`)
return
}
emit("add-request", {
name: name.value,
folder: props.folder,
path: props.folderPath,
})
}
const hideModal = () => {
emit("hide-modal")
}
</script>

View File

@@ -1,6 +1,10 @@
<template>
<div v-if="show">
<SmartTabs :id="'collections_tab'" v-model="selectedCollectionTab">
<SmartTabs
:id="'collections_tab'"
v-model="selectedCollectionTab"
render-inactive-tabs
>
<SmartTab
:id="'my-collections'"
:label="`${$t('collection.my_collections')}`"

View File

@@ -26,6 +26,7 @@
<span>
<ButtonPrimary
:label="$t('action.save')"
:loading="loadingState"
@click.native="saveCollection"
/>
<ButtonSecondary
@@ -44,6 +45,7 @@ export default defineComponent({
props: {
show: Boolean,
editingCollectionName: { type: String, default: null },
loadingState: Boolean,
},
data() {
return {
@@ -62,7 +64,6 @@ export default defineComponent({
return
}
this.$emit("submit", this.name)
this.hideModal()
},
hideModal() {
this.name = null

View File

@@ -24,7 +24,11 @@
</template>
<template #footer>
<span>
<ButtonPrimary :label="$t('action.save')" @click.native="editFolder" />
<ButtonPrimary
:label="$t('action.save')"
:loading="loadingState"
@click.native="editFolder"
/>
<ButtonSecondary
:label="$t('action.cancel')"
@click.native="hideModal"
@@ -41,6 +45,7 @@ export default defineComponent({
props: {
show: Boolean,
editingFolderName: { type: String, default: null },
loadingState: Boolean,
},
data() {
return {
@@ -59,7 +64,6 @@ export default defineComponent({
return
}
this.$emit("submit", this.name)
this.hideModal()
},
hideModal() {
this.name = null

View File

@@ -24,7 +24,11 @@
</template>
<template #footer>
<span>
<ButtonPrimary :label="$t('action.save')" @click.native="saveRequest" />
<ButtonPrimary
:label="$t('action.save')"
:loading="loadingState"
@click.native="saveRequest"
/>
<ButtonSecondary
:label="$t('action.cancel')"
@click.native="hideModal"
@@ -41,6 +45,7 @@ export default defineComponent({
props: {
show: Boolean,
editingRequestName: { type: String, default: null },
loadingState: Boolean,
},
data() {
return {
@@ -61,7 +66,6 @@ export default defineComponent({
return
}
this.$emit("submit", this.requestUpdateData)
this.hideModal()
},
hideModal() {
this.requestUpdateData = { name: null }

View File

@@ -244,7 +244,7 @@ const createCollectionGist = async () => {
return
}
getJSONCollection()
await getJSONCollection()
try {
const res = await axios.$post(
@@ -316,8 +316,8 @@ const importToTeams = async (content: HoppCollection<HoppRESTRequest>) => {
importingMyCollections.value = false
}
const exportJSON = () => {
getJSONCollection()
const exportJSON = async () => {
await getJSONCollection()
const dataToWrite = collectionJson.value
const file = new Blob([dataToWrite], { type: "application/json" })

View File

@@ -233,6 +233,7 @@ const saveRequestAs = async () => {
originLocation: "user-collection",
folderPath: picked.value.folderPath,
requestIndex: picked.value.requestIndex,
req: cloneDeep(requestUpdated),
})
requestSaved()
@@ -249,6 +250,7 @@ const saveRequestAs = async () => {
originLocation: "user-collection",
folderPath: picked.value.folderPath,
requestIndex: insertionIndex,
req: cloneDeep(requestUpdated),
})
requestSaved()
@@ -265,6 +267,7 @@ const saveRequestAs = async () => {
originLocation: "user-collection",
folderPath: `${picked.value.collectionIndex}`,
requestIndex: insertionIndex,
req: cloneDeep(requestUpdated),
})
requestSaved()
@@ -293,6 +296,7 @@ const saveRequestAs = async () => {
setRESTSaveContext({
originLocation: "team-collection",
requestID: picked.value.requestID,
req: cloneDeep(requestUpdated),
})
} else if (picked.value.pickedType === "teams-folder") {
if (!isHoppRESTRequest(requestUpdated))
@@ -319,6 +323,7 @@ const saveRequestAs = async () => {
requestID: result.right.createRequestInCollection.id,
teamID: collectionsType.value.selectedTeam.id,
collectionID: picked.value.folderID,
req: cloneDeep(requestUpdated),
})
requestSaved()
@@ -348,6 +353,7 @@ const saveRequestAs = async () => {
requestID: result.right.createRequestInCollection.id,
teamID: collectionsType.value.selectedTeam.id,
collectionID: picked.value.collectionID,
req: cloneDeep(requestUpdated),
})
requestSaved()

View File

@@ -50,12 +50,16 @@ export default defineComponent({
},
methods: {
addFolder() {
// TODO: Blocking when name is null ?
if (!this.name) {
this.$toast.error(`${this.$t("folder.name_length_insufficient")}`)
return
}
this.$emit("add-folder", {
name: this.name,
path: this.folderPath || `${this.collectionIndex}`,
})
this.hideModal()
},
hideModal() {

View File

@@ -0,0 +1,87 @@
<template>
<SmartModal
v-if="show"
dialog
:title="$t('request.new')"
@close="$emit('hide-modal')"
>
<template #body>
<div class="flex flex-col px-2">
<input
id="selectLabelGqlAddRequest"
v-model="name"
v-focus
class="input floating-input"
placeholder=" "
type="text"
autocomplete="off"
@keyup.enter="addRequest"
/>
<label for="selectLabelGqlAddRequest">
{{ $t("action.label") }}
</label>
</div>
</template>
<template #footer>
<span>
<ButtonPrimary :label="$t('action.save')" @click.native="addRequest" />
<ButtonSecondary
:label="$t('action.cancel')"
@click.native="hideModal"
/>
</span>
</template>
</SmartModal>
</template>
<script setup lang="ts">
import { ref, watch } from "@nuxtjs/composition-api"
import { useI18n, useToast } from "~/helpers/utils/composables"
import { getGQLSession } from "~/newstore/GQLSession"
const toast = useToast()
const t = useI18n()
const props = defineProps<{
show: boolean
folderPath?: string
}>()
const emit = defineEmits<{
(e: "hide-modal"): void
(
e: "add-request",
v: {
name: string
path: string | undefined
}
): void
}>()
const name = ref("")
watch(
() => props.show,
(show) => {
if (show) {
name.value = getGQLSession().request.name
}
}
)
const addRequest = () => {
if (!name.value) {
toast.error(`${t("error.empty_req_name")}`)
return
}
emit("add-request", {
name: name.value,
path: props.folderPath,
})
hideModal()
}
const hideModal = () => {
emit("hide-modal")
}
</script>

View File

@@ -29,6 +29,17 @@
</span>
</span>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
svg="file-plus"
:title="$t('request.new')"
class="hidden group-hover:inline-flex"
@click.native="
$emit('add-request', {
path: `${collectionIndex}`,
})
"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
svg="folder-plus"
@@ -61,11 +72,26 @@
class="flex flex-col focus:outline-none"
tabindex="0"
role="menu"
@keyup.r="requestAction.$el.click()"
@keyup.n="folderAction.$el.click()"
@keyup.e="edit.$el.click()"
@keyup.delete="deleteAction.$el.click()"
@keyup.escape="options.tippy().hide()"
>
<SmartItem
ref="requestAction"
svg="file-plus"
:label="`${$t('request.new')}`"
:shortcut="['R']"
@click.native="
() => {
$emit('add-request', {
path: `${collectionIndex}`,
})
options.tippy().hide()
}
"
/>
<SmartItem
ref="folderAction"
svg="folder-plus"
@@ -126,6 +152,7 @@
:collection-index="collectionIndex"
:doc="doc"
:is-filtered="isFiltered"
@add-request="$emit('add-request', $event)"
@add-folder="$emit('add-folder', $event)"
@edit-folder="$emit('edit-folder', $event)"
@edit-request="$emit('edit-request', $event)"
@@ -196,6 +223,7 @@ export default defineComponent({
return {
tippyActions: ref<any | null>(null),
options: ref<any | null>(null),
requestAction: ref<any | null>(null),
folderAction: ref<any | null>(null),
edit: ref<any | null>(null),
deleteAction: ref<any | null>(null),

View File

@@ -29,6 +29,13 @@
</span>
</span>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
svg="file-plus"
:title="$t('request.new')"
class="hidden group-hover:inline-flex"
@click.native="$emit('add-request', { path: folderPath })"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
svg="folder-plus"
@@ -57,11 +64,24 @@
class="flex flex-col focus:outline-none"
tabindex="0"
role="menu"
@keyup.r="requestAction.$el.click()"
@keyup.n="folderAction.$el.click()"
@keyup.e="edit.$el.click()"
@keyup.delete="deleteAction.$el.click()"
@keyup.escape="options.tippy().hide()"
>
<SmartItem
ref="requestAction"
svg="file-plus"
:label="`${$t('request.new')}`"
:shortcut="['R']"
@click.native="
() => {
$emit('add-request', { path: folderPath })
options.tippy().hide()
}
"
/>
<SmartItem
ref="folderAction"
svg="folder-plus"
@@ -120,6 +140,7 @@
:collection-index="collectionIndex"
:doc="doc"
:is-filtered="isFiltered"
@add-request="$emit('add-request', $event)"
@add-folder="$emit('add-folder', $event)"
@edit-folder="$emit('edit-folder', $event)"
@edit-request="$emit('edit-request', $event)"
@@ -193,6 +214,7 @@ export default defineComponent({
return {
tippyActions: ref<any | null>(null),
options: ref<any | null>(null),
requestAction: ref<any | null>(null),
folderAction: ref<any | null>(null),
edit: ref<any | null>(null),
deleteAction: ref<any | null>(null),

View File

@@ -49,6 +49,7 @@
:is-filtered="filterText.length > 0"
:saving-mode="savingMode"
@edit-collection="editCollection(collection, index)"
@add-request="addRequest($event)"
@add-folder="addFolder($event)"
@edit-folder="editFolder($event)"
@edit-request="editRequest($event)"
@@ -96,6 +97,12 @@
:editing-collection-name="editingCollection ? editingCollection.name : ''"
@hide-modal="displayModalEdit(false)"
/>
<CollectionsGraphqlAddRequest
:show="showModalAddRequest"
:folder-path="editingFolderPath"
@add-request="onAddRequest($event)"
@hide-modal="displayModalAddRequest(false)"
/>
<CollectionsGraphqlAddFolder
:show="showModalAddFolder"
:folder-path="editingFolderPath"
@@ -136,6 +143,7 @@ import {
addGraphqlFolder,
saveGraphqlRequestAs,
} from "~/newstore/collections"
import { getGQLSession, setGQLSession } from "~/newstore/GQLSession"
export default defineComponent({
props: {
@@ -156,6 +164,7 @@ export default defineComponent({
showModalAdd: false,
showModalEdit: false,
showModalImportExport: false,
showModalAddRequest: false,
showModalAddFolder: false,
showModalEditFolder: false,
showModalEditRequest: false,
@@ -222,6 +231,11 @@ export default defineComponent({
displayModalImportExport(shouldDisplay) {
this.showModalImportExport = shouldDisplay
},
displayModalAddRequest(shouldDisplay) {
this.showModalAddRequest = shouldDisplay
if (!shouldDisplay) this.resetSelectedData()
},
displayModalAddFolder(shouldDisplay) {
this.showModalAddFolder = shouldDisplay
@@ -242,6 +256,26 @@ export default defineComponent({
this.$data.editingCollectionIndex = collectionIndex
this.displayModalEdit(true)
},
onAddRequest({ name, path }) {
const newRequest = {
...getGQLSession().request,
name,
}
saveGraphqlRequestAs(path, newRequest)
setGQLSession({
request: newRequest,
schema: "",
response: "",
})
this.displayModalAddRequest(false)
},
addRequest(payload) {
const { path } = payload
this.$data.editingFolderPath = path
this.displayModalAddRequest(true)
},
onAddFolder({ name, path }) {
addGraphqlFolder(name, path)
this.displayModalAddFolder(false)

View File

@@ -82,6 +82,7 @@
:picked="picked"
:loading-collection-i-ds="loadingCollectionIDs"
@edit-collection="editCollection(collection, index)"
@add-request="addRequest($event)"
@add-folder="addFolder($event)"
@edit-folder="editFolder($event)"
@edit-request="editRequest($event)"
@@ -93,6 +94,7 @@
@expand-collection="expandCollection"
@remove-collection="removeCollection"
@remove-request="removeRequest"
@remove-folder="removeFolder"
/>
</div>
<div
@@ -146,6 +148,7 @@
</div>
<CollectionsAdd
:show="showModalAdd"
:loading-state="modalLoadingState"
@submit="addNewRootCollection"
@hide-modal="displayModalAdd(false)"
/>
@@ -156,13 +159,23 @@
? editingCollection.name || editingCollection.title
: ''
"
:loading-state="modalLoadingState"
@hide-modal="displayModalEdit(false)"
@submit="updateEditingCollection"
/>
<CollectionsAddRequest
:show="showModalAddRequest"
:folder="editingFolder"
:folder-path="editingFolderPath"
:loading-state="modalLoadingState"
@add-request="onAddRequest($event)"
@hide-modal="displayModalAddRequest(false)"
/>
<CollectionsAddFolder
:show="showModalAddFolder"
:folder="editingFolder"
:folder-path="editingFolderPath"
:loading-state="modalLoadingState"
@add-folder="onAddFolder($event)"
@hide-modal="displayModalAddFolder(false)"
/>
@@ -171,12 +184,14 @@
:editing-folder-name="
editingFolder ? editingFolder.name || editingFolder.title : ''
"
:loading-state="modalLoadingState"
@submit="updateEditingFolder"
@hide-modal="displayModalEditFolder(false)"
/>
<CollectionsEditRequest
:show="showModalEditRequest"
:editing-request-name="editingRequest ? editingRequest.name : ''"
:loading-state="modalLoadingState"
@submit="updateEditingRequest"
@hide-modal="displayModalEditRequest(false)"
/>
@@ -186,6 +201,13 @@
@hide-modal="displayModalImportExport(false)"
@update-team-collections="updateTeamCollections"
/>
<SmartConfirmModal
:show="showConfirmModal"
:title="confirmModalTitle"
:loading-state="modalLoadingState"
@hide-modal="showConfirmModal = false"
@resolve="resolveConfirmModal"
/>
</div>
</template>
@@ -204,11 +226,17 @@ import {
editRESTCollection,
addRESTFolder,
removeRESTCollection,
removeRESTFolder,
editRESTFolder,
removeRESTRequest,
editRESTRequest,
saveRESTRequestAs,
} from "~/newstore/collections"
import {
setRESTRequest,
getRESTRequest,
getRESTSaveContext,
} from "~/newstore/RESTSession"
import {
useReadonlyStream,
useStreamSubscriber,
@@ -250,17 +278,22 @@ export default defineComponent({
showModalAdd: false,
showModalEdit: false,
showModalImportExport: false,
showModalAddRequest: false,
showModalAddFolder: false,
showModalEditFolder: false,
showModalEditRequest: false,
showConfirmModal: false,
modalLoadingState: false,
editingCollection: undefined,
editingCollectionIndex: undefined,
editingCollectionID: undefined,
editingFolder: undefined,
editingFolderName: undefined,
editingFolderIndex: undefined,
editingFolderPath: undefined,
editingRequest: undefined,
editingRequestIndex: undefined,
confirmModalTitle: undefined,
filterText: "",
collectionsType: {
type: "my-collections",
@@ -375,14 +408,18 @@ export default defineComponent({
requests: [],
})
)
this.displayModalAdd(false)
} else if (
this.collectionsType.type === "team-collections" &&
this.collectionsType.selectedTeam.myRole !== "VIEWER"
) {
this.modalLoadingState = true
runMutation(CreateNewRootCollectionDocument, {
title: name,
teamID: this.collectionsType.selectedTeam.id,
})().then((result) => {
this.modalLoadingState = false
if (E.isLeft(result)) {
if (result.left.error === "team_coll/short_title")
this.$toast.error(this.$t("collection.name_length_insufficient"))
@@ -390,10 +427,10 @@ export default defineComponent({
console.error(result.left.error)
} else {
this.$toast.success(this.$t("collection.created"))
this.displayModalAdd(false)
}
})
}
this.displayModalAdd(false)
},
// Intented to be called by CollectionEdit modal submit event
updateEditingCollection(newName) {
@@ -408,66 +445,107 @@ export default defineComponent({
}
editRESTCollection(this.editingCollectionIndex, collectionUpdated)
this.displayModalEdit(false)
} else if (
this.collectionsType.type === "team-collections" &&
this.collectionsType.selectedTeam.myRole !== "VIEWER"
) {
this.modalLoadingState = true
runMutation(RenameCollectionDocument, {
collectionID: this.editingCollection.id,
newTitle: newName,
})().then((result) => {
this.modalLoadingState = false
if (E.isLeft(result)) {
this.$toast.error(this.$t("error.something_went_wrong"))
console.error(e)
console.error(result.left.error)
} else {
this.$toast.success(this.$t("collection.renamed"))
this.displayModalEdit(false)
}
})
}
this.displayModalEdit(false)
},
// Intended to be called by CollectionEditFolder modal submit event
updateEditingFolder(name) {
if (this.collectionsType.type === "my-collections") {
editRESTFolder(this.editingFolderPath, { ...this.editingFolder, name })
this.displayModalEditFolder(false)
} else if (
this.collectionsType.type === "team-collections" &&
this.collectionsType.selectedTeam.myRole !== "VIEWER"
) {
this.modalLoadingState = true
runMutation(RenameCollectionDocument, {
collectionID: this.editingFolder.id,
newTitle: name,
})().then((result) => {
this.modalLoadingState = false
if (E.isLeft(result)) {
this.$toast.error(this.$t("error.something_went_wrong"))
console.error(e)
if (result.left.error === "team_coll/short_title")
this.$toast.error(this.$t("folder.name_length_insufficient"))
else this.$toast.error(this.$t("error.something_went_wrong"))
console.error(result.left.error)
} else {
this.$toast.success(this.$t("folder.renamed"))
this.displayModalEditFolder(false)
}
})
}
this.displayModalEditFolder(false)
},
// Intented to by called by CollectionsEditRequest modal submit event
updateEditingRequest(requestUpdateData) {
const saveCtx = getRESTSaveContext()
const requestUpdated = {
...this.editingRequest,
name: requestUpdateData.name || this.editingRequest.name,
}
if (this.collectionsType.type === "my-collections") {
// Update REST Session with the updated state
if (
saveCtx &&
saveCtx.originLocation === "user-collection" &&
saveCtx.requestIndex === this.editingRequestIndex &&
saveCtx.folderPath === this.editingFolderPath
) {
setRESTRequest({
...getRESTRequest(),
name: requestUpdateData.name,
})
}
editRESTRequest(
this.editingFolderPath,
this.editingRequestIndex,
requestUpdated
)
this.displayModalEditRequest(false)
} else if (
this.collectionsType.type === "team-collections" &&
this.collectionsType.selectedTeam.myRole !== "VIEWER"
) {
this.modalLoadingState = true
const requestName = requestUpdateData.name || this.editingRequest.name
// Update REST Session with the updated state
if (
saveCtx &&
saveCtx.originLocation === "team-collection" &&
saveCtx.requestID === this.editingRequestIndex
) {
setRESTRequest({
...getRESTRequest(),
name: requestUpdateData.name,
})
}
runMutation(UpdateRequestDocument, {
data: {
request: JSON.stringify(requestUpdated),
@@ -475,17 +553,18 @@ export default defineComponent({
},
requestID: this.editingRequestIndex,
})().then((result) => {
this.modalLoadingState = false
if (E.isLeft(result)) {
this.$toast.error(this.$t("error.something_went_wrong"))
console.error(e)
console.error(result.left.error)
} else {
this.$toast.success(this.$t("request.renamed"))
this.$emit("update-team-collections")
this.displayModalEditRequest(false)
}
})
}
this.displayModalEditRequest(false)
},
displayModalAdd(shouldDisplay) {
this.showModalAdd = shouldDisplay
@@ -498,6 +577,11 @@ export default defineComponent({
displayModalImportExport(shouldDisplay) {
this.showModalImportExport = shouldDisplay
},
displayModalAddRequest(shouldDisplay) {
this.showModalAddRequest = shouldDisplay
if (!shouldDisplay) this.resetSelectedData()
},
displayModalAddFolder(shouldDisplay) {
this.showModalAddFolder = shouldDisplay
@@ -513,6 +597,11 @@ export default defineComponent({
if (!shouldDisplay) this.resetSelectedData()
},
displayConfirmModal(shouldDisplay) {
this.showConfirmModal = shouldDisplay
if (!shouldDisplay) this.resetSelectedData()
},
editCollection(collection, collectionIndex) {
this.$data.editingCollection = collection
this.$data.editingCollectionIndex = collectionIndex
@@ -521,26 +610,29 @@ export default defineComponent({
onAddFolder({ name, folder, path }) {
if (this.collectionsType.type === "my-collections") {
addRESTFolder(name, path)
} else if (this.collectionsType.type === "team-collections") {
if (this.collectionsType.selectedTeam.myRole !== "VIEWER") {
runMutation(CreateChildCollectionDocument, {
childTitle: name,
collectionID: folder.id,
})().then((result) => {
if (E.isLeft(result)) {
if (result.left.error === "team_coll/short_title")
this.$toast.error(this.$t("folder.name_length_insufficient"))
else this.$toast.error(this.$t("error.something_went_wrong"))
console.error(result.left.error)
} else {
this.$toast.success(this.$t("folder.created"))
this.$emit("update-team-collections")
}
})
}
this.displayModalAddFolder(false)
} else if (
this.collectionsType.type === "team-collections" &&
this.collectionsType.selectedTeam.myRole !== "VIEWER"
) {
this.modalLoadingState = true
runMutation(CreateChildCollectionDocument, {
childTitle: name,
collectionID: folder.id,
})().then((result) => {
this.modalLoadingState = false
if (E.isLeft(result)) {
if (result.left.error === "team_coll/short_title")
this.$toast.error(this.$t("folder.name_length_insufficient"))
else this.$toast.error(this.$t("error.something_went_wrong"))
console.error(result.left.error)
} else {
this.$toast.success(this.$t("folder.created"))
this.displayModalAddFolder(false)
this.$emit("update-team-collections")
}
})
}
this.displayModalAddFolder(false)
},
addFolder(payload) {
const { folder, path } = payload
@@ -578,16 +670,30 @@ export default defineComponent({
resetSelectedData() {
this.$data.editingCollection = undefined
this.$data.editingCollectionIndex = undefined
this.$data.editingCollectionID = undefined
this.$data.editingFolder = undefined
this.$data.editingFolderPath = undefined
this.$data.editingFolderIndex = undefined
this.$data.editingRequest = undefined
this.$data.editingRequestIndex = undefined
this.$data.confirmModalTitle = undefined
},
expandCollection(collectionID) {
this.teamCollectionAdapter.expandCollection(collectionID)
},
removeCollection({ collectionsType, collectionIndex, collectionID }) {
if (collectionsType.type === "my-collections") {
removeCollection({ collectionIndex, collectionID }) {
this.$data.editingCollectionIndex = collectionIndex
this.$data.editingCollectionID = collectionID
this.confirmModalTitle = `${this.$t("confirm.remove_collection")}`
this.displayConfirmModal(true)
},
onRemoveCollection() {
const collectionIndex = this.$data.editingCollectionIndex
const collectionID = this.$data.editingCollectionID
if (this.collectionsType.type === "my-collections") {
// Cancel pick if picked collection is deleted
if (
this.picked &&
@@ -598,8 +704,12 @@ export default defineComponent({
}
removeRESTCollection(collectionIndex)
this.$toast.success(this.$t("state.deleted"))
} else if (collectionsType.type === "team-collections") {
this.displayConfirmModal(false)
} else if (this.collectionsType.type === "team-collections") {
this.modalLoadingState = true
// Cancel pick if picked collection is deleted
if (
this.picked &&
@@ -609,21 +719,89 @@ export default defineComponent({
this.$emit("select", { picked: null })
}
if (collectionsType.selectedTeam.myRole !== "VIEWER") {
if (this.collectionsType.selectedTeam.myRole !== "VIEWER") {
runMutation(DeleteCollectionDocument, {
collectionID,
})().then((result) => {
this.modalLoadingState = false
if (E.isLeft(result)) {
this.$toast.error(this.$t("error.something_went_wrong"))
console.error(e)
console.error(result.left.error)
} else {
this.$toast.success(this.$t("state.deleted"))
this.displayConfirmModal(false)
}
})
}
}
},
removeFolder({ collectionID, folder, folderPath }) {
this.$data.editingCollectionID = collectionID
this.$data.editingFolder = folder
this.$data.editingFolderPath = folderPath
this.confirmModalTitle = `${this.$t("confirm.remove_folder")}`
this.displayConfirmModal(true)
},
onRemoveFolder() {
const folder = this.$data.editingFolder
const folderPath = this.$data.editingFolderPath
if (this.collectionsType.type === "my-collections") {
// Cancel pick if picked folder was deleted
if (
this.picked &&
this.picked.pickedType === "my-folder" &&
this.picked.folderPath === folderPath
) {
this.$emit("select", { picked: null })
}
removeRESTFolder(folderPath)
this.$toast.success(this.$t("state.deleted"))
this.displayConfirmModal(false)
} else if (this.collectionsType.type === "team-collections") {
this.modalLoadingState = true
// Cancel pick if picked collection folder was deleted
if (
this.picked &&
this.picked.pickedType === "teams-folder" &&
this.picked.folderID === folder.id
) {
this.$emit("select", { picked: null })
}
if (this.collectionsType.selectedTeam.myRole !== "VIEWER") {
runMutation(DeleteCollectionDocument, {
collectionID: folder.id,
})().then((result) => {
this.modalLoadingState = false
if (E.isLeft(result)) {
this.$toast.error(`${this.$t("error.something_went_wrong")}`)
console.error(result.left.error)
} else {
this.$toast.success(`${this.$t("state.deleted")}`)
this.displayConfirmModal(false)
this.updateTeamCollections()
}
})
}
}
},
removeRequest({ requestIndex, folderPath }) {
this.$data.editingRequestIndex = requestIndex
this.$data.editingFolderPath = folderPath
this.confirmModalTitle = `${this.$t("confirm.remove_request")}`
this.displayConfirmModal(true)
},
onRemoveRequest() {
const requestIndex = this.$data.editingRequestIndex
const folderPath = this.$data.editingFolderPath
if (this.collectionsType.type === "my-collections") {
// Cancel pick if the picked item is being deleted
if (
@@ -635,8 +813,11 @@ export default defineComponent({
this.$emit("select", { picked: null })
}
removeRESTRequest(folderPath, requestIndex)
this.$toast.success(this.$t("state.deleted"))
this.displayConfirmModal(false)
} else if (this.collectionsType.type === "team-collections") {
this.modalLoadingState = true
// Cancel pick if the picked item is being deleted
if (
this.picked &&
@@ -649,11 +830,68 @@ export default defineComponent({
runMutation(DeleteRequestDocument, {
requestID: requestIndex,
})().then((result) => {
this.modalLoadingState = false
if (E.isLeft(result)) {
this.$toast.error(this.$t("error.something_went_wrong"))
console.error(e)
console.error(result.left.error)
} else {
this.$toast.success(this.$t("state.deleted"))
this.displayConfirmModal(false)
}
})
}
},
addRequest(payload) {
// TODO: check if the request being worked on
// is being overwritten (selected or not)
const { folder, path } = payload
this.$data.editingFolder = folder
this.$data.editingFolderPath = path
this.displayModalAddRequest(true)
},
onAddRequest({ name, folder, path }) {
const newRequest = {
...cloneDeep(getRESTRequest()),
name,
}
if (this.collectionsType.type === "my-collections") {
const insertionIndex = saveRESTRequestAs(path, newRequest)
// point to it
setRESTRequest(newRequest, {
originLocation: "user-collection",
folderPath: path,
requestIndex: insertionIndex,
})
this.displayModalAddRequest(false)
} else if (
this.collectionsType.type === "team-collections" &&
this.collectionsType.selectedTeam.myRole !== "VIEWER"
) {
this.modalLoadingState = true
runMutation(CreateRequestInCollectionDocument, {
collectionID: folder.id,
data: {
request: JSON.stringify(newRequest),
teamID: this.collectionsType.selectedTeam.id,
title: name,
},
})().then((result) => {
this.modalLoadingState = false
if (E.isLeft(result)) {
this.$toast.error(this.$t("error.something_went_wrong"))
console.error(result.left.error)
} else {
const { createRequestInCollection } = result.right
// point to it
setRESTRequest(newRequest, {
originLocation: "team-collection",
requestID: createRequestInCollection.id,
collectionID: createRequestInCollection.collection.id,
teamID: createRequestInCollection.collection.team.id,
})
this.displayModalAddRequest(false)
}
})
}
@@ -681,6 +919,22 @@ export default defineComponent({
})
}
},
resolveConfirmModal(title) {
if (title === `${this.$t("confirm.remove_collection")}`)
this.onRemoveCollection()
else if (title === `${this.$t("confirm.remove_request")}`)
this.onRemoveRequest()
else if (title === `${this.$t("confirm.remove_folder")}`)
this.onRemoveFolder()
else {
console.error(
`Confirm modal title ${title} is not handled by the component`
)
this.$toast.error(this.$t("error.something_went_wrong"))
this.displayConfirmModal(false)
}
},
},
})
// request inside folder is not being deleted, you dumb fuck
</script>

View File

@@ -45,6 +45,18 @@
color="green"
@click.native="$emit('unselect-collection')"
/>
<ButtonSecondary
v-if="!doc"
v-tippy="{ theme: 'tooltip' }"
svg="file-plus"
:title="$t('request.new')"
class="hidden group-hover:inline-flex"
@click.native="
$emit('add-request', {
path: `${collectionIndex}`,
})
"
/>
<ButtonSecondary
v-if="!doc"
v-tippy="{ theme: 'tooltip' }"
@@ -79,12 +91,27 @@
class="flex flex-col focus:outline-none"
tabindex="0"
role="menu"
@keyup.r="requestAction.$el.click()"
@keyup.n="folderAction.$el.click()"
@keyup.e="edit.$el.click()"
@keyup.delete="deleteAction.$el.click()"
@keyup.x="exportAction.$el.click()"
@keyup.escape="options.tippy().hide()"
>
<SmartItem
ref="requestAction"
svg="file-plus"
:label="$t('request.new')"
:shortcut="['R']"
@click.native="
() => {
$emit('add-request', {
path: `${collectionIndex}`,
})
options.tippy().hide()
}
"
/>
<SmartItem
ref="folderAction"
svg="folder-plus"
@@ -131,7 +158,7 @@
:shortcut="['⌫']"
@click.native="
() => {
confirmRemove = true
removeCollection()
options.tippy().hide()
}
"
@@ -159,12 +186,14 @@
:collections-type="collectionsType"
:is-filtered="isFiltered"
:picked="picked"
@add-request="$emit('add-request', $event)"
@add-folder="$emit('add-folder', $event)"
@edit-folder="$emit('edit-folder', $event)"
@edit-request="$emit('edit-request', $event)"
@duplicate-request="$emit('duplicate-request', $event)"
@select="$emit('select', $event)"
@remove-request="$emit('remove-request', $event)"
@remove-folder="$emit('remove-folder', $event)"
/>
<CollectionsMyRequest
v-for="(request, index) in collection.requests"
@@ -205,12 +234,6 @@
</div>
</div>
</div>
<SmartConfirmModal
:show="confirmRemove"
:title="$t('confirm.remove_collection')"
@hide-modal="confirmRemove = false"
@resolve="removeCollection"
/>
</div>
</template>
@@ -233,6 +256,7 @@ export default defineComponent({
return {
tippyActions: ref<any | null>(null),
options: ref<any | null>(null),
requestAction: ref<any | null>(null),
folderAction: ref<any | null>(null),
edit: ref<any | null>(null),
deleteAction: ref<any | null>(null),
@@ -244,7 +268,6 @@ export default defineComponent({
showChildren: false,
dragging: false,
selectedFolder: {},
confirmRemove: false,
prevCursor: "",
cursor: "",
pageNo: 0,
@@ -297,7 +320,6 @@ export default defineComponent({
},
removeCollection() {
this.$emit("remove-collection", {
collectionsType: this.collectionsType,
collectionIndex: this.collectionIndex,
collectionID: this.collection.id,
})

View File

@@ -29,6 +29,13 @@
</span>
</span>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
svg="file-plus"
:title="t('request.new')"
class="hidden group-hover:inline-flex"
@click.native="$emit('add-request', { path: folderPath })"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
svg="folder-plus"
@@ -57,12 +64,25 @@
class="flex flex-col focus:outline-none"
tabindex="0"
role="menu"
@keyup.r="requestAction.$el.click()"
@keyup.n="folderAction.$el.click()"
@keyup.e="edit.$el.click()"
@keyup.delete="deleteAction.$el.click()"
@keyup.x="exportAction.$el.click()"
@keyup.escape="options.tippy().hide()"
>
<SmartItem
ref="requestAction"
svg="file-plus"
:label="$t('request.new')"
:shortcut="['R']"
@click.native="
() => {
$emit('add-request', { path: folderPath })
options.tippy().hide()
}
"
/>
<SmartItem
ref="folderAction"
svg="folder-plus"
@@ -111,7 +131,7 @@
:shortcut="['⌫']"
@click.native="
() => {
confirmRemove = true
removeFolder()
options.tippy().hide()
}
"
@@ -138,13 +158,15 @@
:collections-type="collectionsType"
:folder-path="`${folderPath}/${subFolderIndex}`"
:picked="picked"
@add-request="$emit('add-request', $event)"
@add-folder="$emit('add-folder', $event)"
@edit-folder="$emit('edit-folder', $event)"
@edit-request="$emit('edit-request', $event)"
@duplicate-request="$emit('duplicate-request', $event)"
@update-team-collections="$emit('update-team-collections')"
@select="$emit('select', $event)"
@remove-request="removeRequest"
@remove-request="$emit('remove-request', $event)"
@remove-folder="$emit('remove-folder', $event)"
/>
<CollectionsMyRequest
v-for="(request, index) in folder.requests"
@@ -162,7 +184,7 @@
@edit-request="$emit('edit-request', $event)"
@duplicate-request="$emit('duplicate-request', $event)"
@select="$emit('select', $event)"
@remove-request="removeRequest"
@remove-request="$emit('remove-request', $event)"
/>
<div
v-if="
@@ -185,23 +207,13 @@
</div>
</div>
</div>
<SmartConfirmModal
:show="confirmRemove"
:title="t('confirm.remove_folder')"
@hide-modal="confirmRemove = false"
@resolve="removeFolder"
/>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "@nuxtjs/composition-api"
import { useI18n } from "~/helpers/utils/composables"
import {
removeRESTFolder,
removeRESTRequest,
moveRESTRequest,
} from "~/newstore/collections"
import { moveRESTRequest } from "~/newstore/collections"
export default defineComponent({
name: "Folder",
@@ -222,6 +234,7 @@ export default defineComponent({
return {
tippyActions: ref<any | null>(null),
options: ref<any | null>(null),
requestAction: ref<any | null>(null),
folderAction: ref<any | null>(null),
edit: ref<any | null>(null),
deleteAction: ref<any | null>(null),
@@ -233,7 +246,6 @@ export default defineComponent({
return {
showChildren: false,
dragging: false,
confirmRemove: false,
prevCursor: "",
cursor: "",
}
@@ -284,17 +296,10 @@ export default defineComponent({
this.showChildren = !this.showChildren
},
removeFolder() {
// TODO: Bubble it up ?
// Cancel pick if picked folder was deleted
if (
this.picked &&
this.picked.pickedType === "my-folder" &&
this.picked.folderPath === this.folderPath
) {
this.$emit("select", { picked: null })
}
removeRESTFolder(this.folderPath)
this.$toast.success(`${this.$t("state.deleted")}`)
this.$emit("remove-folder", {
folder: this.folder,
folderPath: this.folderPath,
})
},
dropEvent({ dataTransfer }) {
this.dragging = !this.dragging
@@ -302,19 +307,6 @@ export default defineComponent({
const requestIndex = dataTransfer.getData("requestIndex")
moveRESTRequest(folderPath, requestIndex, this.folderPath)
},
removeRequest({ requestIndex }) {
// TODO: Bubble it up to root ?
// Cancel pick if the picked item is being deleted
if (
this.picked &&
this.picked.pickedType === "my-request" &&
this.picked.folderPath === this.folderPath &&
this.picked.requestIndex === requestIndex
) {
this.$emit("select", { picked: null })
}
removeRESTRequest(this.folderPath, requestIndex)
},
},
})
</script>

View File

@@ -32,15 +32,10 @@
{{ request.name }}
</span>
<span
v-if="
active &&
active.originLocation === 'user-collection' &&
active.folderPath === folderPath &&
active.requestIndex === requestIndex
"
v-if="isActive"
v-tippy="{ theme: 'tooltip' }"
class="relative h-1.5 w-1.5 flex flex-shrink-0 mx-3"
:title="`${$t('collection.request_in_use')}`"
:title="`${t('collection.request_in_use')}`"
>
<span
class="absolute inline-flex flex-shrink-0 w-full h-full bg-green-500 rounded-full opacity-75 animate-ping"
@@ -56,7 +51,7 @@
v-if="!saveRequest && !doc"
v-tippy="{ theme: 'tooltip' }"
svg="rotate-ccw"
:title="$t('action.restore')"
:title="t('action.restore')"
class="hidden group-hover:inline-flex"
@click.native="!doc ? selectRequest() : {}"
/>
@@ -72,7 +67,7 @@
<template #trigger>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.more')"
:title="t('action.more')"
svg="more-vertical"
/>
</template>
@@ -89,11 +84,11 @@
<SmartItem
ref="edit"
svg="edit"
:label="$t('action.edit')"
:label="t('action.edit')"
:shortcut="['E']"
@click.native="
() => {
$emit('edit-request', {
emit('edit-request', {
collectionIndex,
folderIndex,
folderName,
@@ -112,7 +107,7 @@
:shortcut="['D']"
@click.native="
() => {
$emit('duplicate-request', {
emit('duplicate-request', {
collectionIndex,
folderIndex,
folderName,
@@ -127,11 +122,11 @@
<SmartItem
ref="deleteAction"
svg="trash-2"
:label="$t('action.delete')"
:label="t('action.delete')"
:shortcut="['⌫']"
@click.native="
() => {
confirmRemove = true
removeRequest()
options.tippy().hide()
}
"
@@ -141,131 +136,290 @@
</span>
</div>
</div>
<SmartConfirmModal
:show="confirmRemove"
:title="$t('confirm.remove_request')"
@hide-modal="confirmRemove = false"
@resolve="removeRequest"
<HttpReqChangeConfirmModal
:show="confirmChange"
@hide-modal="confirmChange = false"
@save-change="saveRequestChange"
@discard-change="discardRequestChange"
/>
<CollectionsSaveRequest
mode="rest"
:show="showSaveRequestModal"
@hide-modal="showSaveRequestModal = false"
/>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "@nuxtjs/composition-api"
<script setup lang="ts">
import { ref, computed } from "@nuxtjs/composition-api"
import {
HoppRESTRequest,
safelyExtractRESTRequest,
translateToNewRequest,
isEqualHoppRESTRequest,
} from "@hoppscotch/data"
import { useReadonlyStream } from "~/helpers/utils/composables"
import * as E from "fp-ts/Either"
import cloneDeep from "lodash/cloneDeep"
import {
useI18n,
useToast,
useReadonlyStream,
} from "~/helpers/utils/composables"
import {
getDefaultRESTRequest,
getRESTRequest,
restSaveContext$,
setRESTRequest,
setRESTSaveContext,
getRESTSaveContext,
} from "~/newstore/RESTSession"
import { editRESTRequest } from "~/newstore/collections"
import { runMutation } from "~/helpers/backend/GQLClient"
import { UpdateRequestDocument } from "~/helpers/backend/graphql"
import { HoppRequestSaveContext } from "~/helpers/types/HoppRequestSaveContext"
export default defineComponent({
props: {
request: { type: Object, default: () => {} },
collectionIndex: { type: Number, default: null },
folderIndex: { type: Number, default: null },
folderName: { type: String, default: null },
// eslint-disable-next-line vue/require-default-prop
requestIndex: [Number, String],
doc: Boolean,
saveRequest: Boolean,
collectionsType: { type: Object, default: () => {} },
folderPath: { type: String, default: null },
picked: { type: Object, default: () => {} },
},
setup() {
const active = useReadonlyStream(restSaveContext$, null)
return {
active,
tippyActions: ref<any | null>(null),
options: ref<any | null>(null),
edit: ref<any | null>(null),
duplicate: ref<any | null>(null),
deleteAction: ref<any | null>(null),
}
},
data() {
return {
dragging: false,
requestMethodLabels: {
get: "text-green-500",
post: "text-yellow-500",
put: "text-blue-500",
delete: "text-red-500",
default: "text-gray-500",
},
confirmRemove: false,
}
},
computed: {
isSelected(): boolean {
return (
this.picked &&
this.picked.pickedType === "my-request" &&
this.picked.folderPath === this.folderPath &&
this.picked.requestIndex === this.requestIndex
)
},
},
methods: {
selectRequest() {
if (
this.active &&
this.active.originLocation === "user-collection" &&
this.active.folderPath === this.folderPath &&
this.active.requestIndex === this.requestIndex
) {
setRESTSaveContext(null)
return
}
if (this.$props.saveRequest)
this.$emit("select", {
const props = defineProps<{
request: HoppRESTRequest
collectionIndex: number
folderIndex: number
folderName: string
requestIndex: number
doc: boolean
saveRequest: boolean
collectionsType: object
folderPath: string
picked?: {
pickedType: string
collectionIndex: number
folderPath: string
folderName: string
requestIndex: number
}
}>()
const emit = defineEmits<{
(
e: "select",
data:
| {
picked: {
pickedType: "my-request",
collectionIndex: this.collectionIndex,
folderPath: this.folderPath,
folderName: this.folderName,
requestIndex: this.requestIndex,
},
})
else {
setRESTRequest(
safelyExtractRESTRequest(
translateToNewRequest(this.request),
getDefaultRESTRequest()
),
{
originLocation: "user-collection",
folderPath: this.folderPath,
requestIndex: this.requestIndex,
pickedType: string
collectionIndex: number
folderPath: string
folderName: string
requestIndex: number
}
)
}
},
dragStart({ dataTransfer }) {
this.dragging = !this.dragging
dataTransfer.setData("folderPath", this.folderPath)
dataTransfer.setData("requestIndex", this.requestIndex)
},
removeRequest() {
this.$emit("remove-request", {
collectionIndex: this.$props.collectionIndex,
folderName: this.$props.folderName,
folderPath: this.folderPath,
requestIndex: this.$props.requestIndex,
})
},
getRequestLabelColor(method: string): string {
return (
this.requestMethodLabels[method.toLowerCase()] ||
this.requestMethodLabels.default
}
| undefined
): void
(
e: "remove-request",
data: {
folderPath: string
requestIndex: number
}
): void
(
e: "duplicate-request",
data: {
collectionIndex: number
folderIndex: number
folderName: string
request: HoppRESTRequest
folderPath: string
requestIndex: number
}
): void
(
e: "edit-request",
data: {
collectionIndex: number
folderIndex: number
folderName: string
request: HoppRESTRequest
folderPath: string
requestIndex: number
}
): void
}>()
const t = useI18n()
const toast = useToast()
const dragging = ref(false)
const requestMethodLabels = {
get: "text-green-500",
post: "text-yellow-500",
put: "text-blue-500",
delete: "text-red-500",
default: "text-gray-500",
}
const confirmChange = ref(false)
const showSaveRequestModal = ref(false)
// Template refs
const tippyActions = ref<any | null>(null)
const options = ref<any | null>(null)
const edit = ref<any | null>(null)
const duplicate = ref<any | null>(null)
const deleteAction = ref<any | null>(null)
const active = useReadonlyStream(restSaveContext$, null)
const isSelected = computed(
() =>
props.picked &&
props.picked.pickedType === "my-request" &&
props.picked.folderPath === props.folderPath &&
props.picked.requestIndex === props.requestIndex
)
const isActive = computed(
() =>
active.value &&
active.value.originLocation === "user-collection" &&
active.value.folderPath === props.folderPath &&
active.value.requestIndex === props.requestIndex
)
const dragStart = ({ dataTransfer }: DragEvent) => {
if (dataTransfer) {
dragging.value = !dragging.value
dataTransfer.setData("folderPath", props.folderPath)
dataTransfer.setData("requestIndex", props.requestIndex.toString())
}
}
const removeRequest = () => {
emit("remove-request", {
folderPath: props.folderPath,
requestIndex: props.requestIndex,
})
}
const getRequestLabelColor = (method: string) =>
requestMethodLabels[
method.toLowerCase() as keyof typeof requestMethodLabels
] || requestMethodLabels.default
const setRestReq = (request: any) => {
setRESTRequest(
cloneDeep(
safelyExtractRESTRequest(
translateToNewRequest(request),
getDefaultRESTRequest()
)
},
},
})
),
{
originLocation: "user-collection",
folderPath: props.folderPath,
requestIndex: props.requestIndex,
req: cloneDeep(request),
}
)
}
/** Loads request from the save once, checks for unsaved changes, but ignores default values */
const selectRequest = () => {
// Check if this is a save as request popup, if so we don't need to prompt the confirm change popup.
if (props.saveRequest) {
emit("select", {
picked: {
pickedType: "my-request",
collectionIndex: props.collectionIndex,
folderPath: props.folderPath,
folderName: props.folderName,
requestIndex: props.requestIndex,
},
})
} else if (isEqualHoppRESTRequest(props.request, getDefaultRESTRequest())) {
confirmChange.value = false
setRestReq(props.request)
} else if (!active.value) {
confirmChange.value = true
} else {
const currentReqWithNoChange = active.value.req
const currentFullReq = getRESTRequest()
// Check if whether user clicked the same request or not
if (!isActive.value && currentReqWithNoChange !== undefined) {
// Check if there is any changes done on the current request
if (isEqualHoppRESTRequest(currentReqWithNoChange, currentFullReq)) {
setRestReq(props.request)
} else {
confirmChange.value = true
}
} else {
setRESTSaveContext(null)
}
}
}
/** Save current request to the collection */
const saveRequestChange = () => {
const saveCtx = getRESTSaveContext()
saveCurrentRequest(saveCtx)
confirmChange.value = false
}
/** Discard changes and change the current request and context */
const discardRequestChange = () => {
setRestReq(props.request)
if (!isActive.value) {
setRESTSaveContext({
originLocation: "user-collection",
folderPath: props.folderPath,
requestIndex: props.requestIndex,
req: cloneDeep(props.request),
})
}
confirmChange.value = false
}
const saveCurrentRequest = (saveCtx: HoppRequestSaveContext | null) => {
if (!saveCtx) {
showSaveRequestModal.value = true
return
}
if (saveCtx.originLocation === "user-collection") {
try {
editRESTRequest(
saveCtx.folderPath,
saveCtx.requestIndex,
getRESTRequest()
)
setRestReq(props.request)
toast.success(`${t("request.saved")}`)
} catch (e) {
setRESTSaveContext(null)
saveCurrentRequest(saveCtx)
}
} else if (saveCtx.originLocation === "team-collection") {
const req = getRESTRequest()
try {
runMutation(UpdateRequestDocument, {
requestID: saveCtx.requestID,
data: {
title: req.name,
request: JSON.stringify(req),
},
})().then((result) => {
if (E.isLeft(result)) {
toast.error(`${t("profile.no_permission")}`)
} else {
toast.success(`${t("request.saved")}`)
}
})
setRestReq(props.request)
} catch (error) {
showSaveRequestModal.value = true
toast.error(`${t("error.something_went_wrong")}`)
console.error(error)
}
}
}
</script>

View File

@@ -45,6 +45,19 @@
color="green"
@click.native="$emit('unselect-collection')"
/>
<ButtonSecondary
v-if="collectionsType.selectedTeam.myRole !== 'VIEWER'"
v-tippy="{ theme: 'tooltip' }"
svg="file-plus"
:title="$t('request.new')"
class="hidden group-hover:inline-flex"
@click.native="
$emit('add-request', {
folder: collection,
path: `${collectionIndex}`,
})
"
/>
<ButtonSecondary
v-if="collectionsType.selectedTeam.myRole !== 'VIEWER'"
v-tippy="{ theme: 'tooltip' }"
@@ -80,12 +93,28 @@
class="flex flex-col focus:outline-none"
tabindex="0"
role="menu"
@keyup.r="requestAction.$el.click()"
@keyup.n="folderAction.$el.click()"
@keyup.e="edit.$el.click()"
@keyup.delete="deleteAction.$el.click()"
@keyup.x="exportAction.$el.click()"
@keyup.escape="options.tippy().hide()"
>
<SmartItem
ref="requestAction"
svg="file-plus"
:label="t('request.new')"
:shortcut="['R']"
@click.native="
() => {
$emit('add-request', {
folder: collection,
path: `${collectionIndex}`,
})
options.tippy().hide()
}
"
/>
<SmartItem
ref="folderAction"
svg="folder-plus"
@@ -128,7 +157,7 @@
:shortcut="['⌫']"
@click.native="
() => {
confirmRemove = true
removeCollection()
options.tippy().hide()
}
"
@@ -157,12 +186,14 @@
:is-filtered="isFiltered"
:picked="picked"
:loading-collection-i-ds="loadingCollectionIDs"
@add-request="$emit('add-request', $event)"
@add-folder="$emit('add-folder', $event)"
@edit-folder="$emit('edit-folder', $event)"
@edit-request="$emit('edit-request', $event)"
@select="$emit('select', $event)"
@expand-collection="expandCollection"
@remove-request="removeRequest"
@remove-request="$emit('remove-request', $event)"
@remove-folder="$emit('remove-folder', $event)"
@duplicate-request="$emit('duplicate-request', $event)"
/>
<CollectionsTeamsRequest
@@ -180,7 +211,7 @@
:picked="picked"
@edit-request="editRequest($event)"
@select="$emit('select', $event)"
@remove-request="removeRequest"
@remove-request="$emit('remove-request', $event)"
@duplicate-request="$emit('duplicate-request', $event)"
/>
<div
@@ -211,12 +242,6 @@
</div>
</div>
</div>
<SmartConfirmModal
:show="confirmRemove"
:title="t('confirm.remove_collection')"
@hide-modal="confirmRemove = false"
@resolve="removeCollection"
/>
</div>
</template>
@@ -248,6 +273,7 @@ export default defineComponent({
return {
tippyActions: ref<any | null>(null),
options: ref<any | null>(null),
requestAction: ref<any | null>(null),
folderAction: ref<any | null>(null),
edit: ref<any | null>(null),
deleteAction: ref<any | null>(null),
@@ -261,7 +287,6 @@ export default defineComponent({
showChildren: false,
dragging: false,
selectedFolder: {},
confirmRemove: false,
prevCursor: "",
cursor: "",
pageNo: 0,
@@ -344,7 +369,6 @@ export default defineComponent({
},
removeCollection() {
this.$emit("remove-collection", {
collectionsType: this.collectionsType,
collectionIndex: this.collectionIndex,
collectionID: this.collection.id,
})
@@ -362,13 +386,6 @@ export default defineComponent({
if (E.isLeft(moveRequestResult))
this.$toast.error(`${this.$t("error.something_went_wrong")}`)
},
removeRequest({ collectionIndex, folderName, requestIndex }: any) {
this.$emit("remove-request", {
collectionIndex,
folderName,
requestIndex,
})
},
},
})
</script>

View File

@@ -29,6 +29,14 @@
</span>
</span>
<div class="flex">
<ButtonSecondary
v-if="collectionsType.selectedTeam.myRole !== 'VIEWER'"
v-tippy="{ theme: 'tooltip' }"
svg="file-plus"
:title="$t('request.new')"
class="hidden group-hover:inline-flex"
@click.native="$emit('add-request', { folder, path: folderPath })"
/>
<ButtonSecondary
v-if="collectionsType.selectedTeam.myRole !== 'VIEWER'"
v-tippy="{ theme: 'tooltip' }"
@@ -59,12 +67,25 @@
class="flex flex-col focus:outline-none"
tabindex="0"
role="menu"
@keyup.r="requestAction.$el.click()"
@keyup.n="folderAction.$el.click()"
@keyup.e="edit.$el.click()"
@keyup.delete="deleteAction.$el.click()"
@keyup.x="exportAction.$el.click()"
@keyup.escape="options.tippy().hide()"
>
<SmartItem
ref="requestAction"
svg="file-plus"
:label="$t('request.new')"
:shortcut="['R']"
@click.native="
() => {
$emit('add-request', { folder, path: folderPath })
options.tippy().hide()
}
"
/>
<SmartItem
ref="folderAction"
svg="folder-plus"
@@ -109,7 +130,7 @@
:shortcut="['⌫']"
@click.native="
() => {
confirmRemove = true
removeFolder()
options.tippy().hide()
}
"
@@ -137,13 +158,15 @@
:folder-path="`${folderPath}/${subFolderIndex}`"
:picked="picked"
:loading-collection-i-ds="loadingCollectionIDs"
@add-request="$emit('add-request', $event)"
@add-folder="$emit('add-folder', $event)"
@edit-folder="$emit('edit-folder', $event)"
@edit-request="$emit('edit-request', $event)"
@update-team-collections="$emit('update-team-collections')"
@select="$emit('select', $event)"
@expand-collection="expandCollection"
@remove-request="removeRequest"
@remove-request="$emit('remove-request', $event)"
@remove-folder="$emit('remove-folder', $event)"
@duplicate-request="$emit('duplicate-request', $event)"
/>
<CollectionsTeamsRequest
@@ -161,7 +184,7 @@
:collection-i-d="folder.id"
@edit-request="$emit('edit-request', $event)"
@select="$emit('select', $event)"
@remove-request="removeRequest"
@remove-request="$emit('remove-request', $event)"
@duplicate-request="$emit('duplicate-request', $event)"
/>
<div
@@ -190,20 +213,12 @@
</div>
</div>
</div>
<SmartConfirmModal
:show="confirmRemove"
:title="$t('confirm.remove_folder')"
@hide-modal="confirmRemove = false"
@resolve="removeFolder"
/>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "@nuxtjs/composition-api"
import * as E from "fp-ts/Either"
import { runMutation } from "~/helpers/backend/GQLClient"
import { DeleteCollectionDocument } from "~/helpers/backend/graphql"
import {
getCompleteCollectionTree,
teamCollToHoppRESTColl,
@@ -228,6 +243,7 @@ export default defineComponent({
return {
tippyActions: ref<any | null>(null),
options: ref<any | null>(null),
requestAction: ref<any | null>(null),
folderAction: ref<any | null>(null),
edit: ref<any | null>(null),
deleteAction: ref<any | null>(null),
@@ -239,7 +255,6 @@ export default defineComponent({
return {
showChildren: false,
dragging: false,
confirmRemove: false,
prevCursor: "",
cursor: "",
}
@@ -310,30 +325,10 @@ export default defineComponent({
this.showChildren = !this.showChildren
},
removeFolder() {
if (this.collectionsType.selectedTeam.myRole !== "VIEWER") {
// Cancel pick if picked collection folder was deleted
if (
this.picked &&
this.picked.pickedType === "teams-folder" &&
this.picked.folderID === this.folder.id
) {
this.$emit("select", { picked: null })
}
runMutation(DeleteCollectionDocument, {
collectionID: this.folder.id,
})().then((result) => {
if (E.isLeft(result)) {
this.$toast.error(`${this.$t("error.something_went_wrong")}`)
console.error(result.left)
} else {
this.$toast.success(`${this.$t("state.deleted")}`)
this.$emit("update-team-collections")
}
})
this.$emit("update-team-collections")
}
this.$emit("remove-folder", {
collectionsType: this.collectionsType,
folder: this.folder,
})
},
expandCollection(collectionID: number) {
this.$emit("expand-collection", collectionID)
@@ -348,13 +343,6 @@ export default defineComponent({
if (E.isLeft(moveRequestResult))
this.$toast.error(`${this.$t("error.something_went_wrong")}`)
},
removeRequest({ collectionIndex, folderName, requestIndex }: any) {
this.$emit("remove-request", {
collectionIndex,
folderName,
requestIndex,
})
},
},
})
</script>

View File

@@ -32,11 +32,7 @@
{{ request.name }}
</span>
<span
v-if="
active &&
active.originLocation === 'team-collection' &&
active.requestID === requestIndex
"
v-if="isActive"
v-tippy="{ theme: 'tooltip' }"
class="relative h-1.5 w-1.5 flex flex-shrink-0 mx-3"
:title="`${$t('collection.request_in_use')}`"
@@ -93,7 +89,7 @@
:shortcut="['E']"
@click.native="
() => {
$emit('edit-request', {
emit('edit-request', {
collectionIndex,
folderIndex,
folderName,
@@ -111,7 +107,7 @@
:shortcut="['D']"
@click.native="
() => {
$emit('duplicate-request', {
emit('duplicate-request', {
request,
requestIndex,
collectionID,
@@ -127,7 +123,7 @@
:shortcut="['⌫']"
@click.native="
() => {
confirmRemove = true
removeRequest()
options.tippy().hide()
}
"
@@ -137,122 +133,272 @@
</span>
</div>
</div>
<SmartConfirmModal
:show="confirmRemove"
:title="$t('confirm.remove_request')"
@hide-modal="confirmRemove = false"
@resolve="removeRequest"
<HttpReqChangeConfirmModal
:show="confirmChange"
@hide-modal="confirmChange = false"
@save-change="saveRequestChange"
@discard-change="discardRequestChange"
/>
<CollectionsSaveRequest
mode="rest"
:show="showSaveRequestModal"
@hide-modal="showSaveRequestModal = false"
/>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "@nuxtjs/composition-api"
<script setup lang="ts">
import { ref, computed } from "@nuxtjs/composition-api"
import {
HoppRESTRequest,
isEqualHoppRESTRequest,
safelyExtractRESTRequest,
translateToNewRequest,
} from "@hoppscotch/data"
import { useReadonlyStream } from "~/helpers/utils/composables"
import * as E from "fp-ts/Either"
import {
useI18n,
useToast,
useReadonlyStream,
} from "~/helpers/utils/composables"
import {
getDefaultRESTRequest,
restSaveContext$,
setRESTRequest,
setRESTSaveContext,
getRESTSaveContext,
getRESTRequest,
} from "~/newstore/RESTSession"
import { editRESTRequest } from "~/newstore/collections"
import { runMutation } from "~/helpers/backend/GQLClient"
import { Team, UpdateRequestDocument } from "~/helpers/backend/graphql"
import { HoppRequestSaveContext } from "~/helpers/types/HoppRequestSaveContext"
export default defineComponent({
props: {
request: { type: Object, default: () => {} },
collectionIndex: { type: Number, default: null },
folderIndex: { type: Number, default: null },
folderName: { type: String, default: null },
// eslint-disable-next-line vue/require-default-prop
requestIndex: [Number, String],
doc: Boolean,
saveRequest: Boolean,
collectionsType: { type: Object, default: () => {} },
picked: { type: Object, default: () => {} },
collectionID: { type: String, default: null },
},
setup() {
const active = useReadonlyStream(restSaveContext$, null)
return {
active,
tippyActions: ref<any | null>(null),
options: ref<any | null>(null),
edit: ref<any | null>(null),
deleteAction: ref<any | null>(null),
duplicate: ref<any | null>(null),
}
},
data() {
return {
dragging: false,
requestMethodLabels: {
get: "text-green-500",
post: "text-yellow-500",
put: "text-blue-500",
delete: "text-red-500",
default: "text-gray-500",
},
confirmRemove: false,
}
},
computed: {
isSelected(): boolean {
return (
this.picked &&
this.picked.pickedType === "teams-request" &&
this.picked.requestID === this.requestIndex
)
},
},
methods: {
selectRequest() {
if (
this.active &&
this.active.originLocation === "team-collection" &&
this.active.requestID === this.requestIndex
) {
setRESTSaveContext(null)
return
}
if (this.$props.saveRequest)
this.$emit("select", {
const props = defineProps<{
request: HoppRESTRequest
collectionIndex: number
folderIndex: number
folderName?: string
requestIndex: string
doc: boolean
saveRequest: boolean
collectionsType: {
type: "my-collections" | "team-collections"
selectedTeam: Team | undefined
}
collectionID: string
picked?: {
pickedType: string
requestID: string
}
}>()
const emit = defineEmits<{
(
e: "select",
data:
| {
picked: {
pickedType: "teams-request",
requestID: this.requestIndex,
},
})
else
setRESTRequest(
safelyExtractRESTRequest(
translateToNewRequest(this.request),
getDefaultRESTRequest()
),
{
originLocation: "team-collection",
requestID: this.requestIndex as string,
pickedType: string
requestID: string
}
)
},
dragStart({ dataTransfer }) {
this.dragging = !this.dragging
dataTransfer.setData("requestIndex", this.requestIndex)
},
removeRequest() {
this.$emit("remove-request", {
collectionIndex: this.$props.collectionIndex,
folderName: this.$props.folderName,
requestIndex: this.$props.requestIndex,
}
| undefined
): void
(
e: "remove-request",
data: {
folderPath: string | undefined
requestIndex: string
}
): void
(
e: "edit-request",
data: {
collectionIndex: number
folderIndex: number
folderName: string | undefined
requestIndex: string
request: HoppRESTRequest
}
): void
(
e: "duplicate-request",
data: {
collectionID: number | string
requestIndex: string
request: HoppRESTRequest
}
): void
}>()
const t = useI18n()
const toast = useToast()
const dragging = ref(false)
const requestMethodLabels = {
get: "text-green-500",
post: "text-yellow-500",
put: "text-blue-500",
delete: "text-red-500",
default: "text-gray-500",
}
const confirmChange = ref(false)
const showSaveRequestModal = ref(false)
// Template refs
const tippyActions = ref<any | null>(null)
const options = ref<any | null>(null)
const edit = ref<any | null>(null)
const duplicate = ref<any | null>(null)
const deleteAction = ref<any | null>(null)
const active = useReadonlyStream(restSaveContext$, null)
const isSelected = computed(
() =>
props.picked &&
props.picked.pickedType === "teams-collection" &&
props.picked.requestID === props.requestIndex
)
const isActive = computed(
() =>
active.value &&
active.value.originLocation === "team-collection" &&
active.value.requestID === props.requestIndex
)
const dragStart = ({ dataTransfer }: DragEvent) => {
if (dataTransfer) {
dragging.value = !dragging.value
dataTransfer.setData("requestIndex", props.requestIndex)
}
}
const removeRequest = () => {
emit("remove-request", {
folderPath: props.folderName,
requestIndex: props.requestIndex,
})
}
const getRequestLabelColor = (method: string): string => {
return (
(requestMethodLabels as any)[method.toLowerCase()] ||
requestMethodLabels.default
)
}
const setRestReq = (request: HoppRESTRequest) => {
setRESTRequest(
safelyExtractRESTRequest(
translateToNewRequest(request),
getDefaultRESTRequest()
),
{
originLocation: "team-collection",
requestID: props.requestIndex,
req: request,
}
)
}
const selectRequest = () => {
// Check if this is a save as request popup, if so we don't need to prompt the confirm change popup.
if (props.saveRequest) {
emit("select", {
picked: {
pickedType: "teams-collection",
requestID: props.requestIndex,
},
})
} else if (isEqualHoppRESTRequest(props.request, getDefaultRESTRequest())) {
confirmChange.value = false
setRestReq(props.request)
} else if (!active.value) {
confirmChange.value = true
} else {
const currentReqWithNoChange = active.value.req
const currentFullReq = getRESTRequest()
// Check if whether user clicked the same request or not
if (!isActive.value && currentReqWithNoChange) {
// Check if there is any changes done on the current request
if (isEqualHoppRESTRequest(currentReqWithNoChange, currentFullReq)) {
setRestReq(props.request)
} else {
confirmChange.value = true
}
} else {
setRESTSaveContext(null)
}
}
}
/** Save current request to the collection */
const saveRequestChange = () => {
const saveCtx = getRESTSaveContext()
saveCurrentRequest(saveCtx)
confirmChange.value = false
}
/** Discard changes and change the current request and context */
const discardRequestChange = () => {
setRestReq(props.request)
if (!isActive.value) {
setRESTSaveContext({
originLocation: "team-collection",
requestID: props.requestIndex,
req: props.request,
})
}
confirmChange.value = false
}
const saveCurrentRequest = (saveCtx: HoppRequestSaveContext | null) => {
if (!saveCtx) {
showSaveRequestModal.value = true
return
}
if (saveCtx.originLocation === "team-collection") {
const req = getRESTRequest()
try {
runMutation(UpdateRequestDocument, {
requestID: saveCtx.requestID,
data: {
title: req.name,
request: JSON.stringify(req),
},
})().then((result) => {
if (E.isLeft(result)) {
toast.error(`${t("profile.no_permission")}`)
} else {
toast.success(`${t("request.saved")}`)
}
})
},
getRequestLabelColor(method: any) {
return (
(this.requestMethodLabels as any)[method.toLowerCase()] ||
this.requestMethodLabels.default
setRestReq(props.request)
} catch (error) {
showSaveRequestModal.value = true
toast.error(`${t("error.something_went_wrong")}`)
console.error(error)
}
} else if (saveCtx.originLocation === "user-collection") {
try {
editRESTRequest(
saveCtx.folderPath,
saveCtx.requestIndex,
getRESTRequest()
)
},
},
})
setRestReq(props.request)
toast.success(`${t("request.saved")}`)
} catch (e) {
setRESTSaveContext(null)
saveCurrentRequest(null)
}
}
}
</script>

View File

@@ -2,7 +2,7 @@
<SmartModal
v-if="show"
dialog
:title="$t(`environment.${action}`)"
:title="t(`environment.${action}`)"
@close="hideModal"
>
<template #body>
@@ -20,24 +20,24 @@
@keyup.enter="saveEnvironment"
/>
<label for="selectLabelEnvEdit">
{{ $t("action.label") }}
{{ t("action.label") }}
</label>
</div>
<div class="flex items-center justify-between flex-1">
<label for="variableList" class="p-4">
{{ $t("environment.variable_list") }}
{{ t("environment.variable_list") }}
</label>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.clear_all')"
:title="t('action.clear_all')"
:svg="clearIcon"
@click.native="clearContent()"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
svg="plus"
:title="$t('add.new')"
:title="t('add.new')"
@click.native="addEnvironmentVariable"
/>
</div>
@@ -46,7 +46,7 @@
v-if="evnExpandError"
class="w-full px-4 py-2 mb-2 overflow-auto font-mono text-red-400 whitespace-normal rounded bg-primaryLight"
>
{{ $t("environment.nested_overflow") }}
{{ t("environment.nested_overflow") }}
</div>
<div class="border rounded divide-y divide-dividerLight border-divider">
<div
@@ -57,12 +57,12 @@
<input
v-model="variable.key"
class="flex flex-1 px-4 py-2 bg-transparent"
:placeholder="`${$t('count.variable', { count: index + 1 })}`"
:placeholder="`${t('count.variable', { count: index + 1 })}`"
:name="'param' + index"
/>
<SmartEnvInput
v-model="variable.value"
:placeholder="`${$t('count.value', { count: index + 1 })}`"
:placeholder="`${t('count.value', { count: index + 1 })}`"
:envs="liveEnvs"
:name="'value' + index"
/>
@@ -70,7 +70,7 @@
<ButtonSecondary
id="variable"
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.remove')"
:title="t('action.remove')"
svg="trash"
color="red"
@click.native="removeEnvironmentVariable(index)"
@@ -85,13 +85,13 @@
:src="`/images/states/${$colorMode.value}/blockchain.svg`"
loading="lazy"
class="inline-flex flex-col object-contain object-center w-16 h-16 my-4"
:alt="`${$t('empty.environments')}`"
:alt="`${t('empty.environments')}`"
/>
<span class="pb-4 text-center">
{{ $t("empty.environments") }}
{{ t("empty.environments") }}
</span>
<ButtonSecondary
:label="`${$t('add.new')}`"
:label="`${t('add.new')}`"
filled
class="mb-4"
@click.native="addEnvironmentVariable"
@@ -103,11 +103,11 @@
<template #footer>
<span>
<ButtonPrimary
:label="`${$t('action.save')}`"
:label="`${t('action.save')}`"
@click.native="saveEnvironment"
/>
<ButtonSecondary
:label="`${$t('action.cancel')}`"
:label="`${t('action.cancel')}`"
@click.native="hideModal"
/>
</span>
@@ -115,151 +115,163 @@
</SmartModal>
</template>
<script lang="ts">
<script setup lang="ts">
import clone from "lodash/clone"
import { computed, defineComponent, PropType } from "@nuxtjs/composition-api"
import { computed, ref, watch } from "@nuxtjs/composition-api"
import * as E from "fp-ts/Either"
import { Environment, parseTemplateStringE } from "@hoppscotch/data"
import { refAutoReset } from "@vueuse/core"
import {
createEnvironment,
environments$,
getEnviroment,
getEnvironment,
getGlobalVariables,
globalEnv$,
setCurrentEnvironment,
setGlobalEnvVariables,
updateEnvironment,
} from "~/newstore/environments"
import { useReadonlyStream } from "~/helpers/utils/composables"
import {
useReadonlyStream,
useI18n,
useToast,
} from "~/helpers/utils/composables"
export default defineComponent({
props: {
show: Boolean,
action: {
type: String as PropType<"new" | "edit">,
default: "edit",
},
editingEnvironmentIndex: {
type: [Number, String] as PropType<number | "Global" | null>,
default: null,
},
envVars: {
type: Function as PropType<() => Environment["variables"]>,
default: () => [],
},
},
setup(props) {
const globalVars = useReadonlyStream(globalEnv$, [])
const t = useI18n()
const toast = useToast()
const workingEnv = computed(() => {
if (props.editingEnvironmentIndex === "Global") {
return {
name: "Global",
variables: getGlobalVariables(),
} as Environment
} else if (props.action === "new") {
return {
name: "",
variables: props.envVars(),
}
} else if (props.editingEnvironmentIndex !== null) {
return getEnviroment(props.editingEnvironmentIndex)
} else {
return null
}
})
const props = withDefaults(
defineProps<{
show: boolean
action: "edit" | "new"
editingEnvironmentIndex: number | "Global" | null
envVars: () => Environment["variables"]
}>(),
{
show: false,
action: "edit",
editingEnvironmentIndex: null,
envVars: () => [],
}
)
const emit = defineEmits<{
(e: "hide-modal"): void
}>()
const name = ref<string | null>(null)
const vars = ref([{ key: "", value: "" }])
const clearIcon = refAutoReset<"trash-2" | "check">("trash-2", 1000)
const globalVars = useReadonlyStream(globalEnv$, [])
const workingEnv = computed(() => {
if (props.editingEnvironmentIndex === "Global") {
return {
globalVars,
workingEnv,
envList: useReadonlyStream(environments$, []) || props.envVars(),
}
},
data() {
name: "Global",
variables: getGlobalVariables(),
} as Environment
} else if (props.action === "new") {
return {
name: null as string | null,
vars: [] as { key: string; value: string }[],
clearIcon: "trash-2",
name: "",
variables: props.envVars(),
}
},
computed: {
evnExpandError(): boolean {
for (const variable of this.vars) {
const result = parseTemplateStringE(variable.value, this.vars)
if (E.isLeft(result)) {
console.error("error", result.left)
return true
}
}
return false
},
liveEnvs(): Array<{ key: string; value: string; source: string }> {
if (this.evnExpandError) {
return []
}
if (this.$props.editingEnvironmentIndex === "Global") {
return [...this.vars.map((x) => ({ ...x, source: this.name! }))]
} else {
return [
...this.vars.map((x) => ({ ...x, source: this.name! })),
...this.globalVars.map((x) => ({ ...x, source: "Global" })),
]
}
},
},
watch: {
show() {
this.name = this.workingEnv?.name ?? null
this.vars = clone(this.workingEnv?.variables ?? [])
},
},
methods: {
clearContent() {
this.vars = []
this.clearIcon = "check"
this.$toast.success(`${this.$t("state.cleared")}`)
setTimeout(() => (this.clearIcon = "trash-2"), 1000)
},
addEnvironmentVariable() {
this.vars.push({
key: "",
value: "",
})
},
removeEnvironmentVariable(index: number) {
this.vars.splice(index, 1)
},
saveEnvironment() {
if (!this.name) {
this.$toast.error(`${this.$t("environment.invalid_name")}`)
return
}
if (this.action === "new") {
createEnvironment(this.name)
setCurrentEnvironment(this.envList.length - 1)
}
const environmentUpdated: Environment = {
name: this.name,
variables: this.vars,
}
if (this.editingEnvironmentIndex === "Global")
setGlobalEnvVariables(environmentUpdated.variables)
else if (this.action === "new") {
updateEnvironment(this.envList.length - 1, environmentUpdated)
} else {
updateEnvironment(this.editingEnvironmentIndex!, environmentUpdated)
}
this.hideModal()
},
hideModal() {
this.name = null
this.$emit("hide-modal")
},
},
} else if (props.editingEnvironmentIndex !== null) {
return getEnvironment(props.editingEnvironmentIndex)
} else {
return null
}
})
const envList = useReadonlyStream(environments$, []) || props.envVars()
const evnExpandError = computed(() => {
for (const variable of vars.value) {
const result = parseTemplateStringE(variable.value.toString(), vars.value)
if (E.isLeft(result)) {
console.error("error", result.left)
return true
}
}
return false
})
const liveEnvs = computed(() => {
if (evnExpandError) {
return []
}
if (props.editingEnvironmentIndex === "Global") {
return [...vars.value.map((x) => ({ ...x, source: name.value! }))]
} else {
return [
...vars.value.map((x) => ({ ...x, source: name.value! })),
...globalVars.value.map((x) => ({ ...x, source: "Global" })),
]
}
})
watch(
() => props.show,
(show) => {
if (show) {
name.value = workingEnv.value?.name ?? null
vars.value = clone(workingEnv.value?.variables ?? [])
}
}
)
const clearContent = () => {
vars.value = []
clearIcon.value = "check"
toast.success(`${t("state.cleared")}`)
}
const addEnvironmentVariable = () => {
vars.value.push({
key: "",
value: "",
})
}
const removeEnvironmentVariable = (index: number) => {
vars.value.splice(index, 1)
}
const saveEnvironment = () => {
if (!name.value) {
toast.error(`${t("environment.invalid_name")}`)
return
}
const environmentUpdated: Environment = {
name: name.value,
variables: vars.value,
}
if (props.action === "new") {
// Creating a new environment
createEnvironment(name.value)
updateEnvironment(envList.value.length - 1, environmentUpdated)
setCurrentEnvironment(envList.value.length - 1)
toast.success(`${t("environment.created")}`)
} else if (props.editingEnvironmentIndex === "Global") {
// Editing the Global environment
setGlobalEnvVariables(environmentUpdated.variables)
toast.success(`${t("environment.updated")}`)
} else if (props.editingEnvironmentIndex !== null) {
// Editing an environment
updateEnvironment(props.editingEnvironmentIndex, environmentUpdated)
toast.success(`${t("environment.updated")}`)
}
hideModal()
}
const hideModal = () => {
name.value = null
emit("hide-modal")
}
</script>

View File

@@ -5,13 +5,13 @@
>
<span
class="flex items-center justify-center px-4 cursor-pointer"
@click="$emit('edit-environment')"
@click="emit('edit-environment')"
>
<SmartIcon class="svg-icons" name="layers" />
</span>
<span
class="flex flex-1 min-w-0 py-2 pr-2 cursor-pointer transition group-hover:text-secondaryDark"
@click="$emit('edit-environment')"
@click="emit('edit-environment')"
>
<span class="truncate">
{{ environment.name }}
@@ -29,7 +29,7 @@
<template #trigger>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.more')"
:title="t('action.more')"
svg="more-vertical"
/>
</template>
@@ -48,11 +48,11 @@
<SmartItem
ref="edit"
svg="edit"
:label="`${$t('action.edit')}`"
:label="`${t('action.edit')}`"
:shortcut="['E']"
@click.native="
() => {
$emit('edit-environment')
emit('edit-environment')
options.tippy().hide()
}
"
@@ -60,11 +60,11 @@
<SmartItem
ref="duplicate"
svg="copy"
:label="`${$t('action.duplicate')}`"
:label="`${t('action.duplicate')}`"
:shortcut="['D']"
@click.native="
() => {
duplicateEnvironment()
duplicateEnvironments()
options.tippy().hide()
}
"
@@ -73,7 +73,7 @@
v-if="!(environmentIndex === 'Global')"
ref="deleteAction"
svg="trash-2"
:label="`${$t('action.delete')}`"
:label="`${t('action.delete')}`"
:shortcut="['⌫']"
@click.native="
() => {
@@ -87,15 +87,17 @@
</span>
<SmartConfirmModal
:show="confirmRemove"
:title="`${$t('confirm.remove_environment')}`"
:title="`${t('confirm.remove_environment')}`"
@hide-modal="confirmRemove = false"
@resolve="removeEnvironment"
/>
</div>
</template>
<script lang="ts">
import { defineComponent, PropType, ref } from "@nuxtjs/composition-api"
<script setup lang="ts">
import { ref } from "@nuxtjs/composition-api"
import { Environment } from "@hoppscotch/data"
import cloneDeep from "lodash/cloneDeep"
import {
deleteEnvironment,
duplicateEnvironment,
@@ -104,47 +106,43 @@ import {
getGlobalVariables,
environmentsStore,
} from "~/newstore/environments"
import { useI18n, useToast } from "~/helpers/utils/composables"
export default defineComponent({
props: {
environment: { type: Object, default: () => {} },
environmentIndex: {
type: [Number, String] as PropType<number | "Global">,
default: null,
},
},
setup() {
return {
tippyActions: ref<any | null>(null),
options: ref<any | null>(null),
edit: ref<any | null>(null),
duplicate: ref<any | null>(null),
deleteAction: ref<any | null>(null),
}
},
data() {
return {
confirmRemove: false,
}
},
methods: {
removeEnvironment() {
if (this.environmentIndex !== "Global")
deleteEnvironment(this.environmentIndex)
this.$toast.success(`${this.$t("state.deleted")}`)
},
duplicateEnvironment() {
if (this.environmentIndex === "Global") {
createEnvironment(`Global - ${this.$t("action.duplicate")}`)
setEnvironmentVariables(
environmentsStore.value.environments.length - 1,
getGlobalVariables().reduce((gVars, gVar) => {
gVars.push({ key: gVar.key, value: gVar.value })
return gVars
}, [])
)
} else duplicateEnvironment(this.environmentIndex)
},
},
})
const t = useI18n()
const toast = useToast()
const props = defineProps<{
environment: Environment
environmentIndex: number | "Global" | null
}>()
const emit = defineEmits<{
(e: "edit-environment"): void
}>()
const confirmRemove = ref(false)
const tippyActions = ref<any | null>(null)
const options = ref<any | null>(null)
const edit = ref<any | null>(null)
const duplicate = ref<any | null>(null)
const deleteAction = ref<any | null>(null)
const removeEnvironment = () => {
if (props.environmentIndex === null) return
if (props.environmentIndex !== "Global")
deleteEnvironment(props.environmentIndex)
toast.success(`${t("state.deleted")}`)
}
const duplicateEnvironments = () => {
if (props.environmentIndex === null) return
if (props.environmentIndex === "Global") {
createEnvironment(`Global - ${t("action.duplicate")}`)
setEnvironmentVariables(
environmentsStore.value.environments.length - 1,
cloneDeep(getGlobalVariables())
)
} else duplicateEnvironment(props.environmentIndex)
}
</script>

View File

@@ -5,7 +5,7 @@
<template #trigger>
<span
v-tippy="{ theme: 'tooltip' }"
:title="`${$t('environment.select')}`"
:title="`${t('environment.select')}`"
class="flex-1 bg-transparent border-b border-dividerLight select-wrapper"
>
<ButtonSecondary
@@ -15,20 +15,20 @@
/>
<ButtonSecondary
v-else
:label="`${$t('environment.select')}`"
:label="`${t('environment.select')}`"
class="flex-1 !justify-start pr-8 rounded-none"
/>
</span>
</template>
<div class="flex flex-col" role="menu">
<SmartItem
:label="`${$t('environment.no_environment')}`"
:label="`${t('environment.no_environment')}`"
:info-icon="selectedEnvironmentIndex === -1 ? 'done' : ''"
:active-info-icon="selectedEnvironmentIndex === -1"
@click.native="
() => {
selectedEnvironmentIndex = -1
$refs.options.tippy().hide()
options.tippy().hide()
}
"
/>
@@ -42,7 +42,7 @@
@click.native="
() => {
selectedEnvironmentIndex = index
$refs.options.tippy().hide()
options.tippy().hide()
}
"
/>
@@ -51,7 +51,7 @@
<div class="flex justify-between flex-1 border-b border-dividerLight">
<ButtonSecondary
svg="plus"
:label="`${$t('action.new')}`"
:label="`${t('action.new')}`"
class="!rounded-none"
@click.native="displayModalAdd(true)"
/>
@@ -60,13 +60,13 @@
v-tippy="{ theme: 'tooltip' }"
to="https://docs.hoppscotch.io/features/environments"
blank
:title="$t('app.wiki')"
:title="t('app.wiki')"
svg="help-circle"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
svg="archive"
:title="$t('modal.import_export')"
:title="t('modal.import_export')"
@click.native="displayModalImportExport(true)"
/>
</div>
@@ -95,13 +95,13 @@
:src="`/images/states/${$colorMode.value}/blockchain.svg`"
loading="lazy"
class="inline-flex flex-col object-contain object-center w-16 h-16 my-4"
:alt="`${$t('empty.environments')}`"
:alt="`${t('empty.environments')}`"
/>
<span class="pb-4 text-center">
{{ $t("empty.environments") }}
{{ t("empty.environments") }}
</span>
<ButtonSecondary
:label="`${$t('add.new')}`"
:label="`${t('add.new')}`"
filled
class="mb-4"
@click.native="displayModalAdd(true)"
@@ -120,9 +120,13 @@
</div>
</template>
<script lang="ts">
import { computed, defineComponent } from "@nuxtjs/composition-api"
import { useReadonlyStream, useStream } from "~/helpers/utils/composables"
<script setup lang="ts">
import { computed, ref } from "@nuxtjs/composition-api"
import {
useReadonlyStream,
useStream,
useI18n,
} from "~/helpers/utils/composables"
import {
environments$,
setCurrentEnvironment,
@@ -130,55 +134,49 @@ import {
globalEnv$,
} from "~/newstore/environments"
export default defineComponent({
setup() {
const globalEnv = useReadonlyStream(globalEnv$, [])
const t = useI18n()
const globalEnvironment = computed(() => ({
name: "Global",
variables: globalEnv.value,
}))
const options = ref<any | null>(null)
return {
environments: useReadonlyStream(environments$, []),
globalEnvironment,
selectedEnvironmentIndex: useStream(
selectedEnvIndex$,
-1,
setCurrentEnvironment
),
}
},
data() {
return {
showModalImportExport: false,
showModalDetails: false,
action: "edit" as "new" | "edit",
editingEnvironmentIndex: undefined as number | "Global" | undefined,
}
},
methods: {
displayModalAdd(shouldDisplay: boolean) {
this.action = "new"
this.showModalDetails = shouldDisplay
},
displayModalEdit(shouldDisplay: boolean) {
this.action = "edit"
this.showModalDetails = shouldDisplay
const globalEnv = useReadonlyStream(globalEnv$, [])
if (!shouldDisplay) this.resetSelectedData()
},
displayModalImportExport(shouldDisplay: boolean) {
this.showModalImportExport = shouldDisplay
},
editEnvironment(environmentIndex: number | "Global") {
this.$data.editingEnvironmentIndex = environmentIndex
this.action = "edit"
this.displayModalEdit(true)
},
resetSelectedData() {
this.$data.editingEnvironmentIndex = undefined
},
},
})
const globalEnvironment = computed(() => ({
name: "Global",
variables: globalEnv.value,
}))
const environments = useReadonlyStream(environments$, [])
const selectedEnvironmentIndex = useStream(
selectedEnvIndex$,
-1,
setCurrentEnvironment
)
const showModalImportExport = ref(false)
const showModalDetails = ref(false)
const action = ref<"new" | "edit">("edit")
const editingEnvironmentIndex = ref<number | "Global" | null>(null)
const displayModalAdd = (shouldDisplay: boolean) => {
action.value = "new"
showModalDetails.value = shouldDisplay
}
const displayModalEdit = (shouldDisplay: boolean) => {
action.value = "edit"
showModalDetails.value = shouldDisplay
if (!shouldDisplay) resetSelectedData()
}
const displayModalImportExport = (shouldDisplay: boolean) => {
showModalImportExport.value = shouldDisplay
}
const editEnvironment = (environmentIndex: number | "Global") => {
editingEnvironmentIndex.value = environmentIndex
action.value = "edit"
displayModalEdit(true)
}
const resetSelectedData = () => {
editingEnvironmentIndex.value = null
}
</script>

View File

@@ -3,6 +3,7 @@
<SmartTabs
v-model="selectedOptionTab"
styles="sticky bg-primary top-upperPrimaryStickyFold z-10"
render-inactive-tabs
>
<SmartTab
:id="'query'"
@@ -312,6 +313,7 @@ import {
import draggable from "vuedraggable"
import isEqual from "lodash/isEqual"
import cloneDeep from "lodash/cloneDeep"
import { refAutoReset } from "@vueuse/core"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import {
useNuxt,
@@ -612,10 +614,13 @@ useCodemirror(queryEditor, gqlQueryString, {
environmentHighlights: false,
})
const copyQueryIcon = ref("copy")
const copyVariablesIcon = ref("copy")
const prettifyQueryIcon = ref("wand")
const prettifyVariablesIcon = ref("wand")
const copyQueryIcon = refAutoReset<"copy" | "check">("copy", 1000)
const copyVariablesIcon = refAutoReset<"copy" | "check">("copy", 1000)
const prettifyQueryIcon = refAutoReset<"wand" | "check" | "info">("wand", 1000)
const prettifyVariablesIcon = refAutoReset<"wand" | "check" | "info">(
"wand",
1000
)
const showSaveRequestModal = ref(false)
@@ -623,7 +628,6 @@ const copyQuery = () => {
copyToClipboard(gqlQueryString.value)
copyQueryIcon.value = "check"
toast.success(`${t("state.copied_to_clipboard")}`)
setTimeout(() => (copyQueryIcon.value = "copy"), 1000)
}
const response = useStream(gqlResponse$, "", setGQLResponse)
@@ -699,7 +703,6 @@ const prettifyQuery = () => {
toast.error(`${t("error.gql_prettify_invalid_query")}`)
prettifyQueryIcon.value = "info"
}
setTimeout(() => (prettifyQueryIcon.value = "wand"), 1000)
}
const saveRequest = () => {
@@ -710,7 +713,6 @@ const copyVariables = () => {
copyToClipboard(variableString.value)
copyVariablesIcon.value = "check"
toast.success(`${t("state.copied_to_clipboard")}`)
setTimeout(() => (copyVariablesIcon.value = "copy"), 1000)
}
const prettifyVariableString = () => {
@@ -723,7 +725,6 @@ const prettifyVariableString = () => {
prettifyVariablesIcon.value = "info"
toast.error(`${t("error.json_prettify_invalid_body")}`)
}
setTimeout(() => (prettifyVariablesIcon.value = "wand"), 1000)
}
const clearGQLQuery = () => {

View File

@@ -78,6 +78,7 @@
<script setup lang="ts">
import { reactive, ref } from "@nuxtjs/composition-api"
import { refAutoReset } from "@vueuse/core"
import { useCodemirror } from "~/helpers/editor/codemirror"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import {
@@ -111,14 +112,16 @@ useCodemirror(
})
)
const downloadResponseIcon = ref("download")
const copyResponseIcon = ref("copy")
const downloadResponseIcon = refAutoReset<"download" | "check">(
"download",
1000
)
const copyResponseIcon = refAutoReset<"copy" | "check">("copy", 1000)
const copyResponse = () => {
copyToClipboard(responseString.value!)
copyResponseIcon.value = "check"
toast.success(`${t("state.copied_to_clipboard")}`)
setTimeout(() => (copyResponseIcon.value = "copy"), 1000)
}
const downloadResponse = () => {
@@ -135,7 +138,6 @@ const downloadResponse = () => {
setTimeout(() => {
document.body.removeChild(a)
URL.revokeObjectURL(url)
downloadResponseIcon.value = "download"
}, 1000)
}
</script>

View File

@@ -3,6 +3,7 @@
v-model="selectedNavigationTab"
styles="sticky bg-primary z-10 top-0"
vertical
render-inactive-tabs
>
<SmartTab :id="'history'" icon="clock" :label="`${t('tab.history')}`">
<History
@@ -64,6 +65,7 @@
<SmartTabs
v-model="selectedGqlTab"
styles="border-t border-b border-dividerLight bg-primary sticky z-10 top-sidebarPrimaryStickyFold"
render-inactive-tabs
>
<SmartTab
v-if="queryFields.length > 0"
@@ -193,6 +195,7 @@ import { computed, nextTick, reactive, ref } from "@nuxtjs/composition-api"
import { GraphQLField, GraphQLType } from "graphql"
import { map } from "rxjs/operators"
import { GQLHeader } from "@hoppscotch/data"
import { refAutoReset } from "@vueuse/core"
import { useCodemirror } from "~/helpers/editor/codemirror"
import { GQLConnection } from "~/helpers/GQLConnection"
import { copyToClipboard } from "~/helpers/utils/clipboard"
@@ -306,8 +309,8 @@ const graphqlTypes = useReadonlyStream(
[]
)
const downloadSchemaIcon = ref("download")
const copySchemaIcon = ref("copy")
const downloadSchemaIcon = refAutoReset<"download" | "check">("download", 1000)
const copySchemaIcon = refAutoReset<"copy" | "check">("copy", 1000)
const graphqlFieldsFilterText = ref("")
@@ -423,7 +426,6 @@ const downloadSchema = () => {
setTimeout(() => {
document.body.removeChild(a)
URL.revokeObjectURL(url)
downloadSchemaIcon.value = "download"
}, 1000)
}
@@ -432,7 +434,6 @@ const copySchema = () => {
copyToClipboard(schemaString.value)
copySchemaIcon.value = "check"
setTimeout(() => (copySchemaIcon.value = "copy"), 1000)
}
const handleUseHistory = (entry: GQLHistoryEntry) => {

View File

@@ -36,7 +36,7 @@
open
>
<summary
class="flex items-center justify-between flex-1 min-w-0 transition cursor-pointer focus:outline-none text-secondaryLight text-tiny group"
class="flex items-center justify-between flex-1 min-w-0 cursor-pointer transition focus:outline-none text-secondaryLight text-tiny group"
>
<span
class="px-4 py-2 truncate transition group-hover:text-secondary capitalize-first"
@@ -97,16 +97,32 @@
@hide-modal="confirmRemove = false"
@resolve="clearHistory"
/>
<HttpReqChangeConfirmModal
:show="confirmChange"
@hide-modal="confirmChange = false"
@save-change="saveRequestChange"
@discard-change="discardRequestChange"
/>
<CollectionsSaveRequest
mode="rest"
:show="showSaveRequestModal"
@hide-modal="showSaveRequestModal = false"
/>
</div>
</template>
<script setup lang="ts">
import { computed, ref, Ref } from "@nuxtjs/composition-api"
import { safelyExtractRESTRequest } from "@hoppscotch/data"
import {
HoppRESTRequest,
isEqualHoppRESTRequest,
safelyExtractRESTRequest,
} from "@hoppscotch/data"
import groupBy from "lodash/groupBy"
import { useTimeAgo } from "@vueuse/core"
import { pipe } from "fp-ts/function"
import * as A from "fp-ts/Array"
import * as E from "fp-ts/Either"
import {
useI18n,
useReadonlyStream,
@@ -124,17 +140,17 @@ import {
RESTHistoryEntry,
GQLHistoryEntry,
} from "~/newstore/history"
import { getDefaultRESTRequest, setRESTRequest } from "~/newstore/RESTSession"
const props = defineProps<{
page: "rest" | "graphql"
}>()
const filterText = ref("")
const showMore = ref(false)
const confirmRemove = ref(false)
const toast = useToast()
const t = useI18n()
import {
getDefaultRESTRequest,
getRESTRequest,
getRESTSaveContext,
setRESTRequest,
setRESTSaveContext,
} from "~/newstore/RESTSession"
import { editRESTRequest } from "~/newstore/collections"
import { runMutation } from "~/helpers/backend/GQLClient"
import { UpdateRequestDocument } from "~/helpers/backend/graphql"
import { HoppRequestSaveContext } from "~/helpers/types/HoppRequestSaveContext"
type HistoryEntry = GQLHistoryEntry | RESTHistoryEntry
@@ -143,6 +159,21 @@ type TimedHistoryEntry = {
timeAgo: Ref<string>
}
const props = defineProps<{
page: "rest" | "graphql"
}>()
const toast = useToast()
const t = useI18n()
const filterText = ref("")
const showMore = ref(false)
const confirmRemove = ref(false)
const clickedHistory = ref<HistoryEntry | null>(null)
const confirmChange = ref(false)
const showSaveRequestModal = ref(false)
const history = useReadonlyStream<RESTHistoryEntry[] | GQLHistoryEntry[]>(
props.page === "rest" ? restHistory$ : graphqlHistory$,
[]
@@ -199,11 +230,100 @@ const clearHistory = () => {
toast.success(`${t("state.history_deleted")}`)
}
const useHistory = (entry: any) => {
if (props.page === "rest")
setRESTRequest(
safelyExtractRESTRequest(entry.request, getDefaultRESTRequest())
const setRestReq = (request: HoppRESTRequest | null | undefined) => {
setRESTRequest(safelyExtractRESTRequest(request, getDefaultRESTRequest()))
}
// NOTE: For GQL, the HistoryGraphqlCard component already implements useEntry
// (That is not a really good behaviour tho ¯\_(ツ)_/¯)
const useHistory = (entry: RESTHistoryEntry) => {
const currentFullReq = getRESTRequest()
// Initial state trigers a popup
if (!clickedHistory.value) {
clickedHistory.value = entry
confirmChange.value = true
return
}
// Checks if there are any change done in current request and the history request
if (
!isEqualHoppRESTRequest(
currentFullReq,
clickedHistory.value.request as HoppRESTRequest
)
) {
clickedHistory.value = entry
confirmChange.value = true
} else {
props.page === "rest" && setRestReq(entry.request as HoppRESTRequest)
clickedHistory.value = entry
}
}
/** Save current request to the collection */
const saveRequestChange = () => {
const saveCtx = getRESTSaveContext()
saveCurrentRequest(saveCtx)
confirmChange.value = false
}
/** Discard changes and change the current request and remove the collection context */
const discardRequestChange = () => {
const saveCtx = getRESTSaveContext()
if (saveCtx) {
setRESTSaveContext(null)
}
clickedHistory.value &&
setRestReq(clickedHistory.value.request as HoppRESTRequest)
confirmChange.value = false
}
const saveCurrentRequest = (saveCtx: HoppRequestSaveContext | null) => {
if (!saveCtx) {
showSaveRequestModal.value = true
return
}
if (saveCtx.originLocation === "user-collection") {
try {
editRESTRequest(
saveCtx.folderPath,
saveCtx.requestIndex,
getRESTRequest()
)
clickedHistory.value &&
setRestReq(clickedHistory.value.request as HoppRESTRequest)
setRESTSaveContext(null)
toast.success(`${t("request.saved")}`)
} catch (e) {
console.error(e)
setRESTSaveContext(null)
saveCurrentRequest(null)
}
} else if (saveCtx.originLocation === "team-collection") {
const req = getRESTRequest()
try {
runMutation(UpdateRequestDocument, {
requestID: saveCtx.requestID,
data: {
title: req.name,
request: JSON.stringify(req),
},
})().then((result) => {
if (E.isLeft(result)) {
toast.error(`${t("profile.no_permission")}`)
} else {
toast.success(`${t("request.saved")}`)
}
})
clickedHistory.value &&
setRestReq(clickedHistory.value.request as HoppRESTRequest)
setRESTSaveContext(null)
} catch (error) {
showSaveRequestModal.value = true
toast.error(`${t("error.something_went_wrong")}`)
console.error(error)
setRESTSaveContext(null)
}
}
}
const isRESTHistoryEntry = (
@@ -225,14 +345,16 @@ const deleteBatchHistoryEntry = (entries: TimedHistoryEntry[]) => {
toast.success(`${t("state.deleted")}`)
}
const deleteHistory = (entry: any) => {
if (props.page === "rest") deleteRESTHistoryEntry(entry)
else deleteGraphqlHistoryEntry(entry)
const deleteHistory = (entry: HistoryEntry) => {
if (props.page === "rest") deleteRESTHistoryEntry(entry as RESTHistoryEntry)
else deleteGraphqlHistoryEntry(entry as GQLHistoryEntry)
toast.success(`${t("state.deleted")}`)
}
const toggleStar = (entry: any) => {
if (props.page === "rest") toggleRESTHistoryEntryStar(entry)
else toggleGraphqlHistoryEntryStar(entry)
const toggleStar = (entry: HistoryEntry) => {
// History entry type specified because function does not know the type
if (props.page === "rest")
toggleRESTHistoryEntryStar(entry as RESTHistoryEntry)
else toggleGraphqlHistoryEntryStar(entry as GQLHistoryEntry)
}
</script>

View File

@@ -22,7 +22,10 @@
/>
</span>
</template>
<div class="flex flex-col" role="menu">
<div
class="flex flex-col space-y-1 divide-y divide-dividerLight"
role="menu"
>
<SmartItem
:label="$t('state.none').toLowerCase()"
:info-icon="contentType === null ? 'done' : ''"
@@ -34,19 +37,36 @@
}
"
/>
<SmartItem
v-for="(contentTypeItem, index) in validContentTypes"
:key="`contentTypeItem-${index}`"
:label="contentTypeItem"
:info-icon="contentTypeItem === contentType ? 'done' : ''"
:active-info-icon="contentTypeItem === contentType"
@click.native="
() => {
contentType = contentTypeItem
$refs.contentTypeOptions.tippy().hide()
}
"
/>
<div
v-for="(
contentTypeItems, contentTypeItemsIndex
) in segmentedContentTypes"
:key="`contentTypeItems-${contentTypeItemsIndex}`"
class="flex flex-col py-2 text-left"
>
<div class="flex rounded py-2 px-4">
<span class="text-tiny text-secondaryLight font-bold">
{{ $t(contentTypeItems.title) }}
</span>
</div>
<div class="flex flex-col">
<SmartItem
v-for="(
contentTypeItem, contentTypeIndex
) in contentTypeItems.contentTypes"
:key="`contentTypeItem-${contentTypeIndex}`"
:label="contentTypeItem"
:info-icon="contentTypeItem === contentType ? 'done' : ''"
:active-info-icon="contentTypeItem === contentType"
@click.native="
() => {
contentType = contentTypeItem
$refs.contentTypeOptions.tippy().hide()
}
"
/>
</div>
</div>
</div>
</tippy>
<ButtonSecondary
@@ -106,7 +126,7 @@ import * as A from "fp-ts/Array"
import * as O from "fp-ts/Option"
import { RequestOptionTabs } from "./RequestOptions.vue"
import { useStream } from "~/helpers/utils/composables"
import { knownContentTypes } from "~/helpers/utils/contenttypes"
import { segmentedContentTypes } from "~/helpers/utils/contenttypes"
import {
restContentType$,
restHeaders$,
@@ -119,7 +139,6 @@ const emit = defineEmits<{
(e: "change-tab", value: string): void
}>()
const validContentTypes = Object.keys(knownContentTypes)
const contentType = useStream(restContentType$, null, setRESTContentType)
// The functional headers list (the headers actually in the system)

View File

@@ -38,8 +38,8 @@
drag-class="cursor-grabbing"
>
<div
v-for="(param, index) in workingParams"
:key="`param-${index}`"
v-for="({ id, entry }, index) in workingParams"
:key="`param=${id}-${index}`"
class="flex border-b divide-x divide-dividerLight border-dividerLight draggable-content group"
>
<span>
@@ -54,21 +54,21 @@
/>
</span>
<SmartEnvInput
v-model="param.key"
v-model="entry.key"
:placeholder="`${$t('count.parameter', { count: index + 1 })}`"
@change="
updateBodyParam(index, {
key: $event,
value: param.value,
active: param.active,
isFile: param.isFile,
value: entry.value,
active: entry.active,
isFile: entry.isFile,
})
"
/>
<div v-if="param.isFile" class="file-chips-container hide-scrollbar">
<div v-if="entry.isFile" class="file-chips-container hide-scrollbar">
<div class="space-x-2 file-chips-wrapper">
<SmartFileChip
v-for="(file, fileIndex) in param.value"
v-for="(file, fileIndex) in entry.value"
:key="`param-${index}-file-${fileIndex}`"
>{{ file.name }}</SmartFileChip
>
@@ -76,14 +76,14 @@
</div>
<span v-else class="flex flex-1">
<SmartEnvInput
v-model="param.value"
v-model="entry.value"
:placeholder="`${$t('count.value', { count: index + 1 })}`"
@change="
updateBodyParam(index, {
key: param.key,
key: entry.key,
value: $event,
active: param.active,
isFile: param.isFile,
active: entry.active,
isFile: entry.isFile,
})
"
/>
@@ -97,7 +97,7 @@
type="file"
multiple
class="p-1 cursor-pointer transition file:transition file:cursor-pointer text-secondaryLight hover:text-secondaryDark file:mr-2 file:py-1 file:px-4 file:rounded file:border-0 file:text-tiny text-tiny file:text-secondary hover:file:text-secondaryDark file:bg-primaryLight hover:file:bg-primaryDark"
@change="setRequestAttachment(index, param, $event)"
@change="setRequestAttachment(index, entry, $event)"
/>
</label>
</span>
@@ -105,15 +105,15 @@
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="
param.hasOwnProperty('active')
? param.active
entry.hasOwnProperty('active')
? entry.active
? $t('action.turn_off')
: $t('action.turn_on')
: $t('action.turn_off')
"
:svg="
param.hasOwnProperty('active')
? param.active
entry.hasOwnProperty('active')
? entry.active
? 'check-circle'
: 'circle'
: 'check-circle'
@@ -121,10 +121,10 @@
color="green"
@click.native="
updateBodyParam(index, {
key: param.key,
value: param.value,
active: param.hasOwnProperty('active') ? !param.active : false,
isFile: param.isFile,
key: entry.key,
value: entry.value,
active: entry.hasOwnProperty('active') ? !entry.active : false,
isFile: entry.isFile,
})
"
/>
@@ -164,6 +164,9 @@
<script setup lang="ts">
import { ref, Ref, watch } from "@nuxtjs/composition-api"
import { flow, pipe } from "fp-ts/function"
import * as O from "fp-ts/Option"
import * as A from "fp-ts/Array"
import { FormDataKeyValue } from "@hoppscotch/data"
import isEqual from "lodash/isEqual"
import { clone } from "lodash"
@@ -171,10 +174,14 @@ import draggable from "vuedraggable"
import { pluckRef, useI18n, useToast } from "~/helpers/utils/composables"
import { useRESTRequestBody } from "~/newstore/RESTSession"
type WorkingFormDataKeyValue = { id: number; entry: FormDataKeyValue }
const t = useI18n()
const toast = useToast()
const idTicker = ref(0)
const deletionToast = ref<{ goAway: (delay: number) => void } | null>(null)
const bodyParams = pluckRef<any, any>(useRESTRequestBody(), "body") as Ref<
@@ -182,23 +189,32 @@ const bodyParams = pluckRef<any, any>(useRESTRequestBody(), "body") as Ref<
>
// The UI representation of the parameters list (has the empty end param)
const workingParams = ref<FormDataKeyValue[]>([
const workingParams = ref<WorkingFormDataKeyValue[]>([
{
key: "",
value: "",
active: true,
isFile: false,
id: idTicker.value++,
entry: {
key: "",
value: "",
active: true,
isFile: false,
},
},
])
// Rule: Working Params always have last element is always an empty param
watch(workingParams, (paramsList) => {
if (paramsList.length > 0 && paramsList[paramsList.length - 1].key !== "") {
if (
paramsList.length > 0 &&
paramsList[paramsList.length - 1].entry.key !== ""
) {
workingParams.value.push({
key: "",
value: "",
active: true,
isFile: false,
id: idTicker.value++,
entry: {
key: "",
value: "",
active: true,
isFile: false,
},
})
}
})
@@ -208,19 +224,37 @@ watch(
bodyParams,
(newParamsList) => {
// Sync should overwrite working params
const filteredWorkingParams = workingParams.value.filter(
(e) => e.key !== ""
const filteredWorkingParams = pipe(
workingParams.value,
A.filterMap(
flow(
O.fromPredicate((e) => e.entry.key !== ""),
O.map((e) => e.entry)
)
)
)
if (!isEqual(newParamsList, filteredWorkingParams)) {
workingParams.value = newParamsList
workingParams.value = pipe(
newParamsList,
A.map((x) => ({ id: idTicker.value++, entry: x }))
)
}
},
{ immediate: true }
)
watch(workingParams, (newWorkingParams) => {
const fixedParams = newWorkingParams.filter((e) => e.key !== "")
const fixedParams = pipe(
newWorkingParams,
A.filterMap(
flow(
O.fromPredicate((e) => e.entry.key !== ""),
O.map((e) => e.entry)
)
)
)
if (!isEqual(bodyParams.value, fixedParams)) {
bodyParams.value = fixedParams
}
@@ -228,16 +262,19 @@ watch(workingParams, (newWorkingParams) => {
const addBodyParam = () => {
workingParams.value.push({
key: "",
value: "",
active: true,
isFile: false,
id: idTicker.value++,
entry: {
key: "",
value: "",
active: true,
isFile: false,
},
})
}
const updateBodyParam = (index: number, param: FormDataKeyValue) => {
const updateBodyParam = (index: number, entry: FormDataKeyValue) => {
workingParams.value = workingParams.value.map((h, i) =>
i === index ? param : h
i === index ? { id: h.id, entry } : h
)
}
@@ -280,10 +317,13 @@ const clearContent = () => {
// set params list to the initial state
workingParams.value = [
{
key: "",
value: "",
active: true,
isFile: false,
id: idTicker.value++,
entry: {
key: "",
value: "",
active: true,
isFile: false,
},
},
]
}

View File

@@ -87,6 +87,7 @@
import { computed, ref, watch } from "@nuxtjs/composition-api"
import * as O from "fp-ts/Option"
import { Environment, makeRESTRequest } from "@hoppscotch/data"
import { refAutoReset } from "@vueuse/core"
import { useCodemirror } from "~/helpers/editor/codemirror"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import {
@@ -118,9 +119,10 @@ const options = ref<any | null>(null)
const request = ref(getRESTRequest())
const codegenType = ref<CodegenName>("shell-curl")
const copyIcon = ref("copy")
const errorState = ref(false)
const copyIcon = refAutoReset<"copy" | "check">("copy", 1000)
const requestCode = computed(() => {
const aggregateEnvs = getAggregateEnvs()
const env: Environment = {
@@ -184,7 +186,6 @@ const copyRequestCode = () => {
copyToClipboard(requestCode.value)
copyIcon.value = "check"
toast.success(`${t("state.copied_to_clipboard")}`)
setTimeout(() => (copyIcon.value = "copy"), 1000)
}
const searchQuery = ref("")

View File

@@ -137,6 +137,47 @@
/>
</span>
</div>
<div
v-for="(header, index) in computedHeaders"
:key="`header-${index}`"
class="flex border-b divide-x divide-dividerLight border-dividerLight draggable-content group"
>
<span>
<ButtonSecondary
svg="lock"
class="opacity-25 cursor-auto text-secondaryLight bg-divider"
tabindex="-1"
/>
</span>
<SmartEnvInput
v-model="header.header.key"
:placeholder="`${t('count.value', { count: index + 1 })}`"
readonly
/>
<SmartEnvInput
:value="mask(header)"
:placeholder="`${t('count.value', { count: index + 1 })}`"
readonly
/>
<span>
<ButtonSecondary
v-if="header.source === 'auth'"
:svg="masking ? 'eye' : 'eye-off'"
@click.native="toggleMask()"
/>
<ButtonSecondary
v-else
svg="arrow-up-right"
class="cursor-auto text-primary hover:text-primary"
/>
</span>
<span>
<ButtonSecondary
svg="arrow-up-right"
@click.native="changeTab(header.source)"
/>
</span>
</div>
</draggable>
<div
v-if="workingHeaders.length === 0"
@@ -162,7 +203,7 @@
</template>
<script setup lang="ts">
import { Ref, ref, watch } from "@nuxtjs/composition-api"
import { computed, Ref, ref, watch } from "@nuxtjs/composition-api"
import isEqual from "lodash/isEqual"
import {
HoppRESTHeader,
@@ -177,13 +218,29 @@ import * as O from "fp-ts/Option"
import * as A from "fp-ts/Array"
import cloneDeep from "lodash/cloneDeep"
import draggable from "vuedraggable"
import { RequestOptionTabs } from "./RequestOptions.vue"
import { useCodemirror } from "~/helpers/editor/codemirror"
import { restHeaders$, setRESTHeaders } from "~/newstore/RESTSession"
import {
getRESTRequest,
restHeaders$,
restRequest$,
setRESTHeaders,
} from "~/newstore/RESTSession"
import { commonHeaders } from "~/helpers/headers"
import { useI18n, useStream, useToast } from "~/helpers/utils/composables"
import {
useI18n,
useReadonlyStream,
useStream,
useToast,
} from "~/helpers/utils/composables"
import linter from "~/helpers/editor/linting/rawKeyValue"
import { throwError } from "~/helpers/functional/error"
import { objRemoveKey } from "~/helpers/functional/object"
import {
ComputedHeader,
getComputedHeaders,
} from "~/helpers/utils/EffectiveURL"
import { aggregateEnvs$, getAggregateEnvs } from "~/newstore/environments"
const t = useI18n()
const toast = useToast()
@@ -196,6 +253,10 @@ const bulkEditor = ref<any | null>(null)
const deletionToast = ref<{ goAway: (delay: number) => void } | null>(null)
const emit = defineEmits<{
(e: "change-tab", value: RequestOptionTabs): void
}>()
useCodemirror(bulkEditor, bulkHeaders, {
extendedEditorConfig: {
mode: "text/x-yaml",
@@ -379,4 +440,28 @@ const clearContent = () => {
bulkHeaders.value = ""
}
const restRequest = useReadonlyStream(restRequest$, getRESTRequest())
const aggregateEnvs = useReadonlyStream(aggregateEnvs$, getAggregateEnvs())
const computedHeaders = computed(() =>
getComputedHeaders(restRequest.value, aggregateEnvs.value)
)
const masking = ref(true)
const toggleMask = () => {
masking.value = !masking.value
}
const mask = (header: ComputedHeader) => {
if (header.source === "auth" && masking.value)
return header.header.value.replace(/\S/gi, "*")
return header.header.value
}
const changeTab = (tab: ComputedHeader["source"]) => {
if (tab === "auth") emit("change-tab", "authorization")
else emit("change-tab", "bodyParams")
}
</script>

View File

@@ -39,6 +39,7 @@
<script setup lang="ts">
import { ref, watch } from "@nuxtjs/composition-api"
import { refAutoReset } from "@vueuse/core"
import { useCodemirror } from "~/helpers/editor/codemirror"
import { setRESTRequest } from "~/newstore/RESTSession"
import { useI18n, useToast } from "~/helpers/utils/composables"
@@ -95,7 +96,7 @@ const handleImport = () => {
hideModal()
}
const pasteIcon = ref("clipboard")
const pasteIcon = refAutoReset<"clipboard" | "check">("clipboard", 1000)
const handlePaste = async () => {
try {
@@ -103,7 +104,6 @@ const handlePaste = async () => {
if (text) {
curl.value = text
pasteIcon.value = "check"
setTimeout(() => (pasteIcon.value = "clipboard"), 1000)
}
} catch (e) {
console.error("Failed to copy: ", e)

View File

@@ -61,6 +61,7 @@ import { computed, reactive, Ref, ref } from "@nuxtjs/composition-api"
import * as TO from "fp-ts/TaskOption"
import { pipe } from "fp-ts/function"
import { HoppRESTReqBody, ValidContentTypes } from "@hoppscotch/data"
import { refAutoReset } from "@vueuse/core"
import { useCodemirror } from "~/helpers/editor/codemirror"
import { getEditorLangForMimeType } from "~/helpers/editorutils"
import { pluckRef, useI18n, useToast } from "~/helpers/utils/composables"
@@ -91,7 +92,8 @@ const rawParamsBody = pluckRef(
>,
"body"
)
const prettifyIcon = ref("wand")
const prettifyIcon = refAutoReset<"wand" | "check" | "info">("wand", 1000)
const rawInputEditorLang = computed(() =>
getEditorLangForMimeType(props.contentType)
@@ -148,6 +150,5 @@ const prettifyRequestBody = () => {
prettifyIcon.value = "info"
toast.error(`${t("error.json_prettify_invalid_body")}`)
}
setTimeout(() => (prettifyIcon.value = "wand"), 1000)
}
</script>

View File

@@ -0,0 +1,59 @@
<template>
<SmartModal
v-if="show"
dialog
:title="$t('modal.confirm')"
aria-modal="true"
@close="hideModal"
>
<template #body>
<div class="flex flex-col px-2">
<label>
{{ t("confirm.request_change") }}
</label>
</div>
</template>
<template #footer>
<span>
<ButtonPrimary
v-focus
:label="t('action.save')"
@click.native="saveApiChange"
/>
<ButtonSecondary
:label="t('action.dont_save')"
@click.native="discardApiChange"
/>
</span>
<ButtonSecondary :label="t('action.cancel')" @click.native="hideModal" />
</template>
</SmartModal>
</template>
<script setup lang="ts">
import { useI18n } from "~/helpers/utils/composables"
const t = useI18n()
defineProps<{
show: Boolean
}>()
const emit = defineEmits<{
(e: "save-change"): void
(e: "discard-change"): void
(e: "hide-modal"): void
}>()
const saveApiChange = () => {
emit("save-change")
}
const discardApiChange = () => {
emit("discard-change")
}
const hideModal = () => {
emit("hide-modal")
}
</script>

View File

@@ -171,6 +171,12 @@
}
"
/>
<SmartItem
svg="link-2"
:label="`${t('request.view_my_links')}`"
to="/profile"
/>
<hr />
<SmartItem
ref="saveRequestAction"
:label="`${t('request.save_as')}`"
@@ -208,6 +214,8 @@
import { computed, ref, watch } from "@nuxtjs/composition-api"
import { isLeft, isRight } from "fp-ts/lib/Either"
import * as E from "fp-ts/Either"
import cloneDeep from "lodash/cloneDeep"
import { refAutoReset } from "@vueuse/core"
import {
updateRESTResponse,
restEndpoint$,
@@ -386,7 +394,11 @@ const clearContent = () => {
resetRESTRequest()
}
const copyLinkIcon = hasNavigatorShare ? ref("share-2") : ref("copy")
const copyLinkIcon = refAutoReset<"share-2" | "copy" | "check">(
hasNavigatorShare ? "share-2" : "copy",
1000
)
const shareLink = ref<string | null>("")
const fetchingShareLink = ref(false)
@@ -441,7 +453,6 @@ const copyShareLink = (shareLink: string) => {
copyLinkIcon.value = "check"
copyToClipboard(`https://hopp.sh/r${shareLink}`)
toast.success(`${t("state.copied_to_clipboard")}`)
setTimeout(() => (copyLinkIcon.value = "copy"), 2000)
}
}
@@ -477,14 +488,21 @@ const saveRequest = () => {
showSaveRequestModal.value = true
return
}
if (saveCtx.originLocation === "user-collection") {
const req = getRESTRequest()
try {
editRESTRequest(
saveCtx.folderPath,
saveCtx.requestIndex,
getRESTRequest()
)
setRESTSaveContext({
originLocation: "user-collection",
folderPath: saveCtx.folderPath,
requestIndex: saveCtx.requestIndex,
req: cloneDeep(req),
})
toast.success(`${t("request.saved")}`)
} catch (e) {
setRESTSaveContext(null)
@@ -505,6 +523,11 @@ const saveRequest = () => {
if (E.isLeft(result)) {
toast.error(`${t("profile.no_permission")}`)
} else {
setRESTSaveContext({
originLocation: "team-collection",
requestID: saveCtx.requestID,
req: cloneDeep(req),
})
toast.success(`${t("request.saved")}`)
}
})

View File

@@ -2,6 +2,7 @@
<SmartTabs
v-model="selectedRealtimeTab"
styles="sticky bg-primary top-upperMobilePrimaryStickyFold sm:top-upperPrimaryStickyFold z-10"
render-inactive-tabs
>
<SmartTab
:id="'params'"
@@ -18,7 +19,7 @@
:label="`${$t('tab.headers')}`"
:info="`${newActiveHeadersCount$}`"
>
<HttpHeaders />
<HttpHeaders @change-tab="changeTab" />
</SmartTab>
<SmartTab :id="'authorization'" :label="`${$t('tab.authorization')}`">
<HttpAuthorization />

View File

@@ -117,9 +117,21 @@
<span class="text-secondary"> {{ t("response.time") }}: </span>
{{ `${response.meta.responseDuration} ms` }}
</span>
<span v-if="response.meta && response.meta.responseSize">
<span
v-if="response.meta && response.meta.responseSize"
v-tippy="
readableResponseSize
? { theme: 'tooltip' }
: { onShow: () => false }
"
:title="`${response.meta.responseSize} B`"
>
<span class="text-secondary"> {{ t("response.size") }}: </span>
{{ `${response.meta.responseSize} B` }}
{{
readableResponseSize
? readableResponseSize
: `${response.meta.responseSize} B`
}}
</span>
</div>
</div>
@@ -141,6 +153,29 @@ const props = defineProps<{
response: HoppRESTResponse
}>()
/**
* Gives the response size in a human readable format
* (changes unit from B to MB/KB depending on the size)
* If no changes (error res state) or value can be made (size < 1KB ?),
* it returns undefined
*/
const readableResponseSize = computed(() => {
if (
props.response.type === "loading" ||
props.response.type === "network_fail" ||
props.response.type === "script_fail" ||
props.response.type === "fail"
)
return undefined
const size = props.response.meta.responseSize
if (size >= 100000) return (size / 1000000).toFixed(2) + " MB"
if (size >= 1000) return (size / 1000).toFixed(2) + " KB"
return undefined
})
const statusCategory = computed(() => {
if (
props.response.type === "loading" ||

View File

@@ -3,6 +3,7 @@
v-model="selectedNavigationTab"
styles="sticky bg-primary z-10 top-0"
vertical
render-inactive-tabs
>
<SmartTab :id="'history'" icon="clock" :label="`${$t('tab.history')}`">
<History ref="historyComponent" :page="'rest'" />

View File

@@ -12,10 +12,13 @@
<span class="text-secondaryDark">
{{ env.key }}
</span>
<span class="text-secondaryDark">
<span class="text-secondaryDark pl-2 break-all">
{{ ` \xA0 — \xA0 ${env.value}` }}
</span>
<span v-if="status === 'updations'" class="text-secondaryLight">
<span
v-if="status === 'updations'"
class="text-secondaryLight px-2 break-all"
>
{{ ` \xA0 ← \xA0 ${env.previousValue}` }}
</span>
</div>

View File

@@ -17,32 +17,17 @@
/>
</div>
</div>
<div
<LensesHeadersRendererEntry
v-for="(header, index) in headers"
:key="`header-${index}`"
class="flex border-b divide-x divide-dividerLight border-dividerLight group"
>
<span
class="flex flex-1 min-w-0 px-4 py-2 transition group-hover:text-secondaryDark"
>
<span class="truncate rounded-sm select-all">
{{ header.key }}
</span>
</span>
<span
class="flex flex-1 min-w-0 px-4 py-2 transition group-hover:text-secondaryDark"
>
<span class="truncate rounded-sm select-all">
{{ header.value }}
</span>
</span>
</div>
:key="index"
:header="header"
/>
</div>
</template>
<script setup lang="ts">
import { ref } from "@nuxtjs/composition-api"
import { HoppRESTHeader } from "@hoppscotch/data"
import { refAutoReset } from "@vueuse/core"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import { useI18n, useToast } from "~/helpers/utils/composables"
@@ -54,12 +39,11 @@ const props = defineProps<{
headers: Array<HoppRESTHeader>
}>()
const copyIcon = ref("copy")
const copyIcon = refAutoReset<"copy" | "check">("copy", 1000)
const copyHeaders = () => {
copyToClipboard(JSON.stringify(props.headers))
copyIcon.value = "check"
toast.success(`${t("state.copied_to_clipboard")}`)
setTimeout(() => (copyIcon.value = "copy"), 1000)
}
</script>

View File

@@ -0,0 +1,51 @@
<template>
<div
class="flex border-b divide-x divide-dividerLight border-dividerLight group"
>
<span
class="flex flex-1 min-w-0 px-4 py-2 transition group-hover:text-secondaryDark"
>
<span class="truncate rounded-sm select-all">
{{ header.key }}
</span>
</span>
<span
class="flex flex-1 min-w-0 pl-4 py-2 transition group-hover:text-secondaryDark justify-between"
>
<span class="truncate rounded-sm select-all">
{{ header.value }}
</span>
<ButtonSecondary
ref="copyHeader"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.copy')"
:svg="copyIcon"
class="hidden group-hover:inline-flex !py-0"
@click.native="copyHeader(header.value)"
/>
</span>
</div>
</template>
<script setup lang="ts">
import { refAutoReset } from "@vueuse/core"
import { HoppRESTHeader } from "~/../hoppscotch-data/dist"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import { useI18n, useToast } from "~/helpers/utils/composables"
const t = useI18n()
const toast = useToast()
defineProps<{
header: HoppRESTHeader
}>()
const copyIcon = refAutoReset<"copy" | "check">("copy", 1000)
const copyHeader = (headerValue: string) => {
copyToClipboard(headerValue)
copyIcon.value = "check"
toast.success(`${t("state.copied_to_clipboard")}`)
}
</script>

View File

@@ -3,6 +3,7 @@
v-if="response"
v-model="selectedLensTab"
styles="sticky z-10 bg-primary top-lowerPrimaryStickyFold"
render-inactive-tabs
>
<SmartTab
v-for="(lens, index) in validLenses"

View File

@@ -1,12 +1,15 @@
<template>
<div class="flex flex-col flex-1">
<div
v-if="response.type === 'success' || response.type === 'fail'"
class="flex flex-col flex-1"
>
<div
class="sticky z-10 flex items-center justify-between pl-4 border-b bg-primary border-dividerLight top-lowerSecondaryStickyFold"
>
<label class="font-semibold text-secondaryLight">
{{ t("response.body") }}
</label>
<div class="flex">
<div class="flex items-center">
<ButtonSecondary
v-if="response.body"
v-tippy="{ theme: 'tooltip' }"
@@ -15,6 +18,14 @@
svg="wrap-text"
@click.native.prevent="linewrapEnabled = !linewrapEnabled"
/>
<ButtonSecondary
v-if="response.body"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.filter_response')"
svg="filter"
:class="{ '!text-accent': toggleFilter }"
@click.native.prevent="toggleFilterState"
/>
<ButtonSecondary
v-if="response.body"
ref="downloadResponse"
@@ -33,7 +44,47 @@
/>
</div>
</div>
<div ref="jsonResponse" class="flex flex-col flex-1"></div>
<div
v-if="toggleFilter"
class="bg-primary flex sticky top-lowerTertiaryStickyFold z-10 border-b border-dividerLight"
>
<div
class="bg-primaryLight border-divider text-secondaryDark inline-flex flex-1 items-center"
>
<span class="inline-flex flex-1 items-center px-4">
<SmartIcon name="search" class="h-4 w-4 text-secondaryLight" />
<input
v-model="filterQueryText"
v-focus
class="input !border-0 !px-2"
:placeholder="`${t('response.filter_response_body')}`"
type="text"
/>
</span>
<div
v-if="filterResponseError"
class="px-2 py-1 text-tiny flex items-center justify-center text-accentContrast rounded"
:class="{
'bg-red-500':
filterResponseError.type === 'JSON_PARSE_FAILED' ||
filterResponseError.type === 'JSON_PATH_QUERY_ERROR',
'bg-amber-500': filterResponseError.type === 'RESPONSE_EMPTY',
}"
>
<SmartIcon name="info" class="svg-icons mr-1.5" />
<span>{{ filterResponseError.error }}</span>
</div>
<ButtonSecondary
v-if="response.body"
v-tippy="{ theme: 'tooltip' }"
:title="t('app.wiki')"
svg="help-circle"
to="https://github.com/JSONPath-Plus/JSONPath"
blank
/>
</div>
</div>
<div ref="jsonResponse" class="flex flex-col flex-1 h-auto h-full"></div>
<div
v-if="outlinePath"
class="sticky bottom-0 z-10 flex px-2 overflow-auto border-t bg-primaryLight border-dividerLight flex-nowrap hide-scrollbar"
@@ -142,8 +193,10 @@
<script setup lang="ts">
import * as LJSON from "lossless-json"
import * as O from "fp-ts/Option"
import * as E from "fp-ts/Either"
import { pipe } from "fp-ts/function"
import { computed, ref, reactive } from "@nuxtjs/composition-api"
import { JSONPath } from "jsonpath-plus"
import { useCodemirror } from "~/helpers/editor/codemirror"
import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"
import jsonParse, { JSONObjectMember, JSONValue } from "~/helpers/jsonParse"
@@ -165,16 +218,51 @@ const props = defineProps<{
const { responseBodyText } = useResponseBody(props.response)
const { copyIcon, copyResponse } = useCopyResponse(responseBodyText)
const toggleFilter = ref(false)
const filterQueryText = ref("")
const { downloadIcon, downloadResponse } = useDownloadResponse(
"application/json",
responseBodyText
type BodyParseError =
| { type: "JSON_PARSE_FAILED" }
| { type: "JSON_PATH_QUERY_FAILED"; error: Error }
const responseJsonObject = computed(() =>
pipe(
responseBodyText.value,
E.tryCatchK(
LJSON.parse,
(): BodyParseError => ({ type: "JSON_PARSE_FAILED" })
)
)
)
const jsonResponseBodyText = computed(() => {
if (filterQueryText.value.length > 0) {
return pipe(
responseJsonObject.value,
E.chain((parsedJSON) =>
E.tryCatch(
() =>
JSONPath({
path: filterQueryText.value,
json: parsedJSON,
}) as undefined,
(err): BodyParseError => ({
type: "JSON_PATH_QUERY_FAILED",
error: err as Error,
})
)
),
E.map(JSON.stringify)
)
} else {
return E.right(responseBodyText.value)
}
})
const jsonBodyText = computed(() =>
pipe(
responseBodyText.value,
jsonResponseBodyText.value,
E.getOrElse(() => responseBodyText.value),
O.tryCatchK(LJSON.parse),
O.map((val) => LJSON.stringify(val, undefined, 2)),
O.getOrElse(() => responseBodyText.value)
@@ -189,6 +277,38 @@ const ast = computed(() =>
)
)
const filterResponseError = computed(() =>
pipe(
jsonResponseBodyText.value,
E.match(
(e) => {
switch (e.type) {
case "JSON_PATH_QUERY_FAILED":
return { type: "JSON_PATH_QUERY_ERROR", error: e.error.message }
case "JSON_PARSE_FAILED":
return {
type: "JSON_PARSE_FAILED",
error: t("error.json_parsing_failed").toString(),
}
}
},
(result) =>
result === "[]"
? {
type: "RESPONSE_EMPTY",
error: t("error.no_results_found").toString(),
}
: undefined
)
)
)
const { copyIcon, copyResponse } = useCopyResponse(jsonBodyText)
const { downloadIcon, downloadResponse } = useDownloadResponse(
"application/json",
jsonBodyText
)
const outlineOptions = ref<any | null>(null)
const jsonResponse = ref<any | null>(null)
const linewrapEnabled = ref(true)
@@ -227,6 +347,11 @@ const outlinePath = computed(() =>
O.getOrElseW(() => null)
)
)
const toggleFilterState = () => {
filterQueryText.value = ""
toggleFilter.value = !toggleFilter.value
}
</script>
<style lang="scss" scoped>

View File

@@ -0,0 +1,136 @@
<template>
<div
class="table-row-groups lg:flex block my-6 lg:my-0 w-full border lg:border-0 divide-y lg:divide-y-0 lg:divide-x divide-dividerLight border-dividerLight"
>
<div
class="table-column font-mono text-tiny"
:data-label="t('shortcodes.short_code')"
>
{{ shortcode.id }}
</div>
<div
class="table-column"
:class="requestLabelColor"
:data-label="t('shortcodes.method')"
>
{{ parseShortcodeRequest.method }}
</div>
<div class="table-column" :data-label="t('shortcodes.url')">
{{ parseShortcodeRequest.endpoint }}
</div>
<div
ref="timeStampRef"
class="table-column"
:data-label="t('shortcodes.created_on')"
>
<span v-tippy="{ theme: 'tooltip' }" :title="timeStamp">
{{ dateStamp }}
</span>
</div>
<div
class="flex flex-1 items-center justify-center px-3"
:data-label="t('shortcodes.actions')"
>
<SmartAnchor
v-tippy="{ theme: 'tooltip' }"
:title="t('action.open_workspace')"
:to="`https://hopp.sh/r/${shortcode.id}`"
blank
svg="external-link"
class="px-3 text-accent hover:text-accent"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.copy')"
color="green"
:svg="copyIconRefs"
class="px-3"
@click.native="copyShortcode(shortcode.id)"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.delete')"
svg="trash"
color="red"
class="px-3"
@click.native="deleteShortcode(shortcode.id)"
/>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from "@nuxtjs/composition-api"
import { pipe } from "fp-ts/function"
import * as RR from "fp-ts/ReadonlyRecord"
import * as O from "fp-ts/Option"
import { translateToNewRequest } from "@hoppscotch/data"
import { refAutoReset } from "@vueuse/core"
import { useI18n, useToast } from "~/helpers/utils/composables"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import { Shortcode } from "~/helpers/shortcodes/Shortcode"
const t = useI18n()
const toast = useToast()
const props = defineProps<{
shortcode: Shortcode
}>()
const emit = defineEmits<{
(e: "delete-shortcode", codeID: string): void
}>()
const deleteShortcode = (codeID: string) => {
emit("delete-shortcode", codeID)
}
const requestMethodLabels = {
get: "text-green-500",
post: "text-yellow-500",
put: "text-blue-500",
delete: "text-red-500",
default: "text-gray-500",
} as const
const timeStampRef = ref()
const copyIconRefs = refAutoReset<"copy" | "check">("copy", 1000)
const parseShortcodeRequest = computed(() =>
pipe(props.shortcode.request, JSON.parse, translateToNewRequest)
)
const requestLabelColor = computed(() =>
pipe(
requestMethodLabels,
RR.lookup(parseShortcodeRequest.value.method.toLowerCase()),
O.getOrElseW(() => requestMethodLabels.default)
)
)
const dateStamp = computed(() =>
new Date(props.shortcode.createdOn).toLocaleDateString()
)
const timeStamp = computed(() =>
new Date(props.shortcode.createdOn).toLocaleTimeString()
)
const copyShortcode = (codeID: string) => {
copyToClipboard(`https://hopp.sh/r/${codeID}`)
toast.success(`${t("state.copied_to_clipboard")}`)
copyIconRefs.value = "check"
}
</script>
<style lang="scss">
.table-column {
@apply flex flex-1 items-center px-3 py-3 truncate;
}
.table-row-groups {
.table-column {
@apply before:text-secondary before:font-bold before:content-[attr(data-label)] lg:before:hidden;
}
}
</style>

View File

@@ -0,0 +1,222 @@
<template>
<div class="flex flex-col flex-1">
<div v-if="showEventField" class="flex items-center justify-between p-4">
<input
id="event_name"
v-model="eventName"
class="input"
name="event_name"
:placeholder="`${t('socketio.event_name')}`"
type="text"
autocomplete="off"
/>
</div>
<div
class="sticky z-10 flex items-center justify-between pl-4 border-b bg-primary border-dividerLight top-upperSecondaryStickyFold"
>
<span class="flex items-center">
<label class="font-semibold text-secondaryLight">
{{ $t("websocket.message") }}
</label>
<tippy
ref="contentTypeOptions"
interactive
trigger="click"
theme="popover"
arrow
>
<template #trigger>
<span class="select-wrapper">
<ButtonSecondary
:label="contentType || $t('state.none').toLowerCase()"
class="pr-8 ml-2 rounded-none"
/>
</span>
</template>
<div class="flex flex-col" role="menu">
<SmartItem
v-for="(contentTypeItem, index) in validContentTypes"
:key="`contentTypeItem-${index}`"
:label="contentTypeItem"
:info-icon="contentTypeItem === contentType ? 'done' : ''"
:active-info-icon="contentTypeItem === contentType"
@click.native="
() => {
contentType = contentTypeItem
$refs.contentTypeOptions.tippy().hide()
}
"
/>
</div>
</tippy>
</span>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip', delay: [500, 20], allowHTML: true }"
:title="`${t('action.send')}`"
:label="`${t('action.send')}`"
:disabled="!communicationBody || !isConnected"
svg="send"
class="rounded-none !text-accent !hover:text-accentDark"
@click.native="sendMessage()"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
to="https://docs.hoppscotch.io/features/body"
blank
:title="t('app.wiki')"
svg="help-circle"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('state.linewrap')"
:class="{ '!text-accent': linewrapEnabled }"
svg="wrap-text"
@click.native.prevent="linewrapEnabled = !linewrapEnabled"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.clear')"
svg="trash-2"
@click.native="clearContent"
/>
<ButtonSecondary
v-if="contentType && contentType == 'JSON'"
ref="prettifyRequest"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.prettify')"
:svg="prettifyIcon"
@click.native="prettifyRequestBody"
/>
<label for="payload">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('import.title')"
svg="file-plus"
@click.native="$refs.payload.click()"
/>
</label>
<input
ref="payload"
class="input"
name="payload"
type="file"
@change="uploadPayload"
/>
</div>
</div>
<div ref="wsCommunicationBody" class="flex flex-col flex-1"></div>
</div>
</template>
<script setup lang="ts">
import { computed, reactive, ref } from "@nuxtjs/composition-api"
import { pipe } from "fp-ts/function"
import * as TO from "fp-ts/TaskOption"
import * as O from "fp-ts/Option"
import { refAutoReset } from "@vueuse/core"
import { useCodemirror } from "~/helpers/editor/codemirror"
import jsonLinter from "~/helpers/editor/linting/json"
import { readFileAsText } from "~/helpers/functional/files"
import { useI18n, useToast } from "~/helpers/utils/composables"
import { isJSONContentType } from "~/helpers/utils/contenttypes"
defineProps({
showEventField: {
type: Boolean,
default: false,
},
isConnected: {
type: Boolean,
default: false,
},
})
const emit = defineEmits<{
(
e: "send-message",
body: {
eventName: string
message: string
}
): void
}>()
const t = useI18n()
const toast = useToast()
const linewrapEnabled = ref(true)
const wsCommunicationBody = ref<HTMLElement>()
const prettifyIcon = refAutoReset<"wand" | "check" | "info">("wand", 1000)
const knownContentTypes = {
JSON: "application/ld+json",
Raw: "text/plain",
} as const
const validContentTypes = Object.keys(knownContentTypes)
const contentType = ref<keyof typeof knownContentTypes>("JSON")
const eventName = ref("")
const communicationBody = ref("")
const rawInputEditorLang = computed(() => knownContentTypes[contentType.value])
const langLinter = computed(() =>
isJSONContentType(contentType.value) ? jsonLinter : null
)
useCodemirror(
wsCommunicationBody,
communicationBody,
reactive({
extendedEditorConfig: {
lineWrapping: linewrapEnabled,
mode: rawInputEditorLang,
placeholder: t("websocket.message").toString(),
},
linter: langLinter,
completer: null,
environmentHighlights: true,
})
)
const clearContent = () => {
communicationBody.value = ""
}
const sendMessage = () => {
if (!communicationBody.value) return
emit("send-message", {
eventName: eventName.value,
message: communicationBody.value,
})
communicationBody.value = ""
}
const uploadPayload = async (e: InputEvent) => {
const result = await pipe(
(e.target as HTMLInputElement).files?.[0],
TO.fromNullable,
TO.chain(readFileAsText)
)()
if (O.isSome(result)) {
communicationBody.value = result.value
toast.success(`${t("state.file_imported")}`)
} else {
toast.error(`${t("action.choose_file")}`)
}
}
const prettifyRequestBody = () => {
try {
const jsonObj = JSON.parse(communicationBody.value)
communicationBody.value = JSON.stringify(jsonObj, null, 2)
prettifyIcon.value = "check"
} catch (e) {
console.error(e)
prettifyIcon.value = "info"
toast.error(`${t("error.json_prettify_invalid_body")}`)
}
}
</script>

View File

@@ -1,77 +1,129 @@
<template>
<div class="flex flex-col flex-1">
<div ref="container" class="flex flex-col flex-1 overflow-y-auto">
<div
class="sticky top-0 z-10 flex items-center justify-between pl-4 border-b bg-primary border-dividerLight"
class="sticky top-0 z-10 flex items-center justify-between flex-none pl-4 border-b bg-primary border-dividerLight"
>
<label for="log" class="py-2 font-semibold text-secondaryLight">
{{ title }}
</label>
<div>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.delete')"
svg="trash"
@click.native="emit('delete')"
/>
<ButtonSecondary
id="bottompage"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.scroll_to_top')"
svg="arrow-up"
@click.native="scrollTo('top')"
/>
<ButtonSecondary
id="bottompage"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.scroll_to_bottom')"
svg="arrow-down"
@click.native="scrollTo('bottom')"
/>
<ButtonSecondary
id="bottompage"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.autoscroll')"
svg="chevrons-down"
:class="toggleAutoscrollColor"
@click.native="toggleAutoscroll()"
/>
</div>
</div>
<div ref="logsRef" name="log" class="realtime-log">
<span v-if="log" class="space-y-2">
<span
<div
v-if="log.length !== 0"
ref="logs"
class="overflow-y-auto border-b border-dividerLight"
>
<div
class="flex flex-col h-auto h-full border-r divide-y divide-dividerLight border-dividerLight"
>
<RealtimeLogEntry
v-for="(entry, index) in log"
:key="`entry-${index}`"
:style="{ color: entry.color }"
class="font-mono"
>{{ entry.ts }}{{ source(entry.source) }}{{ entry.payload }}</span
>
</span>
<span v-else>{{ t("response.waiting_for_connection") }}</span>
:entry="entry"
/>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { nextTick, ref, watch } from "@nuxtjs/composition-api"
import { getSourcePrefix as source } from "~/helpers/utils/string"
import { ref, PropType, computed, watch } from "@nuxtjs/composition-api"
import { useThrottleFn, useScroll } from "@vueuse/core"
import { useI18n } from "~/helpers/utils/composables"
const t = useI18n()
export type LogEntryData = {
prefix?: string
ts: number | undefined
source: "info" | "client" | "server" | "disconnected"
payload: string
event: "connecting" | "connected" | "disconnected" | "error"
}
const props = defineProps({
log: { type: Array, default: () => [] },
log: { type: Array as PropType<LogEntryData[]>, default: () => [] },
title: {
type: String,
default: "",
},
})
const logsRef = ref<any | null>(null)
const BOTTOM_SCROLL_DIST_INACCURACY = 5
const emit = defineEmits<{
(e: "delete"): void
}>()
const t = useI18n()
const container = ref<HTMLElement | null>(null)
const logs = ref<HTMLElement | null>(null)
const autoScrollEnabled = ref(true)
const logListScroll = useScroll(logs)
// Disable autoscroll when scrolling to top
watch(logListScroll.isScrolling, (isScrolling) => {
if (isScrolling && logListScroll.directions.top)
autoScrollEnabled.value = false
})
const scrollTo = (position: "top" | "bottom") => {
if (position === "top") {
logs.value?.scroll({
behavior: "smooth",
top: 0,
})
} else if (position === "bottom") {
logs.value?.scroll({
behavior: "smooth",
top: logs.value?.scrollHeight,
})
}
}
watch(
() => props.log,
() => {
if (!logsRef.value) return
const distToBottom =
logsRef.value.scrollHeight -
logsRef.value.scrollTop -
logsRef.value.clientHeight
if (distToBottom < BOTTOM_SCROLL_DIST_INACCURACY) {
nextTick(() => (logsRef.value.scrollTop = logsRef.value.scrollHeight))
}
}
useThrottleFn(() => {
if (autoScrollEnabled.value) scrollTo("bottom")
}, 200),
{ flush: "post" }
)
const toggleAutoscroll = () => {
autoScrollEnabled.value = !autoScrollEnabled.value
}
const toggleAutoscrollColor = computed(() =>
autoScrollEnabled.value ? "text-green-500" : "text-red-500"
)
</script>
<style scoped lang="scss">
.realtime-log {
@apply p-4;
@apply bg-transparent;
@apply text-secondary;
@apply overflow-auto;
height: 256px;
&,
span {
@apply select-text;
}
span {
@apply block;
@apply break-words break-all;
}
}
</style>
<style></style>

View File

@@ -0,0 +1,392 @@
<template>
<div v-if="entry" class="divide-y divide-dividerLight">
<div :style="{ color: entryColor }" class="realtime-log">
<div class="flex group">
<div class="flex flex-1 divide-x divide-dividerLight">
<div class="inline-flex items-center p-2">
<SmartIcon
class="svg-icons"
:name="iconName"
:style="{ color: iconColor }"
@click.native="copyQuery(entry.payload)"
/>
</div>
<div
v-if="entry.ts !== undefined"
class="items-center hidden px-1 w-18 sm:inline-flex"
>
<span
v-tippy="{ theme: 'tooltip' }"
:title="relativeTime"
class="mx-auto truncate ts-font text-secondaryLight hover:text-secondary hover:text-center"
>
{{ new Date(entry.ts).toLocaleTimeString() }}
</span>
</div>
<div
class="items-center flex-1 min-w-0 p-2 inline-grid"
@click="toggleExpandPayload()"
>
<div class="truncate">
<span v-if="entry.prefix !== undefined" class="!inline">{{
entry.prefix
}}</span>
{{ entry.payload }}
</div>
</div>
</div>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.copy')"
:svg="`${copyQueryIcon}`"
class="hidden group-hover:inline-flex"
@click.native="copyQuery(entry.payload)"
/>
<ButtonSecondary
svg="chevron-down"
class="transform"
:class="{ 'rotate-180': !minimized }"
@click.native="toggleExpandPayload()"
/>
</div>
</div>
<div v-if="!minimized" class="overflow-hidden bg-primaryLight">
<SmartTabs
v-model="selectedTab"
styles="bg-primaryLight"
render-inactive-tabs
>
<SmartTab v-if="isJSON(entry.payload)" id="json" label="JSON" />
<SmartTab id="raw" label="Raw" />
</SmartTabs>
<div
class="z-10 flex items-center justify-between pl-4 border-b border-dividerLight top-lowerSecondaryStickyFold"
>
<label class="font-semibold text-secondaryLight">
{{ t("response.body") }}
</label>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('state.linewrap')"
:class="{ '!text-accent': linewrapEnabled }"
svg="wrap-text"
@click.native.prevent="linewrapEnabled = !linewrapEnabled"
/>
<ButtonSecondary
ref="downloadResponse"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.download_file')"
:svg="downloadIcon"
@click.native="downloadResponse"
/>
<ButtonSecondary
ref="copyResponse"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.copy')"
:svg="copyIcon"
@click.native="copyResponse"
/>
</div>
</div>
<div ref="editor"></div>
<div
v-if="outlinePath && selectedTab === 'json'"
class="sticky bottom-0 z-10 flex px-2 overflow-auto border-t bg-primaryLight border-dividerLight flex-nowrap hide-scrollbar"
>
<div
v-for="(item, index) in outlinePath"
:key="`item-${index}`"
class="flex items-center"
>
<tippy
ref="outlineOptions"
interactive
trigger="click"
theme="popover"
arrow
>
<template #trigger>
<div v-if="item.kind === 'RootObject'" class="outline-item">
{}
</div>
<div v-if="item.kind === 'RootArray'" class="outline-item">
[]
</div>
<div v-if="item.kind === 'ArrayMember'" class="outline-item">
{{ item.index }}
</div>
<div v-if="item.kind === 'ObjectMember'" class="outline-item">
{{ item.name }}
</div>
</template>
<div
v-if="item.kind === 'ArrayMember' || item.kind === 'ObjectMember'"
>
<div
v-if="item.kind === 'ArrayMember'"
class="flex flex-col"
role="menu"
>
<SmartItem
v-for="(arrayMember, astIndex) in item.astParent.values"
:key="`ast-${astIndex}`"
:label="`${astIndex}`"
@click.native="
() => {
jumpCursor(arrayMember)
outlineOptions[index].tippy().hide()
}
"
/>
</div>
<div
v-if="item.kind === 'ObjectMember'"
class="flex flex-col"
role="menu"
>
<SmartItem
v-for="(objectMember, astIndex) in item.astParent.members"
:key="`ast-${astIndex}`"
:label="objectMember.key.value"
@click.native="
() => {
jumpCursor(objectMember)
outlineOptions[index].tippy().hide()
}
"
/>
</div>
</div>
<div
v-if="item.kind === 'RootObject'"
class="flex flex-col"
role="menu"
>
<SmartItem
label="{}"
@click.native="
() => {
jumpCursor(item.astValue)
outlineOptions[index].tippy().hide()
}
"
/>
</div>
<div
v-if="item.kind === 'RootArray'"
class="flex flex-col"
role="menu"
>
<SmartItem
label="[]"
@click.native="
() => {
jumpCursor(item.astValue)
outlineOptions[index].tippy().hide()
}
"
/>
</div>
</tippy>
<i
v-if="index + 1 !== outlinePath.length"
class="opacity-50 text-secondaryLight material-icons"
>
chevron_right
</i>
</div>
</div>
</div>
</div>
<div v-else>{{ t("response.waiting_for_connection") }}</div>
</template>
<script setup lang="ts">
import * as LJSON from "lossless-json"
import * as O from "fp-ts/Option"
import { pipe } from "fp-ts/function"
import { ref, computed, reactive, watch } from "@nuxtjs/composition-api"
import { refAutoReset, useTimeAgo } from "@vueuse/core"
import { LogEntryData } from "./Log.vue"
import { useI18n } from "~/helpers/utils/composables"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import { isJSON } from "~/helpers/functional/json"
import useCopyResponse from "~/helpers/lenses/composables/useCopyResponse"
import useDownloadResponse from "~/helpers/lenses/composables/useDownloadResponse"
import { useCodemirror } from "~/helpers/editor/codemirror"
import jsonParse, { JSONObjectMember, JSONValue } from "~/helpers/jsonParse"
import { getJSONOutlineAtPos } from "~/helpers/newOutline"
import {
convertIndexToLineCh,
convertLineChToIndex,
} from "~/helpers/editor/utils"
const t = useI18n()
const props = defineProps<{ entry: LogEntryData }>()
const outlineOptions = ref<any | null>(null)
const editor = ref<any | null>(null)
const linewrapEnabled = ref(true)
const logPayload = computed(() => props.entry.payload)
const selectedTab = ref<"json" | "raw">(
isJSON(props.entry.payload) ? "json" : "raw"
)
// CodeMirror Implementation
const jsonBodyText = computed(() =>
pipe(
logPayload.value,
O.tryCatchK(LJSON.parse),
O.map((val) => LJSON.stringify(val, undefined, 2)),
O.getOrElse(() => logPayload.value)
)
)
const ast = computed(() =>
pipe(
jsonBodyText.value,
O.tryCatchK(jsonParse),
O.getOrElseW(() => null)
)
)
const editorText = computed(() => {
if (selectedTab.value === "json") return jsonBodyText.value
else return logPayload.value
})
const editorMode = computed(() => {
if (selectedTab.value === "json") return "application/ld+json"
else return "text/plain"
})
const { cursor } = useCodemirror(
editor,
editorText,
reactive({
extendedEditorConfig: {
mode: editorMode,
readOnly: true,
lineWrapping: linewrapEnabled,
},
linter: null,
completer: null,
environmentHighlights: false,
})
)
const jumpCursor = (ast: JSONValue | JSONObjectMember) => {
const pos = convertIndexToLineCh(jsonBodyText.value, ast.start)
pos.line--
cursor.value = pos
}
const outlinePath = computed(() =>
pipe(
ast.value,
O.fromNullable,
O.map((ast) =>
getJSONOutlineAtPos(
ast,
convertLineChToIndex(jsonBodyText.value, cursor.value)
)
),
O.getOrElseW(() => null)
)
)
// Code for UI Changes
const minimized = ref(true)
watch(minimized, () => {
selectedTab.value = isJSON(props.entry.payload) ? "json" : "raw"
})
const toggleExpandPayload = () => {
minimized.value = !minimized.value
}
const { copyIcon, copyResponse } = useCopyResponse(logPayload)
const { downloadIcon, downloadResponse } = useDownloadResponse(
"application/json",
logPayload
)
const copyQueryIcon = refAutoReset<"copy" | "check">("copy", 1000)
const copyQuery = (entry: string) => {
copyToClipboard(entry)
copyQueryIcon.value = "check"
}
// Relative Time
// TS could be undefined here. We're just assigning a default value to 0 because we're not showing it in the UI
const relativeTime = useTimeAgo(computed(() => props.entry.ts ?? 0))
const ENTRY_COLORS = {
connected: "#10b981",
connecting: "#10b981",
error: "#ff5555",
disconnected: "#ff5555",
} as const
// Assigns color based on entry event
const entryColor = computed(() => ENTRY_COLORS[props.entry.event])
const ICONS = {
info: {
iconName: "info-realtime",
iconColor: "#10b981",
},
client: {
iconName: "arrow-up-right",
iconColor: "#eaaa45",
},
server: {
iconName: "arrow-down-left",
iconColor: "#38d4ea",
},
disconnected: {
iconName: "info-disconnect",
iconColor: "#ff5555",
},
} as const
const iconColor = computed(() => ICONS[props.entry.source].iconColor)
const iconName = computed(() => ICONS[props.entry.source].iconName)
</script>
<style scoped lang="scss">
.realtime-log {
@apply text-secondary;
@apply overflow-hidden;
&,
span {
@apply select-text;
}
span {
@apply block;
@apply break-words break-all;
}
}
.outline-item {
@apply cursor-pointer;
@apply flex-grow-0 flex-shrink-0;
@apply text-secondaryLight;
@apply inline-flex;
@apply items-center;
@apply px-2;
@apply py-1;
@apply transition;
@apply hover: text-secondary;
}
.ts-font {
font-size: 0.6rem;
}
</style>

View File

@@ -1,382 +0,0 @@
<template>
<AppPaneLayout>
<template #primary>
<div
class="sticky top-0 z-10 flex flex-shrink-0 p-4 overflow-x-auto space-x-2 bg-primary hide-scrollbar"
>
<div class="inline-flex flex-1 space-x-2">
<input
id="mqtt-url"
v-model="url"
type="url"
autocomplete="off"
spellcheck="false"
class="w-full px-4 py-2 border rounded bg-primaryLight border-divider text-secondaryDark"
:placeholder="$t('mqtt.url')"
:disabled="connectionState"
@keyup.enter="validUrl ? toggleConnection() : null"
/>
<ButtonPrimary
id="connect"
:disabled="!validUrl"
class="w-32"
:label="
connectionState ? $t('action.disconnect') : $t('action.connect')
"
:loading="connectingState"
@click.native="toggleConnection"
/>
</div>
<div class="flex space-x-4">
<input
id="mqtt-username"
v-model="username"
type="text"
spellcheck="false"
class="input"
:placeholder="$t('authorization.username')"
/>
<input
id="mqtt-password"
v-model="password"
type="password"
spellcheck="false"
class="input"
:placeholder="$t('authorization.password')"
/>
</div>
</div>
</template>
<template #secondary>
<RealtimeLog :title="$t('mqtt.log')" :log="log" />
</template>
<template #sidebar>
<div class="flex items-center justify-between p-4">
<label for="pub_topic" class="font-semibold text-secondaryLight">
{{ $t("mqtt.topic") }}
</label>
</div>
<div class="flex px-4">
<input
id="pub_topic"
v-model="pub_topic"
class="input"
:placeholder="$t('mqtt.topic_name')"
type="text"
autocomplete="off"
spellcheck="false"
/>
</div>
<div class="flex items-center justify-between p-4">
<label for="mqtt-message" class="font-semibold text-secondaryLight">
{{ $t("mqtt.communication") }}
</label>
</div>
<div class="flex px-4 space-x-2">
<input
id="mqtt-message"
v-model="msg"
class="input"
type="text"
autocomplete="off"
:placeholder="$t('mqtt.message')"
spellcheck="false"
/>
<ButtonPrimary
id="publish"
name="get"
:disabled="!canpublish"
:label="$t('mqtt.publish')"
@click.native="publish"
/>
</div>
<div
class="flex items-center justify-between p-4 mt-4 border-t border-dividerLight"
>
<label for="sub_topic" class="font-semibold text-secondaryLight">
{{ $t("mqtt.topic") }}
</label>
</div>
<div class="flex px-4 space-x-2">
<input
id="sub_topic"
v-model="sub_topic"
type="text"
autocomplete="off"
:placeholder="$t('mqtt.topic_name')"
spellcheck="false"
class="input"
/>
<ButtonPrimary
id="subscribe"
name="get"
:disabled="!cansubscribe"
:label="
subscriptionState ? $t('mqtt.unsubscribe') : $t('mqtt.subscribe')
"
reverse
@click.native="toggleSubscription"
/>
</div>
</template>
</AppPaneLayout>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
import Paho from "paho-mqtt"
import debounce from "lodash/debounce"
import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
import {
MQTTEndpoint$,
setMQTTEndpoint,
MQTTConnectingState$,
MQTTConnectionState$,
setMQTTConnectingState,
setMQTTConnectionState,
MQTTSubscriptionState$,
setMQTTSubscriptionState,
MQTTSocket$,
setMQTTSocket,
MQTTLog$,
setMQTTLog,
addMQTTLogLine,
} from "~/newstore/MQTTSession"
import { useStream } from "~/helpers/utils/composables"
export default defineComponent({
setup() {
return {
url: useStream(MQTTEndpoint$, "", setMQTTEndpoint),
connectionState: useStream(
MQTTConnectionState$,
false,
setMQTTConnectionState
),
connectingState: useStream(
MQTTConnectingState$,
false,
setMQTTConnectingState
),
subscriptionState: useStream(
MQTTSubscriptionState$,
false,
setMQTTSubscriptionState
),
log: useStream(MQTTLog$, null, setMQTTLog),
client: useStream(MQTTSocket$, null, setMQTTSocket),
}
},
data() {
return {
isUrlValid: true,
pub_topic: "",
sub_topic: "",
msg: "",
manualDisconnect: false,
username: "",
password: "",
}
},
computed: {
validUrl() {
return this.isUrlValid
},
canpublish() {
return this.pub_topic !== "" && this.msg !== "" && this.connectionState
},
cansubscribe() {
return this.sub_topic !== "" && this.connectionState
},
},
watch: {
url() {
this.debouncer()
},
},
created() {
if (process.browser) {
this.worker = this.$worker.createRejexWorker()
this.worker.addEventListener("message", this.workerResponseHandler)
}
},
destroyed() {
this.worker.terminate()
},
methods: {
debouncer: debounce(function () {
this.worker.postMessage({ type: "ws", url: this.url })
}, 1000),
workerResponseHandler({ data }) {
if (data.url === this.url) this.isUrlValid = data.result
},
connect() {
this.connectingState = true
this.log = [
{
payload: this.$t("state.connecting_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
},
]
const parseUrl = new URL(this.url)
this.client = new Paho.Client(
`${parseUrl.hostname}${
parseUrl.pathname !== "/" ? parseUrl.pathname : ""
}`,
parseUrl.port !== "" ? Number(parseUrl.port) : 8081,
"hoppscotch"
)
const connectOptions = {
onSuccess: this.onConnectionSuccess,
onFailure: this.onConnectionFailure,
useSSL: parseUrl.protocol !== "ws:",
}
if (this.username !== "") {
connectOptions.userName = this.username
}
if (this.password !== "") {
connectOptions.password = this.password
}
this.client.connect(connectOptions)
this.client.onConnectionLost = this.onConnectionLost
this.client.onMessageArrived = this.onMessageArrived
logHoppRequestRunToAnalytics({
platform: "mqtt",
})
},
onConnectionFailure() {
this.connectingState = false
this.connectionState = false
addMQTTLogLine({
payload: this.$t("error.something_went_wrong"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
onConnectionSuccess() {
this.connectingState = false
this.connectionState = true
addMQTTLogLine({
payload: this.$t("state.connected_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
})
this.$toast.success(this.$t("state.connected"))
},
onMessageArrived({ payloadString, destinationName }) {
addMQTTLogLine({
payload: `Message: ${payloadString} arrived on topic: ${destinationName}`,
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
})
},
toggleConnection() {
if (this.connectionState) {
this.disconnect()
} else {
this.connect()
}
},
disconnect() {
this.manualDisconnect = true
this.client.disconnect()
addMQTTLogLine({
payload: this.$t("state.disconnected_from", { name: this.url }),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
onConnectionLost() {
this.connectingState = false
this.connectionState = false
if (this.manualDisconnect) {
this.$toast.error(this.$t("state.disconnected"))
} else {
this.$toast.error(this.$t("error.something_went_wrong"))
}
this.manualDisconnect = false
this.subscriptionState = false
},
publish() {
try {
this.client.publish(this.pub_topic, this.msg, 0, false)
addMQTTLogLine({
payload: `Published message: ${this.msg} to topic: ${this.pub_topic}`,
ts: new Date().toLocaleTimeString(),
source: "info",
color: "var(--accent-color)",
})
} catch (e) {
addMQTTLogLine({
payload:
this.$t("error.something_went_wrong") +
`while publishing msg: ${this.msg} to topic: ${this.pub_topic}`,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
}
},
toggleSubscription() {
if (this.subscriptionState) {
this.unsubscribe()
} else {
this.subscribe()
}
},
subscribe() {
try {
this.client.subscribe(this.sub_topic, {
onSuccess: this.usubSuccess,
onFailure: this.usubFailure,
})
} catch (e) {
addMQTTLogLine({
payload:
this.$t("error.something_went_wrong") +
`while subscribing to topic: ${this.sub_topic}`,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
}
},
usubSuccess() {
this.subscriptionState = !this.subscriptionState
addMQTTLogLine({
payload:
`Successfully ` +
(this.subscriptionState ? "subscribed" : "unsubscribed") +
` to topic: ${this.sub_topic}`,
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
})
},
usubFailure() {
addMQTTLogLine({
payload:
`Failed to ` +
(this.subscriptionState ? "unsubscribe" : "subscribe") +
` to topic: ${this.sub_topic}`,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
unsubscribe() {
this.client.unsubscribe(this.sub_topic, {
onSuccess: this.usubSuccess,
onFailure: this.usubFailure,
})
},
},
})
</script>

View File

@@ -1,521 +0,0 @@
<template>
<AppPaneLayout>
<template #primary>
<div
class="sticky top-0 z-10 flex flex-shrink-0 p-4 overflow-x-auto space-x-2 bg-primary hide-scrollbar"
>
<div class="inline-flex flex-1 space-x-2">
<div class="flex flex-1">
<label for="client-version">
<tippy
ref="versionOptions"
interactive
trigger="click"
theme="popover"
arrow
>
<template #trigger>
<span class="select-wrapper">
<input
id="client-version"
v-tippy="{ theme: 'tooltip' }"
title="socket.io-client version"
class="flex px-4 py-2 font-semibold border rounded-l cursor-pointer bg-primaryLight border-divider text-secondaryDark w-26"
:value="`Client ${clientVersion}`"
readonly
:disabled="connectionState"
/>
</span>
</template>
<div class="flex flex-col" role="menu">
<SmartItem
v-for="(_, version) in socketIoClients"
:key="`client-${version}`"
:label="`Client ${version}`"
@click.native="onSelectVersion(version)"
/>
</div>
</tippy>
</label>
<input
id="socketio-url"
v-model="url"
type="url"
autocomplete="off"
spellcheck="false"
:class="{ error: !urlValid }"
class="flex flex-1 w-full px-4 py-2 border bg-primaryLight border-divider text-secondaryDark"
:placeholder="$t('socketio.url')"
:disabled="connectionState"
@keyup.enter="urlValid ? toggleConnection() : null"
/>
<input
id="socketio-path"
v-model="path"
class="flex flex-1 w-full px-4 py-2 border rounded-r bg-primaryLight border-divider text-secondaryDark"
spellcheck="false"
:disabled="connectionState"
@keyup.enter="urlValid ? toggleConnection() : null"
/>
</div>
<ButtonPrimary
id="connect"
:disabled="!urlValid"
name="connect"
class="w-32"
:label="
!connectionState ? $t('action.connect') : $t('action.disconnect')
"
:loading="connectingState"
@click.native="toggleConnection"
/>
</div>
</div>
<div
class="sticky z-10 flex items-center justify-between pl-4 border-b bg-primary border-dividerLight top-upperPrimaryStickyFold"
>
<span class="flex items-center">
<label class="font-semibold text-secondaryLight">
{{ $t("authorization.type") }}
</label>
<tippy
ref="authTypeOptions"
interactive
trigger="click"
theme="popover"
arrow
>
<template #trigger>
<span class="select-wrapper">
<ButtonSecondary
class="pr-8 ml-2 rounded-none"
:label="authType"
/>
</span>
</template>
<div class="flex flex-col" role="menu">
<SmartItem
label="None"
:icon="
authType === 'None'
? 'radio_button_checked'
: 'radio_button_unchecked'
"
:active="authType === 'None'"
@click.native="
() => {
authType = 'None'
authTypeOptions.tippy().hide()
}
"
/>
<SmartItem
label="Bearer Token"
:icon="
authType === 'Bearer'
? 'radio_button_checked'
: 'radio_button_unchecked'
"
:active="authType === 'Bearer'"
@click.native="
() => {
authType = 'Bearer'
authTypeOptions.tippy().hide()
}
"
/>
</div>
</tippy>
</span>
<div class="flex">
<SmartCheckbox
:on="authActive"
class="px-2"
@change="authActive = !authActive"
>
{{ $t("state.enabled") }}
</SmartCheckbox>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
to="https://docs.hoppscotch.io/features/authorization"
blank
:title="$t('app.wiki')"
svg="help-circle"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.clear')"
svg="trash-2"
@click.native="clearContent"
/>
</div>
</div>
<div
v-if="authType === 'None'"
class="flex flex-col items-center justify-center p-4 text-secondaryLight"
>
<img
:src="`/images/states/${$colorMode.value}/login.svg`"
loading="lazy"
class="inline-flex flex-col object-contain object-center w-16 h-16 my-4"
:alt="$t('empty.authorization')"
/>
<span class="pb-4 text-center">
This SocketIO connection does not use any authentication.
</span>
<ButtonSecondary
outline
:label="$t('app.documentation')"
to="https://docs.hoppscotch.io/features/authorization"
blank
svg="external-link"
reverse
class="mb-4"
/>
</div>
<div
v-if="authType === 'Bearer'"
class="flex flex-1 border-b border-dividerLight"
>
<div class="w-2/3 border-r border-dividerLight">
<div class="flex flex-1 border-b border-dividerLight">
<SmartEnvInput v-model="bearerToken" placeholder="Token" />
</div>
</div>
<div
class="sticky h-full p-4 overflow-auto bg-primary top-upperTertiaryStickyFold min-w-46 max-w-1/3 z-9"
>
<div class="p-2">
<div class="pb-2 text-secondaryLight">
{{ $t("helpers.authorization") }}
</div>
<SmartAnchor
class="link"
:label="`${$t('authorization.learn')} \xA0 →`"
to="https://docs.hoppscotch.io/features/authorization"
blank
/>
</div>
</div>
</div>
</template>
<template #secondary>
<RealtimeLog :title="$t('socketio.log')" :log="log" />
</template>
<template #sidebar>
<div class="flex items-center justify-between p-4">
<label for="events" class="font-semibold text-secondaryLight">
{{ $t("socketio.events") }}
</label>
</div>
<div class="flex px-4">
<input
id="event_name"
v-model="communication.eventName"
class="input"
name="event_name"
:placeholder="$t('socketio.event_name')"
type="text"
autocomplete="off"
:disabled="!connectionState"
/>
</div>
<div class="flex items-center justify-between p-4">
<label class="font-semibold text-secondaryLight">
{{ $t("socketio.communication") }}
</label>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('add.new')"
svg="plus"
@click.native="addCommunicationInput"
/>
</div>
</div>
<div class="flex flex-col px-4 pb-4 space-y-2">
<div
v-for="(input, index) of communication.inputs"
:key="`input-${index}`"
>
<div class="flex space-x-2">
<input
v-model="communication.inputs[index]"
class="input"
name="message"
:placeholder="$t('count.message', { count: index + 1 })"
type="text"
autocomplete="off"
:disabled="!connectionState"
@keyup.enter="connectionState ? sendMessage() : null"
/>
<ButtonSecondary
v-if="index + 1 !== communication.inputs.length"
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.remove')"
svg="trash"
color="red"
outline
@click.native="removeCommunicationInput({ index })"
/>
<ButtonPrimary
v-if="index + 1 === communication.inputs.length"
id="send"
name="send"
:disabled="!connectionState"
:label="$t('action.send')"
@click.native="sendMessage"
/>
</div>
</div>
</div>
</template>
</AppPaneLayout>
</template>
<script>
import { defineComponent, ref } from "@nuxtjs/composition-api"
// All Socket.IO client version imports
import ClientV2 from "socket.io-client-v2"
import { io as ClientV3 } from "socket.io-client-v3"
import { io as ClientV4 } from "socket.io-client-v4"
import wildcard from "socketio-wildcard"
import debounce from "lodash/debounce"
import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
import {
SIOEndpoint$,
setSIOEndpoint,
SIOVersion$,
setSIOVersion,
SIOPath$,
setSIOPath,
SIOConnectionState$,
SIOConnectingState$,
setSIOConnectionState,
setSIOConnectingState,
SIOSocket$,
setSIOSocket,
SIOLog$,
setSIOLog,
addSIOLogLine,
} from "~/newstore/SocketIOSession"
import { useStream } from "~/helpers/utils/composables"
const socketIoClients = {
v4: ClientV4,
v3: ClientV3,
v2: ClientV2,
}
export default defineComponent({
setup() {
return {
socketIoClients,
url: useStream(SIOEndpoint$, "", setSIOEndpoint),
clientVersion: useStream(SIOVersion$, "", setSIOVersion),
path: useStream(SIOPath$, "", setSIOPath),
connectingState: useStream(
SIOConnectingState$,
false,
setSIOConnectingState
),
connectionState: useStream(
SIOConnectionState$,
false,
setSIOConnectionState
),
io: useStream(SIOSocket$, null, setSIOSocket),
log: useStream(SIOLog$, [], setSIOLog),
authTypeOptions: ref(null),
}
},
data() {
return {
isUrlValid: true,
communication: {
eventName: "",
inputs: [""],
},
authType: "None",
bearerToken: "",
authActive: true,
}
},
computed: {
urlValid() {
return this.isUrlValid
},
},
watch: {
url() {
this.debouncer()
},
connectionState(connected) {
if (connected) this.$refs.versionOptions.tippy().disable()
else this.$refs.versionOptions.tippy().enable()
},
},
created() {
if (process.browser) {
this.worker = this.$worker.createRejexWorker()
this.worker.addEventListener("message", this.workerResponseHandler)
}
},
destroyed() {
this.worker.terminate()
},
methods: {
debouncer: debounce(function () {
this.worker.postMessage({ type: "socketio", url: this.url })
}, 1000),
workerResponseHandler({ data }) {
if (data.url === this.url) this.isUrlValid = data.result
},
removeCommunicationInput({ index }) {
this.$delete(this.communication.inputs, index)
},
addCommunicationInput() {
this.communication.inputs.push("")
},
toggleConnection() {
// If it is connecting:
if (!this.connectionState) return this.connect()
// Otherwise, it's disconnecting.
else return this.disconnect()
},
connect() {
this.connectingState = true
this.log = [
{
payload: this.$t("state.connecting_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
},
]
try {
if (!this.path) {
this.path = "/socket.io"
}
const Client = socketIoClients[this.clientVersion]
if (this.authActive && this.authType === "Bearer") {
this.io = new Client(this.url, {
path: this.path,
auth: {
token: this.bearerToken,
},
})
} else {
this.io = new Client(this.url, { path: this.path })
}
// Add ability to listen to all events
wildcard(Client.Manager)(this.io)
this.io.on("connect", () => {
this.connectingState = false
this.connectionState = true
this.log = [
{
payload: this.$t("state.connected_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
},
]
this.$toast.success(this.$t("state.connected"))
})
this.io.on("*", ({ data }) => {
const [eventName, message] = data
addSIOLogLine({
payload: `[${eventName}] ${message ? JSON.stringify(message) : ""}`,
source: "server",
ts: new Date().toLocaleTimeString(),
})
})
this.io.on("connect_error", (error) => {
this.handleError(error)
})
this.io.on("reconnect_error", (error) => {
this.handleError(error)
})
this.io.on("error", () => {
this.handleError()
})
this.io.on("disconnect", () => {
this.connectingState = false
this.connectionState = false
addSIOLogLine({
payload: this.$t("state.disconnected_from", { name: this.url }),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
this.$toast.error(this.$t("state.disconnected"))
})
} catch (e) {
this.handleError(e)
this.$toast.error(this.$t("error.something_went_wrong"))
}
logHoppRequestRunToAnalytics({
platform: "socketio",
})
},
disconnect() {
this.io.close()
},
handleError(error) {
this.disconnect()
this.connectingState = false
this.connectionState = false
addSIOLogLine({
payload: this.$t("error.something_went_wrong"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
if (error !== null)
addSIOLogLine({
payload: error,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
sendMessage() {
const eventName = this.communication.eventName
const messages = (this.communication.inputs || [])
.map((input) => {
try {
return JSON.parse(input)
} catch (e) {
return input
}
})
.filter((message) => !!message)
if (this.io) {
this.io.emit(eventName, ...messages, (data) => {
// receive response from server
addSIOLogLine({
payload: `[${eventName}] ${JSON.stringify(data)}`,
source: "server",
ts: new Date().toLocaleTimeString(),
})
})
addSIOLogLine({
payload: `[${eventName}] ${JSON.stringify(messages)}`,
source: "client",
ts: new Date().toLocaleTimeString(),
})
this.communication.inputs = [""]
}
},
onSelectVersion(version) {
this.clientVersion = version
this.$refs.versionOptions.tippy().hide()
},
},
})
</script>

View File

@@ -1,222 +0,0 @@
<template>
<AppPaneLayout>
<template #primary>
<div
class="sticky top-0 z-10 flex flex-shrink-0 p-4 overflow-x-auto space-x-2 bg-primary hide-scrollbar"
>
<div class="inline-flex flex-1 space-x-2">
<div class="flex flex-1">
<input
id="server"
v-model="server"
type="url"
autocomplete="off"
:class="{ error: !serverValid }"
class="flex flex-1 w-full px-4 py-2 border rounded-l bg-primaryLight border-divider text-secondaryDark"
:placeholder="$t('sse.url')"
:disabled="connectionSSEState"
@keyup.enter="serverValid ? toggleSSEConnection() : null"
/>
<label
for="event-type"
class="px-4 py-2 font-semibold truncate border-t border-b bg-primaryLight border-divider text-secondaryLight"
>
{{ $t("sse.event_type") }}
</label>
<input
id="event-type"
v-model="eventType"
class="flex flex-1 w-full px-4 py-2 border rounded-r bg-primaryLight border-divider text-secondaryDark"
spellcheck="false"
:disabled="connectionSSEState"
@keyup.enter="serverValid ? toggleSSEConnection() : null"
/>
</div>
<ButtonPrimary
id="start"
:disabled="!serverValid"
name="start"
class="w-32"
:label="
!connectionSSEState ? $t('action.start') : $t('action.stop')
"
:loading="connectingState"
@click.native="toggleSSEConnection"
/>
</div>
</div>
</template>
<template #secondary>
<RealtimeLog :title="$t('sse.log')" :log="log" />
</template>
</AppPaneLayout>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
import "splitpanes/dist/splitpanes.css"
import debounce from "lodash/debounce"
import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
import {
SSEEndpoint$,
setSSEEndpoint,
SSEEventType$,
setSSEEventType,
SSESocket$,
setSSESocket,
SSEConnectingState$,
SSEConnectionState$,
setSSEConnectionState,
setSSEConnectingState,
SSELog$,
setSSELog,
addSSELogLine,
} from "~/newstore/SSESession"
import { useStream } from "~/helpers/utils/composables"
export default defineComponent({
setup() {
return {
connectionSSEState: useStream(
SSEConnectionState$,
false,
setSSEConnectionState
),
connectingState: useStream(
SSEConnectingState$,
false,
setSSEConnectingState
),
server: useStream(SSEEndpoint$, "", setSSEEndpoint),
eventType: useStream(SSEEventType$, "", setSSEEventType),
sse: useStream(SSESocket$, null, setSSESocket),
log: useStream(SSELog$, [], setSSELog),
}
},
data() {
return {
isUrlValid: true,
}
},
computed: {
serverValid() {
return this.isUrlValid
},
},
watch: {
server() {
this.debouncer()
},
},
created() {
if (process.browser) {
this.worker = this.$worker.createRejexWorker()
this.worker.addEventListener("message", this.workerResponseHandler)
}
},
destroyed() {
this.worker.terminate()
},
methods: {
debouncer: debounce(function () {
this.worker.postMessage({ type: "sse", url: this.server })
}, 1000),
workerResponseHandler({ data }) {
if (data.url === this.url) this.isUrlValid = data.result
},
toggleSSEConnection() {
// If it is connecting:
if (!this.connectionSSEState) return this.start()
// Otherwise, it's disconnecting.
else return this.stop()
},
start() {
this.connectingState = true
this.log = [
{
payload: this.$t("state.connecting_to", { name: this.server }),
source: "info",
color: "var(--accent-color)",
},
]
if (typeof EventSource !== "undefined") {
try {
this.sse = new EventSource(this.server)
this.sse.onopen = () => {
this.connectingState = false
this.connectionSSEState = true
this.log = [
{
payload: this.$t("state.connected_to", { name: this.server }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
},
]
this.$toast.success(this.$t("state.connected"))
}
this.sse.onerror = () => {
this.handleSSEError()
}
this.sse.onclose = () => {
this.connectionSSEState = false
addSSELogLine({
payload: this.$t("state.disconnected_from", {
name: this.server,
}),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
this.$toast.error(this.$t("state.disconnected"))
}
this.sse.addEventListener(this.eventType, ({ data }) => {
addSSELogLine({
payload: data,
source: "server",
ts: new Date().toLocaleTimeString(),
})
})
} catch (e) {
this.handleSSEError(e)
this.$toast.error(this.$t("error.something_went_wrong"))
}
} else {
this.log = [
{
payload: this.$t("error.browser_support_sse"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
},
]
}
logHoppRequestRunToAnalytics({
platform: "sse",
})
},
handleSSEError(error) {
this.stop()
this.connectionSSEState = false
addSSELogLine({
payload: this.$t("error.something_went_wrong"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
if (error !== null)
addSSELogLine({
payload: error,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
stop() {
this.sse.close()
this.sse.onclose()
},
},
})
</script>

View File

@@ -1,433 +0,0 @@
<template>
<AppPaneLayout>
<template #primary>
<div
class="sticky top-0 z-10 flex flex-shrink-0 p-4 overflow-x-auto space-x-2 bg-primary hide-scrollbar"
>
<div class="inline-flex flex-1 space-x-2">
<input
id="websocket-url"
v-model="url"
class="w-full px-4 py-2 border rounded bg-primaryLight border-divider text-secondaryDark"
type="url"
autocomplete="off"
spellcheck="false"
:class="{ error: !urlValid }"
:placeholder="$t('websocket.url')"
:disabled="connectionState"
@keyup.enter="urlValid ? toggleConnection() : null"
/>
<ButtonPrimary
id="connect"
:disabled="!urlValid"
class="w-32"
name="connect"
:label="
!connectionState ? $t('action.connect') : $t('action.disconnect')
"
:loading="connectingState"
@click.native="toggleConnection"
/>
</div>
</div>
<div
class="sticky z-10 flex items-center justify-between pl-4 border-b bg-primary border-dividerLight top-upperPrimaryStickyFold"
>
<label class="font-semibold text-secondaryLight">
{{ $t("websocket.protocols") }}
</label>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.clear_all')"
svg="trash-2"
@click.native="clearContent"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('add.new')"
svg="plus"
@click.native="addProtocol"
/>
</div>
</div>
<draggable
v-model="protocols"
animation="250"
handle=".draggable-handle"
draggable=".draggable-content"
ghost-class="cursor-move"
chosen-class="bg-primaryLight"
drag-class="cursor-grabbing"
>
<div
v-for="(protocol, index) of protocols"
:key="`protocol-${index}`"
class="flex border-b divide-x divide-dividerLight border-dividerLight draggable-content group"
>
<span>
<ButtonSecondary
svg="grip-vertical"
class="cursor-auto text-primary hover:text-primary"
:class="{
'draggable-handle group-hover:text-secondaryLight !cursor-grab':
index !== protocols?.length - 1,
}"
tabindex="-1"
/>
</span>
<input
v-model="protocol.value"
class="flex flex-1 px-4 py-2 bg-transparent"
:placeholder="$t('count.protocol', { count: index + 1 })"
name="message"
type="text"
autocomplete="off"
@change="
updateProtocol(index, {
value: $event.target.value,
active: protocol.active,
})
"
/>
<span>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="
protocol.hasOwnProperty('active')
? protocol.active
? $t('action.turn_off')
: $t('action.turn_on')
: $t('action.turn_off')
"
:svg="
protocol.hasOwnProperty('active')
? protocol.active
? 'check-circle'
: 'circle'
: 'check-circle'
"
color="green"
@click.native="
updateProtocol(index, {
value: protocol.value,
active: !protocol.active,
})
"
/>
</span>
<span>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.remove')"
svg="trash"
color="red"
@click.native="deleteProtocol({ index })"
/>
</span>
</div>
</draggable>
<div
v-if="protocols.length === 0"
class="flex flex-col items-center justify-center p-4 text-secondaryLight"
>
<img
:src="`/images/states/${$colorMode.value}/add_category.svg`"
loading="lazy"
class="inline-flex flex-col object-contain object-center w-16 h-16 my-4"
:alt="$t('empty.protocols')"
/>
<span class="mb-4 text-center">
{{ $t("empty.protocols") }}
</span>
</div>
</template>
<template #secondary>
<RealtimeLog :title="$t('websocket.log')" :log="log" />
</template>
<template #sidebar>
<div class="flex items-center justify-between p-4">
<label
for="websocket-message"
class="font-semibold text-secondaryLight"
>
{{ $t("websocket.communication") }}
</label>
</div>
<div class="flex px-4 space-x-2">
<input
id="websocket-message"
v-model="communication.input"
name="message"
type="text"
autocomplete="off"
:disabled="!connectionState"
:placeholder="$t('websocket.message')"
class="input"
@keyup.enter="connectionState ? sendMessage() : null"
@keyup.up="connectionState ? walkHistory('up') : null"
@keyup.down="connectionState ? walkHistory('down') : null"
/>
<ButtonPrimary
id="send"
name="send"
:disabled="!connectionState"
:label="$t('action.send')"
@click.native="sendMessage"
/>
</div>
</template>
</AppPaneLayout>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
import debounce from "lodash/debounce"
import draggable from "vuedraggable"
import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
import {
setWSEndpoint,
WSEndpoint$,
WSProtocols$,
setWSProtocols,
addWSProtocol,
deleteWSProtocol,
updateWSProtocol,
deleteAllWSProtocols,
WSSocket$,
setWSSocket,
setWSConnectionState,
setWSConnectingState,
WSConnectionState$,
WSConnectingState$,
addWSLogLine,
WSLog$,
setWSLog,
} from "~/newstore/WebSocketSession"
import { useStream } from "~/helpers/utils/composables"
export default defineComponent({
components: {
draggable,
},
setup() {
return {
url: useStream(WSEndpoint$, "", setWSEndpoint),
protocols: useStream(WSProtocols$, [], setWSProtocols),
connectionState: useStream(
WSConnectionState$,
false,
setWSConnectionState
),
connectingState: useStream(
WSConnectingState$,
false,
setWSConnectingState
),
socket: useStream(WSSocket$, null, setWSSocket),
log: useStream(WSLog$, [], setWSLog),
}
},
data() {
return {
isUrlValid: true,
communication: {
input: "",
},
currentIndex: -1, // index of the message log array to put in input box
activeProtocols: [],
}
},
computed: {
urlValid() {
return this.isUrlValid
},
},
watch: {
url() {
this.debouncer()
},
protocols: {
handler(newVal) {
this.activeProtocols = newVal
.filter((item) =>
Object.prototype.hasOwnProperty.call(item, "active")
? item.active === true
: true
)
.map(({ value }) => value)
},
deep: true,
},
},
created() {
if (process.browser) {
this.worker = this.$worker.createRejexWorker()
this.worker.addEventListener("message", this.workerResponseHandler)
}
},
destroyed() {
this.worker.terminate()
},
methods: {
clearContent() {
deleteAllWSProtocols()
},
debouncer: debounce(function () {
this.worker.postMessage({ type: "ws", url: this.url })
}, 1000),
workerResponseHandler({ data }) {
if (data.url === this.url) this.isUrlValid = data.result
},
toggleConnection() {
// If it is connecting:
if (!this.connectionState) return this.connect()
// Otherwise, it's disconnecting.
else return this.disconnect()
},
connect() {
this.log = [
{
payload: this.$t("state.connecting_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
},
]
try {
this.connectingState = true
this.socket = new WebSocket(this.url, this.activeProtocols)
this.socket.onopen = () => {
this.connectingState = false
this.connectionState = true
this.log = [
{
payload: this.$t("state.connected_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
},
]
this.$toast.success(this.$t("state.connected"))
}
this.socket.onerror = () => {
this.handleError()
}
this.socket.onclose = () => {
this.connectionState = false
addWSLogLine({
payload: this.$t("state.disconnected_from", { name: this.url }),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
this.$toast.error(this.$t("state.disconnected"))
}
this.socket.onmessage = ({ data }) => {
addWSLogLine({
payload: data,
source: "server",
ts: new Date().toLocaleTimeString(),
})
}
} catch (e) {
this.handleError(e)
this.$toast.error(this.$t("error.something_went_wrong"))
}
logHoppRequestRunToAnalytics({
platform: "wss",
})
},
disconnect() {
if (this.socket) {
this.socket.close()
this.connectionState = false
this.connectingState = false
}
},
handleError(error) {
this.disconnect()
this.connectionState = false
addWSLogLine({
payload: this.$t("error.something_went_wrong"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
if (error !== null)
addWSLogLine({
payload: error,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
sendMessage() {
const message = this.communication.input
this.socket.send(message)
addWSLogLine({
payload: message,
source: "client",
ts: new Date().toLocaleTimeString(),
})
this.communication.input = ""
},
walkHistory(direction) {
const clientMessages = this.log.filter(
({ source }) => source === "client"
)
const length = clientMessages.length
switch (direction) {
case "up":
if (length > 0 && this.currentIndex !== 0) {
// does nothing if message log is empty or the currentIndex is 0 when up arrow is pressed
if (this.currentIndex === -1) {
this.currentIndex = length - 1
this.communication.input =
clientMessages[this.currentIndex].payload
} else if (this.currentIndex === 0) {
this.communication.input = clientMessages[0].payload
} else if (this.currentIndex > 0) {
this.currentIndex = this.currentIndex - 1
this.communication.input =
clientMessages[this.currentIndex].payload
}
}
break
case "down":
if (length > 0 && this.currentIndex > -1) {
if (this.currentIndex === length - 1) {
this.currentIndex = -1
this.communication.input = ""
} else if (this.currentIndex < length - 1) {
this.currentIndex = this.currentIndex + 1
this.communication.input =
clientMessages[this.currentIndex].payload
}
}
break
}
},
addProtocol() {
addWSProtocol({ value: "", active: true })
},
deleteProtocol({ index }) {
const oldProtocols = this.protocols.slice()
deleteWSProtocol(index)
this.$toast.success(this.$t("state.deleted"), {
action: {
text: this.$t("action.undo"),
duration: 4000,
onClick: (_, toastObject) => {
this.protocols = oldProtocols
toastObject.remove()
},
},
})
},
updateProtocol(index, updated) {
updateWSProtocol(index, updated)
},
},
})
</script>

View File

@@ -16,7 +16,12 @@
</template>
<template #footer>
<span>
<ButtonPrimary v-focus :label="yes" @click.native="resolve" />
<ButtonPrimary
v-focus
:label="yes"
:loading="!!loadingState"
@click.native="resolve"
/>
<ButtonSecondary :label="no" @click.native="hideModal" />
</span>
</template>
@@ -42,14 +47,15 @@ export default defineComponent({
return this.$t("action.no")
},
},
loadingState: { type: Boolean, default: null },
},
methods: {
hideModal() {
this.$emit("hide-modal")
},
resolve() {
this.$emit("resolve")
this.$emit("hide-modal")
this.$emit("resolve", this.title)
if (this.loadingState === null) this.$emit("hide-modal")
},
},
})

View File

@@ -29,10 +29,12 @@ import {
placeholder as placeholderExt,
ViewPlugin,
ViewUpdate,
keymap,
} from "@codemirror/view"
import { EditorState, Extension } from "@codemirror/state"
import clone from "lodash/clone"
import { tooltips } from "@codemirror/tooltip"
import { history, historyKeymap } from "@codemirror/history"
import { inputTheme } from "~/helpers/editor/themes/baseTheme"
import { HoppReactiveEnvPlugin } from "~/helpers/editor/extensions/HoppEnvironment"
import { useReadonlyStream } from "~/helpers/utils/composables"
@@ -45,6 +47,7 @@ const props = withDefaults(
styles: string
envs: { key: string; value: string; source: string }[] | null
focus: boolean
readonly: boolean
}>(),
{
value: "",
@@ -52,6 +55,7 @@ const props = withDefaults(
styles: "",
envs: null,
focus: false,
readonly: false,
}
)
@@ -120,7 +124,24 @@ const envTooltipPlugin = new HoppReactiveEnvPlugin(envVars, view)
const initView = (el: any) => {
const extensions: Extension = [
EditorView.contentAttributes.of({ "aria-label": props.placeholder }),
EditorView.updateListener.of((update) => {
if (props.readonly) {
update.view.contentDOM.inputMode = "none"
}
}),
EditorState.changeFilter.of(() => !props.readonly),
inputTheme,
props.readonly
? EditorView.theme({
".cm-content": {
caretColor: "var(--secondary-dark-color) !important",
color: "var(--secondary-dark-color) !important",
backgroundColor: "var(--divider-color) !important",
opacity: 0.25,
},
})
: EditorView.theme({}),
tooltips({
position: "absolute",
}),
@@ -138,6 +159,8 @@ const initView = (el: any) => {
ViewPlugin.fromClass(
class {
update(update: ViewUpdate) {
if (props.readonly) return
if (update.docChanged) {
const prevValue = clone(cachedValue.value)
@@ -172,6 +195,8 @@ const initView = (el: any) => {
}
}
),
history(),
keymap.of([...historyKeymap]),
]
view.value = new EditorView({

View File

@@ -1,33 +1,31 @@
<template>
<SmartItem
:label="label"
:icon="
value === selected ? 'radio_button_checked' : 'radio_button_unchecked'
"
:active="value === selected"
:icon="selected ? 'radio_button_checked' : 'radio_button_unchecked'"
:active="selected"
role="radio"
:aria-checked="value === selected"
@click.native="$emit('change', value)"
:aria-checked="selected"
@click.native="emit('change', value)"
/>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
<script setup lang="ts">
const emit = defineEmits<{
(e: "change", value: string): void
}>()
export default defineComponent({
props: {
value: {
type: String,
default: "",
},
label: {
type: String,
default: "",
},
selected: {
type: String,
default: "",
},
defineProps({
value: {
type: String,
default: "",
},
label: {
type: String,
default: "",
},
selected: {
type: Boolean,
default: false,
},
})
</script>

View File

@@ -5,18 +5,22 @@
:key="`radio-${index}`"
:value="radio.value"
:label="radio.label"
:selected="selected"
@change="$emit('change', radio.value)"
:selected="value === radio.value"
@change="emit('input', radio.value)"
/>
</div>
</template>
<script setup lang="ts">
const emit = defineEmits<{
(e: "input", value: string): void
}>()
defineProps<{
radios: Array<{
value: string
value: string // The key of the radio option
label: string
}>
selected: string
value: string // Should be a radio key given in the radios array
}>()
</script>

View File

@@ -1,5 +1,5 @@
<template>
<div v-show="active" class="flex flex-col flex-1">
<div v-if="shouldRender" v-show="active" class="flex flex-col flex-1">
<slot></slot>
</div>
</template>
@@ -33,11 +33,24 @@ const tabMeta = computed<TabMeta>(() => ({
label: props.label,
}))
const { activeTabID, addTabEntry, updateTabEntry, removeTabEntry } =
inject<TabProvider>("tabs-system")!
const {
activeTabID,
renderInactive,
addTabEntry,
updateTabEntry,
removeTabEntry,
} = inject<TabProvider>("tabs-system")!
const active = computed(() => activeTabID.value === props.id)
const shouldRender = computed(() => {
// If render inactive is true, then it should be rendered nonetheless
if (renderInactive.value) return true
// Else, return whatever is the active state
return active.value
})
onMounted(() => {
addTabEntry(props.id, tabMeta.value)
})

View File

@@ -80,6 +80,8 @@ export type TabMeta = {
}
export type TabProvider = {
// Whether inactive tabs should remain rendered
renderInactive: ComputedRef<boolean>
activeTabID: ComputedRef<string>
addTabEntry: (tabID: string, meta: TabMeta) => void
updateTabEntry: (tabID: string, newMeta: TabMeta) => void
@@ -91,6 +93,10 @@ const props = defineProps({
type: String,
default: "",
},
renderInactiveTabs: {
type: Boolean,
default: false,
},
vertical: {
type: Boolean,
default: false,
@@ -144,6 +150,7 @@ const removeTabEntry = (tabID: string) => {
}
provide<TabProvider>("tabs-system", {
renderInactive: computed(() => props.renderInactiveTabs),
activeTabID: computed(() => props.value),
addTabEntry,
updateTabEntry,

View File

@@ -149,7 +149,7 @@ export class GQLConnection {
.forEach((x) => (finalHeaders[x.key] = x.value))
const reqOptions = {
method: "post",
method: "POST",
url,
headers: {
...finalHeaders,
@@ -213,7 +213,7 @@ export class GQLConnection {
.forEach(({ key, value }) => (finalHeaders[key] = value))
const reqOptions = {
method: "post",
method: "POST",
url,
headers: {
...finalHeaders,

View File

@@ -25,7 +25,7 @@ import { getRESTRequest, setRESTTestResults } from "~/newstore/RESTSession"
import {
environmentsStore,
getCurrentEnvironment,
getEnviroment,
getEnvironment,
getGlobalVariables,
setGlobalEnvVariables,
updateEnvironment,
@@ -97,7 +97,7 @@ export const runRESTRequest$ = (): TaskEither<
setGlobalEnvVariables(runResult.right.envs.global)
if (environmentsStore.value.currentEnvironmentIndex !== -1) {
const env = getEnviroment(
const env = getEnvironment(
environmentsStore.value.currentEnvironmentIndex
)
updateEnvironment(

View File

@@ -45,28 +45,23 @@ import {
} from "~/helpers/fb/auth"
const BACKEND_GQL_URL =
process.env.context === "production"
? "https://api.hoppscotch.io/graphql"
: "https://api.hoppscotch.io/graphql"
process.env.BACKEND_GQL_URL ?? "https://api.hoppscotch.io/graphql"
const BACKEND_WS_URL =
process.env.BACKEND_WS_URL ?? "wss://api.hoppscotch.io/graphql"
// const storage = makeDefaultStorage({
// idbName: "hoppcache-v1",
// maxAge: 7,
// })
const subscriptionClient = new SubscriptionClient(
process.env.context === "production"
? "wss://api.hoppscotch.io/graphql"
: "wss://api.hoppscotch.io/graphql",
{
reconnect: true,
connectionParams: () => {
return {
authorization: `Bearer ${authIdToken$.value}`,
}
},
}
)
const subscriptionClient = new SubscriptionClient(BACKEND_WS_URL, {
reconnect: true,
connectionParams: () => {
return {
authorization: `Bearer ${authIdToken$.value}`,
}
},
})
authIdToken$.subscribe(() => {
subscriptionClient.client?.close()

View File

@@ -0,0 +1,3 @@
mutation DeleteShortcode($code: ID!) {
revokeShortcode(code: $code)
}

View File

@@ -0,0 +1,7 @@
query GetUserShortcodes($cursor: ID) {
myShortcodes(cursor: $cursor) {
id
request
createdOn
}
}

View File

@@ -0,0 +1,7 @@
subscription ShortcodeCreated {
myShortcodesCreated {
id
request
createdOn
}
}

View File

@@ -0,0 +1,5 @@
subscription ShortcodeDeleted {
myShortcodesRevoked {
id
}
}

View File

@@ -17,7 +17,7 @@ import {
GetCollectionTitleDocument,
} from "./graphql"
const BACKEND_PAGE_SIZE = 10
export const BACKEND_PAGE_SIZE = 10
const getCollectionChildrenIDs = async (collID: string) => {
const collsList: string[] = []

View File

@@ -4,8 +4,13 @@ import {
CreateShortcodeDocument,
CreateShortcodeMutation,
CreateShortcodeMutationVariables,
DeleteShortcodeDocument,
DeleteShortcodeMutation,
DeleteShortcodeMutationVariables,
} from "../graphql"
type DeleteShortcodeErrors = "shortcode/not_found"
export const createShortcode = (request: HoppRESTRequest) =>
runMutation<CreateShortcodeMutation, CreateShortcodeMutationVariables, "">(
CreateShortcodeDocument,
@@ -13,3 +18,12 @@ export const createShortcode = (request: HoppRESTRequest) =>
request: JSON.stringify(request),
}
)
export const deleteShortcode = (code: string) =>
runMutation<
DeleteShortcodeMutation,
DeleteShortcodeMutationVariables,
DeleteShortcodeErrors
>(DeleteShortcodeDocument, {
code,
})

View File

@@ -768,11 +768,52 @@ const samples = [
testScript: "",
}),
},
{
command: `curl \`
google.com -H "content-type: application/json"`,
response: makeRESTRequest({
method: "GET",
name: "Untitled request",
endpoint: "https://google.com/",
auth: {
authType: "none",
authActive: true,
},
body: {
contentType: null,
body: null,
},
params: [],
headers: [],
preRequestScript: "",
testScript: "",
}),
},
{
command: `curl 192.168.0.24:8080/ping`,
response: makeRESTRequest({
method: "GET",
name: "Untitled request",
endpoint: "http://192.168.0.24:8080/ping",
auth: {
authType: "none",
authActive: true,
},
body: {
contentType: null,
body: null,
},
params: [],
headers: [],
preRequestScript: "",
testScript: "",
}),
},
]
describe("parseCurlToHoppRESTReq", () => {
describe("Parse curl command to Hopp REST Request", () => {
for (const [i, { command, response }] of samples.entries()) {
test(`matches expectation for sample #${i + 1}`, () => {
test(`for sample #${i + 1}:\n\n${command}`, () => {
expect(parseCurlToHoppRESTReq(command)).toEqual(response)
})
}

View File

@@ -12,7 +12,7 @@ import { getHeaders, recordToHoppHeaders } from "./sub_helpers/headers"
// import { getCookies } from "./sub_helpers/cookies"
import { getQueries } from "./sub_helpers/queries"
import { getMethod } from "./sub_helpers/method"
import { concatParams, parseURL } from "./sub_helpers/url"
import { concatParams, getURLObject } from "./sub_helpers/url"
import { preProcessCurlCommand } from "./sub_helpers/preproc"
import { getBody, getFArgumentMultipartData } from "./sub_helpers/body"
import { getDefaultRESTRequest } from "~/newstore/RESTSession"
@@ -42,7 +42,7 @@ export const parseCurlCommand = (curlCommand: string) => {
const method = getMethod(parsedArguments)
// const cookies = getCookies(parsedArguments)
const urlObject = parseURL(parsedArguments)
const urlObject = getURLObject(parsedArguments)
const auth = getAuthObject(parsedArguments, headers, urlObject)
let rawData: string | string[] = pipe(

View File

@@ -161,8 +161,7 @@ const getXMLBody = (rawData: string) =>
const getFormattedJSON = flow(
safeParseJSON,
O.map((parsedJSON) => JSON.stringify(parsedJSON, null, 2)),
O.getOrElse(() => "{}"),
O.of
O.getOrElse(() => "{ }")
)
const getXWWWFormUrlEncodedBody = flow(
@@ -189,7 +188,7 @@ export function parseBody(
case "application/ld+json":
case "application/vnd.api+json":
case "application/json":
return getFormattedJSON(rawData)
return O.some(getFormattedJSON(rawData))
case "application/x-www-form-urlencoded":
return getXWWWFormUrlEncodedBody(rawData)

View File

@@ -50,7 +50,7 @@ const getMethodByDeduction = (parsedArguments: parser.Arguments) => {
R.or(objHasArrayProperty("F", "string"))
)(parsedArguments)
)
return O.some("post")
return O.some("POST")
else return O.none
}

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