diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 4a7ea303..00000000 --- a/.editorconfig +++ /dev/null @@ -1,12 +0,0 @@ -root = true - -[*] -indent_style = space -indent_size = 2 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true - -[*.md] -trim_trailing_whitespace = false diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 7c25c8ac..00000000 --- a/.eslintignore +++ /dev/null @@ -1,14 +0,0 @@ -build -app/renderer -app/static -app/bin -app/dist -app/node_modules -app/typings -assets -website -bin -dist -target -cache -schema.json \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 1fa89a98..00000000 --- a/.eslintrc.json +++ /dev/null @@ -1,161 +0,0 @@ -{ - "plugins": [ - "react", - "prettier", - "@typescript-eslint", - "eslint-comments", - "lodash", - "import" - ], - "extends": [ - "eslint:recommended", - "plugin:react/recommended", - "plugin:prettier/recommended", - "plugin:eslint-comments/recommended" - ], - "parser": "@typescript-eslint/parser", - "parserOptions": { - "sourceType": "module", - "ecmaFeatures": { - "jsx": true, - "impliedStrict": true, - "experimentalObjectRestSpread": true - }, - "allowImportExportEverywhere": true, - "project": [ - "./tsconfig.eslint.json" - ] - }, - "env": { - "es6": true, - "browser": true, - "node": true - }, - "settings": { - "react": { - "version": "detect" - }, - "import/resolver": { - "typescript": {} - }, - "import/internal-regex": "^(electron|react)$" - }, - "rules": { - "func-names": [ - "error", - "as-needed" - ], - "no-shadow": "error", - "no-extra-semi": 0, - "react/prop-types": 0, - "react/react-in-jsx-scope": 0, - "react/no-unescaped-entities": 0, - "react/jsx-no-target-blank": 0, - "react/no-string-refs": 0, - "prettier/prettier": [ - "error", - { - "printWidth": 120, - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "none", - "bracketSpacing": false, - "semi": true, - "useTabs": false, - "bracketSameLine": false - } - ], - "eslint-comments/no-unused-disable": "error", - "react/no-unknown-property":[ - "error", - { - "ignore": [ - "jsx", - "global" - ] - } - ] - }, - "overrides": [ - { - "files": [ - "**.ts", - "**.tsx" - ], - "extends": [ - "plugin:@typescript-eslint/recommended", - "plugin:@typescript-eslint/recommended-requiring-type-checking", - "prettier" - ], - "rules": { - "@typescript-eslint/explicit-function-return-type": "off", - "@typescript-eslint/explicit-module-boundary-types": "off", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-non-null-assertion": "off", - "@typescript-eslint/prefer-optional-chain": "error", - "@typescript-eslint/ban-types": "off", - "no-shadow": "off", - "@typescript-eslint/no-shadow": ["error"], - "@typescript-eslint/no-unsafe-assignment": "off", - "@typescript-eslint/no-unsafe-member-access": "off", - "@typescript-eslint/restrict-template-expressions": "off", - "@typescript-eslint/consistent-type-imports": [ "error", { "disallowTypeAnnotations": false } ], - "lodash/prop-shorthand": [ "error", "always" ], - "lodash/import-scope": [ "error", "method" ], - "lodash/collection-return": "error", - "lodash/collection-method-value": "error", - "import/no-extraneous-dependencies": "error", - "import/no-anonymous-default-export": "error", - "import/order": [ - "error", - { - "groups": [ - "builtin", - "internal", - "external", - "parent", - "sibling", - "index" - ], - "newlines-between": "always", - "alphabetize": { - "order": "asc", - "orderImportKind": "desc", - "caseInsensitive": true - } - } - ] - } - }, - { - "extends": [ - "plugin:jsonc/recommended-with-json", - "plugin:json-schema-validator/recommended" - ], - "files": [ - "*.json" - ], - "parser": "jsonc-eslint-parser", - "plugins": [ - "jsonc", - "json-schema-validator" - ], - "rules": { - "jsonc/array-element-newline": [ - "error", - "consistent" - ], - "jsonc/array-bracket-newline": [ - "error", - "consistent" - ], - "jsonc/indent": [ - "error", - 2 - ], - "prettier/prettier": "off", - "json-schema-validator/no-invalid": "error" - } - } - ] -} diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 97c115ec..00000000 --- a/.gitattributes +++ /dev/null @@ -1,5 +0,0 @@ -* text=auto -*.js text eol=lf -*.ts text eol=lf -*.tsx text eol=lf -bin/* linguist-vendored diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 15db91f4..00000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: Bug report -about: Create a report to help Hyper improve -title: '' -labels: '' -assignees: '' - ---- - - - - -- [ ] I am on the [latest](https://github.com/vercel/hyper/releases/latest) Hyper.app version -- [ ] I have searched the [issues](https://github.com/vercel/hyper/issues) of this repo and believe that this is not a duplicate - - - -- **OS version and name**: -- **Hyper.app version**: -- **Link of a [Gist](https://gist.github.com/) with the contents of your hyper.json**: -- **Relevant information from devtools** _(CMD+ALT+I on macOS, CTRL+SHIFT+I elsewhere)_: -- **The issue is reproducible in vanilla Hyper.app**: - -## Issue - diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index e28a3f4c..00000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Feature request -about: Suggest an idea/feature for Hyper -title: '' -labels: '' -assignees: '' - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 20a51554..00000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,25 +0,0 @@ -version: 2 -updates: -- package-ecosystem: npm - directory: "/" - schedule: - interval: weekly - time: '11:00' - open-pull-requests-limit: 30 - target-branch: canary - versioning-strategy: increase -- package-ecosystem: npm - directory: "/app" - schedule: - interval: weekly - time: '11:00' - open-pull-requests-limit: 30 - target-branch: canary - versioning-strategy: increase -- package-ecosystem: github-actions - directory: "/" - schedule: - interval: weekly - time: '11:00' - open-pull-requests-limit: 30 - target-branch: canary diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index 31a64d36..00000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,8 +0,0 @@ - diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index 569dda76..00000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,67 +0,0 @@ -# For most projects, this workflow file will not need changing; you simply need -# to commit it to your repository. -# -# You may wish to alter this file to override the set of languages analyzed, -# or to provide custom queries or build logic. -# -# ******** NOTE ******** -# We have attempted to detect the languages in your repository. Please check -# the `language` matrix defined below to confirm you have the correct set of -# supported CodeQL languages. -# -name: "CodeQL" - -on: - push: - branches: [ canary ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ canary ] - schedule: - - cron: '37 6 * * 5' - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - - strategy: - fail-fast: false - matrix: - language: [ 'javascript' ] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] - # Learn more: - # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v3 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v3 - - # â„šī¸ Command-line programs to run using the OS shell. - # 📚 https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun - - # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - #- run: | - # make bootstrap - # make release - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/e2e_comment.yml b/.github/workflows/e2e_comment.yml deleted file mode 100644 index 573a4d59..00000000 --- a/.github/workflows/e2e_comment.yml +++ /dev/null @@ -1,63 +0,0 @@ -name: Comment e2e test screenshots on PR -on: - workflow_run: - workflows: ['Node CI'] - types: - - completed -jobs: - e2e_comment: - runs-on: ubuntu-latest - if: github.event.workflow_run.event == 'pull_request' - steps: - - name: Dump Workflow run info from GitHub context - env: - WORKFLOW_RUN_INFO: ${{ toJSON(github.event.workflow_run) }} - run: echo "$WORKFLOW_RUN_INFO" - - name: Download Artifacts - uses: dawidd6/action-download-artifact@v3.1.4 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - workflow: nodejs.yml - run_id: ${{ github.event.workflow_run.id }} - name: e2e - - name: Get PR number - uses: dawidd6/action-download-artifact@v3.1.4 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - workflow: nodejs.yml - run_id: ${{ github.event.workflow_run.id }} - name: pr_num - - name: Read the pr_num file - id: pr_num_reader - uses: juliangruber/read-file-action@v1.1.7 - with: - path: ./pr_num.txt - - name: List images - run: ls -al - - name: Upload images to imgur - id: upload_screenshots - uses: devicons/public-upload-to-imgur@v2.2.2 - with: - path: ./*.png - client_id: ${{ secrets.IMGUR_CLIENT_ID }} - - name: Comment on the PR - uses: jungwinter/comment@v1 - env: - IMG_MARKDOWN: ${{ join(fromJSON(steps.upload_screenshots.outputs.markdown_urls), '') }} - MESSAGE: | - Hi there, - Thank you for contributing to Hyper! - You can get the build artifacts from [here](https://nightly.link/{1}/actions/runs/{2}). - Here are screenshots of Hyper built from this pr. - {0} - with: - type: create - issue_number: ${{ steps.pr_num_reader.outputs.content }} - token: ${{ secrets.GITHUB_TOKEN }} - body: ${{ format(env.MESSAGE, env.IMG_MARKDOWN, github.repository, github.event.workflow_run.id) }} - - name: Hide older comments - uses: kanga333/comment-hider@v0.4.0 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - leave_visible: 1 - issue_number: ${{ steps.pr_num_reader.outputs.content }} diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml deleted file mode 100644 index d42e2995..00000000 --- a/.github/workflows/nodejs.yml +++ /dev/null @@ -1,190 +0,0 @@ -name: Node CI -on: - push: - branches: - - master - - canary - pull_request: -defaults: - run: - shell: bash -env: - NODE_VERSION: 18.x -jobs: - build: - runs-on: ${{matrix.os}} - strategy: - matrix: - os: - - macos-latest - - ubuntu-latest - - windows-latest - fail-fast: false - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Use Node.js ${{ env.NODE_VERSION }} - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - - name: Fix node-gyp and Python - run: python3 -m pip install packaging setuptools - - name: Get yarn cache directory path - id: yarn-cache-dir-path - run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT - - uses: actions/cache/restore@v4 - with: - path: ${{ steps.yarn-cache-dir-path.outputs.dir }} - key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock', 'app/yarn.lock') }} - restore-keys: | - ${{ runner.os }}-yarn- - - name: Install - run: yarn install - env: - npm_config_node_gyp: ${{ github.workspace }}${{ runner.os == 'Windows' && '\node_modules\node-gyp\bin\node-gyp.js' || '/node_modules/node-gyp/bin/node-gyp.js' }} - - name: Install libarchive-tools - if: runner.os == 'Linux' - run: | - sudo apt update - sudo apt install libarchive-tools - - name: Lint and Run Unit Tests - run: yarn run test - - name: Getting Build Icon - if: github.ref == 'refs/heads/canary' || github.base_ref == 'canary' - run: | - cp build/canary.ico build/icon.ico - cp build/canary.icns build/icon.icns - - name: Build - run: | - if [ -z "$CSC_LINK" ] ; then unset CSC_LINK ; fi - if [ -z "$CSC_KEY_PASSWORD" ] ; then unset CSC_KEY_PASSWORD ; fi - if [ -z "$WIN_CSC_LINK" ] ; then unset WIN_CSC_LINK ; fi - if [ -z "$WIN_CSC_KEY_PASSWORD" ] ; then unset WIN_CSC_KEY_PASSWORD ; fi - if [ -z "$APPLE_ID" ] ; then unset APPLE_ID ; fi - if [ -z "$APPLE_APP_SPECIFIC_PASSWORD" ] ; then unset APPLE_APP_SPECIFIC_PASSWORD ; fi - yarn run dist - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - CSC_LINK: ${{ secrets.MAC_CERT_P12_BASE64 }} - CSC_KEY_PASSWORD: ${{ secrets.MAC_CERT_P12_PASSWORD }} - WIN_CSC_LINK: ${{ secrets.WIN_CERT_P12_BASE64 }} - WIN_CSC_KEY_PASSWORD: ${{ secrets.WIN_CERT_P12_PASSWORD }} - APPLE_ID: ${{ secrets.APPLE_ID }} - APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_PASSWORD }} - - name: Archive Build Artifacts - uses: LabhanshAgrawal/upload-artifact@v3 - with: - path: | - dist/*.dmg - dist/*.snap - dist/*.AppImage - dist/*.deb - dist/*.rpm - dist/*.pacman - dist/*.exe - - name: Run E2E Tests - if: runner.os != 'Linux' - run: yarn run test:e2e - - name: Run E2E Tests on Linux - if: runner.os == 'Linux' - uses: GabrielBB/xvfb-action@v1.6 - with: - run: yarn run test:e2e - env: - SHELL: /bin/bash - - name: Archive E2E test screenshot - uses: actions/upload-artifact@v3 - with: - name: e2e - path: dist/tmp/*.png - - name: Save the pr number in an artifact - if: github.event_name == 'pull_request' - env: - PR_NUM: ${{ github.event.number }} - run: echo $PR_NUM > pr_num.txt - - name: Upload the pr num - uses: actions/upload-artifact@v3 - if: github.event_name == 'pull_request' - with: - name: pr_num - path: ./pr_num.txt - - uses: actions/cache/save@v4 - if: github.event_name == 'push' - with: - path: ${{ steps.yarn-cache-dir-path.outputs.dir }} - key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock', 'app/yarn.lock') }} - - build-linux-arm: - runs-on: ubuntu-latest - strategy: - matrix: - include: - - name: armv7l - cpu: cortex-a8 - image: raspios_lite:latest - - name: arm64 - cpu: cortex-a53 - image: raspios_lite_arm64:latest - fail-fast: false - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Use Node.js ${{ env.NODE_VERSION }} - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - - name: Fix node-gyp and Python - run: python3 -m pip install packaging setuptools - - name: Get yarn cache directory path - id: yarn-cache-dir-path - run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT - - uses: actions/cache/restore@v4 - with: - path: ${{ steps.yarn-cache-dir-path.outputs.dir }} - key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock', 'app/yarn.lock') }} - restore-keys: | - ${{ runner.os }}-yarn- - - name: Install - run: | - yarn install - sudo apt update - sudo apt install libarchive-tools - - name: Compile - run: yarn run build - - name: rebuild node-pty - uses: pguyot/arm-runner-action@v2.5.2 - with: - image_additional_mb: 2000 - base_image: ${{ matrix.image }} - cpu: ${{ matrix.cpu }} - shell: bash - copy_artifact_path: target/node_modules/node-pty - copy_artifact_dest: target/node_modules - commands: | - wget https://nodejs.org/dist/v18.16.0/node-v18.16.0-linux-${{ matrix.name }}.tar.xz - tar -xJf node-v18.16.0-linux-${{ matrix.name }}.tar.xz - sudo cp node-v18.16.0-linux-${{ matrix.name }}/* /usr/local/ -R - npm run rebuild-node-pty - - name: chown node-pty - run: | - sudo chown -R $USER:$USER target/node_modules/node-pty - - name: Prepare v8 snapshot - if: matrix.name == 'armv7l' - run: | - sudo dpkg --add-architecture i386 - sudo apt update - sudo apt install -y libglib2.0-0:i386 libexpat1:i386 libgcc-s1:i386 - npm_config_arch=armv7l yarn run v8-snapshot:arch - - name: Build - run: yarn run electron-builder -l deb rpm AppImage pacman --${{ matrix.name }} -c electron-builder-linux-ci.json - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - name: Archive Build Artifacts - uses: LabhanshAgrawal/upload-artifact@v3 - with: - path: | - dist/*.snap - dist/*.AppImage - dist/*.deb - dist/*.rpm - dist/*.pacman diff --git a/.gitignore b/.gitignore index 9c5932fb..15daa358 100644 --- a/.gitignore +++ b/.gitignore @@ -1,23 +1,13 @@ # build output dist -app/renderer -target -bin/cli.* -cache +build # dependencies node_modules # logs npm-debug.log -yarn-error.log - -# optional dev config file and plugins directory -hyper.json -schema.json -plugins +# other +.next .DS_Store -.vscode/* -!.vscode/launch.json -.idea diff --git a/.husky/.gitignore b/.husky/.gitignore deleted file mode 100644 index 31354ec1..00000000 --- a/.husky/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_ diff --git a/.husky/pre-push b/.husky/pre-push deleted file mode 100755 index f077c917..00000000 --- a/.husky/pre-push +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -. "$(dirname "$0")/_/husky.sh" - -yarn test diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 747bb7b0..00000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "type": "node", - "request": "launch", - "name": "Launch Hyper", - "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron", - "program": "${workspaceRoot}/target/index.js", - "protocol": "inspector" - }, - { - "type": "node", - "request": "launch", - "name": "cli", - "runtimeExecutable": "node", - "program": "${workspaceRoot}/bin/cli.js", - "args": ["--help"], - "protocol": "inspector" - } - ] -} diff --git a/.yarnrc b/.yarnrc deleted file mode 100644 index 45291c13..00000000 --- a/.yarnrc +++ /dev/null @@ -1 +0,0 @@ -registry "https://registry.npmjs.org/" diff --git a/HISTORY.md b/HISTORY.md new file mode 100644 index 00000000..6467f811 --- /dev/null +++ b/HISTORY.md @@ -0,0 +1,66 @@ + +0.4.2 / 2016-07-13 +================== + + * fix close icon by copying static assets to build [@rauchg] + +0.4.1 / 2016-07-13 +================== + + * noop bump to test updates + +0.4.0 / 2016-07-13 +================== + + * implement extensible redux actions system [@rauchg] + * add support for config (~/.hyperterm.js) [@rauchg, @nfcampos] + * add support for plugins (~/.hyperterm_modules) [@rauchg] + * improve menubar look [@leo, @rauchg] + * beautiful default colors [@hharnisc, @dzannotti] + * add close icon for tabs [@johanbrook] + * add support for font size shortcuts [@jhaynie, @nfcampos] + * add support for maximizing upon double click [@jhaynie] + * add fallback fonts for linux and windows [@olliv] + * improve menu items [@rauchg, @sindresorhus] + * add proper auto updates system [@matiastucci, @rauchg] + +0.3.1 / 2016-07-04 +================== + + * implement most recent hterm with lots of bugfixes [@dbkaplun, @rauchg] + +0.3.0 / 2016-07-04 +================== + + * revamp the menu to be a lot more standard (#38) [@rauchg] + * move menu into its own file and refactor [@rauchg] + * add static icon, move icons to static folder [@rauchg] + * add cross-platform font family settings (#26) [@OlliV, @rauchg] + * remove `xterm.css` (no longer used, smaller build!) [@rauchg] + * change font size with command shortcuts (#34) [@jhaynie] + * implement a more reasonable update interval check frequency (#33) [@rauchg] + * add standard behavior when you double click window (#32) [@jhaynie] + +0.2.1 / 2016-07-03 +================== + + * improvements to update checker + +0.2.0 / 2016-07-03 +================== + + * Implement hterm (#28) [@rauchg] + * Fix "Download" link being clickable when hidden (#7) [@rauchg] + * Jump to begining of end at edges of tabs when moving sideways (#22) [@rauchg] + * Make clear where to run `npm start` (#19) [@montogeek] + * Add fullscreen menu item (#1) [@rauchg, @montogeek] + * Improve README and scripts (#15) [@leo] + * Add support for cmd+shift+[|] [@rauchg] + * Add dev build instructions to README (#3) [@rauchg] + * Make `ctrl+c` close instead of `cmd+w` (#2) [@rauchg] + * Improve `zip` builds to not include nested directory [@rauchg] + +0.1.0 / 2016-07-01 +================== + + * initial release diff --git a/LICENSE b/LICENSE deleted file mode 100644 index fe231dc9..00000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -# MIT License - -Copyright (c) 2018 Vercel, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/PLUGINS.md b/PLUGINS.md deleted file mode 100644 index afc284a3..00000000 --- a/PLUGINS.md +++ /dev/null @@ -1,210 +0,0 @@ -# Plugin development - -## Workflow - -### Run Hyper in dev mode -Hyper can be run in dev mode by cloning this repository and following the ["Contributing" section of our README](https://github.com/vercel/hyper#contribute). - -In dev mode you'll get more ouput and access to React/Redux dev-tools in Electron. - -Prerequisites and steps are described in the ["Contributing" section of our README](https://github.com/vercel/hyper#contribute). -Be sure to use the `canary` branch. - -### Create a dev config file -Copy your config file `hyper.json` to the root of your cloned repository. Hyper, in dev mode, will use this copied config file. That means that you can continue to use your main installation of Hyper with your day-to-day configuration. -After the first run, Hyper, in dev mode, will have created a new `plugins` directory in your repository directory. - -### Setup your plugin -Go to your recently created `/plugins/local` directory and create/clone your plugin repo. An even better method on macOS/Linux is to add a symlink to your plugin directory. - -Edit your dev config file, and add your plugin name (directory name in your `local` directory) in the `localPlugins` array. -```js -module.exports = { - config: { - ... - }, - plugins: [], - localPlugins: ['hyper-awesome-plugin'], - ... -} -``` - -### Running your plugin -To load, your plugin should expose at least one API method. All possible methods are listed [here](https://github.com/vercel/hyper/blob/canary/app/plugins/extensions.ts). - -After launching Hyper in dev mode, run `yarn run app`, it should log that your plugin has been correcty loaded: `Plugin hyper-awesome-plugin (0.1.0) loaded.`. Name and version printed are the ones in your plugins `package.json` file. - -When you put a `console.log()` in your plugin code, it will be displayed in the Electron dev-tools, but only if it is located in a renderer method, like component decorators. If it is located in the Electron main process method, like the `onApp` handler, it will be displayed in your terminal where you ran `yarn run app` or in your VSCode console. - -## Recipes -Almost all available API methods can be found on https://hyper.is. -If there's any missing, let us know or submit a PR to document it! - -### Components -You can decorate almost all Hyper components with a Higher-Order Component (HOC). To understand their architecture, the easiest way is to use React dev-tools to dig in to their hierarchy. - -Multiple plugins can decorate the same Hyper component. Thus, `Component` passed as first argument to your decorator function could possibly not be an original Hyper component but a HOC of a previous plugin. If you need to retrieve a reference to a real Hyper component, you can pass down a `onDecorated` handler. -```js -exports.decorateTerms = (Terms, {React}) => { - return class extends React.Component { - constructor(props, context) { - super(props, context); - this.terms = null; - this.onDecorated = this.onDecorated.bind(this); - } - - onDecorated(terms) { - this.terms = terms; - // Don't forget to propagate it to HOC chain - if (this.props.onDecorated) this.props.onDecorated(terms); - } - - render() { - return React.createElement( - Terms, - Object.assign({}, this.props, { - onDecorated: this.onDecorated - }) - ); - // Or if you use JSX: - // - } - } -``` -:warning: Note that you have to execute `this.props.onDecorated` to not break the handler chain. Without this, you could break other plugins that decorate the same component. - -### Keymaps -If you want to add some keymaps, you need to do 2 things: - -#### Declare your key bindings -Use the `decorateKeymaps` API handler to modify existing keymaps and add yours with the following format `command: hotkeys`. -```js -// Adding Keymaps -exports.decorateKeymaps = keymaps => { - const newKeymaps = { - 'pane:maximize': 'ctrl+shift+m', - 'pane:invert': 'ctrl+shift+i' - } - return Object.assign({}, keymaps, newKeymaps); -} -``` -The command name can be whatever you want, but the following is better to respect the default naming convention: `:`. -Hotkeys are composed by [Mousetrap supported keys](https://craig.is/killing/mice#keys). - -**Bonus feature**: if your command ends with `:prefix`, it would mean that you want to use this command with an additional digit to the command. Then Hyper will create all your commands under the hood. For example, this keymap `'pane:hide:prefix': 'ctrl+shift'` will automatically generate the following: -``` -{ - 'pane:hide:1': 'ctrl+shift+1', - 'pane:hide:2': 'ctrl+shift+2', - ... - 'pane:hide:8': 'ctrl+shift+8', - 'pane:hide:last': 'ctrl+shift+9' -} -``` -Notice that `9` has been replaced by `last` because most of the time this is handy if you have more than 9 items. - - -#### Register a handler for your commands -##### Renderer/Window -Most of time, you'll want to execute some sort of handler in context of the renderer, like dispatching a Redux action. -To trigger these handlers, you'll have to register them with the `registerCommands` Terms method. -```js -this.terms.registerCommands({ - 'pane:maximize': e => { - this.props.onMaximizePane(); - // e parameter is React key event - e.preventDefault(); - } -}) -``` - -##### Main process -If there is no handler in the renderer for an existing command, an `rpc` message is emitted. -If you want to execute a handler in main process you have to subscribe to a message, for example: -```js -rpc.on('command pane:snapshot', () => { - /* Awesome snapshot feature */ -}); -``` - -### Menu -Your plugin can expose a `decorateMenu` function to modify the Hyper menu template. -Check the [Electron documentation](https://electronjs.org/docs/api/menu-item) for more details about the different menu item types/options available. - -Be careful, a click handler will be executed on the main process. If you need to trigger a handler in the render process you need to use an `rpc` message like this: -```js -exports.decorateMenu = (menu) => { - debug('decorateMenu'); - const isMac = process.platform === 'darwin'; - // menu label is different on mac - const menuLabel = isMac ? 'Shell' : 'File'; - - return menu.map(menuCategory => { - if (menuCategory.label !== menuLabel) { - return menuItem; - } - return [ - ...menuCategory, - { - type: 'separator' - }, - { - label: 'Clear all panes in all tabs', - accelerator: 'ctrl+shift+y', - click(item, focusedWindow) { - // on macOS, menu item can clicked without or minized window - if (focusedWindow) { - focusedWindow.rpc.emit('clear allPanes'); - } - } - } - ] - }); -} -/* Plugin needs to register a rpc handler on renderer side for example in a Terms HOC*/ -exports.decorateTerms = (Terms, { React }) => { - return class extends React.Component { - componentDidMount() { - window.rpc.on('clear allPanes',() => { - /* Awesome plugin feature */ - }) - } - } -} -``` - -### Cursor -If your plugin needs to know cursor position/size, it can decorate the Term component and pass a handler. This handler will be called with each cursor move while passing back all information about the cursor. -```js -exports.decorateTerm = (Term, { React, notify }) => { - // Define and return our higher order component. - return class extends React.Component { - onCursorMove (cursorFrame) { - // Don't forget to propagate it to HOC chain - if (this.props.onCursorMove) this.props.onCursorMove(cursorFrame); - - const { x, y, width, height, col, row } = cursorFrame; - /* Awesome cursor feature */ - } - } -} -``` - -### Require Electron -Hyper doesn't provide a reference to electron. However plugins can directly require electron. - -```js -const electron = require('electron') -// or -const { dialog, Menu } = require('electron') -``` - -This is needed in order to allow show/hide to have proper return of focus. - -## Hyper v2 breaking changes -Hyper v2 uses `xterm.js` instead of `hterm`. It means that PTY output renders now in a canvas element, not with a hackable DOM structure. -For example, plugins can't use TermCSS in order to modify text or link styles anymore. It is now required to use available configuration params that are passed down to `xterm.js`. - -If your plugin was deeply linked with the `hterm` API (even public methods), it certainly doesn't work anymore. - -If your plugin needs some unavailable API to tweak `xterm.js`, please open an issue. We'll be happy to expose some existing `xterm.js` API or implement new ones. diff --git a/README.md b/README.md index 8c11085e..74e9cf9d 100644 --- a/README.md +++ b/README.md @@ -1,116 +1,28 @@ -![](https://assets.vercel.com/image/upload/v1549723846/repositories/hyper/hyper-3-repo-banner.png) - -

- - - -

- -[![Node CI](https://github.com/vercel/hyper/workflows/Node%20CI/badge.svg?event=push)](https://github.com/vercel/hyper/actions?query=workflow%3A%22Node+CI%22+branch%3Acanary+event%3Apush) -[![Changelog #213](https://img.shields.io/badge/changelog-%23213-lightgrey.svg)](https://changelog.com/213) - -For more details, head to: https://hyper.is - -## Project goals - -The goal of the project is to create a beautiful and extensible experience for command-line interface users, built on open web standards. In the beginning, our focus will be primarily around speed, stability and the development of the correct API for extension authors. - -In the future, we anticipate the community will come up with innovative additions to enhance what could be the simplest, most powerful and well-tested interface for productivity. - -## Usage - -[Download the latest release!](https://hyper.is/#installation) - -### Linux -#### Arch and derivatives -Hyper is available in the [AUR](https://aur.archlinux.org/packages/hyper/). Use an AUR [package manager](https://wiki.archlinux.org/index.php/AUR_helpers) e.g. [paru](https://github.com/Morganamilo/paru) - -```sh -paru -S hyper -``` - -#### NixOS -Hyper is available as [Nix package](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/misc/hyper/default.nix), to install the app run this command: - -```sh -nix-env -i hyper -``` - -### macOS - -Use [Homebrew Cask](https://brew.sh) to download the app by running these commands: - -```bash -brew update -brew install --cask hyper -``` - -### Windows - -Use [chocolatey](https://chocolatey.org/) to install the app by running the following command (package information can be found [here](https://chocolatey.org/packages/hyper/)): - -```bash -choco install hyper -``` - -**Note:** The version available on [Homebrew Cask](https://brew.sh), [Chocolatey](https://chocolatey.org), [Snapcraft](https://snapcraft.io/store) or the [AUR](https://aur.archlinux.org) may not be the latest. Please consider downloading it from [here](https://hyper.is/#installation) if that's the case. +# hyperterm ## Contribute -Regardless of the platform you are working on, you will need to have Yarn installed. If you have never installed Yarn before, you can find out how at: https://yarnpkg.com/en/docs/install. - -1. Install necessary packages: - * Windows - - Be sure to run `yarn global add windows-build-tools` from an elevated prompt (as an administrator) to install `windows-build-tools`. - * macOS - - Once you have installed Yarn, you can skip this section! - * Linux (You can see [here](https://en.wikipedia.org/wiki/List_of_Linux_distributions) what your Linux is based on.) - - RPM-based - + `GraphicsMagick` - + `libicns-utils` - + `xz` (Installed by default on some distributions.) - - Debian-based - + `graphicsmagick` - + `icnsutils` - + `xz-utils` -2. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device -3. Install the dependencies: `yarn` -4. Build the code and watch for changes: `yarn run dev` -5. To run `hyper` - * `yarn run app` from another terminal tab/window/pane - * If you are using **Visual Studio Code**, select `Launch Hyper` in debugger configuration to launch a new Hyper instance with debugger attached. - * If you interrupt `yarn run dev`, you'll need to relaunch it each time you want to test something. Webpack will watch changes and will rebuild renderer code when needed (and only what have changed). You'll just have to relaunch electron by using yarn run app or VSCode launch task. - -To make sure that your code works in the finished application, you can generate the binaries like this: +To install `package.json` dependencies in a way where the native +modules are built with `electron`, run: ```bash -yarn run dist +$ ./scripts/install.sh ``` -After that, you will see the binary in the `./dist` folder! +Then, you want to make sure `app/dist` is populated. I recommend +running `webpack` with `--watch` so that any changes you make +to the app are detected. -#### Known issues that can happen during development +```bash +$ cd app/ +$ npm install +$ webpack --watch +``` -##### Error building `node-pty` +Then you can run in the main directory: -If after building during development you get an alert dialog related to `node-pty` issues, -make sure its build process is working correctly by running `yarn run rebuild-node-pty`. +```bash +$ npm start +``` -If you are on macOS, this typically is related to Xcode issues (like not having agreed -to the Terms of Service by running `sudo xcodebuild` after a fresh Xcode installation). - -##### Error with `C++` on macOS when running `yarn` - -If you are getting compiler errors when running `yarn` add the environment variable `export CXX=clang++` - -##### Error with `codesign` on macOS when running `yarn run dist` - -If you have issues in the `codesign` step when running `yarn run dist` on macOS, you can temporarily disable code signing locally by setting -`export CSC_IDENTITY_AUTO_DISCOVERY=false` for the current terminal session. - -## Related Repositories - -- [Website](https://github.com/vercel/hyper-site) -- [Sample Extension](https://github.com/vercel/hyperpower) -- [Sample Theme](https://github.com/vercel/hyperyellow) -- [Awesome Hyper](https://github.com/bnb/awesome-hyper) +...to launch the app! diff --git a/app/.yarnrc b/app/.yarnrc deleted file mode 100644 index 45291c13..00000000 --- a/app/.yarnrc +++ /dev/null @@ -1 +0,0 @@ -registry "https://registry.npmjs.org/" diff --git a/app/assets/icons.svg b/app/assets/icons.svg new file mode 100644 index 00000000..482a666b --- /dev/null +++ b/app/assets/icons.svg @@ -0,0 +1,8 @@ + + + + close + + + + diff --git a/app/auto-updater-linux.ts b/app/auto-updater-linux.ts deleted file mode 100644 index aa95c1d7..00000000 --- a/app/auto-updater-linux.ts +++ /dev/null @@ -1,52 +0,0 @@ -import {EventEmitter} from 'events'; - -import fetch from 'electron-fetch'; - -class AutoUpdater extends EventEmitter implements Electron.AutoUpdater { - updateURL!: string; - quitAndInstall() { - this.emitError('QuitAndInstall unimplemented'); - } - getFeedURL() { - return this.updateURL; - } - - setFeedURL(options: Electron.FeedURLOptions) { - this.updateURL = options.url; - } - - checkForUpdates() { - if (!this.updateURL) { - return this.emitError('Update URL is not set'); - } - this.emit('checking-for-update'); - - fetch(this.updateURL) - .then((res) => { - if (res.status === 204) { - this.emit('update-not-available'); - return; - } - return res.json().then(({name, notes, pub_date}: {name: string; notes: string; pub_date: string}) => { - // Only name is mandatory, needed to construct release URL. - if (!name) { - throw new Error('Malformed server response: release name is missing.'); - } - const date = pub_date ? new Date(pub_date) : new Date(); - this.emit('update-available', {}, notes, name, date); - }); - }) - .catch(this.emitError.bind(this)); - } - - emitError(error: string | Error) { - if (typeof error === 'string') { - error = new Error(error); - } - this.emit('error', error); - } -} - -const autoUpdaterLinux = new AutoUpdater(); - -export default autoUpdaterLinux; diff --git a/app/commands.ts b/app/commands.ts deleted file mode 100644 index 469a5a3d..00000000 --- a/app/commands.ts +++ /dev/null @@ -1,170 +0,0 @@ -import {app, Menu} from 'electron'; -import type {BrowserWindow} from 'electron'; - -import {openConfig, getConfig} from './config'; -import {updatePlugins} from './plugins'; -import {installCLI} from './utils/cli-install'; -import * as systemContextMenu from './utils/system-context-menu'; - -const commands: Record void> = { - 'window:new': () => { - // If window is created on the same tick, it will consume event too - setTimeout(app.createWindow, 0); - }, - 'tab:new': (focusedWindow) => { - if (focusedWindow) { - focusedWindow.rpc.emit('termgroup add req', {}); - } else { - setTimeout(app.createWindow, 0); - } - }, - 'pane:splitRight': (focusedWindow) => { - focusedWindow?.rpc.emit('split request vertical', {}); - }, - 'pane:splitDown': (focusedWindow) => { - focusedWindow?.rpc.emit('split request horizontal', {}); - }, - 'pane:close': (focusedWindow) => { - focusedWindow?.rpc.emit('termgroup close req'); - }, - 'window:preferences': () => { - void openConfig(); - }, - 'editor:clearBuffer': (focusedWindow) => { - focusedWindow?.rpc.emit('session clear req'); - }, - 'editor:selectAll': (focusedWindow) => { - focusedWindow?.rpc.emit('term selectAll'); - }, - 'plugins:update': () => { - updatePlugins(); - }, - 'window:reload': (focusedWindow) => { - focusedWindow?.rpc.emit('reload'); - }, - 'window:reloadFull': (focusedWindow) => { - focusedWindow?.reload(); - }, - 'window:devtools': (focusedWindow) => { - if (!focusedWindow) { - return; - } - const webContents = focusedWindow.webContents; - if (webContents.isDevToolsOpened()) { - webContents.closeDevTools(); - } else { - webContents.openDevTools({mode: 'detach'}); - } - }, - 'zoom:reset': (focusedWindow) => { - focusedWindow?.rpc.emit('reset fontSize req'); - }, - 'zoom:in': (focusedWindow) => { - focusedWindow?.rpc.emit('increase fontSize req'); - }, - 'zoom:out': (focusedWindow) => { - focusedWindow?.rpc.emit('decrease fontSize req'); - }, - 'tab:prev': (focusedWindow) => { - focusedWindow?.rpc.emit('move left req'); - }, - 'tab:next': (focusedWindow) => { - focusedWindow?.rpc.emit('move right req'); - }, - 'pane:prev': (focusedWindow) => { - focusedWindow?.rpc.emit('prev pane req'); - }, - 'pane:next': (focusedWindow) => { - focusedWindow?.rpc.emit('next pane req'); - }, - 'editor:movePreviousWord': (focusedWindow) => { - focusedWindow?.rpc.emit('session move word left req'); - }, - 'editor:moveNextWord': (focusedWindow) => { - focusedWindow?.rpc.emit('session move word right req'); - }, - 'editor:moveBeginningLine': (focusedWindow) => { - focusedWindow?.rpc.emit('session move line beginning req'); - }, - 'editor:moveEndLine': (focusedWindow) => { - focusedWindow?.rpc.emit('session move line end req'); - }, - 'editor:deletePreviousWord': (focusedWindow) => { - focusedWindow?.rpc.emit('session del word left req'); - }, - 'editor:deleteNextWord': (focusedWindow) => { - focusedWindow?.rpc.emit('session del word right req'); - }, - 'editor:deleteBeginningLine': (focusedWindow) => { - focusedWindow?.rpc.emit('session del line beginning req'); - }, - 'editor:deleteEndLine': (focusedWindow) => { - focusedWindow?.rpc.emit('session del line end req'); - }, - 'editor:break': (focusedWindow) => { - focusedWindow?.rpc.emit('session break req'); - }, - 'editor:stop': (focusedWindow) => { - focusedWindow?.rpc.emit('session stop req'); - }, - 'editor:quit': (focusedWindow) => { - focusedWindow?.rpc.emit('session quit req'); - }, - 'editor:tmux': (focusedWindow) => { - focusedWindow?.rpc.emit('session tmux req'); - }, - 'editor:search': (focusedWindow) => { - focusedWindow?.rpc.emit('session search'); - }, - 'editor:search-close': (focusedWindow) => { - focusedWindow?.rpc.emit('session search close'); - }, - 'cli:install': () => { - void installCLI(true); - }, - 'window:hamburgerMenu': () => { - if (process.platform !== 'darwin' && ['', true].includes(getConfig().showHamburgerMenu)) { - Menu.getApplicationMenu()!.popup({x: 25, y: 22}); - } - }, - 'systemContextMenu:add': () => { - systemContextMenu.add(); - }, - 'systemContextMenu:remove': () => { - systemContextMenu.remove(); - }, - 'window:toggleKeepOnTop': (focusedWindow) => { - focusedWindow?.setAlwaysOnTop(!focusedWindow.isAlwaysOnTop()); - } -}; - -//Special numeric command -([1, 2, 3, 4, 5, 6, 7, 8, 'last'] as const).forEach((cmdIndex) => { - const index = cmdIndex === 'last' ? cmdIndex : cmdIndex - 1; - commands[`tab:jump:${cmdIndex}`] = (focusedWindow) => { - focusedWindow?.rpc.emit('move jump req', index); - }; -}); - -//Profile specific commands -getConfig().profiles.forEach((profile) => { - commands[`window:new:${profile.name}`] = () => { - setTimeout(() => app.createWindow(undefined, undefined, profile.name), 0); - }; - commands[`tab:new:${profile.name}`] = (focusedWindow) => { - focusedWindow?.rpc.emit('termgroup add req', {profile: profile.name}); - }; - commands[`pane:splitRight:${profile.name}`] = (focusedWindow) => { - focusedWindow?.rpc.emit('split request vertical', {profile: profile.name}); - }; - commands[`pane:splitDown:${profile.name}`] = (focusedWindow) => { - focusedWindow?.rpc.emit('split request horizontal', {profile: profile.name}); - }; -}); - -export const execCommand = (command: string, focusedWindow?: BrowserWindow) => { - const fn = commands[command]; - if (fn) { - fn(focusedWindow); - } -}; diff --git a/app/config.ts b/app/config.ts deleted file mode 100644 index b4613d57..00000000 --- a/app/config.ts +++ /dev/null @@ -1,156 +0,0 @@ -import {app} from 'electron'; - -import chokidar from 'chokidar'; - -import type {parsedConfig, configOptions} from '../typings/config'; - -import {_import, getDefaultConfig} from './config/import'; -import _openConfig from './config/open'; -import {cfgPath, cfgDir} from './config/paths'; -import notify from './notify'; -import {getColorMap} from './utils/colors'; - -const watchers: Function[] = []; -let cfg: parsedConfig = {} as any; -let _watcher: chokidar.FSWatcher; - -export const getDeprecatedCSS = (config: configOptions) => { - const deprecated: string[] = []; - const deprecatedCSS = ['x-screen', 'x-row', 'cursor-node', '::selection']; - deprecatedCSS.forEach((css) => { - if (config.css?.includes(css) || config.termCSS?.includes(css)) { - deprecated.push(css); - } - }); - return deprecated; -}; - -const checkDeprecatedConfig = () => { - if (!cfg.config) { - return; - } - const deprecated = getDeprecatedCSS(cfg.config); - if (deprecated.length === 0) { - return; - } - const deprecatedStr = deprecated.join(', '); - notify('Configuration warning', `Your configuration uses some deprecated CSS classes (${deprecatedStr})`); -}; - -const _watch = () => { - if (_watcher) { - return; - } - - const onChange = () => { - // Need to wait 100ms to ensure that write is complete - setTimeout(() => { - cfg = _import(); - notify('Configuration updated', 'Hyper configuration reloaded!'); - watchers.forEach((fn) => { - fn(); - }); - checkDeprecatedConfig(); - }, 100); - }; - - _watcher = chokidar.watch(cfgPath); - _watcher.on('change', onChange); - _watcher.on('error', (error) => { - console.error('error watching config', error); - }); - - app.on('before-quit', () => { - if (Object.keys(_watcher.getWatched()).length > 0) { - _watcher.close().catch((err) => { - console.warn(err); - }); - } - }); -}; - -export const subscribe = (fn: Function) => { - watchers.push(fn); - return () => { - watchers.splice(watchers.indexOf(fn), 1); - }; -}; - -export const getConfigDir = () => { - // expose config directory to load plugin from the right place - return cfgDir; -}; - -export const getDefaultProfile = () => { - return cfg.config.defaultProfile || cfg.config.profiles[0]?.name || 'default'; -}; - -// get config for the default profile, keeping it for backward compatibility -export const getConfig = () => { - return getProfileConfig(getDefaultProfile()); -}; - -export const getProfiles = () => { - return cfg.config.profiles; -}; - -export const getProfileConfig = (profileName: string): configOptions => { - const {profiles, defaultProfile, ...baseConfig} = cfg.config; - const profileConfig = profiles.find((p) => p.name === profileName)?.config || {}; - for (const key in profileConfig) { - if (typeof baseConfig[key] === 'object' && !Array.isArray(baseConfig[key])) { - baseConfig[key] = {...baseConfig[key], ...profileConfig[key]}; - } else { - baseConfig[key] = profileConfig[key]; - } - } - return {...baseConfig, defaultProfile, profiles}; -}; - -export const openConfig = () => { - return _openConfig(); -}; - -export const getPlugins = (): {plugins: string[]; localPlugins: string[]} => { - return { - plugins: cfg.plugins, - localPlugins: cfg.localPlugins - }; -}; - -export const getKeymaps = () => { - return cfg.keymaps; -}; - -export const setup = () => { - cfg = _import(); - _watch(); - checkDeprecatedConfig(); -}; - -export {get as getWin, recordState as winRecord, defaults as windowDefaults} from './config/windows'; - -export const fixConfigDefaults = (decoratedConfig: configOptions) => { - const defaultConfig = getDefaultConfig().config!; - decoratedConfig.colors = getColorMap(decoratedConfig.colors) || {}; - // We must have default colors for xterm css. - decoratedConfig.colors = {...defaultConfig.colors, ...decoratedConfig.colors}; - return decoratedConfig; -}; - -export const htermConfigTranslate = (config: configOptions) => { - const cssReplacements: Record = { - 'x-screen x-row([ {.[])': '.xterm-rows > div$1', - '.cursor-node([ {.[])': '.terminal-cursor$1', - '::selection([ {.[])': '.terminal .xterm-selection div$1', - 'x-screen a([ {.[])': '.terminal a$1', - 'x-row a([ {.[])': '.terminal a$1' - }; - Object.keys(cssReplacements).forEach((pattern) => { - const searchvalue = new RegExp(pattern, 'g'); - const newvalue = cssReplacements[pattern]; - config.css = config.css?.replace(searchvalue, newvalue); - config.termCSS = config.termCSS?.replace(searchvalue, newvalue); - }); - return config; -}; diff --git a/app/config/config-default.json b/app/config/config-default.json deleted file mode 100644 index 2a6a66ff..00000000 --- a/app/config/config-default.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "$schema": "./schema.json", - "config": { - "updateChannel": "stable", - "fontSize": 12, - "fontFamily": "Menlo, \"DejaVu Sans Mono\", Consolas, \"Lucida Console\", monospace", - "fontWeight": "normal", - "fontWeightBold": "bold", - "lineHeight": 1, - "letterSpacing": 0, - "scrollback": 1000, - "cursorColor": "rgba(248,28,229,0.8)", - "cursorAccentColor": "#000", - "cursorShape": "BLOCK", - "cursorBlink": false, - "foregroundColor": "#fff", - "backgroundColor": "#000", - "selectionColor": "rgba(248,28,229,0.3)", - "borderColor": "#333", - "css": "", - "termCSS": "", - "workingDirectory": "", - "showHamburgerMenu": "", - "showWindowControls": "", - "padding": "12px 14px", - "colors": { - "black": "#000000", - "red": "#C51E14", - "green": "#1DC121", - "yellow": "#C7C329", - "blue": "#0A2FC4", - "magenta": "#C839C5", - "cyan": "#20C5C6", - "white": "#C7C7C7", - "lightBlack": "#686868", - "lightRed": "#FD6F6B", - "lightGreen": "#67F86F", - "lightYellow": "#FFFA72", - "lightBlue": "#6A76FB", - "lightMagenta": "#FD7CFC", - "lightCyan": "#68FDFE", - "lightWhite": "#FFFFFF", - "limeGreen": "#32CD32", - "lightCoral": "#F08080" - }, - "shell": "", - "shellArgs": [ - "--login" - ], - "env": {}, - "bell": "SOUND", - "bellSound": null, - "bellSoundURL": null, - "copyOnSelect": false, - "defaultSSHApp": true, - "quickEdit": false, - "macOptionSelectionMode": "vertical", - "webGLRenderer": false, - "webLinksActivationKey": "", - "disableLigatures": true, - "disableAutoUpdates": false, - "autoUpdatePlugins": true, - "preserveCWD": true, - "screenReaderMode": false, - "imageSupport": true, - "defaultProfile": "default", - "profiles": [ - { - "name": "default", - "config": {} - } - ] - }, - "plugins": [], - "localPlugins": [], - "keymaps": {} -} diff --git a/app/config/import.ts b/app/config/import.ts deleted file mode 100644 index b9965375..00000000 --- a/app/config/import.ts +++ /dev/null @@ -1,65 +0,0 @@ -import {readFileSync, mkdirpSync} from 'fs-extra'; - -import type {rawConfig} from '../../typings/config'; -import notify from '../notify'; - -import {_init} from './init'; -import {migrateHyper3Config} from './migrate'; -import {defaultCfg, cfgPath, plugs, defaultPlatformKeyPath} from './paths'; - -let defaultConfig: rawConfig; - -const _importConf = () => { - // init plugin directories if not present - mkdirpSync(plugs.base); - mkdirpSync(plugs.local); - - try { - migrateHyper3Config(); - } catch (err) { - console.error(err); - } - - let defaultCfgRaw = '{}'; - try { - defaultCfgRaw = readFileSync(defaultCfg, 'utf8'); - } catch (err) { - console.log(err); - } - const _defaultCfg = JSON.parse(defaultCfgRaw) as rawConfig; - - // Importing platform specific keymap - let content = '{}'; - try { - content = readFileSync(defaultPlatformKeyPath(), 'utf8'); - } catch (err) { - console.error(err); - } - const mapping = JSON.parse(content) as Record; - _defaultCfg.keymaps = mapping; - - // Import user config - let userCfg: rawConfig; - try { - userCfg = JSON.parse(readFileSync(cfgPath, 'utf8')); - } catch (err) { - notify("Couldn't parse config file. Using default config instead."); - userCfg = JSON.parse(defaultCfgRaw); - } - - return {userCfg, defaultCfg: _defaultCfg}; -}; - -export const _import = () => { - const imported = _importConf(); - defaultConfig = imported.defaultCfg; - const result = _init(imported.userCfg, imported.defaultCfg); - return result; -}; - -export const getDefaultConfig = () => { - if (!defaultConfig) { - defaultConfig = _importConf().defaultCfg; - } - return defaultConfig; -}; diff --git a/app/config/init.ts b/app/config/init.ts deleted file mode 100644 index a41b864c..00000000 --- a/app/config/init.ts +++ /dev/null @@ -1,63 +0,0 @@ -import vm from 'vm'; - -import merge from 'lodash/merge'; - -import type {parsedConfig, rawConfig, configOptions} from '../../typings/config'; -import notify from '../notify'; -import mapKeys from '../utils/map-keys'; - -const _extract = (script?: vm.Script): Record => { - const module: Record = {}; - script?.runInNewContext({module}, {displayErrors: true}); - if (!module.exports) { - throw new Error('Error reading configuration: `module.exports` not set'); - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return module.exports; -}; - -const _syntaxValidation = (cfg: string) => { - try { - return new vm.Script(cfg, {filename: '.hyper.js'}); - } catch (_err) { - const err = _err as {name: string}; - notify(`Error loading config: ${err.name}`, JSON.stringify(err), {error: err}); - } -}; - -const _extractDefault = (cfg: string) => { - return _extract(_syntaxValidation(cfg)); -}; - -// init config -const _init = (userCfg: rawConfig, defaultCfg: rawConfig): parsedConfig => { - return { - config: (() => { - if (userCfg?.config) { - const conf = userCfg.config; - conf.defaultProfile = conf.defaultProfile || 'default'; - conf.profiles = conf.profiles || []; - conf.profiles = conf.profiles.length > 0 ? conf.profiles : [{name: 'default', config: {}}]; - conf.profiles = conf.profiles.map((p, i) => ({ - ...p, - name: p.name || `profile-${i + 1}`, - config: p.config || {} - })); - if (!conf.profiles.map((p) => p.name).includes(conf.defaultProfile)) { - conf.defaultProfile = conf.profiles[0].name; - } - return merge({}, defaultCfg.config, conf); - } else { - notify('Error reading configuration: `config` key is missing'); - return defaultCfg.config || ({} as configOptions); - } - })(), - // Merging platform specific keymaps with user defined keymaps - keymaps: mapKeys({...defaultCfg.keymaps, ...userCfg?.keymaps}), - // Ignore undefined values in plugin and localPlugins array Issue #1862 - plugins: userCfg?.plugins?.filter(Boolean) || [], - localPlugins: userCfg?.localPlugins?.filter(Boolean) || [] - }; -}; - -export {_init, _extractDefault}; diff --git a/app/config/migrate.ts b/app/config/migrate.ts deleted file mode 100644 index 522da1e9..00000000 --- a/app/config/migrate.ts +++ /dev/null @@ -1,190 +0,0 @@ -import {dirname, resolve} from 'path'; - -import {builders, namedTypes} from 'ast-types'; -import type {ExpressionKind} from 'ast-types/lib/gen/kinds'; -import {copy, copySync, existsSync, readFileSync, writeFileSync} from 'fs-extra'; -import merge from 'lodash/merge'; -import {parse, prettyPrint} from 'recast'; -import * as babelParser from 'recast/parsers/babel'; - -import notify from '../notify'; - -import {_extractDefault} from './init'; -import {cfgDir, cfgPath, defaultCfg, legacyCfgPath, plugs, schemaFile, schemaPath} from './paths'; - -// function to remove all json serializable entries from an array expression -function removeElements(node: namedTypes.ArrayExpression): namedTypes.ArrayExpression { - const newElements = node.elements.filter((element) => { - if (namedTypes.ObjectExpression.check(element)) { - const newElement = removeProperties(element); - if (newElement.properties.length === 0) { - return false; - } - } else if (namedTypes.ArrayExpression.check(element)) { - const newElement = removeElements(element); - if (newElement.elements.length === 0) { - return false; - } - } else if (namedTypes.Literal.check(element)) { - return false; - } - return true; - }); - return {...node, elements: newElements}; -} - -// function to remove all json serializable properties from an object expression -function removeProperties(node: namedTypes.ObjectExpression): namedTypes.ObjectExpression { - const newProperties = node.properties.filter((property) => { - if ( - namedTypes.ObjectProperty.check(property) && - (namedTypes.Literal.check(property.key) || namedTypes.Identifier.check(property.key)) && - !property.computed - ) { - if (namedTypes.ObjectExpression.check(property.value)) { - const newValue = removeProperties(property.value); - if (newValue.properties.length === 0) { - return false; - } - } else if (namedTypes.ArrayExpression.check(property.value)) { - const newValue = removeElements(property.value); - if (newValue.elements.length === 0) { - return false; - } - } else if (namedTypes.Literal.check(property.value)) { - return false; - } - } - return true; - }); - return {...node, properties: newProperties}; -} - -export function configToPlugin(code: string): string { - const ast: namedTypes.File = parse(code, { - parser: babelParser - }); - const statements = ast.program.body; - let moduleExportsNode: namedTypes.AssignmentExpression | null = null; - let configNode: ExpressionKind | null = null; - - for (const statement of statements) { - if (namedTypes.ExpressionStatement.check(statement)) { - const expression = statement.expression; - if ( - namedTypes.AssignmentExpression.check(expression) && - expression.operator === '=' && - namedTypes.MemberExpression.check(expression.left) && - namedTypes.Identifier.check(expression.left.object) && - expression.left.object.name === 'module' && - namedTypes.Identifier.check(expression.left.property) && - expression.left.property.name === 'exports' - ) { - moduleExportsNode = expression; - if (namedTypes.ObjectExpression.check(expression.right)) { - const properties = expression.right.properties; - for (const property of properties) { - if ( - namedTypes.ObjectProperty.check(property) && - namedTypes.Identifier.check(property.key) && - property.key.name === 'config' - ) { - configNode = property.value as ExpressionKind; - if (namedTypes.ObjectExpression.check(property.value)) { - configNode = removeProperties(property.value); - } - } - } - } else { - configNode = builders.memberExpression(moduleExportsNode.right, builders.identifier('config')); - } - } - } - } - - if (!moduleExportsNode) { - console.log('No module.exports found in config'); - return ''; - } - if (!configNode) { - console.log('No config field found in module.exports'); - return ''; - } - if (namedTypes.ObjectExpression.check(configNode) && configNode.properties.length === 0) { - return ''; - } - - moduleExportsNode.right = builders.objectExpression([ - builders.property( - 'init', - builders.identifier('decorateConfig'), - builders.arrowFunctionExpression( - [builders.identifier('_config')], - builders.callExpression( - builders.memberExpression(builders.identifier('Object'), builders.identifier('assign')), - [builders.objectExpression([]), builders.identifier('_config'), configNode] - ) - ) - ) - ]); - - return prettyPrint(ast, {tabWidth: 2}).code; -} - -export const _write = (path: string, data: string) => { - // This method will take text formatted as Unix line endings and transform it - // to text formatted with DOS line endings. We do this because the default - // text editor on Windows (notepad) doesn't Deal with LF files. Still. In 2017. - const crlfify = (str: string) => { - return str.replace(/\r?\n/g, '\r\n'); - }; - const format = process.platform === 'win32' ? crlfify(data.toString()) : data; - writeFileSync(path, format, 'utf8'); -}; - -// Migrate Hyper3 config to Hyper4 but only if the user hasn't manually -// touched the new config and if the old config is not a symlink -export const migrateHyper3Config = () => { - copy(schemaPath, resolve(cfgDir, schemaFile), (err) => { - if (err) { - console.error(err); - } - }); - - if (existsSync(cfgPath)) { - return; - } - - if (!existsSync(legacyCfgPath)) { - copySync(defaultCfg, cfgPath); - return; - } - - // Migrate - copySync(resolve(dirname(legacyCfgPath), '.hyper_plugins', 'local'), plugs.local); - - const defaultCfgData = JSON.parse(readFileSync(defaultCfg, 'utf8')); - let newCfgData; - try { - const legacyCfgRaw = readFileSync(legacyCfgPath, 'utf8'); - const legacyCfgData = _extractDefault(legacyCfgRaw); - newCfgData = merge({}, defaultCfgData, legacyCfgData); - - const pluginCode = configToPlugin(legacyCfgRaw); - if (pluginCode) { - const pluginPath = resolve(plugs.local, 'migrated-hyper3-config.js'); - newCfgData.localPlugins = ['migrated-hyper3-config', ...(newCfgData.localPlugins || [])]; - _write(pluginPath, pluginCode); - } - } catch (e) { - console.error(e); - notify( - 'Hyper 4', - `Failed to migrate your config from Hyper 3.\nDefault config will be created instead at ${cfgPath}` - ); - newCfgData = defaultCfgData; - } - _write(cfgPath, JSON.stringify(newCfgData, null, 2)); - - notify('Hyper 4', `Settings location and format has changed to ${cfgPath}`); -}; diff --git a/app/config/open.ts b/app/config/open.ts deleted file mode 100644 index 264c2292..00000000 --- a/app/config/open.ts +++ /dev/null @@ -1,80 +0,0 @@ -import {exec} from 'child_process'; - -import {shell} from 'electron'; - -import * as Registry from 'native-reg'; - -import {cfgPath} from './paths'; - -const getUserChoiceKey = () => { - try { - // Load FileExts keys for .js files - const fileExtsKeys = Registry.openKey( - Registry.HKCU, - 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.js', - Registry.Access.READ - ); - const keys = fileExtsKeys ? Registry.enumKeyNames(fileExtsKeys) : []; - Registry.closeKey(fileExtsKeys); - - // Find UserChoice key - const userChoice = keys.find((k) => k.endsWith('UserChoice')); - return userChoice - ? `Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.js\\${userChoice}` - : userChoice; - } catch (error) { - console.error(error); - return; - } -}; - -const hasDefaultSet = () => { - const userChoice = getUserChoiceKey(); - if (!userChoice) return false; - - try { - // Load key values - const userChoiceKey = Registry.openKey(Registry.HKCU, userChoice, Registry.Access.READ)!; - const values: string[] = Registry.enumValueNames(userChoiceKey).map( - (x) => (Registry.queryValue(userChoiceKey, x) as string) || '' - ); - Registry.closeKey(userChoiceKey); - - // Look for default program - const hasDefaultProgramConfigured = values.every( - (value) => value && typeof value === 'string' && !value.includes('WScript.exe') && !value.includes('JSFile') - ); - - return hasDefaultProgramConfigured; - } catch (error) { - console.error(error); - return false; - } -}; - -// This mimics shell.openItem, true if it worked, false if not. -const openNotepad = (file: string) => - new Promise((resolve) => { - exec(`start notepad.exe ${file}`, (error) => { - resolve(!error); - }); - }); - -const openConfig = () => { - // Windows opens .js files with WScript.exe by default - // If the user hasn't set up an editor for .js files, we fallback to notepad. - if (process.platform === 'win32') { - try { - if (hasDefaultSet()) { - return shell.openPath(cfgPath).then((error) => error === ''); - } - console.warn('No default app set for .js files, using notepad.exe fallback'); - } catch (err) { - console.error('Open config with default app error:', err); - } - return openNotepad(cfgPath); - } - return shell.openPath(cfgPath).then((error) => error === ''); -}; - -export default openConfig; diff --git a/app/config/paths.ts b/app/config/paths.ts deleted file mode 100644 index 2c2ce283..00000000 --- a/app/config/paths.ts +++ /dev/null @@ -1,96 +0,0 @@ -// This module exports paths, names, and other metadata that is referenced -import {statSync} from 'fs'; -import {homedir} from 'os'; -import {resolve, join} from 'path'; - -import {app} from 'electron'; - -import isDev from 'electron-is-dev'; - -const cfgFile = 'hyper.json'; -const defaultCfgFile = 'config-default.json'; -const schemaFile = 'schema.json'; -const homeDirectory = homedir(); - -// If the user defines XDG_CONFIG_HOME they definitely want their config there, -// otherwise use the home directory in linux/mac and userdata in windows -let cfgDir = process.env.XDG_CONFIG_HOME - ? join(process.env.XDG_CONFIG_HOME, 'Hyper') - : process.platform === 'win32' - ? app.getPath('userData') - : join(homeDirectory, '.config', 'Hyper'); - -const legacyCfgPath = join( - process.env.XDG_CONFIG_HOME !== undefined - ? join(process.env.XDG_CONFIG_HOME, 'hyper') - : process.platform == 'win32' - ? app.getPath('userData') - : homedir(), - '.hyper.js' -); - -let cfgPath = join(cfgDir, cfgFile); -const schemaPath = resolve(__dirname, schemaFile); - -const devDir = resolve(__dirname, '../..'); -const devCfg = join(devDir, cfgFile); -const defaultCfg = resolve(__dirname, defaultCfgFile); - -if (isDev) { - // if a local config file exists, use it - try { - statSync(devCfg); - cfgPath = devCfg; - cfgDir = devDir; - console.log('using config file:', cfgPath); - } catch (err) { - // ignore - } -} - -const plugins = resolve(cfgDir, 'plugins'); -const plugs = { - base: plugins, - local: resolve(plugins, 'local'), - cache: resolve(plugins, 'cache') -}; -const yarn = resolve(__dirname, '../../bin/yarn-standalone.js'); -const cliScriptPath = resolve(__dirname, '../../bin/hyper'); -const cliLinkPath = '/usr/local/bin/hyper'; - -const icon = resolve(__dirname, '../static/icon96x96.png'); - -const keymapPath = resolve(__dirname, '../keymaps'); -const darwinKeys = join(keymapPath, 'darwin.json'); -const win32Keys = join(keymapPath, 'win32.json'); -const linuxKeys = join(keymapPath, 'linux.json'); - -const defaultPlatformKeyPath = () => { - switch (process.platform) { - case 'darwin': - return darwinKeys; - case 'win32': - return win32Keys; - case 'linux': - return linuxKeys; - default: - return darwinKeys; - } -}; - -export { - cfgDir, - cfgPath, - legacyCfgPath, - cfgFile, - defaultCfg, - icon, - defaultPlatformKeyPath, - plugs, - yarn, - cliScriptPath, - cliLinkPath, - homeDirectory, - schemaFile, - schemaPath -}; diff --git a/app/config/schema.json b/app/config/schema.json deleted file mode 100644 index 6bcf8500..00000000 --- a/app/config/schema.json +++ /dev/null @@ -1,756 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "definitions": { - "FontWeight": { - "anyOf": [ - { - "enum": [ - "100", - "200", - "300", - "400", - "500", - "600", - "700", - "800", - "900", - "bold", - "normal" - ], - "type": "string" - }, - { - "type": "number" - } - ], - "description": "A string or number representing text font weight." - }, - "Partial": { - "properties": { - "backgroundColor": { - "description": "terminal background color\n\nopacity is only supported on macOS", - "type": "string" - }, - "bell": { - "description": "Supported Options:\n1. 'SOUND' -> Enables the bell as a sound\n2. false: turns off the bell", - "enum": [ - "SOUND", - false - ] - }, - "bellSound": { - "description": "base64 encoded string of the sound file to use for the bell\nif null, the default bell will be used", - "type": [ - "string", - "null" - ] - }, - "bellSoundURL": { - "description": "An absolute file path to a sound file on the machine.", - "type": [ - "string", - "null" - ] - }, - "borderColor": { - "description": "border color (window, tabs)", - "type": "string" - }, - "colors": { - "description": "the full list. if you're going to provide the full color palette,\nincluding the 6 x 6 color cubes and the grayscale map, just provide\nan array here instead of a color map object", - "properties": { - "black": { - "type": "string" - }, - "blue": { - "type": "string" - }, - "cyan": { - "type": "string" - }, - "green": { - "type": "string" - }, - "lightBlack": { - "type": "string" - }, - "lightBlue": { - "type": "string" - }, - "lightCyan": { - "type": "string" - }, - "lightGreen": { - "type": "string" - }, - "lightMagenta": { - "type": "string" - }, - "lightRed": { - "type": "string" - }, - "lightWhite": { - "type": "string" - }, - "lightYellow": { - "type": "string" - }, - "magenta": { - "type": "string" - }, - "red": { - "type": "string" - }, - "white": { - "type": "string" - }, - "yellow": { - "type": "string" - } - }, - "required": [ - "black", - "blue", - "cyan", - "green", - "lightBlack", - "lightBlue", - "lightCyan", - "lightGreen", - "lightMagenta", - "lightRed", - "lightWhite", - "lightYellow", - "magenta", - "red", - "white", - "yellow" - ], - "type": "object" - }, - "copyOnSelect": { - "description": "if `true` selected text will automatically be copied to the clipboard", - "type": "boolean" - }, - "css": { - "description": "custom CSS to embed in the main window", - "type": "string" - }, - "cursorAccentColor": { - "description": "terminal text color under BLOCK cursor", - "type": "string" - }, - "cursorBlink": { - "description": "set to `true` for blinking cursor", - "type": "boolean" - }, - "cursorColor": { - "description": "terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)", - "type": "string" - }, - "cursorShape": { - "description": "`'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █", - "enum": [ - "BEAM", - "BLOCK", - "UNDERLINE" - ], - "type": "string" - }, - "disableLigatures": { - "description": "if `false` Hyper will use ligatures provided by some fonts", - "type": "boolean" - }, - "env": { - "additionalProperties": { - "type": "string" - }, - "description": "for environment variables", - "type": "object" - }, - "fontFamily": { - "description": "font family with optional fallbacks", - "type": "string" - }, - "fontSize": { - "description": "default font size in pixels for all tabs", - "type": "number" - }, - "fontWeight": { - "$ref": "#/definitions/FontWeight", - "description": "default font weight eg:'normal', '400', 'bold'" - }, - "fontWeightBold": { - "$ref": "#/definitions/FontWeight", - "description": "font weight for bold characters eg:'normal', '600', 'bold'" - }, - "foregroundColor": { - "description": "color of the text", - "type": "string" - }, - "imageSupport": { - "description": "Whether to enable Sixel and iTerm2 inline image protocol support or not.", - "type": "boolean" - }, - "letterSpacing": { - "description": "letter spacing as a relative unit", - "type": "number" - }, - "lineHeight": { - "description": "line height as a relative unit", - "type": "number" - }, - "macOptionSelectionMode": { - "description": "choose either `'vertical'`, if you want the column mode when Option key is hold during selection (Default)\nor `'force'`, if you want to force selection regardless of whether the terminal is in mouse events mode\n(inside tmux or vim with mouse mode enabled for example).", - "type": "string" - }, - "modifierKeys": { - "properties": { - "altIsMeta": { - "type": "boolean" - }, - "cmdIsMeta": { - "type": "boolean" - } - }, - "required": [ - "altIsMeta", - "cmdIsMeta" - ], - "type": "object" - }, - "padding": { - "description": "custom padding (CSS format, i.e.: `top right bottom left` or `top horizontal bottom` or `vertical horizontal` or `all`)", - "type": "string" - }, - "preserveCWD": { - "description": "set to true to preserve working directory when creating splits or tabs", - "type": "boolean" - }, - "quickEdit": { - "description": "if `true` on right click selected text will be copied or pasted if no\nselection is present (`true` by default on Windows and disables the context menu feature)", - "type": "boolean" - }, - "screenReaderMode": { - "description": "set to true to enable screen reading apps (like NVDA) to read the contents of the terminal", - "type": "boolean" - }, - "scrollback": { - "type": "number" - }, - "selectionColor": { - "description": "terminal selection color", - "type": "string" - }, - "shell": { - "description": "the shell to run when spawning a new session (e.g. /usr/local/bin/fish)\nif left empty, your system's login shell will be used by default\n\nWindows\n- Make sure to use a full path if the binary name doesn't work\n- Remove `--login` in shellArgs\n\nWindows Subsystem for Linux (WSL) - previously Bash on Windows\n- Example: `C:\\\\Windows\\\\System32\\\\wsl.exe`\n\nGit-bash on Windows\n- Example: `C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe`\n\nPowerShell on Windows\n- Example: `C:\\\\WINDOWS\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`\n\nCygwin\n- Example: `C:\\\\cygwin64\\\\bin\\\\bash.exe`\n\nGit Bash\n- Example: `C:\\\\Program Files\\\\Git\\\\git-cmd.exe`\nThen Add `--command=usr/bin/bash.exe` to shellArgs", - "type": "string" - }, - "shellArgs": { - "description": "for setting shell arguments (e.g. for using interactive shellArgs: `['-i']`)\nby default `['--login']` will be used", - "items": { - "type": "string" - }, - "type": "array" - }, - "showHamburgerMenu": { - "description": "if you're using a Linux setup which show native menus, set to false\n\ndefault: `true` on Linux, `true` on Windows, ignored on macOS", - "enum": [ - "", - false, - true - ] - }, - "showWindowControls": { - "description": "set to `false` if you want to hide the minimize, maximize and close buttons\n\nadditionally, set to `'left'` if you want them on the left, like in Ubuntu\n\ndefault: `true` on Windows and Linux, ignored on macOS", - "enum": [ - "", - false, - "left", - true - ] - }, - "termCSS": { - "description": "custom CSS to embed in the terminal window", - "type": "string" - }, - "uiFontFamily": { - "type": "string" - }, - "webGLRenderer": { - "description": "Whether to use the WebGL renderer. Set it to false to use canvas-based\nrendering (slower, but supports transparent backgrounds)", - "type": "boolean" - }, - "webLinksActivationKey": { - "description": "keypress required for weblink activation: [ctrl | alt | meta | shift]", - "enum": [ - "", - "alt", - "ctrl", - "meta", - "shift" - ], - "type": "string" - }, - "windowSize": { - "description": "Initial window size in pixels", - "items": [ - { - "type": "number" - }, - { - "type": "number" - } - ], - "maxItems": 2, - "minItems": 2, - "type": "array" - }, - "workingDirectory": { - "description": "set custom startup directory (must be an absolute path)", - "type": "string" - } - }, - "type": "object" - }, - "configOptions": { - "allOf": [ - { - "properties": { - "autoUpdatePlugins": { - "description": "if `true` (default), Hyper will update plugins every 5 hours\nyou can also set it to a custom time e.g. `1d` or `2h`", - "type": [ - "string", - "boolean" - ] - }, - "defaultSSHApp": { - "description": "if `true` hyper will be set as the default protocol client for SSH", - "type": "boolean" - }, - "disableAutoUpdates": { - "description": "if `true` hyper will not check for updates", - "type": "boolean" - }, - "updateChannel": { - "description": "choose either `'stable'` for receiving highly polished, or `'canary'` for less polished but more frequent updates", - "enum": [ - "canary", - "stable" - ], - "type": "string" - }, - "useConpty": { - "type": "boolean" - } - }, - "required": [ - "autoUpdatePlugins", - "defaultSSHApp", - "disableAutoUpdates", - "updateChannel" - ], - "type": "object" - }, - { - "properties": { - "backgroundColor": { - "description": "terminal background color\n\nopacity is only supported on macOS", - "type": "string" - }, - "bell": { - "description": "Supported Options:\n1. 'SOUND' -> Enables the bell as a sound\n2. false: turns off the bell", - "enum": [ - "SOUND", - false - ] - }, - "bellSound": { - "description": "base64 encoded string of the sound file to use for the bell\nif null, the default bell will be used", - "type": [ - "string", - "null" - ] - }, - "bellSoundURL": { - "description": "An absolute file path to a sound file on the machine.", - "type": [ - "string", - "null" - ] - }, - "borderColor": { - "description": "border color (window, tabs)", - "type": "string" - }, - "colors": { - "description": "the full list. if you're going to provide the full color palette,\nincluding the 6 x 6 color cubes and the grayscale map, just provide\nan array here instead of a color map object", - "properties": { - "black": { - "type": "string" - }, - "blue": { - "type": "string" - }, - "cyan": { - "type": "string" - }, - "green": { - "type": "string" - }, - "lightBlack": { - "type": "string" - }, - "lightBlue": { - "type": "string" - }, - "lightCyan": { - "type": "string" - }, - "lightGreen": { - "type": "string" - }, - "lightMagenta": { - "type": "string" - }, - "lightRed": { - "type": "string" - }, - "lightWhite": { - "type": "string" - }, - "lightYellow": { - "type": "string" - }, - "magenta": { - "type": "string" - }, - "red": { - "type": "string" - }, - "white": { - "type": "string" - }, - "yellow": { - "type": "string" - } - }, - "required": [ - "black", - "blue", - "cyan", - "green", - "lightBlack", - "lightBlue", - "lightCyan", - "lightGreen", - "lightMagenta", - "lightRed", - "lightWhite", - "lightYellow", - "magenta", - "red", - "white", - "yellow" - ], - "type": "object" - }, - "copyOnSelect": { - "description": "if `true` selected text will automatically be copied to the clipboard", - "type": "boolean" - }, - "css": { - "description": "custom CSS to embed in the main window", - "type": "string" - }, - "cursorAccentColor": { - "description": "terminal text color under BLOCK cursor", - "type": "string" - }, - "cursorBlink": { - "description": "set to `true` for blinking cursor", - "type": "boolean" - }, - "cursorColor": { - "description": "terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)", - "type": "string" - }, - "cursorShape": { - "description": "`'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █", - "enum": [ - "BEAM", - "BLOCK", - "UNDERLINE" - ], - "type": "string" - }, - "disableLigatures": { - "description": "if `false` Hyper will use ligatures provided by some fonts", - "type": "boolean" - }, - "env": { - "additionalProperties": { - "type": "string" - }, - "description": "for environment variables", - "type": "object" - }, - "fontFamily": { - "description": "font family with optional fallbacks", - "type": "string" - }, - "fontSize": { - "description": "default font size in pixels for all tabs", - "type": "number" - }, - "fontWeight": { - "$ref": "#/definitions/FontWeight", - "description": "default font weight eg:'normal', '400', 'bold'" - }, - "fontWeightBold": { - "$ref": "#/definitions/FontWeight", - "description": "font weight for bold characters eg:'normal', '600', 'bold'" - }, - "foregroundColor": { - "description": "color of the text", - "type": "string" - }, - "imageSupport": { - "description": "Whether to enable Sixel and iTerm2 inline image protocol support or not.", - "type": "boolean" - }, - "letterSpacing": { - "description": "letter spacing as a relative unit", - "type": "number" - }, - "lineHeight": { - "description": "line height as a relative unit", - "type": "number" - }, - "macOptionSelectionMode": { - "description": "choose either `'vertical'`, if you want the column mode when Option key is hold during selection (Default)\nor `'force'`, if you want to force selection regardless of whether the terminal is in mouse events mode\n(inside tmux or vim with mouse mode enabled for example).", - "type": "string" - }, - "modifierKeys": { - "properties": { - "altIsMeta": { - "type": "boolean" - }, - "cmdIsMeta": { - "type": "boolean" - } - }, - "required": [ - "altIsMeta", - "cmdIsMeta" - ], - "type": "object" - }, - "padding": { - "description": "custom padding (CSS format, i.e.: `top right bottom left` or `top horizontal bottom` or `vertical horizontal` or `all`)", - "type": "string" - }, - "preserveCWD": { - "description": "set to true to preserve working directory when creating splits or tabs", - "type": "boolean" - }, - "quickEdit": { - "description": "if `true` on right click selected text will be copied or pasted if no\nselection is present (`true` by default on Windows and disables the context menu feature)", - "type": "boolean" - }, - "screenReaderMode": { - "description": "set to true to enable screen reading apps (like NVDA) to read the contents of the terminal", - "type": "boolean" - }, - "scrollback": { - "type": "number" - }, - "selectionColor": { - "description": "terminal selection color", - "type": "string" - }, - "shell": { - "description": "the shell to run when spawning a new session (e.g. /usr/local/bin/fish)\nif left empty, your system's login shell will be used by default\n\nWindows\n- Make sure to use a full path if the binary name doesn't work\n- Remove `--login` in shellArgs\n\nWindows Subsystem for Linux (WSL) - previously Bash on Windows\n- Example: `C:\\\\Windows\\\\System32\\\\wsl.exe`\n\nGit-bash on Windows\n- Example: `C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe`\n\nPowerShell on Windows\n- Example: `C:\\\\WINDOWS\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`\n\nCygwin\n- Example: `C:\\\\cygwin64\\\\bin\\\\bash.exe`\n\nGit Bash\n- Example: `C:\\\\Program Files\\\\Git\\\\git-cmd.exe`\nThen Add `--command=usr/bin/bash.exe` to shellArgs", - "type": "string" - }, - "shellArgs": { - "description": "for setting shell arguments (e.g. for using interactive shellArgs: `['-i']`)\nby default `['--login']` will be used", - "items": { - "type": "string" - }, - "type": "array" - }, - "showHamburgerMenu": { - "description": "if you're using a Linux setup which show native menus, set to false\n\ndefault: `true` on Linux, `true` on Windows, ignored on macOS", - "enum": [ - "", - false, - true - ] - }, - "showWindowControls": { - "description": "set to `false` if you want to hide the minimize, maximize and close buttons\n\nadditionally, set to `'left'` if you want them on the left, like in Ubuntu\n\ndefault: `true` on Windows and Linux, ignored on macOS", - "enum": [ - "", - false, - "left", - true - ] - }, - "termCSS": { - "description": "custom CSS to embed in the terminal window", - "type": "string" - }, - "uiFontFamily": { - "type": "string" - }, - "webGLRenderer": { - "description": "Whether to use the WebGL renderer. Set it to false to use canvas-based\nrendering (slower, but supports transparent backgrounds)", - "type": "boolean" - }, - "webLinksActivationKey": { - "description": "keypress required for weblink activation: [ctrl | alt | meta | shift]", - "enum": [ - "", - "alt", - "ctrl", - "meta", - "shift" - ], - "type": "string" - }, - "windowSize": { - "description": "Initial window size in pixels", - "items": [ - { - "type": "number" - }, - { - "type": "number" - } - ], - "maxItems": 2, - "minItems": 2, - "type": "array" - }, - "workingDirectory": { - "description": "set custom startup directory (must be an absolute path)", - "type": "string" - } - }, - "required": [ - "backgroundColor", - "bell", - "bellSound", - "bellSoundURL", - "borderColor", - "colors", - "copyOnSelect", - "css", - "cursorAccentColor", - "cursorBlink", - "cursorColor", - "cursorShape", - "disableLigatures", - "env", - "fontFamily", - "fontSize", - "fontWeight", - "fontWeightBold", - "foregroundColor", - "imageSupport", - "letterSpacing", - "lineHeight", - "macOptionSelectionMode", - "padding", - "preserveCWD", - "quickEdit", - "screenReaderMode", - "scrollback", - "selectionColor", - "shell", - "shellArgs", - "showHamburgerMenu", - "showWindowControls", - "termCSS", - "webGLRenderer", - "webLinksActivationKey", - "workingDirectory" - ], - "type": "object" - }, - { - "properties": { - "defaultProfile": { - "description": "The default profile name to use when launching a new session", - "type": "string" - }, - "profiles": { - "description": "A list of profiles to use", - "items": { - "properties": { - "config": { - "$ref": "#/definitions/Partial", - "description": "Specify all the options you want to override for each profile.\nOptions set here override the defaults set in the root." - }, - "name": { - "type": "string" - } - }, - "required": [ - "config", - "name" - ], - "type": "object" - }, - "type": "array" - } - }, - "required": [ - "defaultProfile", - "profiles" - ], - "type": "object" - } - ] - } - }, - "properties": { - "config": { - "$ref": "#/definitions/configOptions" - }, - "keymaps": { - "additionalProperties": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "type": "string" - } - ] - }, - "description": "Example\n'window:devtools': 'cmd+alt+o',", - "type": "object" - }, - "localPlugins": { - "description": "in development, you can create a directory under\n`plugins/local/` and include it here\nto load it and avoid it being `npm install`ed", - "items": { - "type": "string" - }, - "type": "array" - }, - "plugins": { - "description": "a list of plugins to fetch and install from npm\nformat: [@org/]project[#version]\nexamples:\n `hyperpower`\n `@company/project`\n `project#1.0.1`", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "type": "object" -} - diff --git a/app/config/windows.ts b/app/config/windows.ts deleted file mode 100644 index 4cd6d500..00000000 --- a/app/config/windows.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type {BrowserWindow} from 'electron'; - -import Config from 'electron-store'; - -export const defaults = { - windowPosition: [50, 50] as [number, number], - windowSize: [540, 380] as [number, number] -}; - -// local storage -const cfg = new Config({defaults}); - -export function get() { - const position = cfg.get('windowPosition', defaults.windowPosition); - const size = cfg.get('windowSize', defaults.windowSize); - return {position, size}; -} -export function recordState(win: BrowserWindow) { - cfg.set('windowPosition', win.getPosition()); - cfg.set('windowSize', win.getSize()); -} diff --git a/app/index.html b/app/index.html index 3d16602e..8c3858e9 100644 --- a/app/index.html +++ b/app/index.html @@ -1,38 +1,26 @@ - Hyper - - - - - + HyperTerm +
- - + diff --git a/app/index.ts b/app/index.ts deleted file mode 100644 index 84a804a4..00000000 --- a/app/index.ts +++ /dev/null @@ -1,243 +0,0 @@ -// eslint-disable-next-line import/order -import {cfgPath} from './config/paths'; - -// Print diagnostic information for a few arguments instead of running Hyper. -if (['--help', '-v', '--version'].includes(process.argv[1])) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - const {version} = require('./package'); - console.log(`Hyper version ${version}`); - console.log('Hyper does not accept any command line arguments. Please modify the config file instead.'); - console.log(`Hyper configuration file located at: ${cfgPath}`); - process.exit(); -} - -// Enable remote module -// eslint-disable-next-line import/order -import {initialize as remoteInitialize} from '@electron/remote/main'; -remoteInitialize(); - -// set up config -// eslint-disable-next-line import/order -import * as config from './config'; -config.setup(); - -// Native -import {resolve} from 'path'; - -// Packages -import {app, BrowserWindow, Menu, screen} from 'electron'; - -import isDev from 'electron-is-dev'; -import {gitDescribe} from 'git-describe'; -import parseUrl from 'parse-url'; - -import * as AppMenu from './menus/menu'; -import * as plugins from './plugins'; -import {newWindow} from './ui/window'; -import {installCLI} from './utils/cli-install'; -import * as windowUtils from './utils/window-utils'; - -const windowSet = new Set([]); - -// expose to plugins -app.config = config; -app.plugins = plugins; -app.getWindows = () => new Set([...windowSet]); // return a clone - -// function to retrieve the last focused window in windowSet; -// added to app object in order to expose it to plugins. -app.getLastFocusedWindow = () => { - if (!windowSet.size) { - return null; - } - return Array.from(windowSet).reduce((lastWindow, win) => { - return win.focusTime > lastWindow.focusTime ? win : lastWindow; - }); -}; - -console.log('Disabling Chromium GPU blacklist'); -app.commandLine.appendSwitch('ignore-gpu-blacklist'); - -if (isDev) { - console.log('running in dev mode'); - - // Override default appVersion which is set from package.json - gitDescribe({customArguments: ['--tags']}, (error: any, gitInfo: {raw: string}) => { - if (!error) { - app.setVersion(gitInfo.raw); - } - }); -} else { - console.log('running in prod mode'); -} - -const url = `file://${resolve(isDev ? __dirname : app.getAppPath(), 'index.html')}`; -console.log('electron will open', url); - -async function installDevExtensions(isDev_: boolean) { - if (!isDev_) { - return []; - } - const {default: installer, REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS} = await import('electron-devtools-installer'); - - const extensions = [REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS]; - const forceDownload = Boolean(process.env.UPGRADE_EXTENSIONS); - - return Promise.all( - extensions.map((extension) => installer(extension, {forceDownload, loadExtensionOptions: {allowFileAccess: true}})) - ); -} - -// eslint-disable-next-line @typescript-eslint/no-misused-promises -app.on('ready', () => - installDevExtensions(isDev) - .then(() => { - function createWindow( - fn?: (win: BrowserWindow) => void, - options: {size?: [number, number]; position?: [number, number]} = {}, - profileName: string = config.getDefaultProfile() - ) { - const cfg = plugins.getDecoratedConfig(profileName); - - const winSet = config.getWin(); - let [startX, startY] = winSet.position; - - const [width, height] = options.size ? options.size : cfg.windowSize || winSet.size; - - const winPos = options.position; - - // Open the new window roughly the height of the header away from the - // previous window. This also ensures in multi monitor setups that the - // new terminal is on the correct screen. - const focusedWindow = BrowserWindow.getFocusedWindow() || app.getLastFocusedWindow(); - // In case of options defaults position and size, we should ignore the focusedWindow. - if (winPos !== undefined) { - [startX, startY] = winPos; - } else if (focusedWindow) { - const points = focusedWindow.getPosition(); - const currentScreen = screen.getDisplayNearestPoint({ - x: points[0], - y: points[1] - }); - - const biggestX = points[0] + 100 + width - currentScreen.bounds.x; - const biggestY = points[1] + 100 + height - currentScreen.bounds.y; - - if (biggestX > currentScreen.size.width) { - startX = 50; - } else { - startX = points[0] + 34; - } - if (biggestY > currentScreen.size.height) { - startY = 50; - } else { - startY = points[1] + 34; - } - } - - if (!windowUtils.positionIsValid([startX, startY])) { - [startX, startY] = config.windowDefaults.windowPosition; - } - - const hwin = newWindow({width, height, x: startX, y: startY}, cfg, fn, profileName); - windowSet.add(hwin); - void hwin.loadURL(url); - - // the window can be closed by the browser process itself - hwin.on('close', () => { - hwin.clean(); - windowSet.delete(hwin); - }); - - return hwin; - } - - // when opening create a new window - createWindow(); - - // expose to plugins - app.createWindow = createWindow; - - // mac only. when the dock icon is clicked - // and we don't have any active windows open, - // we open one - app.on('activate', () => { - if (!windowSet.size) { - createWindow(); - } - }); - - app.on('window-all-closed', () => { - if (process.platform !== 'darwin') { - app.quit(); - } - }); - - const makeMenu = () => { - const menu = plugins.decorateMenu(AppMenu.createMenu(createWindow, plugins.getLoadedPluginVersions)); - - // If we're on Mac make a Dock Menu - if (process.platform === 'darwin') { - const dockMenu = Menu.buildFromTemplate([ - { - label: 'New Window', - click() { - createWindow(); - } - } - ]); - app.dock.setMenu(dockMenu); - } - - Menu.setApplicationMenu(AppMenu.buildMenu(menu)); - }; - - plugins.onApp(app); - makeMenu(); - plugins.subscribe(plugins.onApp.bind(undefined, app)); - config.subscribe(makeMenu); - if (!isDev) { - // check if should be set/removed as default ssh protocol client - if (config.getConfig().defaultSSHApp && !app.isDefaultProtocolClient('ssh')) { - console.log('Setting Hyper as default client for ssh:// protocol'); - app.setAsDefaultProtocolClient('ssh'); - } else if (!config.getConfig().defaultSSHApp && app.isDefaultProtocolClient('ssh')) { - console.log('Removing Hyper from default client for ssh:// protocol'); - app.removeAsDefaultProtocolClient('ssh'); - } - void installCLI(false); - } - }) - .catch((err) => { - console.error('Error while loading devtools extensions', err); - }) -); - -/** - * Get last focused BrowserWindow or create new if none and callback - * @param callback Function to call with the BrowserWindow - */ -function GetWindow(callback: (win: BrowserWindow) => void) { - const lastWindow = app.getLastFocusedWindow(); - if (lastWindow) { - callback(lastWindow); - } else if (!lastWindow && {}.hasOwnProperty.call(app, 'createWindow')) { - app.createWindow(callback); - } else { - // If createWindow doesn't exist yet ('ready' event was not fired), - // sets his callback to an app.windowCallback property. - app.windowCallback = callback; - } -} - -app.on('open-file', (_event, path) => { - GetWindow((win: BrowserWindow) => { - win.rpc.emit('open file', {path}); - }); -}); - -app.on('open-url', (_event, sshUrl) => { - GetWindow((win: BrowserWindow) => { - win.rpc.emit('open ssh', parseUrl(sshUrl)); - }); -}); diff --git a/app/keymaps/darwin.json b/app/keymaps/darwin.json deleted file mode 100644 index 30f0f276..00000000 --- a/app/keymaps/darwin.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "window:devtools": "command+alt+i", - "window:reload": "command+shift+r", - "window:reloadFull": "command+shift+f5", - "window:preferences": "command+,", - "zoom:reset": "command+0", - "zoom:in": [ - "command+plus", - "command+=" - ], - "zoom:out": "command+-", - "window:new": "command+n", - "window:minimize": "command+m", - "window:zoom": "ctrl+alt+command+m", - "window:toggleFullScreen": "command+ctrl+f", - "window:close": "command+shift+w", - "tab:new": "command+t", - "tab:next": [ - "command+shift+]", - "command+shift+right", - "command+alt+right", - "ctrl+tab" - ], - "tab:prev": [ - "command+shift+[", - "command+shift+left", - "command+alt+left", - "ctrl+shift+tab" - ], - "tab:jump:prefix": "command", - "pane:next": "command+]", - "pane:prev": "command+[", - "pane:splitRight": "command+d", - "pane:splitDown": "command+shift+d", - "pane:close": "command+w", - "editor:undo": "command+z", - "editor:redo": "command+y", - "editor:cut": "command+x", - "editor:copy": "command+c", - "editor:paste": "command+v", - "editor:selectAll": "command+a", - "editor:search": "command+f", - "editor:search-close": "esc", - "editor:movePreviousWord": "alt+left", - "editor:moveNextWord": "alt+right", - "editor:moveBeginningLine": "command+left", - "editor:moveEndLine": "command+right", - "editor:deletePreviousWord": "alt+backspace", - "editor:deleteNextWord": "alt+delete", - "editor:deleteBeginningLine": "command+backspace", - "editor:deleteEndLine": "command+delete", - "editor:clearBuffer": "command+k", - "editor:break": "ctrl+c", - "plugins:update": "command+shift+u" -} diff --git a/app/keymaps/linux.json b/app/keymaps/linux.json deleted file mode 100644 index da66d671..00000000 --- a/app/keymaps/linux.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "window:devtools": "ctrl+shift+i", - "window:reload": "ctrl+shift+r", - "window:reloadFull": "ctrl+shift+f5", - "window:preferences": "ctrl+,", - "window:hamburgerMenu": "alt+f", - "zoom:reset": "ctrl+0", - "zoom:in": "ctrl+=", - "zoom:out": "ctrl+-", - "window:new": "ctrl+shift+n", - "window:minimize": "ctrl+shift+m", - "window:zoom": "ctrl+shift+alt+m", - "window:toggleFullScreen": "f11", - "window:close": "ctrl+shift+q", - "tab:new": "ctrl+shift+t", - "tab:next": [ - "ctrl+shift+]", - "ctrl+shift+right", - "ctrl+alt+right", - "ctrl+tab" - ], - "tab:prev": [ - "ctrl+shift+[", - "ctrl+shift+left", - "ctrl+alt+left", - "ctrl+shift+tab" - ], - "tab:jump:prefix": "ctrl", - "pane:next": "ctrl+pageup", - "pane:prev": "ctrl+pagedown", - "pane:splitRight": "ctrl+shift+d", - "pane:splitDown": "ctrl+shift+e", - "pane:close": "ctrl+shift+w", - "editor:undo": "ctrl+shift+z", - "editor:redo": "ctrl+shift+y", - "editor:cut": "ctrl+shift+x", - "editor:copy": "ctrl+shift+c", - "editor:paste": "ctrl+shift+v", - "editor:selectAll": "ctrl+shift+a", - "editor:search": "ctrl+shift+f", - "editor:search-close": "esc", - "editor:movePreviousWord": "ctrl+left", - "editor:moveNextWord": "ctrl+right", - "editor:moveBeginningLine": "home", - "editor:moveEndLine": "end", - "editor:deletePreviousWord": "ctrl+backspace", - "editor:deleteNextWord": "ctrl+del", - "editor:deleteBeginningLine": "ctrl+home", - "editor:deleteEndLine": "ctrl+end", - "editor:clearBuffer": "ctrl+shift+k", - "editor:break": "ctrl+c", - "plugins:update": "ctrl+shift+u" -} diff --git a/app/keymaps/win32.json b/app/keymaps/win32.json deleted file mode 100644 index 8e7b1913..00000000 --- a/app/keymaps/win32.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "window:devtools": "ctrl+shift+i", - "window:reload": "ctrl+shift+r", - "window:reloadFull": "ctrl+shift+f5", - "window:preferences": "ctrl+,", - "window:hamburgerMenu": "alt+f", - "zoom:reset": "ctrl+0", - "zoom:in": "ctrl+=", - "zoom:out": "ctrl+-", - "window:new": "ctrl+shift+n", - "window:minimize": "ctrl+shift+m", - "window:zoom": "ctrl+shift+alt+m", - "window:toggleFullScreen": "f11", - "window:close": [ - "ctrl+shift+q", - "alt+f4" - ], - "tab:new": "ctrl+shift+t", - "tab:next": [ - "ctrl+tab" - ], - "tab:prev": [ - "ctrl+shift+tab" - ], - "tab:jump:prefix": "ctrl", - "pane:next": "ctrl+pageup", - "pane:prev": "ctrl+pagedown", - "pane:splitRight": "ctrl+shift+d", - "pane:splitDown": "ctrl+shift+e", - "pane:close": "ctrl+shift+w", - "editor:undo": "ctrl+shift+z", - "editor:redo": "ctrl+shift+y", - "editor:cut": "ctrl+shift+x", - "editor:copy": "ctrl+shift+c", - "editor:paste": "ctrl+shift+v", - "editor:selectAll": "ctrl+shift+a", - "editor:search": "ctrl+shift+f", - "editor:search-close": "esc", - "editor:movePreviousWord": "", - "editor:moveNextWord": "", - "editor:moveBeginningLine": "Home", - "editor:moveEndLine": "End", - "editor:deletePreviousWord": "ctrl+backspace", - "editor:deleteNextWord": "ctrl+del", - "editor:deleteBeginningLine": "ctrl+home", - "editor:deleteEndLine": "ctrl+end", - "editor:clearBuffer": "ctrl+shift+k", - "editor:break": "ctrl+c", - "plugins:update": "ctrl+shift+u" -} diff --git a/app/lib/actions/config.js b/app/lib/actions/config.js new file mode 100644 index 00000000..0842a153 --- /dev/null +++ b/app/lib/actions/config.js @@ -0,0 +1,15 @@ +import { CONFIG_LOAD, CONFIG_RELOAD } from '../constants/config'; + +export function loadConfig (config) { + return { + type: CONFIG_LOAD, + config + }; +} + +export function reloadConfig (config) { + return { + type: CONFIG_RELOAD, + config + }; +} diff --git a/app/lib/actions/header.js b/app/lib/actions/header.js new file mode 100644 index 00000000..c1c05d90 --- /dev/null +++ b/app/lib/actions/header.js @@ -0,0 +1,26 @@ +import { CLOSE_TAB, CHANGE_TAB } from '../constants/tabs'; +import { userExitSession, setActiveSession } from './sessions'; + +export function closeTab (uid) { + return (dispatch, getState) => { + dispatch({ + type: CLOSE_TAB, + uid, + effect () { + dispatch(userExitSession(uid)); + } + }); + }; +} + +export function changeTab (uid) { + return (dispatch, getState) => { + dispatch({ + type: CHANGE_TAB, + uid, + effect () { + dispatch(setActiveSession(uid)); + } + }); + }; +} diff --git a/app/lib/actions/index.js b/app/lib/actions/index.js new file mode 100644 index 00000000..e44c73cc --- /dev/null +++ b/app/lib/actions/index.js @@ -0,0 +1,7 @@ +import { requestSession } from './sessions'; + +export function init () { + return (dispatch) => { + dispatch(requestSession()); + }; +} diff --git a/app/lib/actions/notifications.js b/app/lib/actions/notifications.js new file mode 100644 index 00000000..dda20a08 --- /dev/null +++ b/app/lib/actions/notifications.js @@ -0,0 +1,8 @@ +import { NOTIFICATION_DISMISS } from '../constants/notifications'; + +export function dismissNotification (id) { + return { + type: NOTIFICATION_DISMISS, + id + }; +} diff --git a/app/lib/actions/sessions.js b/app/lib/actions/sessions.js new file mode 100644 index 00000000..92aa347c --- /dev/null +++ b/app/lib/actions/sessions.js @@ -0,0 +1,192 @@ +import rpc from '../rpc'; +import getURL from '../utils/url-command'; +import { keys } from '../utils/object'; +import { + SESSION_ADD, + SESSION_RESIZE, + SESSION_REQUEST, + SESSION_ADD_DATA, + SESSION_PTY_DATA, + SESSION_PTY_EXIT, + SESSION_USER_EXIT, + SESSION_USER_EXIT_ACTIVE, + SESSION_SET_ACTIVE, + SESSION_CLEAR_ACTIVE, + SESSION_USER_DATA, + SESSION_URL_SET, + SESSION_URL_UNSET, + SESSION_SET_XTERM_TITLE, + SESSION_SET_PROCESS_TITLE +} from '../constants/sessions'; + +export function addSession (uid) { + return (dispatch, getState) => { + const { sessions } = getState(); + + // normally this would be encoded as an effect + // but the `SESSION_ADD` action is pretty expensive + // and we want to get this out as soon as possible + const initial = null == sessions.activeUid; + if (initial) rpc.emit('init'); + + dispatch({ + type: SESSION_ADD, + uid + }); + }; +} + +export function requestSession (uid) { + return (dispatch, getState) => { + const { ui } = getState(); + const cols = ui.cols; + const rows = ui.rows; + dispatch({ + type: SESSION_REQUEST, + effect: () => { + rpc.emit('new', { cols, rows }); + } + }); + }; +} + +export function addSessionData (uid, data) { + return (dispatch, getState) => { + dispatch({ + type: SESSION_ADD_DATA, + data, + effect () { + const url = getURL(data); + if (null != url) { + dispatch({ + type: SESSION_URL_SET, + uid, + url + }); + } else { + dispatch({ + type: SESSION_PTY_DATA, + uid, + data + }); + } + } + }); + }; +} + +export function sessionExit (uid) { + return (dispatch, getState) => { + return dispatch({ + type: SESSION_PTY_EXIT, + uid, + effect () { + // we reiterate the same logic as below + // for SESSION_USER_EXIT since the exit + // could happen pty side or optimistic + const sessions = keys(getState().sessions.sessions); + if (!sessions.length) { + window.close(); + } + } + }); + }; +} + +// we want to distinguish an exit +// that's UI initiated vs pty initiated +export function userExitSession (uid) { + return (dispatch, getState) => { + return dispatch({ + type: SESSION_USER_EXIT, + uid, + effect () { + rpc.emit('exit', { uid }); + const sessions = keys(getState().sessions.sessions); + if (!sessions.length) { + window.close(); + } + } + }); + }; +} + +export function userExitActiveSession () { + return (dispatch, getState) => { + dispatch({ + type: SESSION_USER_EXIT_ACTIVE, + effect () { + const uid = getState().sessions.activeUid; + dispatch(userExitSession(uid)); + } + }); + }; +} + +export function setActiveSession (uid) { + return (dispatch, getState) => { + const state = getState(); + const prevUid = state.sessions.activeUid; + dispatch({ + type: SESSION_SET_ACTIVE, + uid, + effect () { + // TODO: this goes away when we are able to poll + // for the title ourseleves, instead of relying + // on Session and focus/blur to subscribe + if (prevUid) rpc.emit('blur', { uid: prevUid }); + rpc.emit('focus', { uid }); + } + }); + }; +} + +export function clearActiveSession () { + return { + type: SESSION_CLEAR_ACTIVE + }; +} + +export function setSessionProcessTitle (uid, title) { + return { + type: SESSION_SET_PROCESS_TITLE, + uid, + title + }; +} + +export function setSessionXtermTitle (uid, title) { + return { + type: SESSION_SET_XTERM_TITLE, + uid, + title + }; +} + +export function resizeSession (uid, cols, rows) { + return { + type: SESSION_RESIZE, + cols, + rows, + effect () { + rpc.emit('resize', { cols, rows }); + } + }; +} + +export function sendSessionData (uid, data) { + return { + type: SESSION_USER_DATA, + data, + effect () { + rpc.emit('data', { uid, data }); + } + }; +} + +export function exitSessionBrowser (uid) { + return { + type: SESSION_URL_UNSET, + uid + }; +} diff --git a/app/lib/actions/ui.js b/app/lib/actions/ui.js new file mode 100644 index 00000000..68e55375 --- /dev/null +++ b/app/lib/actions/ui.js @@ -0,0 +1,143 @@ +import { setActiveSession } from './sessions'; +import { keys } from '../utils/object'; +import { last } from '../utils/array'; +import rpc from '../rpc'; +import { + requestSession, + sendSessionData +} from '../actions/sessions'; +import { + UI_FONT_SIZE_SET, + UI_FONT_SIZE_INCR, + UI_FONT_SIZE_DECR, + UI_FONT_SIZE_RESET, + UI_MOVE_LEFT, + UI_MOVE_RIGHT, + UI_MOVE_TO, + UI_SHOW_PREFERENCES +} from '../constants/ui'; + +export function increaseFontSize () { + return (dispatch, getState) => { + dispatch({ + type: UI_FONT_SIZE_INCR, + effect () { + const state = getState(); + const old = state.ui.fontSizeOverride || state.ui.fontSize; + const value = old + 1; + dispatch({ + type: UI_FONT_SIZE_SET, + value + }); + } + }); + }; +} + +export function decreaseFontSize () { + return (dispatch, getState) => { + dispatch({ + type: UI_FONT_SIZE_DECR, + effect () { + const state = getState(); + const old = state.ui.fontSizeOverride || state.ui.fontSize; + const value = old - 1; + dispatch({ + type: UI_FONT_SIZE_SET, + value + }); + } + }); + }; +} + +export function resetFontSize () { + return { + type: UI_FONT_SIZE_RESET + }; +} + +export function moveLeft () { + return (dispatch, getState) => { + dispatch({ + type: UI_MOVE_LEFT, + effect () { + const { sessions } = getState(); + const uid = sessions.activeUid; + const sessionUids = keys(sessions.sessions); + const index = sessionUids.indexOf(uid); + const next = sessionUids[index - 1] || last(sessionUids); + if (!next || uid === next) { + console.log('ignoring left move action'); + } else { + dispatch(setActiveSession(next)); + } + } + }); + }; +} + +export function moveRight () { + return (dispatch, getState) => { + dispatch({ + type: UI_MOVE_RIGHT, + effect () { + const { sessions } = getState(); + const uid = sessions.activeUid; + const sessionUids = keys(sessions.sessions); + const index = sessionUids.indexOf(uid); + const next = sessionUids[index + 1] || sessionUids[0]; + if (!next || uid === next) { + console.log('ignoring right move action'); + } else { + dispatch(setActiveSession(next)); + } + } + }); + }; +} + +export function moveTo (i) { + return (dispatch, getState) => { + dispatch({ + type: UI_MOVE_TO, + index: i, + effect () { + const { sessions } = getState(); + const uid = sessions.activeUid; + const sessionUids = keys(sessions.sessions); + if (uid === sessionUids[i]) { + console.log('ignoring same uid'); + } else if (null != sessionUids[i]) { + dispatch(setActiveSession(sessionUids[i])); + } else { + console.log('ignoring inexistent index', i); + } + } + }); + }; +} + +export function showPreferences () { + return (dispatch, getState) => { + dispatch({ + type: UI_SHOW_PREFERENCES, + effect () { + dispatch(requestSession()); + // TODO: replace this hack with an async action + rpc.once('session add', ({ uid }) => { + rpc.once('session data', () => { + dispatch(sendSessionData( + uid, + ['# Attempting to open ~/.hyperterm.js with your $EDITOR', + '# If this doesn\'t work, open it manually with your favorite editor!', + '$EDITOR ~/.hyperterm.js && exit', + '' + ].join('\n') + )); + }); + }); + } + }); + }; +} diff --git a/app/lib/actions/updater.js b/app/lib/actions/updater.js new file mode 100644 index 00000000..306a12f6 --- /dev/null +++ b/app/lib/actions/updater.js @@ -0,0 +1,22 @@ +import { + UPDATE_INSTALL, + UPDATE_AVAILABLE +} from '../constants/updater'; +import rpc from '../rpc'; + +export function installUpdate () { + return { + type: UPDATE_INSTALL, + effect: () => { + rpc.emit('quit and install'); + } + }; +} + +export function updateAvailable (version, notes) { + return { + type: UPDATE_AVAILABLE, + version, + notes + }; +} diff --git a/app/lib/component.js b/app/lib/component.js new file mode 100644 index 00000000..bd127000 --- /dev/null +++ b/app/lib/component.js @@ -0,0 +1,70 @@ +import React from 'react'; +import { StyleSheet, css } from 'aphrodite'; +import { shouldComponentUpdate } from 'react-addons-pure-render-mixin'; + +export default class Component extends React.Component { + + constructor () { + super(); + this.styles_ = this.createStyleSheet(); + this.cssHelper = this.cssHelper.bind(this); + if (!this.shouldComponentUpdate) { + this.shouldComponentUpdate = shouldComponentUpdate.bind(this); + } + } + + createStyleSheet () { + if (!this.styles) { + return {}; + } + + const styles = this.styles(); + + if ('object' !== typeof styles) { + throw new TypeError('Component `styles` returns a non-object'); + } + + return StyleSheet.create(this.styles()); + } + + // wrap aphrodite's css helper for two reasons: + // - we can give the element an unaltered global classname + // that can be used to introduce global css side effects + // for example, through the configuration, web inspector + // or user agente extensions + // - the user doesn't need to keep track of both `css` + // and `style`, and we make that whole ordear easier + cssHelper (...args) { + const classes = args + .map((c) => { + if (c) { + // we compute the global name from the given + // css class and we prepend the component name + // it's important classes never get mangled by + // uglifiers so that we can avoid collisions + const component = this.constructor.name + .toString() + .toLowerCase(); + const globalName = `${component}_${c}`; + return [globalName, css(this.styles_[c])]; + } + }) + // skip nulls + .filter((v) => !!v) + // flatten + .reduce((a, b) => a.concat(b)); + return classes.length ? classes.join(' ') : null; + } + + render () { + // convert static objects from `babel-plugin-transform-jsx` + // to `React.Element`. + if (!this.template) { + throw new TypeError("Component doesn't define `template`"); + } + + // invoke the template creator passing our css helper + return this.template(this.cssHelper); + } + +} diff --git a/app/lib/components/header.js b/app/lib/components/header.js new file mode 100644 index 00000000..c9e62d8e --- /dev/null +++ b/app/lib/components/header.js @@ -0,0 +1,92 @@ +import React from 'react'; +import Tabs_ from './tabs'; +import overrideStyles from '../utils/override-style'; +import Component from '../component'; +import { decorate, getTabsProps } from '../utils/plugins'; + +const Tabs = decorate(Tabs_, 'Tabs'); + +export default class Header extends Component { + + constructor () { + super(); + this.onChangeIntent = this.onChangeIntent.bind(this); + this.onHeaderMouseDown = this.onHeaderMouseDown.bind(this); + } + + onChangeIntent (active) { + // we ignore clicks if they're a byproduct of a drag + // motion to move the window + if (window.screenX !== this.headerMouseDownWindowX || + window.screenY !== this.headerMouseDownWindowY) { + return; + } + + this.props.onChangeTab(active); + } + + onHeaderMouseDown () { + this.headerMouseDownWindowX = window.screenX; + this.headerMouseDownWindowY = window.screenY; + + this.clicks = this.clicks || 1; + + if (this.clicks++ >= 2) { + if (this.maximized) { + this.rpc.emit('unmaximize'); + } else { + this.rpc.emit('maximize'); + } + this.clicks = 0; + this.maximized = !this.maximized; + } else { + // http://www.quirksmode.org/dom/events/click.html + // https://en.wikipedia.org/wiki/Double-click + this.clickTimer = setTimeout(() => { + this.clicks = 0; + }, 500); + } + } + + componentWillUnmount () { + delete this.clicks; + clearTimeout(this.clickTimer); + } + + template (css) { + const { isMac, backgroundColor } = this.props; + const props = getTabsProps(this.props, { + tabs: this.props.tabs, + borderColor: this.props.borderColor, + onClose: this.props.onCloseTab, + onChange: this.onChangeIntent + }); + return
+ { this.props.customChildrenBefore } + + { this.props.customChildren } +
; + } + + styles () { + return { + header: { + position: 'fixed', + top: '1px', + left: '1px', + right: '1px', + background: '#000', + zIndex: '100' + }, + + headerRounded: { + borderTopLeftRadius: '6px', + borderTopRightRadius: '6px' + } + }; + } + +} diff --git a/app/lib/components/notification.js b/app/lib/components/notification.js new file mode 100644 index 00000000..58da887d --- /dev/null +++ b/app/lib/components/notification.js @@ -0,0 +1,116 @@ +import React from 'react'; +import Component from '../component'; + +export default class Notification extends Component { + + constructor () { + super(); + this.state = { + dismissing: false + }; + this.dismiss = this.dismiss.bind(this); + this.onElement = this.onElement.bind(this); + } + + componentDidMount () { + if (this.props.dismissAfter) { + this.setDismissTimer(); + } + } + + componentWillReceiveProps (next) { + // if we have a timer going and the notification text + // changed we rest the timer + if (next.text !== this.props.text) { + if (this.props.dismissAfter) { + this.resetDismissTimer(); + } + if (this.state.dismissing) { + this.setState({ dismissing: false }); + } + } + } + + dismiss () { + this.setState({ dismissing: true }); + } + + onElement (el) { + if (el) { + el.addEventListener('webkitTransitionEnd', () => { + if (this.state.dismissing) { + this.props.onDismiss(); + } + }); + // aprhodie !important override :( + const { backgroundColor } = this.props; + if (backgroundColor) { + el.style.setProperty( + 'background-color', + backgroundColor, + 'important' + ); + } + } + } + + setDismissTimer (after) { + this.dismissTimer = setTimeout(() => { + this.dismiss(); + }, this.props.dismissAfter); + } + + resetDismissTimer (after) { + clearTimeout(this.dismissTimer); + this.setDismissTimer(); + } + + componentWillUnmount () { + clearTimeout(this.dismissTimer); + } + + template (css) { + const { backgroundColor } = this.props; + const opacity = this.state.dismissing ? 0 : 1; + return
+ { this.props.customChildrenBefore } + { this.props.children || this.props.text } + { + this.props.userDismissable + ? [x] + : null + } + { this.props.customChildren } +
; + } + + styles () { + return { + indicator: { + display: 'inline-block', + cursor: 'default', + WebkitUserSelect: 'none', + background: 'rgba(255, 255, 255, .2)', + padding: '6px 14px', + marginLeft: '10px', + transition: '150ms opacity ease', + color: '#fff', + font: '11px Menlo' + }, + + dismissLink: { + cursor: 'pointer', + color: '#528D11', + ':hover': { + color: '#2A5100' + } + } + }; + } + +} diff --git a/app/lib/components/notifications.js b/app/lib/components/notifications.js new file mode 100644 index 00000000..988d1b82 --- /dev/null +++ b/app/lib/components/notifications.js @@ -0,0 +1,70 @@ +import React from 'react'; +import Component from '../component'; +import Notification_ from './notification'; +import { decorate } from '../utils/plugins'; + +const Notification = decorate(Notification_); + +export default class Notifications extends Component { + + template (css) { + return
+ { this.props.customChildrenBefore } + { + this.props.fontShowing && + + } + + { + this.props.resizeShowing && + + } + + { + this.props.updateShowing && + + Version { this.props.updateVersion} available. + { this.props.updateNote && ` ${this.props.updateNote.trim().replace(/\.$/, '')}.` } + { ' ' } + + Restart + + { ' ' } + + } + { this.props.customChildren } +
; + } + + styles () { + return { + view: { + position: 'fixed', + bottom: '20px', + right: '20px' + } + }; + } + +} diff --git a/app/lib/components/tab.js b/app/lib/components/tab.js new file mode 100644 index 00000000..b2344d76 --- /dev/null +++ b/app/lib/components/tab.js @@ -0,0 +1,175 @@ +import React from 'react'; +import Component from '../component'; +import overrideStyle from '../utils/override-style'; + +export default class Tab extends Component { + constructor () { + super(); + this.hover = this.hover.bind(this); + this.blur = this.blur.bind(this); + this.state = { + hovered: false + }; + } + + hover () { + this.setState({ hovered: true }); + } + + blur () { + this.setState({ hovered: false }); + } + + template (css) { + const { isActive, isFirst, isLast, borderColor, hasActivity } = this.props; + const { hovered } = this.state; + + return
  • + { this.props.customChildrenBefore } + + + { this.props.text } + + + + + + + + { this.props.customChildren } +
  • ; + } + + styles () { + return { + tab: { + color: '#ccc', + listStyleType: 'none', + flexGrow: 1, + position: 'relative', + ':hover': { + color: '#ccc' + } + }, + + first: { + marginLeft: '76px' + }, + + active: { + color: '#fff', + ':before': { + position: 'absolute', + content: '" "', + borderBottom: '1px solid #000', + display: 'block', + left: '0px', + right: '0px', + bottom: '-1px' + }, + ':hover': { + color: '#fff' + } + }, + + hasActivity: { + color: '#50E3C2', + ':hover': { + color: '#50E3C2' + } + }, + + text: { + transition: 'color .2s ease', + height: '34px', + display: 'block', + width: '100%', + position: 'relative', + borderLeft: '1px solid transparent', + borderRight: '1px solid transparent', + overflow: 'hidden' + }, + + textInner: { + position: 'absolute', + left: 0, + right: 0, + top: 0, + bottom: 0, + textAlign: 'center' + }, + + textLast: { + borderRightWidth: 0 + }, + + textActive: { + borderColor: 'inherit' + }, + + icon: { + transition: `opacity .2s ease, color .2s ease, + transform .25s ease, background-color .1s ease`, + pointerEvents: 'none', + position: 'absolute', + right: '7px', + top: '10px', + display: 'inline-block', + width: '14px', + height: '14px', + borderRadius: '100%', + color: '#e9e9e9', + opacity: 0, + transform: 'scale(.95)', + + ':hover': { + backgroundColor: 'rgba(255,255,255, .13)', + color: '#fff' + }, + + ':active': { + backgroundColor: 'rgba(255,255,255, .1)', + color: '#909090' + } + }, + + iconHovered: { + opacity: 1, + transform: 'none', + pointerEvents: 'all' + }, + + shape: { + position: 'absolute', + left: '4px', + top: '4px', + width: '6px', + height: '6px', + verticalAlign: 'middle', + fill: 'currentColor' + } + }; + } + +} diff --git a/app/lib/components/tabs.js b/app/lib/components/tabs.js new file mode 100644 index 00000000..1a5c7b79 --- /dev/null +++ b/app/lib/components/tabs.js @@ -0,0 +1,81 @@ +import Tab_ from './tab'; +import React from 'react'; +import Component from '../component'; +import overrideStyle from '../utils/override-style'; +import { decorate, getTabProps } from '../utils/plugins'; + +const Tab = decorate(Tab_, 'Tab'); + +export default class Tabs extends Component { + + template (css) { + const { + tabs = [], + borderColor, + onChange, + onClose + } = this.props; + + return ; + } + + styles () { + return { + nav: { + fontSize: '12px', + fontFamily: `-apple-system, BlinkMacSystemFont, + "Segoe UI", "Roboto", "Oxygen", + "Ubuntu", "Cantarell", "Fira Sans", + "Droid Sans", "Helvetica Neue", sans-serif`, + height: '34px', + lineHeight: '34px', + verticalAlign: 'middle', + color: '#9B9B9B', + cursor: 'default', + WebkitUserSelect: 'none', + WebkitAppRegion: 'drag' + }, + + title: { + textAlign: 'center', + color: '#fff' + }, + + list: { + borderBottom: '1px solid #333', + maxHeight: '34px', + display: 'flex', + flexFlow: 'row' + } + }; + } + +} diff --git a/app/lib/components/term.js b/app/lib/components/term.js new file mode 100644 index 00000000..32af8f5b --- /dev/null +++ b/app/lib/components/term.js @@ -0,0 +1,206 @@ +/* global Blob,URL */ +import React from 'react'; +import hterm from '../hterm'; +import Component from '../component'; + +export default class Term extends Component { + + constructor (props) { + super(props); + this.state = { scrollable: false }; + this.onWheel = this.onWheel.bind(this); + this.onScrollEnter = this.onScrollEnter.bind(this); + this.onScrollLeave = this.onScrollLeave.bind(this); + props.ref_(this); + } + + componentDidMount () { + const { props } = this; + this.term = new hterm.Terminal(); + + // the first term that's created has unknown size + // subsequent new tabs have size + if (props.cols && props.rows) { + this.term.realizeSize_(props.cols, props.rows); + } + + this.term.prefs_.set('font-family', props.fontFamily); + this.term.prefs_.set('font-size', props.fontSize); + this.term.prefs_.set('cursor-color', props.cursorColor); + this.term.prefs_.set('enable-clipboard-notice', false); + this.term.prefs_.set('foreground-color', props.foregroundColor); + this.term.prefs_.set('background-color', props.backgroundColor); + this.term.prefs_.set('color-palette-overrides', props.colors); + this.term.prefs_.set('user-css', this.getStylesheet(props.customCSS)); + this.term.prefs_.set('scrollbar-visible', false); + + this.term.onTerminalReady = () => { + const io = this.term.io.push(); + io.onVTKeystroke = io.sendString = props.onData; + io.onTerminalResize = (cols, rows) => { + if (cols !== this.props.cols && rows !== this.props.rows) { + props.onResize(cols, rows); + } + }; + }; + this.term.decorate(this.refs.term); + this.term.installKeyboard(); + if (this.props.onTerminal) this.props.onTerminal(this.term); + + const iframeWindow = this.getTermDocument().defaultView; + iframeWindow.addEventListener('wheel', this.onWheel); + } + + onWheel () { + this.term.prefs_.set('scrollbar-visible', true); + clearTimeout(this.scrollbarsHideTimer); + if (!this.scrollMouseEnter) { + this.scrollbarsHideTimer = setTimeout(() => { + this.term.prefs_.set('scrollbar-visible', false); + }, 1000); + } + } + + onScrollEnter () { + clearTimeout(this.scrollbarsHideTimer); + this.term.prefs_.set('scrollbar-visible', true); + this.scrollMouseEnter = true; + } + + onScrollLeave () { + this.term.prefs_.set('scrollbar-visible', false); + this.scrollMouseEnter = false; + } + + write (data) { + this.term.io.print(data); + } + + focus () { + this.term.focus(); + } + + clear () { + this.term.clearPreserveCursorRow(); + } + + getTermDocument () { + return this.term.document_; + } + + getStylesheet (css) { + const blob = new Blob([` + .cursor-node[focus="false"] { + border-width: 1px !important; + } + ${css} + `]); + return URL.createObjectURL(blob, { type: 'text/css' }); + } + + componentWillReceiveProps (nextProps) { + if (this.props.url !== nextProps.url) { + // when the url prop changes, we make sure + // the terminal starts or stops ignoring + // key input so that it doesn't conflict + // with the + if (nextProps.url) { + const io = this.term.io.push(); + io.onVTKeystroke = io.sendString = (str) => { + if (1 === str.length && 3 === str.charCodeAt(0) /* Ctrl + C */) { + this.props.onURLAbort(); + } + }; + } else { + this.term.io.pop(); + } + } + + if (!this.props.cleared && nextProps.cleared) { + this.clear(); + } + + if (this.props.fontSize !== nextProps.fontSize) { + this.term.prefs_.set('font-size', nextProps.fontSize); + } + + if (this.props.foregroundColor !== nextProps.foregroundColor) { + this.term.prefs_.set('foreground-color', nextProps.foregroundColor); + } + + if (this.props.backgroundColor !== nextProps.backgroundColor) { + this.term.prefs_.set('background-color', nextProps.backgroundColor); + } + + if (this.props.fontFamily !== nextProps.fontFamily) { + this.term.prefs_.set('font-family', nextProps.fontFamily); + } + + if (this.props.cursorColor !== nextProps.cursorColor) { + this.term.prefs_.set('cursor-color', nextProps.cursorColor); + } + + if (this.props.colors !== nextProps.colors) { + this.term.prefs_.set('color-palette-overrides', nextProps.colors); + } + + if (this.props.customCSS !== nextProps.customCSS) { + this.term.prefs_.set('user-css', this.getStylesheet(nextProps.customCSS)); + } + } + + componentWillUnmount () { + const iframeWindow = this.getTermDocument().defaultView; + iframeWindow.addEventListener('wheel', this.onWheel); + clearTimeout(this.scrollbarsHideTimer); + this.props.ref_(null); + } + + template (css) { + return
    + { this.props.customChildrenBefore } +
    + { this.props.url + ? + : null + } +
    + { this.props.customChildren } +
    ; + } + + styles () { + return { + fit: { + width: '100%', + height: '100%' + }, + + term: { + position: 'relative' + }, + + scrollbarShim: { + position: 'fixed', + right: 0, + width: '50px', + top: 0, + bottom: 0 + } + }; + } + +} diff --git a/app/lib/components/terms.js b/app/lib/components/terms.js new file mode 100644 index 00000000..a971c7e2 --- /dev/null +++ b/app/lib/components/terms.js @@ -0,0 +1,182 @@ +import React from 'react'; +import Term_ from './term'; +import Component from '../component'; +import { shouldComponentUpdate } from 'react-addons-pure-render-mixin'; +import { last } from '../utils/array'; +import { decorate, getTermProps } from '../utils/plugins'; + +const Term = decorate(Term_, 'Term'); + +export default class Terms extends Component { + + constructor (props, context) { + super(props, context); + this.terms = {}; + this.bound = new WeakMap(); + this.onRef = this.onRef.bind(this); + props.ref_(this); + } + + componentWillReceiveProps (next) { + const { write } = next; + if (write && this.props.write !== write) { + this.getTermByUid(write.uid).write(write.data); + } + + // if we just rendered, we consider the first tab active + // why is this decided here? because what session becomes + // active is a *view* and *layout* concern. for example, + // if a split is closed (and we had split), the next active + // session after the close would be the one next to it + // *in the view*, not necessarily the model datastructure + if (next.sessions && next.sessions.length) { + if (!this.props.activeSession && next.sessions.length) { + this.props.onActive(next.sessions[0].uid); + } else if (this.props.sessions.length !== next.sessions.length) { + if (next.sessions.length > this.props.sessions.length) { + // if we are adding, we focused on the new one + this.props.onActive(last(next.sessions).uid); + return; + } + + const newUids = uids(next.sessions); + const curActive = this.props.activeSession; + + // if we closed an item that wasn't focused, nothing changes + if (~newUids.indexOf(curActive)) { + return; + } + + const oldIndex = uids(this.props.sessions).indexOf(curActive); + if (newUids[oldIndex]) { + this.props.onActive(newUids[oldIndex]); + } else { + this.props.onActive(last(next.sessions).uid); + } + } + } else { + this.props.onActive(null); + } + } + + shouldComponentUpdate (nextProps, nextState) { + let nextProps_ = nextProps; + if (this.props.write || nextProps.write) { + // ignore `write` when performing the comparison + nextProps_ = Object.assign({}, nextProps, { write: null }); + } + return shouldComponentUpdate.call(this, nextProps_); + } + + onRef (uid, term) { + if (term) { + this.terms[uid] = term; + } else { + delete this.terms[uid]; + } + } + + getTermByUid (uid) { + return this.terms[uid]; + } + + getActiveTerm () { + return this.getTermByUid(this.props.activeSession); + } + + bind (fn, thisObj, uid) { + if (!this.bound.has(fn)) { + this.bound.set(fn, {}); + } + const map = this.bound.get(fn); + if (!map[uid]) { + map[uid] = fn.bind(thisObj, uid); + } + return map[uid]; + } + + getTermProps (uid) { + return getTermProps(uid, this.props); + } + + onTerminal (uid, term) { + this.terms[uid] = term; + } + + componentWillUnmount () { + this.props.ref_(null); + } + + template (css) { + return
    + { this.props.customChildrenBefore } + { + this.props.sessions.map((session) => { + const uid = session.uid; + const isActive = uid === this.props.activeSession; + const props = getTermProps(uid, this.props, { + cols: this.props.cols, + rows: this.props.rows, + customCSS: this.props.customCSS, + fontSize: this.props.fontSize, + cursorColor: this.props.cursorColor, + fontFamily: this.props.fontFamily, + foregroundColor: this.props.foregroundColor, + backgroundColor: this.props.backgroundColor, + colors: this.props.colors, + url: session.url, + cleared: session.cleared, + onResize: this.bind(this.props.onResize, null, uid), + onTitle: this.bind(this.props.onTitle, null, uid), + onData: this.bind(this.props.onData, null, uid), + onURLAbort: this.bind(this.props.onURLAbort, null, uid) + }); + return
    + +
    ; + }) + } + { this.props.customChildren } +
    ; + } + + styles () { + return { + terms: { + position: 'absolute', + marginTop: '34px', + top: 0, + right: 0, + left: 0, + bottom: 0, + color: '#fff' + }, + + term: { + display: 'none', + width: '100%', + height: '100%' + }, + + termActive: { + display: 'block' + } + }; + } + +} + +// little memoized helper to compute a map of uids +function uids (sessions) { + if (!sessions._uids) { + sessions._uids = sessions.map((s) => s.uid); + } + return sessions._uids; +} diff --git a/app/lib/constants/config.js b/app/lib/constants/config.js new file mode 100644 index 00000000..5221aa4e --- /dev/null +++ b/app/lib/constants/config.js @@ -0,0 +1,2 @@ +export const CONFIG_LOAD = 'CONFIG_LOAD'; +export const CONFIG_RELOAD = 'CONFIG_RELOAD'; diff --git a/app/lib/constants/index.js b/app/lib/constants/index.js new file mode 100644 index 00000000..d67c7a89 --- /dev/null +++ b/app/lib/constants/index.js @@ -0,0 +1 @@ +export const INIT = 'INIT'; diff --git a/app/lib/constants/notifications.js b/app/lib/constants/notifications.js new file mode 100644 index 00000000..c37e6904 --- /dev/null +++ b/app/lib/constants/notifications.js @@ -0,0 +1 @@ +export const NOTIFICATION_DISMISS = 'NOTIFICATION_DISMISS'; diff --git a/app/lib/constants/sessions.js b/app/lib/constants/sessions.js new file mode 100644 index 00000000..cd610287 --- /dev/null +++ b/app/lib/constants/sessions.js @@ -0,0 +1,15 @@ +export const SESSION_ADD = 'SESSION_ADD'; +export const SESSION_RESIZE = 'SESSION_RESIZE'; +export const SESSION_REQUEST = 'SESSION_REQUEST'; +export const SESSION_ADD_DATA = 'SESSION_ADD_DATA'; +export const SESSION_PTY_DATA = 'SESSION_PTY_DATA'; +export const SESSION_PTY_EXIT = 'SESSION_PTY_EXIT'; +export const SESSION_USER_EXIT = 'SESSION_USER_EXIT'; +export const SESSION_USER_EXIT_ACTIVE = 'SESSION_USER_EXIT_ACTIVE'; +export const SESSION_SET_ACTIVE = 'SESSION_SET_ACTIVE'; +export const SESSION_CLEAR_ACTIVE = 'SESSION_CLEAR_ACTIVE'; +export const SESSION_USER_DATA = 'SESSION_USER_DATA'; +export const SESSION_URL_SET = 'SESSION_URL_SET'; +export const SESSION_URL_UNSET = 'SESSION_URL_UNSET'; +export const SESSION_SET_XTERM_TITLE = 'SESSION_SET_XTERM_TITLE'; +export const SESSION_SET_PROCESS_TITLE = 'SESSION_SET_PROCESS_TITLE'; diff --git a/app/lib/constants/tabs.js b/app/lib/constants/tabs.js new file mode 100644 index 00000000..c31375ba --- /dev/null +++ b/app/lib/constants/tabs.js @@ -0,0 +1,2 @@ +export const CLOSE_TAB = 'CLOSE_TAB'; +export const CHANGE_TAB = 'CHANGE_TAB'; diff --git a/app/lib/constants/ui.js b/app/lib/constants/ui.js new file mode 100644 index 00000000..2f902513 --- /dev/null +++ b/app/lib/constants/ui.js @@ -0,0 +1,8 @@ +export const UI_FONT_SIZE_SET = 'UI_FONT_SIZE_SET'; +export const UI_FONT_SIZE_INCR = 'UI_FONT_SIZE_INCR'; +export const UI_FONT_SIZE_DECR = 'UI_FONT_SIZE_DECR'; +export const UI_FONT_SIZE_RESET = 'UI_FONT_SIZE_RESET'; +export const UI_MOVE_LEFT = 'UI_MOVE_LEFT'; +export const UI_MOVE_RIGHT = 'UI_MOVE_RIGHT'; +export const UI_MOVE_TO = 'UI_MOVE_TO'; +export const UI_SHOW_PREFERENCES = 'UI_SHOW_PREFERENCES'; diff --git a/app/lib/constants/updater.js b/app/lib/constants/updater.js new file mode 100644 index 00000000..624115a9 --- /dev/null +++ b/app/lib/constants/updater.js @@ -0,0 +1,2 @@ +export const UPDATE_INSTALL = 'UPDATE_INSTALL'; +export const UPDATE_AVAILABLE = 'UPDATE_AVAILABLE'; diff --git a/app/lib/containers/header.js b/app/lib/containers/header.js new file mode 100644 index 00000000..c3576459 --- /dev/null +++ b/app/lib/containers/header.js @@ -0,0 +1,48 @@ +import Header from '../components/header'; +import { closeTab, changeTab } from '../actions/header'; +import { values } from '../utils/object'; +import { createSelector } from 'reselect'; +import { connect } from '../utils/plugins'; + +const isMac = /Mac/.test(navigator.userAgent); + +const getSessions = (sessions) => sessions.sessions; +const getActiveUid = (sessions) => sessions.activeUid; +const getActivityMarkers = (sessions, ui) => ui.activityMarkers; +const getTabs = createSelector( + [getSessions, getActiveUid, getActivityMarkers], + (sessions, activeUid, activityMarkers) => values(sessions).map((s) => { + return { + uid: s.uid, + title: s.title, + isActive: s.uid === activeUid, + hasActivity: activityMarkers[s.uid] + }; + }) +); + +const HeaderContainer = connect( + (state) => { + return { + // active is an index + isMac, + tabs: getTabs(state.sessions, state.ui), + activeMarkers: state.ui.activityMarkers, + borderColor: state.ui.borderColor, + backgroundColor: state.ui.backgroundColor + }; + }, + (dispatch) => { + return { + onCloseTab: (i) => { + dispatch(closeTab(i)); + }, + + onChangeTab: (i) => { + dispatch(changeTab(i)); + } + }; + } +)(Header, 'Header'); + +export default HeaderContainer; diff --git a/app/lib/containers/hyperterm.js b/app/lib/containers/hyperterm.js new file mode 100644 index 00000000..091eb22f --- /dev/null +++ b/app/lib/containers/hyperterm.js @@ -0,0 +1,137 @@ +import React from 'react'; +import HeaderContainer from './header'; +import TermsContainer from './terms'; +import NotificationsContainer from './notifications'; +import Component from '../component'; +import Mousetrap from 'mousetrap'; +import overrideStyles from '../utils/override-style'; +import { moveTo, moveLeft, moveRight } from '../actions/ui'; +import { connect } from '../utils/plugins'; + +const isMac = /Mac/.test(navigator.userAgent); + +class HyperTerm extends Component { + constructor (props) { + super(props); + this.focusActive = this.focusActive.bind(this); + document.body.style.backgroundColor = props.backgroundColor; + this.onTermsRef = this.onTermsRef.bind(this); + } + + componentWillReceiveProps (next) { + if (this.props.backgroundColor !== next.backgroundColor) { + document.body.style.backgroundColor = next.backgroundColor; + } + } + + focusActive () { + const term = this.terms.getActiveTerm(); + if (term) term.focus(); + } + + attachKeyListeners () { + const { moveTo, moveLeft, moveRight } = this.props; + const term = this.terms.getActiveTerm(); + if (!term) return; + const document = term.getTermDocument(); + const keys = new Mousetrap(document); + keys.bind('command+1', moveTo.bind(this, 0)); + keys.bind('command+2', moveTo.bind(this, 1)); + keys.bind('command+3', moveTo.bind(this, 2)); + keys.bind('command+4', moveTo.bind(this, 3)); + keys.bind('command+5', moveTo.bind(this, 4)); + keys.bind('command+6', moveTo.bind(this, 5)); + keys.bind('command+7', moveTo.bind(this, 6)); + keys.bind('command+8', moveTo.bind(this, 7)); + keys.bind('command+9', moveTo.bind(this, 8)); + keys.bind('command+shift+left', moveLeft); + keys.bind('command+shift+right', moveRight); + keys.bind('command+shift+[', moveLeft); + keys.bind('command+shift+]', moveRight); + keys.bind('command+alt+left', moveLeft); + keys.bind('command+alt+right', moveRight); + this.keys = keys; + } + + onTermsRef (terms) { + this.terms = terms; + } + + componentDidUpdate (prev) { + if (prev.activeSession !== this.props.activeSession) { + if (this.keys) this.keys.reset(); + this.focusActive(); + this.attachKeyListeners(); + } + } + + componentWillUnmount () { + if (this.keys) this.keys.reset(); + document.body.style.backgroundColor = 'inherit'; + } + + template (css) { + const { isMac, customCSS, borderColor } = this.props; + return
    +
    + + +
    + + + - - ); -}); - -Header.displayName = 'Header'; - -export default Header; diff --git a/lib/components/new-tab.tsx b/lib/components/new-tab.tsx deleted file mode 100644 index 3fe99543..00000000 --- a/lib/components/new-tab.tsx +++ /dev/null @@ -1,149 +0,0 @@ -import React, {useRef, useState} from 'react'; - -import {VscChevronDown} from '@react-icons/all-files/vsc/VscChevronDown'; -import useClickAway from 'react-use/lib/useClickAway'; - -import type {configOptions} from '../../typings/config'; - -interface Props { - defaultProfile: string; - profiles: configOptions['profiles']; - openNewTab: (name: string) => void; - backgroundColor: string; - borderColor: string; - tabsVisible: boolean; -} -const isMac = /Mac/.test(navigator.userAgent); - -const DropdownButton = ({defaultProfile, profiles, openNewTab, backgroundColor, borderColor, tabsVisible}: Props) => { - const [dropdownOpen, setDropdownOpen] = useState(false); - const ref = useRef(null); - - const toggleDropdown = () => { - setDropdownOpen(!dropdownOpen); - }; - - useClickAway(ref, () => { - setDropdownOpen(false); - }); - - return ( -
    e.stopPropagation()} - onBlur={() => setDropdownOpen(false)} - > - - - {dropdownOpen && ( -
      - {profiles.map((profile) => ( -
    • { - openNewTab(profile.name); - setDropdownOpen(false); - }} - className={`profile_dropdown_item ${ - profile.name === defaultProfile && profiles.length > 1 ? 'profile_dropdown_item_default' : '' - }`} - > - {profile.name} -
    • - ))} -
    - )} - - -
    - ); -}; - -export default DropdownButton; diff --git a/lib/components/notification.tsx b/lib/components/notification.tsx deleted file mode 100644 index 68b7a2df..00000000 --- a/lib/components/notification.tsx +++ /dev/null @@ -1,110 +0,0 @@ -import React, {forwardRef, useEffect, useRef, useState} from 'react'; - -import type {NotificationProps} from '../../typings/hyper'; - -const Notification = forwardRef>((props, ref) => { - const dismissTimer = useRef(undefined); - const [dismissing, setDismissing] = useState(false); - - useEffect(() => { - setDismissTimer(); - }, []); - - useEffect(() => { - // if we have a timer going and the notification text - // changed we reset the timer - resetDismissTimer(); - setDismissing(false); - }, [props.text]); - - const handleDismiss = () => { - setDismissing(true); - }; - - const onElement = (el: HTMLDivElement | null) => { - if (el) { - el.addEventListener('webkitTransitionEnd', () => { - if (dismissing) { - props.onDismiss(); - } - }); - const {backgroundColor} = props; - if (backgroundColor) { - el.style.setProperty('background-color', backgroundColor, 'important'); - } - - if (ref) { - if (typeof ref === 'function') ref(el); - else ref.current = el; - } - } - }; - - const setDismissTimer = () => { - if (typeof props.dismissAfter === 'number') { - dismissTimer.current = setTimeout(() => { - handleDismiss(); - }, props.dismissAfter); - } - }; - - const resetDismissTimer = () => { - clearTimeout(dismissTimer.current); - setDismissTimer(); - }; - - useEffect(() => { - return () => { - clearTimeout(dismissTimer.current); - }; - }, []); - - const {backgroundColor, color} = props; - const opacity = dismissing ? 0 : 1; - return ( -
    - {props.customChildrenBefore} - {props.children || props.text} - {props.userDismissable ? ( - - [x] - - ) : null} - {props.customChildren} - - -
    - ); -}); - -Notification.displayName = 'Notification'; - -export default Notification; diff --git a/lib/components/notifications.tsx b/lib/components/notifications.tsx deleted file mode 100644 index 79e6ede3..00000000 --- a/lib/components/notifications.tsx +++ /dev/null @@ -1,132 +0,0 @@ -import React, {forwardRef} from 'react'; - -import type {NotificationsProps} from '../../typings/hyper'; -import {decorate} from '../utils/plugins'; - -import Notification_ from './notification'; - -const Notification = decorate(Notification_, 'Notification'); - -const Notifications = forwardRef((props, ref) => { - return ( -
    - {props.customChildrenBefore} - {props.fontShowing && ( - - )} - - {props.resizeShowing && ( - - )} - - {props.messageShowing && ( - - {props.messageURL ? ( - <> - {props.messageText} ( - { - void window.require('electron').shell.openExternal(ev.currentTarget.href); - ev.preventDefault(); - }} - href={props.messageURL} - > - more - - ) - - ) : null} - - )} - - {props.updateShowing && ( - - Version {props.updateVersion} ready. - {props.updateNote && ` ${props.updateNote.trim().replace(/\.$/, '')}`} ( - { - void window.require('electron').shell.openExternal(ev.currentTarget.href); - ev.preventDefault(); - }} - href={`https://github.com/vercel/hyper/releases/tag/${props.updateVersion}`} - > - notes - - ).{' '} - {props.updateCanInstall ? ( - - Restart - - ) : ( - { - void window.require('electron').shell.openExternal(ev.currentTarget.href); - ev.preventDefault(); - }} - href={props.updateReleaseUrl!} - > - Download - - )} - .{' '} - - )} - {props.customChildren} - - -
    - ); -}); - -Notifications.displayName = 'Notifications'; - -export default Notifications; diff --git a/lib/components/searchBox.tsx b/lib/components/searchBox.tsx deleted file mode 100644 index 55a72f16..00000000 --- a/lib/components/searchBox.tsx +++ /dev/null @@ -1,237 +0,0 @@ -import React, {useCallback, useRef, useEffect, forwardRef} from 'react'; - -import {VscArrowDown} from '@react-icons/all-files/vsc/VscArrowDown'; -import {VscArrowUp} from '@react-icons/all-files/vsc/VscArrowUp'; -import {VscCaseSensitive} from '@react-icons/all-files/vsc/VscCaseSensitive'; -import {VscClose} from '@react-icons/all-files/vsc/VscClose'; -import {VscRegex} from '@react-icons/all-files/vsc/VscRegex'; -import {VscWholeWord} from '@react-icons/all-files/vsc/VscWholeWord'; -import clsx from 'clsx'; - -import type {SearchBoxProps} from '../../typings/hyper'; - -type SearchButtonColors = { - foregroundColor: string; - selectionColor: string; - backgroundColor: string; -}; - -type SearchButtonProps = React.PropsWithChildren< - { - onClick: () => void; - active: boolean; - title: string; - } & SearchButtonColors ->; - -const SearchButton = ({ - onClick, - active, - title, - foregroundColor, - backgroundColor, - selectionColor, - children -}: SearchButtonProps) => { - const handleKeyUp = useCallback( - (event: React.KeyboardEvent) => { - if (event.key === 'Enter' || event.key === ' ') { - onClick(); - } - }, - [onClick] - ); - - return ( -
    - {children} - -
    - ); -}; - -const SearchBox = forwardRef((props, ref) => { - const { - caseSensitive, - wholeWord, - regex, - results, - toggleCaseSensitive, - toggleWholeWord, - toggleRegex, - next, - prev, - close, - backgroundColor, - foregroundColor, - borderColor, - selectionColor, - font - } = props; - - const searchTermRef = useRef(''); - const inputRef = useRef(null); - - const handleChange = useCallback( - (event: React.KeyboardEvent) => { - searchTermRef.current = event.currentTarget.value; - if (event.shiftKey && event.key === 'Enter') { - prev(searchTermRef.current); - } else if (event.key === 'Enter') { - next(searchTermRef.current); - } - }, - [prev, next] - ); - - useEffect(() => { - inputRef.current?.focus(); - }, [inputRef.current]); - - const searchButtonColors: SearchButtonColors = { - backgroundColor: borderColor, - selectionColor, - foregroundColor - }; - - return ( -
    -
    - - - - - - - - - - - - - -
    - - - {results === undefined - ? '' - : results.resultCount === 0 - ? 'No results' - : `${results.resultIndex + 1} of ${results.resultCount}`} - - -
    - prev(searchTermRef.current)} - active={false} - title="Previous Match" - {...searchButtonColors} - > - - - - next(searchTermRef.current)} - active={false} - title="Next Match" - {...searchButtonColors} - > - - - - - - -
    - - -
    - ); -}); - -SearchBox.displayName = 'SearchBox'; - -export default SearchBox; diff --git a/lib/components/split-pane.tsx b/lib/components/split-pane.tsx deleted file mode 100644 index aea53f6f..00000000 --- a/lib/components/split-pane.tsx +++ /dev/null @@ -1,191 +0,0 @@ -import React, {useState, useEffect, useRef, forwardRef} from 'react'; - -import sum from 'lodash/sum'; - -import type {SplitPaneProps} from '../../typings/hyper'; - -const SplitPane = forwardRef((props, ref) => { - const dragPanePosition = useRef(0); - const dragTarget = useRef(null); - const paneIndex = useRef(0); - const d1 = props.direction === 'horizontal' ? 'height' : 'width'; - const d2 = props.direction === 'horizontal' ? 'top' : 'left'; - const d3 = props.direction === 'horizontal' ? 'clientY' : 'clientX'; - const panesSize = useRef(null); - const [dragging, setDragging] = useState(false); - - const handleAutoResize = (ev: React.MouseEvent, index: number) => { - ev.preventDefault(); - - paneIndex.current = index; - - const sizes_ = getSizes(); - sizes_[paneIndex.current] = 0; - sizes_[paneIndex.current + 1] = 0; - - const availableWidth = 1 - sum(sizes_); - sizes_[paneIndex.current] = availableWidth / 2; - sizes_[paneIndex.current + 1] = availableWidth / 2; - - props.onResize(sizes_); - }; - - const handleDragStart = (ev: React.MouseEvent, index: number) => { - ev.preventDefault(); - setDragging(true); - window.addEventListener('mousemove', onDrag); - window.addEventListener('mouseup', onDragEnd); - - const target = ev.target as HTMLDivElement; - dragTarget.current = target; - dragPanePosition.current = dragTarget.current.getBoundingClientRect()[d2]; - panesSize.current = target.parentElement!.getBoundingClientRect()[d1]; - paneIndex.current = index; - }; - - const getSizes = () => { - const {sizes} = props; - let sizes_: number[]; - - if (sizes) { - sizes_ = [...sizes.asMutable()]; - } else { - const total = props.children.length; - const count = new Array(total).fill(1 / total); - - sizes_ = count; - } - return sizes_; - }; - - const onDrag = (ev: MouseEvent) => { - const sizes_ = getSizes(); - - const i = paneIndex.current; - const pos = ev[d3]; - const d = Math.abs(dragPanePosition.current - pos) / panesSize.current!; - if (pos > dragPanePosition.current) { - sizes_[i] += d; - sizes_[i + 1] -= d; - } else { - sizes_[i] -= d; - sizes_[i + 1] += d; - } - props.onResize(sizes_); - }; - - const onDragEnd = () => { - window.removeEventListener('mousemove', onDrag); - window.removeEventListener('mouseup', onDragEnd); - setDragging(false); - }; - - useEffect(() => { - return () => { - onDragEnd(); - }; - }, []); - - const {children, direction, borderColor} = props; - const sizeProperty = direction === 'horizontal' ? 'height' : 'width'; - // workaround for the fact that if we don't specify - // sizes, sometimes flex fails to calculate the - // right height for the horizontal panes - const sizes = props.sizes || new Array(children.length).fill(1 / children.length); - return ( -
    - {children.map((child, i) => { - const style = { - // flexBasis doesn't work for the first horizontal pane, height need to be specified - [sizeProperty]: `${sizes[i] * 100}%`, - flexBasis: `${sizes[i] * 100}%`, - flexGrow: 0 - }; - - return ( - -
    - {child} -
    - {i < children.length - 1 ? ( -
    handleDragStart(e, i)} - onDoubleClick={(e) => handleAutoResize(e, i)} - style={{backgroundColor: borderColor}} - className={`splitpane_divider splitpane_divider_${direction}`} - /> - ) : null} - - ); - })} -
    - - -
    - ); -}); - -SplitPane.displayName = 'SplitPane'; - -export default SplitPane; diff --git a/lib/components/style-sheet.tsx b/lib/components/style-sheet.tsx deleted file mode 100644 index 86d89424..00000000 --- a/lib/components/style-sheet.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import React, {forwardRef} from 'react'; - -import type {StyleSheetProps} from '../../typings/hyper'; - -const StyleSheet = forwardRef((props, ref) => { - const {borderColor} = props; - - return ( - - ); -}); - -StyleSheet.displayName = 'StyleSheet'; - -export default StyleSheet; diff --git a/lib/components/tab.tsx b/lib/components/tab.tsx deleted file mode 100644 index c977c039..00000000 --- a/lib/components/tab.tsx +++ /dev/null @@ -1,168 +0,0 @@ -import React, {forwardRef} from 'react'; - -import type {TabProps} from '../../typings/hyper'; - -const Tab = forwardRef((props, ref) => { - const handleClick = (event: React.MouseEvent) => { - const isLeftClick = event.nativeEvent.which === 1; - - if (isLeftClick && !props.isActive) { - props.onSelect(); - } - }; - - const handleMouseUp = (event: React.MouseEvent) => { - const isMiddleClick = event.nativeEvent.which === 2; - - if (isMiddleClick) { - props.onClose(); - } - }; - - const {isActive, isFirst, isLast, borderColor, hasActivity} = props; - - return ( - <> -
  • - {props.customChildrenBefore} - - - {props.text} - - - - - - - - {props.customChildren} -
  • - - - - ); -}); - -Tab.displayName = 'Tab'; - -export default Tab; diff --git a/lib/components/tabs.tsx b/lib/components/tabs.tsx deleted file mode 100644 index 49043e7d..00000000 --- a/lib/components/tabs.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import React, {forwardRef} from 'react'; - -import type {TabsProps} from '../../typings/hyper'; -import {decorate, getTabProps} from '../utils/plugins'; - -import DropdownButton from './new-tab'; -import Tab_ from './tab'; - -const Tab = decorate(Tab_, 'Tab'); -const isMac = /Mac/.test(navigator.userAgent); - -const Tabs = forwardRef((props, ref) => { - const {tabs = [], borderColor, onChange, onClose, fullScreen} = props; - - const hide = !isMac && tabs.length === 1; - - return ( - - ); -}); - -Tabs.displayName = 'Tabs'; - -export default Tabs; diff --git a/lib/components/term-group.tsx b/lib/components/term-group.tsx deleted file mode 100644 index 5e6e66ec..00000000 --- a/lib/components/term-group.tsx +++ /dev/null @@ -1,158 +0,0 @@ -import React from 'react'; - -import {connect} from 'react-redux'; - -import type {HyperState, HyperDispatch, TermGroupProps, TermGroupOwnProps} from '../../typings/hyper'; -import {resizeTermGroup} from '../actions/term-groups'; -import {decorate, getTermProps, getTermGroupProps} from '../utils/plugins'; - -import SplitPane_ from './split-pane'; -import Term_ from './term'; - -const Term = decorate(Term_, 'Term'); -const SplitPane = decorate(SplitPane_, 'SplitPane'); - -class TermGroup_ extends React.PureComponent { - bound: WeakMap<(uid: string, ...args: any[]) => any, Record any>>; - term?: Term_ | null; - constructor(props: TermGroupProps, context: any) { - super(props, context); - this.bound = new WeakMap(); - } - - bind any>( - fn: T, - thisObj: any, - uid: string - ): (...args: T extends (uid: string, ..._args: infer I) => any ? I : never) => ReturnType { - if (!this.bound.has(fn)) { - this.bound.set(fn, {}); - } - const map = this.bound.get(fn)!; - if (!map[uid]) { - map[uid] = fn.bind(thisObj, uid); - } - return map[uid]; - } - - renderSplit(groups: JSX.Element[]) { - const [first, ...rest] = groups; - if (rest.length === 0) { - return first; - } - - const direction = this.props.termGroup.direction!.toLowerCase() as 'horizontal' | 'vertical'; - return ( - - {groups} - - ); - } - - onTermRef = (uid: string, term: Term_ | null) => { - this.term = term; - this.props.ref_(uid, term); - }; - - renderTerm(uid: string) { - const session = this.props.sessions[uid]; - const termRef = this.props.terms[uid]; - const props = getTermProps(uid, this.props, { - isTermActive: uid === this.props.activeSession, - term: termRef ? termRef.term : null, - fitAddon: termRef ? termRef.fitAddon : null, - searchAddon: termRef ? termRef.searchAddon : null, - scrollback: this.props.scrollback, - backgroundColor: this.props.backgroundColor, - foregroundColor: this.props.foregroundColor, - colors: this.props.colors, - cursorBlink: this.props.cursorBlink, - cursorShape: this.props.cursorShape, - cursorColor: this.props.cursorColor, - cursorAccentColor: this.props.cursorAccentColor, - fontSize: this.props.fontSize, - fontFamily: this.props.fontFamily, - uiFontFamily: this.props.uiFontFamily, - fontSmoothing: this.props.fontSmoothing, - fontWeight: this.props.fontWeight, - fontWeightBold: this.props.fontWeightBold, - lineHeight: this.props.lineHeight, - letterSpacing: this.props.letterSpacing, - modifierKeys: this.props.modifierKeys, - padding: this.props.padding, - cleared: session.cleared, - search: session.search, - cols: session.cols, - rows: session.rows, - copyOnSelect: this.props.copyOnSelect, - bell: this.props.bell, - bellSoundURL: this.props.bellSoundURL, - bellSound: this.props.bellSound, - onActive: this.bind(this.props.onActive, null, uid), - onResize: this.bind(this.props.onResize, null, uid), - onTitle: this.bind(this.props.onTitle, null, uid), - onData: this.bind(this.props.onData, null, uid), - onOpenSearch: this.bind(this.props.onOpenSearch, null, uid), - onCloseSearch: this.bind(this.props.onCloseSearch, null, uid), - onContextMenu: this.bind(this.props.onContextMenu, null, uid), - borderColor: this.props.borderColor, - selectionColor: this.props.selectionColor, - quickEdit: this.props.quickEdit, - webGLRenderer: this.props.webGLRenderer, - webLinksActivationKey: this.props.webLinksActivationKey, - macOptionSelectionMode: this.props.macOptionSelectionMode, - disableLigatures: this.props.disableLigatures, - screenReaderMode: this.props.screenReaderMode, - windowsPty: this.props.windowsPty, - imageSupport: this.props.imageSupport, - uid - }); - - // This will create a new ref_ function for every render, - // which is inefficient. Should maybe do something similar - // to this.bind. - return ; - } - - render() { - const {childGroups, termGroup} = this.props; - if (termGroup.sessionUid) { - return this.renderTerm(termGroup.sessionUid); - } - - const groups = childGroups.asMutable().map((child) => { - const props = getTermGroupProps( - child.uid, - this.props.parentProps, - Object.assign({}, this.props, {termGroup: child}) - ); - - return ; - }); - - return this.renderSplit(groups); - } -} - -const mapStateToProps = (state: HyperState, ownProps: TermGroupOwnProps) => ({ - childGroups: ownProps.termGroup.children.map((uid) => state.termGroups.termGroups[uid]) -}); - -const mapDispatchToProps = (dispatch: HyperDispatch, ownProps: TermGroupOwnProps) => ({ - onTermGroupResize(splitSizes: number[]) { - dispatch(resizeTermGroup(ownProps.termGroup.uid, splitSizes)); - } -}); - -const TermGroup = connect(mapStateToProps, mapDispatchToProps, null, {forwardRef: true})(TermGroup_); - -const DecoratedTermGroup = decorate(TermGroup, 'TermGroup'); - -export default TermGroup; - -export type TermGroupConnectedProps = ReturnType & ReturnType; diff --git a/lib/components/term.tsx b/lib/components/term.tsx deleted file mode 100644 index 45c1464c..00000000 --- a/lib/components/term.tsx +++ /dev/null @@ -1,569 +0,0 @@ -import {clipboard, shell} from 'electron'; -import React from 'react'; - -import Color from 'color'; -import isEqual from 'lodash/isEqual'; -import pickBy from 'lodash/pickBy'; -import {Terminal} from 'xterm'; -import type {ITerminalOptions, IDisposable} from 'xterm'; -import {CanvasAddon} from 'xterm-addon-canvas'; -import {FitAddon} from 'xterm-addon-fit'; -import {ImageAddon} from 'xterm-addon-image'; -import {LigaturesAddon} from 'xterm-addon-ligatures'; -import {SearchAddon} from 'xterm-addon-search'; -import type {ISearchDecorationOptions} from 'xterm-addon-search'; -import {Unicode11Addon} from 'xterm-addon-unicode11'; -import {WebLinksAddon} from 'xterm-addon-web-links'; -import {WebglAddon} from 'xterm-addon-webgl'; - -import type {TermProps} from '../../typings/hyper'; -import terms from '../terms'; -import processClipboard from '../utils/paste'; -import {decorate} from '../utils/plugins'; - -import _SearchBox from './searchBox'; - -import 'xterm/css/xterm.css'; - -const SearchBox = decorate(_SearchBox, 'SearchBox'); - -const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].includes(navigator.platform) || process.platform === 'win32'; - -// map old hterm constants to xterm.js -const CURSOR_STYLES = { - BEAM: 'bar', - UNDERLINE: 'underline', - BLOCK: 'block' -} as const; - -const isWebgl2Supported = (() => { - let isSupported = window.WebGL2RenderingContext ? undefined : false; - return () => { - if (isSupported === undefined) { - const canvas = document.createElement('canvas'); - const gl = canvas.getContext('webgl2', {depth: false, antialias: false}); - isSupported = gl instanceof window.WebGL2RenderingContext; - } - return isSupported; - }; -})(); - -const getTermOptions = (props: TermProps): ITerminalOptions => { - // Set a background color only if it is opaque - const needTransparency = Color(props.backgroundColor).alpha() < 1; - const backgroundColor = needTransparency ? 'rgba(0,0,0,0)' : props.backgroundColor; - - return { - macOptionIsMeta: props.modifierKeys.altIsMeta, - scrollback: props.scrollback, - cursorStyle: CURSOR_STYLES[props.cursorShape], - cursorBlink: props.cursorBlink, - fontFamily: props.fontFamily, - fontSize: props.fontSize, - fontWeight: props.fontWeight, - fontWeightBold: props.fontWeightBold, - lineHeight: props.lineHeight, - letterSpacing: props.letterSpacing, - allowTransparency: needTransparency, - macOptionClickForcesSelection: props.macOptionSelectionMode === 'force', - windowsMode: isWindows, - ...(isWindows && props.windowsPty && {windowsPty: props.windowsPty}), - theme: { - foreground: props.foregroundColor, - background: backgroundColor, - cursor: props.cursorColor, - cursorAccent: props.cursorAccentColor, - selectionBackground: props.selectionColor, - black: props.colors.black, - red: props.colors.red, - green: props.colors.green, - yellow: props.colors.yellow, - blue: props.colors.blue, - magenta: props.colors.magenta, - cyan: props.colors.cyan, - white: props.colors.white, - brightBlack: props.colors.lightBlack, - brightRed: props.colors.lightRed, - brightGreen: props.colors.lightGreen, - brightYellow: props.colors.lightYellow, - brightBlue: props.colors.lightBlue, - brightMagenta: props.colors.lightMagenta, - brightCyan: props.colors.lightCyan, - brightWhite: props.colors.lightWhite - }, - screenReaderMode: props.screenReaderMode, - overviewRulerWidth: 20, - allowProposedApi: true - }; -}; - -export default class Term extends React.PureComponent< - TermProps, - { - searchOptions: { - caseSensitive: boolean; - wholeWord: boolean; - regex: boolean; - }; - searchResults: - | { - resultIndex: number; - resultCount: number; - } - | undefined; - } -> { - termRef: HTMLElement | null; - termWrapperRef: HTMLElement | null; - termOptions: ITerminalOptions; - disposableListeners: IDisposable[]; - defaultBellSound: HTMLAudioElement | null; - bellSound: HTMLAudioElement | null; - fitAddon: FitAddon; - searchAddon: SearchAddon; - static rendererTypes: Record; - term!: Terminal; - resizeObserver!: ResizeObserver; - resizeTimeout!: NodeJS.Timeout; - searchDecorations: ISearchDecorationOptions; - state = { - searchOptions: { - caseSensitive: false, - wholeWord: false, - regex: false - }, - searchResults: undefined - }; - - constructor(props: TermProps) { - super(props); - props.ref_(props.uid, this); - this.termRef = null; - this.termWrapperRef = null; - this.termOptions = {}; - this.disposableListeners = []; - this.defaultBellSound = null; - this.bellSound = null; - this.fitAddon = new FitAddon(); - this.searchAddon = new SearchAddon(); - this.searchDecorations = { - activeMatchColorOverviewRuler: Color(this.props.cursorColor).hex(), - matchOverviewRuler: Color(this.props.borderColor).hex(), - activeMatchBackground: Color(this.props.cursorColor).hex(), - activeMatchBorder: Color(this.props.cursorColor).hex(), - matchBorder: Color(this.props.cursorColor).hex() - }; - } - - // The main process shows this in the About dialog - static reportRenderer(uid: string, type: string) { - const rendererTypes = Term.rendererTypes || {}; - if (rendererTypes[uid] !== type) { - rendererTypes[uid] = type; - Term.rendererTypes = rendererTypes; - window.rpc.emit('info renderer', {uid, type}); - } - } - - componentDidMount() { - const {props} = this; - - this.termOptions = getTermOptions(props); - this.term = props.term || new Terminal(this.termOptions); - this.defaultBellSound = new Audio( - // Source: https://freesound.org/people/altemark/sounds/45759/ - // This sound is released under the Creative Commons Attribution 3.0 Unported - // (CC BY 3.0) license. It was created by 'altemark'. No modifications have been - // made, apart from the conversion to base64. - 'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq' - ); - this.setBellSound(props.bell, props.bellSound); - - // The parent element for the terminal is attached and removed manually so - // that we can preserve it across mounts and unmounts of the component - this.termRef = props.term ? props.term.element!.parentElement! : document.createElement('div'); - this.termRef.className = 'term_fit term_term'; - - this.termWrapperRef?.appendChild(this.termRef); - - if (!props.term) { - const needTransparency = Color(props.backgroundColor).alpha() < 1; - let useWebGL = false; - if (props.webGLRenderer) { - if (needTransparency) { - console.warn( - 'WebGL Renderer has been disabled since it does not support transparent backgrounds yet. ' + - 'Falling back to canvas-based rendering.' - ); - } else if (!isWebgl2Supported()) { - console.warn('WebGL2 is not supported on your machine. Falling back to canvas-based rendering.'); - } else { - // Experimental WebGL renderer needs some more glue-code to make it work on Hyper. - // If you're working on enabling back WebGL, you will also need to look into `xterm-addon-ligatures` support for that renderer. - useWebGL = true; - } - } - Term.reportRenderer(props.uid, useWebGL ? 'WebGL' : 'Canvas'); - - const shallActivateWebLink = (event: MouseEvent): boolean => { - if (!event) return false; - return props.webLinksActivationKey ? event[`${props.webLinksActivationKey}Key`] : true; - }; - - // eslint-disable-next-line @typescript-eslint/unbound-method - this.term.attachCustomKeyEventHandler(this.keyboardHandler); - this.term.loadAddon(this.fitAddon); - this.term.loadAddon(this.searchAddon); - this.term.loadAddon( - new WebLinksAddon((event, uri) => { - if (shallActivateWebLink(event)) void shell.openExternal(uri); - }) - ); - this.term.open(this.termRef); - - if (useWebGL) { - const webglAddon = new WebglAddon(); - this.term.loadAddon(webglAddon); - webglAddon.onContextLoss(() => { - console.warn('WebGL context lost. Falling back to canvas-based rendering.'); - webglAddon.dispose(); - this.term.loadAddon(new CanvasAddon()); - }); - } else { - this.term.loadAddon(new CanvasAddon()); - } - - if (props.disableLigatures !== true && !useWebGL) { - this.term.loadAddon(new LigaturesAddon()); - } - - this.term.loadAddon(new Unicode11Addon()); - this.term.unicode.activeVersion = '11'; - - if (props.imageSupport) { - this.term.loadAddon(new ImageAddon()); - } - } else { - // get the cached plugins - this.fitAddon = props.fitAddon!; - this.searchAddon = props.searchAddon!; - } - - try { - this.term.element!.style.padding = props.padding; - } catch (error) { - console.log(error); - } - - this.fitAddon.fit(); - - if (this.props.isTermActive) { - this.term.focus(); - } - - if (props.onTitle) { - this.disposableListeners.push(this.term.onTitleChange(props.onTitle)); - } - - if (props.onActive) { - this.term.textarea?.addEventListener('focus', props.onActive); - this.disposableListeners.push({ - dispose: () => this.term.textarea?.removeEventListener('focus', this.props.onActive) - }); - } - - if (props.onData) { - this.disposableListeners.push(this.term.onData(props.onData)); - } - - this.term.onBell(() => { - this.ringBell(); - }); - - if (props.onResize) { - this.disposableListeners.push( - this.term.onResize(({cols, rows}) => { - props.onResize(cols, rows); - }) - ); - - // the row and col of init session is null, so reize the node-pty - props.onResize(this.term.cols, this.term.rows); - } - - if (props.onCursorMove) { - this.disposableListeners.push( - this.term.onCursorMove(() => { - const cursorFrame = { - x: this.term.buffer.active.cursorX * (this.term as any)._core._renderService.dimensions.actualCellWidth, - y: this.term.buffer.active.cursorY * (this.term as any)._core._renderService.dimensions.actualCellHeight, - width: (this.term as any)._core._renderService.dimensions.actualCellWidth, - height: (this.term as any)._core._renderService.dimensions.actualCellHeight, - col: this.term.buffer.active.cursorX, - row: this.term.buffer.active.cursorY - }; - props.onCursorMove?.(cursorFrame); - }) - ); - } - - this.disposableListeners.push( - this.searchAddon.onDidChangeResults((results) => { - this.setState((state) => ({ - ...state, - searchResults: results - })); - }) - ); - - window.addEventListener('paste', this.onWindowPaste, { - capture: true - }); - - terms[this.props.uid] = this; - } - - getTermDocument() { - console.warn( - 'The underlying terminal engine of Hyper no longer ' + - 'uses iframes with individual `document` objects for each ' + - 'terminal instance. This method call is retained for ' + - "backwards compatibility reasons. It's ok to attach directly" + - 'to the `document` object of the main `window`.' - ); - return document; - } - - // intercepting paste event for any necessary processing of - // clipboard data, if result is falsy, paste event continues - onWindowPaste = (e: Event) => { - if (!this.props.isTermActive) return; - - const processed = processClipboard(); - if (processed) { - e.preventDefault(); - e.stopPropagation(); - this.term.paste(processed); - } - }; - - onMouseUp = (e: React.MouseEvent) => { - if (this.props.quickEdit && e.button === 2) { - if (this.term.hasSelection()) { - clipboard.writeText(this.term.getSelection()); - this.term.clearSelection(); - } else { - document.execCommand('paste'); - } - } else if (this.props.copyOnSelect && this.term.hasSelection()) { - clipboard.writeText(this.term.getSelection()); - } - }; - - write(data: string | Uint8Array) { - this.term.write(data); - } - - focus = () => { - this.term.focus(); - }; - - clear() { - this.term.clear(); - } - - reset() { - this.term.reset(); - } - - searchNext = (searchTerm: string) => { - this.searchAddon.findNext(searchTerm, { - ...this.state.searchOptions, - decorations: this.searchDecorations - }); - }; - - searchPrevious = (searchTerm: string) => { - this.searchAddon.findPrevious(searchTerm, { - ...this.state.searchOptions, - decorations: this.searchDecorations - }); - }; - - closeSearchBox = () => { - this.props.onCloseSearch(); - this.searchAddon.clearDecorations(); - this.searchAddon.clearActiveDecoration(); - this.setState((state) => ({ - ...state, - searchResults: undefined - })); - this.term.focus(); - }; - - resize(cols: number, rows: number) { - this.term.resize(cols, rows); - } - - selectAll() { - this.term.selectAll(); - } - - fitResize() { - if (!this.termWrapperRef) { - return; - } - this.fitAddon.fit(); - } - - keyboardHandler(e: any) { - // Has Mousetrap flagged this event as a command? - return !e.catched; - } - - setBellSound(bell: 'SOUND' | false, sound: string | null) { - if (bell && bell.toUpperCase() === 'SOUND') { - this.bellSound = sound ? new Audio(sound) : this.defaultBellSound; - } else { - this.bellSound = null; - } - } - - ringBell() { - void this.bellSound?.play(); - } - - componentDidUpdate(prevProps: TermProps) { - if (!prevProps.cleared && this.props.cleared) { - this.clear(); - } - - const nextTermOptions = getTermOptions(this.props); - - if (prevProps.bell !== this.props.bell || prevProps.bellSound !== this.props.bellSound) { - this.setBellSound(this.props.bell, this.props.bellSound); - } - - if (prevProps.search && !this.props.search) { - this.closeSearchBox(); - } - - // Update only options that have changed. - this.term.options = pickBy( - nextTermOptions, - (value, key) => !isEqual(this.termOptions[key as keyof ITerminalOptions], value) - ); - - this.termOptions = nextTermOptions; - - try { - this.term.element!.style.padding = this.props.padding; - } catch (error) { - console.log(error); - } - - if ( - this.props.fontSize !== prevProps.fontSize || - this.props.fontFamily !== prevProps.fontFamily || - this.props.lineHeight !== prevProps.lineHeight || - this.props.letterSpacing !== prevProps.letterSpacing - ) { - // resize to fit the container - this.fitResize(); - } - - if (prevProps.rows !== this.props.rows || prevProps.cols !== this.props.cols) { - this.resize(this.props.cols!, this.props.rows!); - } - } - - onTermWrapperRef = (component: HTMLElement | null) => { - this.termWrapperRef = component; - - if (component) { - this.resizeObserver = new ResizeObserver(() => { - clearTimeout(this.resizeTimeout); - this.resizeTimeout = setTimeout(() => { - this.fitResize(); - }, 500); - }); - this.resizeObserver.observe(component); - } else { - this.resizeObserver.disconnect(); - } - }; - - componentWillUnmount() { - terms[this.props.uid] = null; - this.termWrapperRef?.removeChild(this.termRef!); - this.props.ref_(this.props.uid, null); - - // to clean up the terminal, we remove the listeners - // instead of invoking `destroy`, since it will make the - // term insta un-attachable in the future (which we need - // to do in case of splitting, see `componentDidMount` - this.disposableListeners.forEach((handler) => handler.dispose()); - this.disposableListeners = []; - - window.removeEventListener('paste', this.onWindowPaste, { - capture: true - }); - } - - render() { - return ( -
    - {this.props.customChildrenBefore} -
    - {this.props.customChildren} - {this.props.search ? ( - - this.setState({ - ...this.state, - searchOptions: {...this.state.searchOptions, caseSensitive: !this.state.searchOptions.caseSensitive} - }) - } - toggleWholeWord={() => - this.setState({ - ...this.state, - searchOptions: {...this.state.searchOptions, wholeWord: !this.state.searchOptions.wholeWord} - }) - } - toggleRegex={() => - this.setState({ - ...this.state, - searchOptions: {...this.state.searchOptions, regex: !this.state.searchOptions.regex} - }) - } - selectionColor={this.props.selectionColor} - backgroundColor={this.props.backgroundColor} - foregroundColor={this.props.foregroundColor} - borderColor={this.props.borderColor} - font={this.props.uiFontFamily} - /> - ) : null} - - -
    - ); - } -} diff --git a/lib/components/terms.tsx b/lib/components/terms.tsx deleted file mode 100644 index 3774b02d..00000000 --- a/lib/components/terms.tsx +++ /dev/null @@ -1,199 +0,0 @@ -import React from 'react'; - -import type {TermsProps, HyperDispatch} from '../../typings/hyper'; -import {registerCommandHandlers} from '../command-registry'; -import {ObjectTypedKeys} from '../utils/object'; -import {decorate, getTermGroupProps} from '../utils/plugins'; - -import StyleSheet_ from './style-sheet'; -import type Term from './term'; -import TermGroup_ from './term-group'; - -const TermGroup = decorate(TermGroup_, 'TermGroup'); -const StyleSheet = decorate(StyleSheet_, 'StyleSheet'); - -const isMac = /Mac/.test(navigator.userAgent); - -export default class Terms extends React.Component> { - terms: Record; - registerCommands: (cmds: Record void>) => void; - constructor(props: TermsProps, context: any) { - super(props, context); - this.terms = {}; - this.registerCommands = registerCommandHandlers; - props.ref_(this); - } - - shouldComponentUpdate(nextProps: TermsProps & {children: any}) { - return ( - ObjectTypedKeys(nextProps).some((i) => i !== 'write' && this.props[i] !== nextProps[i]) || - ObjectTypedKeys(this.props).some((i) => i !== 'write' && this.props[i] !== nextProps[i]) - ); - } - - onRef = (uid: string, term: Term | null) => { - if (term) { - this.terms[uid] = term; - } - }; - - getTermByUid(uid: string) { - return this.terms[uid]; - } - - getActiveTerm() { - return this.getTermByUid(this.props.activeSession!); - } - - onTerminal(uid: string, term: Term) { - this.terms[uid] = term; - } - - componentDidMount() { - window.addEventListener('contextmenu', () => { - const selection = window.getSelection()!.toString(); - const { - props: {uid} - } = this.getActiveTerm(); - this.props.onContextMenu(uid, selection); - }); - } - - componentDidUpdate(prevProps: TermsProps) { - for (const uid in prevProps.sessions) { - if (!this.props.sessions[uid]) { - this.terms[uid].term.dispose(); - delete this.terms[uid]; - } - } - } - - componentWillUnmount() { - this.props.ref_(null); - } - - render() { - const shift = !isMac && this.props.termGroups.length > 1; - return ( -
    - {this.props.customChildrenBefore} - {this.props.termGroups.map((termGroup) => { - const {uid} = termGroup; - const isActive = uid === this.props.activeRootGroup; - const props = getTermGroupProps(uid, this.props, { - termGroup, - terms: this.terms, - activeSession: this.props.activeSession, - sessions: this.props.sessions, - scrollback: this.props.scrollback, - backgroundColor: this.props.backgroundColor, - foregroundColor: this.props.foregroundColor, - borderColor: this.props.borderColor, - selectionColor: this.props.selectionColor, - colors: this.props.colors, - cursorShape: this.props.cursorShape, - cursorBlink: this.props.cursorBlink, - cursorColor: this.props.cursorColor, - cursorAccentColor: this.props.cursorAccentColor, - fontSize: this.props.fontSize, - fontFamily: this.props.fontFamily, - uiFontFamily: this.props.uiFontFamily, - fontWeight: this.props.fontWeight, - fontWeightBold: this.props.fontWeightBold, - lineHeight: this.props.lineHeight, - letterSpacing: this.props.letterSpacing, - padding: this.props.padding, - bell: this.props.bell, - bellSoundURL: this.props.bellSoundURL, - bellSound: this.props.bellSound, - copyOnSelect: this.props.copyOnSelect, - modifierKeys: this.props.modifierKeys, - onActive: this.props.onActive, - onResize: this.props.onResize, - onTitle: this.props.onTitle, - onData: this.props.onData, - onOpenSearch: this.props.onOpenSearch, - onCloseSearch: this.props.onCloseSearch, - onContextMenu: this.props.onContextMenu, - quickEdit: this.props.quickEdit, - webGLRenderer: this.props.webGLRenderer, - webLinksActivationKey: this.props.webLinksActivationKey, - macOptionSelectionMode: this.props.macOptionSelectionMode, - disableLigatures: this.props.disableLigatures, - screenReaderMode: this.props.screenReaderMode, - windowsPty: this.props.windowsPty, - imageSupport: this.props.imageSupport, - parentProps: this.props - }); - - return ( -
    - -
    - ); - })} - {this.props.customChildren} - - - -
    - ); - } -} diff --git a/lib/containers/header.ts b/lib/containers/header.ts deleted file mode 100644 index c8e4c9bd..00000000 --- a/lib/containers/header.ts +++ /dev/null @@ -1,86 +0,0 @@ -import {createSelector} from 'reselect'; - -import type {HyperState, HyperDispatch, ITab} from '../../typings/hyper'; -import {closeTab, changeTab, maximize, openHamburgerMenu, unmaximize, minimize, close} from '../actions/header'; -import {requestTermGroup} from '../actions/term-groups'; -import Header from '../components/header'; -import {getRootGroups} from '../selectors'; -import {connect} from '../utils/plugins'; - -const isMac = /Mac/.test(navigator.userAgent); - -const getSessions = ({sessions}: HyperState) => sessions.sessions; -const getActiveRootGroup = ({termGroups}: HyperState) => termGroups.activeRootGroup; -const getActiveSessions = ({termGroups}: HyperState) => termGroups.activeSessions; -const getActivityMarkers = ({ui}: HyperState) => ui.activityMarkers; -const getTabs = createSelector( - [getSessions, getRootGroups, getActiveSessions, getActiveRootGroup, getActivityMarkers], - (sessions, rootGroups, activeSessions, activeRootGroup, activityMarkers) => - rootGroups.map((t): ITab => { - const activeSessionUid = activeSessions[t.uid]; - const session = sessions[activeSessionUid]; - return { - uid: t.uid, - title: session.title, - isActive: t.uid === activeRootGroup, - hasActivity: activityMarkers[session.uid] - }; - }) -); - -const mapStateToProps = (state: HyperState) => { - return { - // active is an index - isMac, - tabs: getTabs(state), - activeMarkers: state.ui.activityMarkers, - borderColor: state.ui.borderColor, - backgroundColor: state.ui.backgroundColor, - maximized: state.ui.maximized, - fullScreen: state.ui.fullScreen, - showHamburgerMenu: state.ui.showHamburgerMenu, - showWindowControls: state.ui.showWindowControls, - defaultProfile: state.ui.defaultProfile, - profiles: state.ui.profiles - }; -}; - -const mapDispatchToProps = (dispatch: HyperDispatch) => { - return { - onCloseTab: (i: string) => { - dispatch(closeTab(i)); - }, - - onChangeTab: (i: string) => { - dispatch(changeTab(i)); - }, - - maximize: () => { - dispatch(maximize()); - }, - - unmaximize: () => { - dispatch(unmaximize()); - }, - - openHamburgerMenu: (coordinates: {x: number; y: number}) => { - dispatch(openHamburgerMenu(coordinates)); - }, - - minimize: () => { - dispatch(minimize()); - }, - - close: () => { - dispatch(close()); - }, - - openNewTab: (profile: string) => { - dispatch(requestTermGroup(undefined, profile)); - } - }; -}; - -export const HeaderContainer = connect(mapStateToProps, mapDispatchToProps, null)(Header, 'Header'); - -export type HeaderConnectedProps = ReturnType & ReturnType; diff --git a/lib/containers/hyper.tsx b/lib/containers/hyper.tsx deleted file mode 100644 index d53083a9..00000000 --- a/lib/containers/hyper.tsx +++ /dev/null @@ -1,167 +0,0 @@ -import React, {forwardRef, useEffect, useRef} from 'react'; - -import Mousetrap from 'mousetrap'; -import type {MousetrapInstance} from 'mousetrap'; -import stylis from 'stylis'; - -import type {HyperState, HyperProps, HyperDispatch} from '../../typings/hyper'; -import * as uiActions from '../actions/ui'; -import {getRegisteredKeys, getCommandHandler, shouldPreventDefault} from '../command-registry'; -import type Terms from '../components/terms'; -import {connect} from '../utils/plugins'; - -import {HeaderContainer} from './header'; -import NotificationsContainer from './notifications'; -import TermsContainer from './terms'; - -const isMac = /Mac/.test(navigator.userAgent); - -const Hyper = forwardRef((props, ref) => { - const mousetrap = useRef(null); - const terms = useRef(null); - - useEffect(() => { - void attachKeyListeners(); - }, [props.lastConfigUpdate]); - useEffect(() => { - handleFocusActive(props.activeSession); - }, [props.activeSession]); - - const handleFocusActive = (uid?: string | null) => { - const term = uid && terms.current?.getTermByUid(uid); - if (term) { - term.focus(); - } - }; - - const handleSelectAll = () => { - const term = terms.current?.getActiveTerm(); - if (term) { - term.selectAll(); - } - }; - - const attachKeyListeners = async () => { - if (!mousetrap.current) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - mousetrap.current = new (Mousetrap as any)(window, true); - mousetrap.current!.stopCallback = () => { - // All events should be intercepted even if focus is in an input/textarea - return false; - }; - } else { - mousetrap.current.reset(); - } - - const keys = await getRegisteredKeys(); - Object.keys(keys).forEach((commandKeys) => { - mousetrap.current?.bind( - commandKeys, - (e) => { - const command = keys[commandKeys]; - // We should tell xterm to ignore this event. - (e as any).catched = true; - props.execCommand(command, getCommandHandler(command), e); - shouldPreventDefault(command) && e.preventDefault(); - }, - 'keydown' - ); - }); - }; - - useEffect(() => { - void attachKeyListeners(); - window.rpc.on('term selectAll', handleSelectAll); - }, []); - - const onTermsRef = (_terms: Terms | null) => { - terms.current = _terms; - window.focusActiveTerm = (uid?: string) => { - if (uid) { - handleFocusActive(uid); - } else { - terms.current?.getActiveTerm()?.focus(); - } - }; - }; - - useEffect(() => { - return () => { - mousetrap.current?.reset(); - }; - }, []); - - const {isMac: isMac_, customCSS, uiFontFamily, borderColor, maximized, fullScreen} = props; - const borderWidth = isMac_ ? '' : `${maximized ? '0' : '1'}px`; - stylis.set({prefix: false}); - return ( -
    -
    - - - {props.customInnerChildren} -
    - - - - {props.customChildren} - - - - {/* - Add custom CSS to Hyper. - We add a scope to the customCSS so that it can get around the weighting applied by styled-jsx - */} -