diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..e79b3df --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,16 @@ +# Code ownership +/.github/CODEOWNERS @hashintel/infra-admins + +# Legal +LICENSE* @hashintel/legal + +# GitHub Actions and CI configuration +/.github/workflows/ @hashintel/infra +/.github/actions/ @hashintel/infra +/.github/scripts/ @hashintel/infra +/.github/dependabot.yml @hashintel/infra +/.github/renovate.json @hashintel/infra + +# Environment variable files +.env @hashintel/infra +.env.* @hashintel/infra diff --git a/.github/renovate.json b/.github/renovate.json new file mode 100644 index 0000000..6d45c2c --- /dev/null +++ b/.github/renovate.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "github>hashintel/actions:renovate-config" + ], + "description": "HASH blocks (hashintel/blocks) Renovate configuration", + "dependencyDashboardOSVVulnerabilitySummary": "none" +} diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 0000000..281767f --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,15 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/housekeeping.yml': + - 'actions/checkout@v6.0.2' + '.github/workflows/preflight-target.yml': [] + '.github/workflows/preflight.yml': [] +dependencies: + 'actions/checkout@v6.0.2': + ref: 'v6.0.2' + commit: 'sha1-de0fac2e4500dabe0009e67214ff5f5447ce83dd' + owner_id: 44036562 + repo_id: 197814629 diff --git a/.github/workflows/housekeeping.yml b/.github/workflows/housekeeping.yml new file mode 100644 index 0000000..4bd1c16 --- /dev/null +++ b/.github/workflows/housekeeping.yml @@ -0,0 +1,77 @@ +name: Housekeeping + +on: + pull_request: + paths: + - ".github/workflows/housekeeping.yml" + - ".github/renovate.json" + schedule: + - cron: "0 3 * * *" + workflow_dispatch: + inputs: + repoCache: + description: "Reset or disable the cache?" + type: choice + default: enabled + options: + - enabled + - disabled + - reset + logLevel: + description: "Override default log level" + type: choice + default: info + options: + - "debug" + - "info" + - "warn" + - "error" + overrideSchedule: + description: "Override all schedules" + type: boolean + default: false + dryRun: + description: "Dry run mode" + type: choice + default: disabled + options: + - disabled + - extract + - lookup + - full + +permissions: {} + +jobs: + validate: + name: Validate + if: github.event_name == 'pull_request' + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@v6.0.2 + + - name: Validate Renovate config + run: jq empty .github/renovate.json + + - name: Validate workflow + run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 .github/workflows/housekeeping.yml + + renovate: + name: Dependencies + if: github.event_name != 'pull_request' + permissions: + actions: read + contents: read + id-token: write + uses: hashintel/actions/.github/workflows/housekeeping-dependencies.yml@86f28f5905ca9e8e105ad5cf9a85b46e6d81e7b1 # main + with: + repoCache: ${{ inputs.repoCache || 'enabled' }} + logLevel: ${{ inputs.logLevel || 'info' }} + overrideSchedule: ${{ inputs.overrideSchedule || false }} + dryRun: ${{ inputs.dryRun || 'disabled' }} + secrets: + CF_ACCESS_STAGE_CLIENT_SECRET: ${{ secrets.CF_ACCESS_STAGE_CLIENT_SECRET }} + RENOVATE_TOKEN_ENC_KEY: ${{ secrets.RENOVATE_TOKEN_ENC_KEY }} diff --git a/.github/workflows/preflight-target.yml b/.github/workflows/preflight-target.yml new file mode 100644 index 0000000..4451af5 --- /dev/null +++ b/.github/workflows/preflight-target.yml @@ -0,0 +1,25 @@ +name: Preflight + +on: + pull_request: + paths: + - ".github/workflows/preflight-target.yml" + pull_request_target: + types: [opened, synchronize, reopened, edited] + merge_group: + +permissions: {} + +jobs: + dependencies: + name: Dependencies + permissions: + contents: read + pull-requests: write + uses: hashintel/actions/.github/workflows/preflight-dependencies.yml@86f28f5905ca9e8e105ad5cf9a85b46e6d81e7b1 # main + + pr-title: + name: PR title + permissions: + contents: read + uses: hashintel/actions/.github/workflows/preflight-pr-title.yml@86f28f5905ca9e8e105ad5cf9a85b46e6d81e7b1 # main diff --git a/.github/workflows/preflight.yml b/.github/workflows/preflight.yml new file mode 100644 index 0000000..adf0096 --- /dev/null +++ b/.github/workflows/preflight.yml @@ -0,0 +1,22 @@ +name: Preflight + +on: + pull_request: + # `edited` matters: the todo-comments scan derives its ticket IDs from the PR title. + types: [opened, synchronize, reopened, edited] + merge_group: + +permissions: {} + +jobs: + todo-comments: + name: Todo comments + permissions: + contents: read + uses: hashintel/actions/.github/workflows/preflight-todo-comments.yml@86f28f5905ca9e8e105ad5cf9a85b46e6d81e7b1 # main + + lint: + name: Lint + permissions: + contents: read + uses: hashintel/actions/.github/workflows/preflight-lint.yml@86f28f5905ca9e8e105ad5cf9a85b46e6d81e7b1 # main diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7ee884d --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +node_modules/ +dist/ +.turbo/ +*.tsbuildinfo +.env +.env.* +.DS_Store diff --git a/LICENSE-APACHE.md b/LICENSE-APACHE.md new file mode 100644 index 0000000..1d1b6f8 --- /dev/null +++ b/LICENSE-APACHE.md @@ -0,0 +1,189 @@ +# Apache License + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +- **(a)** You must give any other recipients of the Work or Derivative Works a copy of + this License; and +- **(b)** You must cause any modified files to carry prominent notices stating that You + changed the files; and +- **(c)** You must retain, in the Source form of any Derivative Works that You distribute, + all copyright, patent, trademark, and attribution notices from the Source form + of the Work, excluding those notices that do not pertain to any part of the + Derivative Works; and +- **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any + Derivative Works that You distribute must include a readable copy of the + attribution notices contained within such NOTICE file, excluding those notices + that do not pertain to any part of the Derivative Works, in at least one of the + following places: within a NOTICE text file distributed as part of the + Derivative Works; within the Source form or documentation, if provided along + with the Derivative Works; or, within a display generated by the Derivative + Works, if and wherever such third-party notices normally appear. The contents of + the NOTICE file are for informational purposes only and do not modify the + License. You may add Your own attribution notices within Derivative Works that + You distribute, alongside or as an addendum to the NOTICE text from the Work, + provided that such additional attribution notices cannot be construed as + modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: Apply the Apache License to a specific file + +To apply the Apache License to an individual file, attach the following notice. +The text should be enclosed in the appropriate comment syntax for the file +format. + + Copyright © 2022–, HASH + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT.md b/LICENSE-MIT.md new file mode 100644 index 0000000..e33c1d3 --- /dev/null +++ b/LICENSE-MIT.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright © 2022–, HASH + +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/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..c8a3c26 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,5 @@ +# License + +Licensed under either the [Apache License, Version 2.0](LICENSE-APACHE.md) or [MIT license](LICENSE-MIT.md), at your option. + +Each block directory also contains its license texts and notices. diff --git a/README.md b/README.md index 6c58067..894a3cf 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,27 @@ -# blocks -🧱 Public collection of @blockprotocol blocks +# Blocks + +A public collection of [Block Protocol](https://blockprotocol.org/) blocks developed by HASH. + +The [`blocks/`](blocks) directory contains 22 blocks, including their source code, assets and licenses. See the [block catalog](blocks/README.md) for descriptions and links to published blocks. + +## Development + +These blocks were moved from [`hashintel/labs`](https://github.com/hashintel/labs/tree/510e82a9e0276827e006acb698a48c9190ee026e/blocks), retaining the `blocks/` paths and package versions. + +The imported packages depend on tooling from the original HASH monorepo. A standalone build requires the following setup: + +- A root Yarn workspace and lockfile must be restored. +- The shared `@local/eslint`, `@local/tsconfig` and `@local/hash-isomorphic-utils` packages must be provided or replaced. +- The Yarn patches referenced by the `embed` and `table` packages must be restored. + +These requirements already existed in Labs. Once the shared tooling is available, each block's `package.json` provides its development, build and serve scripts. + +## Repository setup + +The repository uses HASH's shared PR checks and Renovate workflow. Scheduled dependency updates require access to the `VAULT_STAGE_ADDR` and `CF_ACCESS_STAGE_CLIENT_ID` organization variables, plus the `CF_ACCESS_STAGE_CLIENT_SECRET` and `RENOVATE_TOKEN_ENC_KEY` organization secrets. Pull requests validate the workflow and configuration without starting dependency updates. + +Block publishing workflows must also be configured before publishing from this repository. + +## License + +The blocks are dual-licensed under the MIT and Apache 2.0 licenses. Each block directory contains its license texts and notices. diff --git a/blocks/README.md b/blocks/README.md new file mode 100644 index 0000000..12f9983 --- /dev/null +++ b/blocks/README.md @@ -0,0 +1,83 @@ +[github_banner]: https://hash.dev/?utm_medium=organic&utm_source=github_readme_blocks-repo_blocks +[github_star]: https://github.com/hashintel/blocks# +[`address`]: address +[`ai-chat`]: ai-chat +[`ai-image`]: ai-image +[`ai-text`]: ai-text +[`callout`]: callout +[`chart`]: chart +[`code`]: code +[`countdown`]: countdown +[`divider`]: divider +[`embed`]: embed +[`faq`]: faq +[`heading`]: heading +[`how-to`]: how-to +[`image`]: image +[`kanban-board`]: kanban-board +[`minesweeper`]: minesweeper +[`paragraph`]: paragraph +[`person`]: person +[`shuffle`]: shuffle +[`table`]: table +[`timer`]: timer +[`video`]: video + +[![github_banner](https://hash.ai/cdn-cgi/imagedelivery/EipKtqu98OotgfhvKf6Eew/5a38c5f3-6474-4b6c-71e6-ecf01914f000/github)][github_banner] + +[![github_star](https://img.shields.io/github/stars/hashintel/blocks?label=Star%20on%20GitHub&style=social)][github_star] + +# Blocks + +HASH is built around the open [Block Protocol](https://blockprotocol.org) ([@blockprotocol/blockprotocol](https://github.com/blockprotocol/blockprotocol) on GitHub). The current version of HASH is based upon an adapted version of the [Block Protocol Graph Module](https://blockprotocol.org/spec/graph) which will be formalized at a later date. + +Planned features such as [pages](https://hash.ai/guide/pages) and [apps](https://hash.ai/guide/apps) more directly utilize the [blocks](https://hash.ai/guide/pages/blocks) found in this directory, which contains the source code for all public HASH-developed [Block Protocol](https://blockprotocol.org/) blocks. + +## HASH Blocks + +You can preview most HASH blocks on the [`@hash`](https://blockprotocol.org/@hash/blocks) page in the [Þ Hub](https://blockprotocol.org/hub), and direct links are provided below. + +| Directory | Spec Target | Status | Þ Hub URL | Description | +| ---------------- | ----------- | -------------- | -------------------------------------------------------------------------------- | ----------- | +| [`address`] | 0.3 | **Maintained** | [@hash/blocks/address](https://blockprotocol.org/@hash/blocks/address) | | +| [`ai-chat`] | 0.3 | **Maintained** | [@hash/blocks/ai-chat](https://blockprotocol.org/@hash/blocks/ai-chat) | | +| [`ai-image`] | 0.3 | **Maintained** | [@hash/blocks/ai-image](https://blockprotocol.org/@hash/blocks/ai-image) | | +| [`ai-text`] | 0.3 | **Maintained** | [@hash/blocks/ai-text](https://blockprotocol.org/@hash/blocks/ai-text) | | +| [`callout`] | 0.3 | **Maintained** | [@hash/blocks/callout](https://blockprotocol.org/@hash/blocks/callout) | | +| [`chart`] | 0.1 | **Maintained** | [@hash/blocks/callout](https://blockprotocol.org/@hash/blocks/chart) | | +| [`code`] | 0.3 | **Maintained** | [@hash/blocks/code](https://blockprotocol.org/@hash/blocks/code) | | +| [`countdown`] | 0.3 | **Maintained** | [@hash/blocks/countdown](https://blockprotocol.org/@hash/blocks/countdown) | | +| [`divider`] | 0.3 | **Maintained** | [@hash/blocks/divider](https://blockprotocol.org/@hash/blocks/divider) | | +| [`embed`] | 0.1 | Pending Update | | | +| [`faq`] | 0.3 | **Maintained** | [@hash/blocks/faq](https://blockprotocol.org/@hash/blocks/faq) | | +| [`heading`] | 0.3 | **Maintained** | [@hash/blocks/heading](https://blockprotocol.org/@hash/blocks/heading) | | +| [`how-to`] | 0.3 | **Maintained** | [@hash/blocks/how-to](https://blockprotocol.org/@hash/blocks/how-to) | | +| [`image`] | 0.3 | **Maintained** | [@hash/blocks/image](https://blockprotocol.org/@hash/blocks/image) | | +| [`kanban-board`] | 0.3 | **Maintained** | [@hash/blocks/kanban-board](https://blockprotocol.org/@hash/blocks/kanban-board) | | +| [`minesweeper`] | 0.3 | **Maintained** | [@hash/blocks/minesweeper](https://blockprotocol.org/@hash/blocks/minesweeper) | | +| [`paragraph`] | 0.3 | **Maintained** | [@hash/blocks/paragraph](https://blockprotocol.org/@hash/blocks/paragraph) | | +| [`person`] | 0.2 | Pending Update | | | +| [`shuffle`] | 0.3 | **Maintained** | [@hash/blocks/shuffle](https://blockprotocol.org/@hash/blocks/shuffle) | | +| [`table`] | 0.3 | **Maintained** | [@hash/blocks/table](https://blockprotocol.org/@hash/blocks/table) | | +| [`timer`] | 0.3 | **Maintained** | [@hash/blocks/timer](https://blockprotocol.org/@hash/blocks/timer) | | +| [`video`] | 0.3 | **Maintained** | [@hash/blocks/video](https://blockprotocol.org/@hash/blocks/video) | | + +**Please note:** this table/directory contains HASH-developed blocks which are (or were) published to the [Þ Hub](https://blockprotocol.org/hub) under the official `@hash` namespace. This reflects neither the full extent of available Þ blocks, nor even those originally developed by HASH. A number of other publicly-accessible blocks can be found in the `@hashdeps` GitHub org, including the [Calculation Table](https://github.com/hashdeps/calculation-table-block), [Drawing](https://github.com/hashdeps/tldraw-block), and [Pull/Merge Request Overview](https://github.com/hashdeps/github-pr-overview) blocks. + +## Using blocks + +**In the HASH app (production):** Blocks published to the [Þ Hub](https://blockprotocol.org/hub) can be run within HASH via the 'insert block' (aka. 'slash') menu. + +**In the HASH app (development):** While running the HASH app in development mode, in addition to inserting blocks published to the Þ Hub, you can also test locally-developed blocks out by going to any page, clicking on the menu next to an empty block, and pasting in the URL to your block's distribution folder (i.e. the one containing `block-metadata.json`, `block-schema.json`, and the block's code). If you need a way of serving your folder, try [`serve`](https://github.com/vercel/serve). + +**From the command line:** See the [development requirements](../README.md#development) before running the scripts in a block's `package.json`. + +**From other applications:** Blocks published to the [Þ Hub](https://blockprotocol.org/hub) can be used within any embedding application that integrates with the Block Protocol. + +## Creating blocks + +See the [Developing Blocks](https://blockprotocol.org/docs/developing-blocks) page in the [Þ Docs](https://blockprotocol.org/docs) for instructions on developing and publishing your own blocks. + +## Publishing blocks + +Publishing automation needs to be configured for this repository. For instructions on publishing a block to the [Þ Hub](https://blockprotocol.org/hub), see the [Publishing Blocks guide](https://blockprotocol.org/docs/blocks/develop#publish). diff --git a/blocks/address/.gitignore b/blocks/address/.gitignore new file mode 100644 index 0000000..d5dd5ab --- /dev/null +++ b/blocks/address/.gitignore @@ -0,0 +1,3 @@ +dist +node_modules +.blockprotocolrc diff --git a/blocks/address/LICENSE-APACHE.md b/blocks/address/LICENSE-APACHE.md new file mode 100644 index 0000000..1d1b6f8 --- /dev/null +++ b/blocks/address/LICENSE-APACHE.md @@ -0,0 +1,189 @@ +# Apache License + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +- **(a)** You must give any other recipients of the Work or Derivative Works a copy of + this License; and +- **(b)** You must cause any modified files to carry prominent notices stating that You + changed the files; and +- **(c)** You must retain, in the Source form of any Derivative Works that You distribute, + all copyright, patent, trademark, and attribution notices from the Source form + of the Work, excluding those notices that do not pertain to any part of the + Derivative Works; and +- **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any + Derivative Works that You distribute must include a readable copy of the + attribution notices contained within such NOTICE file, excluding those notices + that do not pertain to any part of the Derivative Works, in at least one of the + following places: within a NOTICE text file distributed as part of the + Derivative Works; within the Source form or documentation, if provided along + with the Derivative Works; or, within a display generated by the Derivative + Works, if and wherever such third-party notices normally appear. The contents of + the NOTICE file are for informational purposes only and do not modify the + License. You may add Your own attribution notices within Derivative Works that + You distribute, alongside or as an addendum to the NOTICE text from the Work, + provided that such additional attribution notices cannot be construed as + modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: Apply the Apache License to a specific file + +To apply the Apache License to an individual file, attach the following notice. +The text should be enclosed in the appropriate comment syntax for the file +format. + + Copyright © 2022–, HASH + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/blocks/address/LICENSE-MIT.md b/blocks/address/LICENSE-MIT.md new file mode 100644 index 0000000..e33c1d3 --- /dev/null +++ b/blocks/address/LICENSE-MIT.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright © 2022–, HASH + +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/blocks/address/LICENSE.md b/blocks/address/LICENSE.md new file mode 100644 index 0000000..8686df9 --- /dev/null +++ b/blocks/address/LICENSE.md @@ -0,0 +1,5 @@ +# License + +Licensed under either of the [Apache License, Version 2.0](LICENSE-APACHE.md) or [MIT license](LICENSE-MIT.md) at your option. + +For more information about contributing to this block, see our top-level [CONTRIBUTING](https://github.com/hashintel/hash/blob/main/.github/CONTRIBUTING.md) policy. diff --git a/blocks/address/README.md b/blocks/address/README.md new file mode 100644 index 0000000..ae73747 --- /dev/null +++ b/blocks/address/README.md @@ -0,0 +1,5 @@ +The address block powered by the Mapbox API allows for finding and displaying information about a specific address or location. + +Whenever an address is selected, the Graph Modules's `createEntity` method is called to save the address information into an `Address` entity and the address map into a `RemoteFile` entity, which are linked to the block. + +The block also stores its state locally in `title` (the address display title), `description`, `addressId` and `zoomLevel` properties. diff --git a/blocks/address/eslint.config.js b/blocks/address/eslint.config.js new file mode 100644 index 0000000..5b6bb9d --- /dev/null +++ b/blocks/address/eslint.config.js @@ -0,0 +1,3 @@ +import { createBlock } from "@local/eslint/deprecated"; + +export default createBlock(import.meta.dirname); diff --git a/blocks/address/package.json b/blocks/address/package.json new file mode 100644 index 0000000..d35d24c --- /dev/null +++ b/blocks/address/package.json @@ -0,0 +1,86 @@ +{ + "name": "@blocks/address", + "version": "0.1.2", + "private": true, + "description": "Search for an address using the Mapbox Address Autofill and Mapbox Static Images APIs", + "keywords": [ + "blockprotocol", + "blocks", + "block" + ], + "repository": { + "type": "git", + "url": "https://github.com/hashintel/blocks.git#main", + "directory": "blocks/address" + }, + "license": "(MIT OR Apache-2.0)", + "author": "HASH", + "type": "module", + "scripts": { + "build": "block-scripts build", + "codegen": "block-scripts codegen && yarn format", + "dev": "block-scripts dev", + "fix:eslint": "eslint --fix .", + "format": "prettier --write --ignore-unknown src/types/generated/*.ts", + "lint:eslint": "eslint --report-unused-disable-directives .", + "lint:tsc": "tsc --noEmit", + "serve": "block-scripts serve" + }, + "prettier": { + "printWidth": 80, + "trailingComma": "all" + }, + "dependencies": { + "@blockprotocol/graph": "0.3.4", + "@blockprotocol/service": "0.1.4", + "@fortawesome/free-regular-svg-icons": "6.7.2", + "@fortawesome/free-solid-svg-icons": "6.7.2", + "@hashintel/block-design-system": "0.0.5", + "@hashintel/design-system": "0.0.9-canary.2", + "@mui/material": "5.18.0", + "lodash.debounce": "4.0.8", + "react-sizeme": "3.0.2", + "rooks": "7.14.1", + "uuid": "13.0.1" + }, + "devDependencies": { + "@local/eslint": "0.0.0-private", + "@types/lodash.debounce": "4.0.9", + "@types/react-dom": "19.1.7", + "block-scripts": "0.3.4", + "eslint": "10.0.3", + "mock-block-dock": "0.1.9", + "prettier": "3.8.1", + "react": "19.1.1", + "react-dom": "19.1.1", + "typescript": "5.9.3" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "block-scripts": { + "port": 63212 + }, + "blockprotocol": { + "blockType": { + "entryPoint": "react" + }, + "displayName": "Address", + "icon": "public/address.svg", + "image": "public/block-preview.png", + "name": "@hash/address", + "protocol": "0.3", + "blockEntityType": "https://blockprotocol.org/@hash/types/entity-type/address-block/v/4", + "codegen": { + "outputFolder": "src/types/generated", + "targets": { + "block-entity.ts": [ + { + "blockEntityType": true + } + ] + } + } + } +} diff --git a/blocks/address/public/address.svg b/blocks/address/public/address.svg new file mode 100644 index 0000000..549b694 --- /dev/null +++ b/blocks/address/public/address.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/blocks/address/public/block-preview.png b/blocks/address/public/block-preview.png new file mode 100644 index 0000000..1a380d1 Binary files /dev/null and b/blocks/address/public/block-preview.png differ diff --git a/blocks/address/src/address-card.tsx b/blocks/address/src/address-card.tsx new file mode 100644 index 0000000..327e1b7 --- /dev/null +++ b/blocks/address/src/address-card.tsx @@ -0,0 +1,363 @@ +import { faCopy } from "@fortawesome/free-regular-svg-icons"; +import { + faArrowRotateLeft, + faMinus, + faPlus, +} from "@fortawesome/free-solid-svg-icons"; +import { EditableField } from "@hashintel/block-design-system"; +import { Button, FontAwesomeIcon, Skeleton } from "@hashintel/design-system"; +import { + Box, + CircularProgress, + Fade, + // @todo: https://linear.app/hash/issue/H-3769/investigate-new-eslint-errors + // eslint-disable-next-line no-restricted-imports + Link, + Stack, + Typography, + useTheme, +} from "@mui/material"; +import { useCallback, useEffect, useMemo, useState } from "react"; + +import { ContentStack } from "./address-card/content-stack"; +import { MapWrapper } from "./address-card/map-wrapper"; +import { StyledCard } from "./address-card/styled-card"; +import { AppleIcon } from "./icons/apple-icon"; +import { GoogleIcon } from "./icons/google-icon"; +import { MapButton } from "./map-button"; + +type AddressCardProps = { + title?: string; + description?: string; + fullAddress: string; + mapUrl?: string; + mapError?: boolean; + hovered: boolean; + readonly?: boolean; + isMobile?: boolean; + onClose: () => void; + updateTitle: (title: string) => void; + updateDescription: (description: string) => void; + incrementZoomLevel?: () => void; + decrementZoomLevel?: () => void; +}; + +export const AddressCard = ({ + title, + fullAddress, + description, + mapUrl, + mapError, + hovered, + readonly, + isMobile, + onClose, + updateTitle, + updateDescription, + incrementZoomLevel, + decrementZoomLevel, +}: AddressCardProps) => { + const theme = useTheme(); + const [titleValue, setTitleValue] = useState(title); + const [descriptionValue, setDescriptionValue] = useState(description); + + useEffect(() => { + if (title !== titleValue) { + setTitleValue(title); + } + // We want to override titleValue with value only when title changes + // otherwise we would lose the changes made to titleValue whenever it is set + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [title]); + + useEffect(() => { + if (description !== descriptionValue) { + setDescriptionValue(description); + } + // We want to override descriptionValue with value only when description changes + // otherwise we would lose the changes made to descriptionValue whenever it is set + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [description]); + + const [googleMapsUrl, appleMapsUrl] = useMemo( + () => + fullAddress + ? [ + `https://www.google.com/maps?q=${encodeURI(fullAddress)}`, + `http://maps.apple.com/?q=${encodeURI(fullAddress)}`, + ] + : ["", ""], + [fullAddress], + ); + + const copyToClipboard = useCallback(() => { + if (fullAddress) { + void navigator.clipboard.writeText(fullAddress); + } + }, [fullAddress]); + + return ( + + + + setTitleValue(event.target.value)} + onBlur={(event) => updateTitle(event.target.value)} + readonly={readonly} + sx={{ + fontWeight: 700, + fontSize: 21, + lineHeight: 1, + letterSpacing: "-0.02em", + color: theme.palette.common.black, + }} + /> + + + {fullAddress ? ( + palette.gray[90], + }} + > + {fullAddress} + + ) : null} + {readonly ? ( + + ) : null} + + + + {googleMapsUrl ? ( + + + + Open in Google Maps + + + ) : null} + {appleMapsUrl ? ( + + + + Open in Apple Maps + + + ) : null} + + + setDescriptionValue(event.target.value)} + onBlur={(event) => { + updateDescription(event.target.value); + }} + readonly={readonly} + sx={{ + fontWeight: 500, + fontSize: 14, + lineHeight: 1.3, + letterSpacing: "-0.02em", + color: theme.palette.gray[90], + }} + /> + + + + {!readonly ? ( + + + + + + + ) : null} + + {mapUrl ? ( + + palette.common.black, + opacity: 0.5, + fontSize: 9, + lineHeight: "11px", + }} + > + ©{" "} + + Mapbox + {" "} + ©{" "} + + OpenStreetMap + + + + ) : mapError ? ( + palette.common.black, + opacity: 0.5, + fontSize: 12, + lineHeight: 1, + }} + > + There was a problem loading the map + + ) : ( + palette.gray[40] }} /> + )} + + {!readonly ? ( + + + + ) : null} + + + ); +}; + +export const AddressCardLoading = ({ isMobile }: { isMobile: boolean }) => { + return ( + + + + + + + + + + + + + + + + + palette.gray[40] }} /> + + + ); +}; diff --git a/blocks/address/src/address-card/content-stack.tsx b/blocks/address/src/address-card/content-stack.tsx new file mode 100644 index 0000000..6de7e81 --- /dev/null +++ b/blocks/address/src/address-card/content-stack.tsx @@ -0,0 +1,29 @@ +import { Stack } from "@mui/material"; +import type { ReactNode } from "react"; + +export const ContentStack = ({ + children, + isMobile, +}: { + children: ReactNode; + isMobile?: boolean; +}) => ( + + {children} + +); diff --git a/blocks/address/src/address-card/map-wrapper.tsx b/blocks/address/src/address-card/map-wrapper.tsx new file mode 100644 index 0000000..a6cbc42 --- /dev/null +++ b/blocks/address/src/address-card/map-wrapper.tsx @@ -0,0 +1,32 @@ +import { Box } from "@mui/material"; +import type { ReactNode } from "react"; + +export const MapWrapper = ({ + children, + isMobile, +}: { + children: ReactNode; + isMobile?: boolean; +}) => ( + ({ + display: "flex", + alignItems: "center", + justifyContent: "center", + position: "relative", + background: palette.gray[10], + borderLeft: `1px solid ${palette.gray[20]}`, + width: 1, + minHeight: 300, + + ...(isMobile + ? { + width: 1, + height: 300, + } + : {}), + })} + > + {children} + +); diff --git a/blocks/address/src/address-card/styled-card.tsx b/blocks/address/src/address-card/styled-card.tsx new file mode 100644 index 0000000..908f248 --- /dev/null +++ b/blocks/address/src/address-card/styled-card.tsx @@ -0,0 +1,29 @@ +import { Card } from "@mui/material"; +import type { ReactNode } from "react"; + +export const StyledCard = ({ + children, + isMobile, +}: { + children: ReactNode; + isMobile?: boolean; +}) => ( + ({ + display: "flex", + maxWidth: 800, + width: 1, + border: `1px solid ${palette.gray[20]}`, + borderRadius: 2.5, + boxShadow: "none", + ...(isMobile + ? { + flexDirection: "column", + width: 1, + } + : {}), + })} + > + {children} + +); diff --git a/blocks/address/src/app.tsx b/blocks/address/src/app.tsx new file mode 100644 index 0000000..7de2512 --- /dev/null +++ b/blocks/address/src/app.tsx @@ -0,0 +1,702 @@ +import { + type BlockComponent, + useEntitySubgraph, + useGraphBlockModule, +} from "@blockprotocol/graph/react"; +import type { AutofillSuggestion } from "@blockprotocol/service/dist/mapbox-types"; +import { faSearch } from "@fortawesome/free-solid-svg-icons"; +import { + BlockErrorMessage, + BlockSettingsButton, + GetHelpLink, +} from "@hashintel/block-design-system"; +import { Autocomplete, FontAwesomeIcon } from "@hashintel/design-system"; +import { theme } from "@hashintel/design-system/theme"; +import { + CircularProgress, + Collapse, + Fade, + ThemeProvider, + Typography, +} from "@mui/material"; +import { autocompleteClasses } from "@mui/material/Autocomplete"; +import Box from "@mui/material/Box"; +import Stack from "@mui/material/Stack"; +import { useCallback, useMemo, useRef, useState } from "react"; +import { SizeMe } from "react-sizeme"; + +import { AddressCard, AddressCardLoading } from "./address-card"; +import { MapboxIcon } from "./icons/mapbox-icon"; +import { TriangleExclamationIcon } from "./icons/triangle-exclamation-icon"; +import type { + Address as AddressEntity, + AddressBlock, + AddressBlockHasAddressLink, + AddressBlockHasMapImageLink, + AddressBlockOutgoingLinkAndTarget, + AddressBlockOutgoingLinksByLinkEntityTypeId, + BlockEntity, + HasAddress, + HasMapImage, + Image, +} from "./types/generated/block-entity"; +import type { Address } from "./use-mapbox"; +import { useMapbox } from "./use-mapbox"; + +const INPUT_MAX_WIDTH = 420; +const DEFAULT_ZOOM_LEVEL = 16; +const ZOOM_LEVEL_STEP_SIZE = 2; +const MAX_ZOOM_LEVEL = 20; +const MIN_ZOOM_LEVEL = 10; + +type BlockEntityKey = keyof BlockEntity["properties"]; +type AddressEntityKey = keyof AddressEntity["properties"]; +type FileUrlEntityKey = keyof Image["properties"]; +type LinkType = keyof AddressBlockOutgoingLinksByLinkEntityTypeId; + +// Root entity property types +export const titleKey: BlockEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/title/"; +export const descriptionKey: BlockEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/description/"; +export const addressIdKey: BlockEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/mapbox-address-id/"; +export const zoomLevelKey: BlockEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/mapbox-static-image-zoom-level/"; + +// Address entity property types +export const regionKey: AddressEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/address-level-1/"; +export const postalCodeKey: AddressEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/postal-code/"; +export const streetKey: AddressEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/street-address-line-1/"; +export const countryKey: AddressEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/alpha-2-country-code/"; +export const fullAddressKey: AddressEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/mapbox-full-address/"; + +// Remote File property types +export const fileUrlKey: FileUrlEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/file-url/"; + +// Link entity types +export const hasAddressLink: LinkType = + "https://blockprotocol.org/@hash/types/entity-type/has-address/v/1"; +export const hasMapImageLink: LinkType = + "https://blockprotocol.org/@hash/types/entity-type/has-map-image/v/2"; + +// Relevant Entity types +export const addressTypeId = + "https://blockprotocol.org/@hash/types/entity-type/address/v/2"; + +const getOptionLabel = (option: AutofillSuggestion | string) => + typeof option === "string" ? option : (option.place_name ?? ""); + +export const App: BlockComponent = ({ + graph: { blockEntitySubgraph, readonly }, +}) => { + const blockRootRef = useRef(null); + /* @ts-expect-error –– @todo H-3839 packages in BP repo needs updating, or this package updating to use graph in this repo */ + const { graphModule } = useGraphBlockModule(blockRootRef); + const { rootEntity: blockEntity, linkedEntities } = useEntitySubgraph< + AddressBlock, + AddressBlockOutgoingLinkAndTarget[] + >(blockEntitySubgraph); + + const { + metadata: { + recordId: { entityId }, + entityTypeId, + }, + properties, + } = blockEntity; + + const [autocompleteFocused, setAutocompleteFocused] = useState(false); + const [hovered, setHovered] = useState(false); + const [mobileSettingsExpanded, setMobileSettingsExpanded] = useState(false); + const [animatingIn, setAnimatingIn] = useState(); + const [animatingOut, setAnimatingOut] = useState(false); + + const { + [titleKey]: title, + [descriptionKey]: description, + [addressIdKey]: addressId, + } = properties; + + const zoomLevel = properties[zoomLevelKey] ?? DEFAULT_ZOOM_LEVEL; + + const addressLinkedEntity = useMemo( + () => + linkedEntities.find( + ({ linkEntity }) => linkEntity.metadata.entityTypeId === hasAddressLink, + ) as AddressBlockHasAddressLink | undefined, + [linkedEntities], + ); + + const addressEntity: AddressEntity | undefined = + addressLinkedEntity?.rightEntity; + const addressLinkEntity: HasAddress | undefined = + addressLinkedEntity?.linkEntity; + + const remoteFullAddress = addressEntity?.properties[fullAddressKey]; + + const mapLinkedEntity = useMemo( + () => + linkedEntities.find(({ linkEntity }) => { + return ( + linkEntity.metadata.entityTypeId === hasMapImageLink && + (linkEntity as HasMapImage).properties[zoomLevelKey] === zoomLevel && + (linkEntity as HasMapImage).properties[addressIdKey] === addressId + ); + }) as AddressBlockHasMapImageLink | undefined, + [linkedEntities, zoomLevel, addressId], + ); + + const mapEntity: Image | undefined = mapLinkedEntity?.rightEntity; + const mapLinkEntity: HasMapImage | undefined = mapLinkedEntity?.linkEntity; + + const mapUrl = mapEntity?.properties[fileUrlKey]; + + const availableZoomLevels = useMemo(() => { + return linkedEntities + .filter(({ linkEntity }) => { + return ( + linkEntity.metadata.entityTypeId === hasMapImageLink && + (linkEntity as HasMapImage).properties[addressIdKey] === addressId + ); + }) + .map( + ({ linkEntity }) => + (linkEntity as HasMapImage).properties[zoomLevelKey], + ); + }, [linkedEntities, addressId]); + + const updateBlockAddress = async (address?: Address) => { + if (readonly) { + return; + } + + await graphModule.updateEntity({ + data: { + entityId, + entityTypeId, + properties: address + ? { + [addressIdKey]: address.addressId, + [titleKey]: address.featureName, + [descriptionKey]: "", + [zoomLevelKey]: DEFAULT_ZOOM_LEVEL, + } + : {}, + }, + }); + }; + + const updateTitle = async (nweTitle: string) => { + if (readonly) { + return; + } + + await graphModule.updateEntity({ + data: { + entityId, + entityTypeId, + properties: { + ...properties, + [titleKey]: nweTitle, + }, + }, + }); + }; + + const updateDescription = async (newDescription: string) => { + if (readonly) { + return; + } + + await graphModule.updateEntity({ + data: { + entityId, + entityTypeId, + properties: { + ...properties, + [descriptionKey]: newDescription, + }, + }, + }); + }; + + const updateZoomLevel = useCallback( + async (newZoomLevel: number) => { + if (readonly) { + return; + } + + await graphModule.updateEntity({ + data: { + entityId, + entityTypeId, + properties: { + ...properties, + [zoomLevelKey]: newZoomLevel, + }, + }, + }); + }, + [entityId, entityTypeId, graphModule, properties, readonly], + ); + + const incrementZoomLevel = useCallback(async () => { + if (zoomLevel <= MAX_ZOOM_LEVEL - ZOOM_LEVEL_STEP_SIZE) { + await updateZoomLevel(zoomLevel + ZOOM_LEVEL_STEP_SIZE); + } + }, [zoomLevel, updateZoomLevel]); + + const decrementZoomLevel = useCallback(async () => { + if (zoomLevel >= MIN_ZOOM_LEVEL + ZOOM_LEVEL_STEP_SIZE) { + await updateZoomLevel(zoomLevel - ZOOM_LEVEL_STEP_SIZE); + } + }, [zoomLevel, updateZoomLevel]); + + const uploadMap = async (mapFile: File, mapAddressId: string) => { + if (readonly) { + return; + } + + await graphModule + .uploadFile({ + data: { + file: mapFile, + description: remoteFullAddress, + }, + }) + .then(async (uploadFileResponse) => { + const fileEntityId = + uploadFileResponse.data?.metadata.recordId.entityId; + + if (!mapLinkEntity && mapAddressId && fileEntityId) { + await graphModule.createEntity({ + data: { + entityTypeId: hasMapImageLink, + properties: { + [zoomLevelKey]: zoomLevel, + [addressIdKey]: mapAddressId, + }, + linkData: { + leftEntityId: entityId, + rightEntityId: fileEntityId, + }, + }, + }); + } + }); + }; + + const updateAddress = async (address?: Address) => { + if (readonly ?? !address) { + return; + } + + const { + addressRegion, + postalCode, + streetAddress, + addressCountry, + fullAddress, + } = address; + + const addressProperties = { + [regionKey]: addressRegion, + [postalCodeKey]: postalCode, + [streetKey]: streetAddress, + [countryKey]: addressCountry, + [fullAddressKey]: fullAddress, + }; + + const createAddressEntityResponse = await (!addressEntity + ? graphModule.createEntity({ + data: { + entityTypeId: addressTypeId, + properties: addressProperties, + }, + }) + : graphModule.updateEntity({ + data: { + entityId: addressEntity.metadata.recordId.entityId, + entityTypeId: addressEntity.metadata.entityTypeId, + properties: addressProperties, + }, + })); + + const addressEntityId = + createAddressEntityResponse.data?.metadata.recordId.entityId; + + if (addressEntityId) { + if (!addressLinkEntity) { + await graphModule.createEntity({ + data: { + entityTypeId: hasAddressLink, + properties: {}, + linkData: { + leftEntityId: entityId, + rightEntityId: addressEntityId, + }, + }, + }); + } + } + }; + + const onSelectAddress = (address: Address) => { + void updateAddress(address); + void updateBlockAddress(address); + }; + + const { + suggestions, + suggestionsLoading, + suggestionsError, + mapError, + fetchSuggestions, + selectAddress, + selectedAddress, + selectedAddressLoading, + } = useMapbox( + blockRootRef, + zoomLevel, + !availableZoomLevels.includes(zoomLevel), + onSelectAddress, + uploadMap, + addressId, + ); + + const resetBlock = async () => { + if (readonly) { + return; + } + + selectAddress(); + void updateBlockAddress(); + + // Remove the address link and all map links + for (const { linkEntity } of linkedEntities) { + await graphModule.deleteEntity({ + data: { + entityId: linkEntity.metadata.recordId.entityId, + }, + }); + } + }; + + const schema = useMemo(() => { + return addressEntity + ? JSON.stringify({ + "@context": "http://schema.org", + "@type": "PostalAddress", + addressCountry: addressEntity.properties[countryKey], + addressRegion: addressEntity.properties[regionKey], + postalCode: addressEntity.properties[postalCodeKey], + streetAddress: addressEntity.properties[streetKey], + }) + : null; + }, [addressEntity]); + + const displayTitle = title ?? selectedAddress?.featureName; + const displayFullAddress = selectedAddress?.fullAddress ?? remoteFullAddress; + + const shouldDisplayCard = !!displayFullAddress || selectedAddressLoading; + + return ( + <> + {schema ? ( + \n", + "initialHeight": 340 + } + ] + }, + { + "name": "YouTube", + "description": "Embed YouTube Video", + "icon": "public/youtube.svg", + "properties": { + "embedType": "YouTube" + }, + "examples": [ + { + "initialHtml": "", + "initialWidth": 600, + "initialHeight": 340 + } + ] + }, + { + "name": "Spotify", + "description": "Embed Spotify Song", + "icon": "public/spotify.svg", + "properties": { + "embedType": "Spotify" + }, + "examples": [ + { + "initialHtml": "", + "initialWidth": 600, + "initialHeight": 340 + } + ] + }, + { + "name": "HASH", + "description": "Embed Simulation", + "icon": "public/hash.svg", + "properties": { + "embedType": "HASH" + }, + "examples": [ + { + "initialHtml": "", + "initialWidth": 600, + "initialHeight": 340 + } + ] + } +] diff --git a/blocks/faq/.npmignore b/blocks/faq/.npmignore new file mode 100644 index 0000000..72c3280 --- /dev/null +++ b/blocks/faq/.npmignore @@ -0,0 +1,4 @@ +/dist +/.turbo +.blockprotocolrc +CHANGELOG.md diff --git a/blocks/faq/LICENSE-APACHE.md b/blocks/faq/LICENSE-APACHE.md new file mode 100644 index 0000000..1d1b6f8 --- /dev/null +++ b/blocks/faq/LICENSE-APACHE.md @@ -0,0 +1,189 @@ +# Apache License + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +- **(a)** You must give any other recipients of the Work or Derivative Works a copy of + this License; and +- **(b)** You must cause any modified files to carry prominent notices stating that You + changed the files; and +- **(c)** You must retain, in the Source form of any Derivative Works that You distribute, + all copyright, patent, trademark, and attribution notices from the Source form + of the Work, excluding those notices that do not pertain to any part of the + Derivative Works; and +- **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any + Derivative Works that You distribute must include a readable copy of the + attribution notices contained within such NOTICE file, excluding those notices + that do not pertain to any part of the Derivative Works, in at least one of the + following places: within a NOTICE text file distributed as part of the + Derivative Works; within the Source form or documentation, if provided along + with the Derivative Works; or, within a display generated by the Derivative + Works, if and wherever such third-party notices normally appear. The contents of + the NOTICE file are for informational purposes only and do not modify the + License. You may add Your own attribution notices within Derivative Works that + You distribute, alongside or as an addendum to the NOTICE text from the Work, + provided that such additional attribution notices cannot be construed as + modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: Apply the Apache License to a specific file + +To apply the Apache License to an individual file, attach the following notice. +The text should be enclosed in the appropriate comment syntax for the file +format. + + Copyright © 2022–, HASH + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/blocks/faq/LICENSE-MIT.md b/blocks/faq/LICENSE-MIT.md new file mode 100644 index 0000000..e33c1d3 --- /dev/null +++ b/blocks/faq/LICENSE-MIT.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright © 2022–, HASH + +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/blocks/faq/LICENSE.md b/blocks/faq/LICENSE.md new file mode 100644 index 0000000..8686df9 --- /dev/null +++ b/blocks/faq/LICENSE.md @@ -0,0 +1,5 @@ +# License + +Licensed under either of the [Apache License, Version 2.0](LICENSE-APACHE.md) or [MIT license](LICENSE-MIT.md) at your option. + +For more information about contributing to this block, see our top-level [CONTRIBUTING](https://github.com/hashintel/hash/blob/main/.github/CONTRIBUTING.md) policy. diff --git a/blocks/faq/README.md b/blocks/faq/README.md new file mode 100644 index 0000000..cf11529 --- /dev/null +++ b/blocks/faq/README.md @@ -0,0 +1,3 @@ +This block typically allows the user to create a frequently asked questions section. + +Each section consists of a `question` and `answer` that is saved on a `FAQ section` entity that is linked to the block entity. diff --git a/blocks/faq/eslint.config.js b/blocks/faq/eslint.config.js new file mode 100644 index 0000000..5b6bb9d --- /dev/null +++ b/blocks/faq/eslint.config.js @@ -0,0 +1,3 @@ +import { createBlock } from "@local/eslint/deprecated"; + +export default createBlock(import.meta.dirname); diff --git a/blocks/faq/package.json b/blocks/faq/package.json new file mode 100644 index 0000000..218b3fc --- /dev/null +++ b/blocks/faq/package.json @@ -0,0 +1,80 @@ +{ + "name": "@blocks/faq", + "version": "0.1.3", + "private": true, + "description": "Create a frequently asked questions section", + "keywords": [ + "blockprotocol", + "blocks", + "block" + ], + "repository": { + "type": "git", + "url": "https://github.com/hashintel/blocks.git#main", + "directory": "blocks/faq" + }, + "license": "(MIT OR Apache-2.0)", + "author": "HASH", + "type": "module", + "scripts": { + "build": "block-scripts build", + "codegen": "block-scripts codegen && yarn format", + "dev": "block-scripts dev", + "fix:eslint": "eslint --fix .", + "format": "prettier --write --ignore-unknown src/types/generated/*.ts", + "lint:eslint": "eslint --report-unused-disable-directives .", + "lint:tsc": "tsc --noEmit", + "serve": "block-scripts serve" + }, + "prettier": { + "printWidth": 80, + "trailingComma": "all" + }, + "dependencies": { + "@blockprotocol/graph": "0.3.4", + "@hashintel/block-design-system": "0.0.5", + "@hashintel/design-system": "0.0.9-canary.2", + "@mui/material": "5.18.0", + "uuid": "13.0.1" + }, + "devDependencies": { + "@local/eslint": "0.0.0-private", + "@types/react-dom": "19.1.7", + "block-scripts": "0.3.4", + "eslint": "10.0.3", + "mock-block-dock": "0.1.9", + "prettier": "3.8.1", + "react": "19.1.1", + "react-dom": "19.1.1", + "typescript": "5.9.3" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "block-scripts": { + "port": 63212 + }, + "blockprotocol": { + "blockType": { + "entryPoint": "react" + }, + "displayName": "FAQ", + "examples": [], + "icon": "public/faq-icon.svg", + "image": "public/block-preview.png", + "name": "@hash/faq", + "protocol": "0.3", + "blockEntityType": "https://blockprotocol.org/@hash/types/entity-type/faq-block/v/1", + "codegen": { + "outputFolder": "src/types/generated", + "targets": { + "block-entity.ts": [ + { + "blockEntityType": true + } + ] + } + } + } +} diff --git a/blocks/faq/public/block-preview.png b/blocks/faq/public/block-preview.png new file mode 100644 index 0000000..73e7c81 Binary files /dev/null and b/blocks/faq/public/block-preview.png differ diff --git a/blocks/faq/public/faq-icon.svg b/blocks/faq/public/faq-icon.svg new file mode 100644 index 0000000..c601a6b --- /dev/null +++ b/blocks/faq/public/faq-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/blocks/faq/src/app.tsx b/blocks/faq/src/app.tsx new file mode 100644 index 0000000..9aa2769 --- /dev/null +++ b/blocks/faq/src/app.tsx @@ -0,0 +1,454 @@ +import type { LinkEntityAndRightEntity } from "@blockprotocol/graph"; +import { + type BlockComponent, + useEntitySubgraph, + useGraphBlockModule, +} from "@blockprotocol/graph/react"; +import { EditableField, GetHelpLink } from "@hashintel/block-design-system"; +import { Button, faPlus, FontAwesomeIcon } from "@hashintel/design-system"; +import { theme } from "@hashintel/design-system/theme"; +import { + Card, + Collapse, + Fade, + Stack, + Switch, + ThemeProvider, + Typography, +} from "@mui/material"; +import Box from "@mui/material/Box"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { v4 as uuid } from "uuid"; + +import { Question } from "./question"; +import type { + BlockEntity, + FAQBlockOutgoingLinksByLinkEntityTypeId, + FrequentlyAskedQuestion, + FrequentlyAskedQuestionProperties, +} from "./types/generated/block-entity"; + +type RootEntityKey = keyof BlockEntity["properties"]; +type QuestionEntityKey = keyof FrequentlyAskedQuestionProperties; + +type LinkType = keyof FAQBlockOutgoingLinksByLinkEntityTypeId; + +// Property types +export const titleKey: RootEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/title/"; +export const descriptionKey: RootEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/description/"; +export const sectionsShouldBeNumberedKey: RootEntityKey = + "https://blockprotocol.org/@hash/types/property-type/sections-should-be-numbered/"; +export const answerVisibilityIsConfigurableKey: RootEntityKey = + "https://blockprotocol.org/@hash/types/property-type/answer-visibility-is-configurable/"; +export const questionKey: QuestionEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/question/"; +export const answerKey: QuestionEntityKey = + "https://blockprotocol.org/@blockprotocol/types/property-type/answer/"; + +// Relevant Entity Types +const frequentlyAskedQuestionType = + "https://blockprotocol.org/@hash/types/entity-type/frequently-asked-question/v/1"; + +// Link Entity Types +const hasFrequentlyAskedQuestion: LinkType = + "https://blockprotocol.org/@hash/types/entity-type/has-frequently-asked-question/v/1"; + +export type QuestionOrAnswer = typeof questionKey | typeof answerKey; +export type EntityType = typeof frequentlyAskedQuestionType; + +export const App: BlockComponent = ({ + graph: { blockEntitySubgraph, readonly }, +}) => { + const blockRootRef = useRef(null); + /* @ts-expect-error –– @todo H-3839 packages in BP repo needs updating, or this package updating to use graph in this repo */ + const { graphModule } = useGraphBlockModule(blockRootRef); + const { rootEntity: blockEntity, linkedEntities } = + useEntitySubgraph(blockEntitySubgraph); + + const { + metadata: { + recordId: { entityId }, + entityTypeId, + }, + properties, + } = blockEntity; + + const { + [titleKey]: title, + [descriptionKey]: description, + [sectionsShouldBeNumberedKey]: shouldDisplayQuestionNumbers, + [answerVisibilityIsConfigurableKey]: shouldDisplayQuestionToggles, + } = properties; + + const questionLinkedEntities: LinkEntityAndRightEntity[] = useMemo( + () => + linkedEntities.filter( + ({ linkEntity }) => + linkEntity.metadata.entityTypeId === hasFrequentlyAskedQuestion, + ), + [linkedEntities], + ); + + const questionEntities: FrequentlyAskedQuestion[] | undefined = + questionLinkedEntities.map((linkEntity) => linkEntity.rightEntity); + + const [hovered, setHovered] = useState(false); + const [titleValue, setTitleValue] = useState(title); + const [descriptionValue, setDescriptionValue] = useState(description); + const [displayNumbers, setDisplayNumbers] = useState( + shouldDisplayQuestionNumbers ?? true, + ); + const [displayToggles, setDisplayToggles] = useState( + shouldDisplayQuestionToggles ?? true, + ); + const [questions, setQuestions] = useState< + { + id: string; + properties: FrequentlyAskedQuestionProperties; + animatingOut?: boolean; + }[] + >( + questionEntities.map((questionEntity) => ({ + id: questionEntity.metadata.recordId.entityId, + properties: questionEntity.properties, + })), + ); + + const updateField = async (value: string | boolean, field: RootEntityKey) => { + await graphModule.updateEntity({ + data: { + entityId, + entityTypeId, + properties: { + ...properties, + [field]: value, + }, + }, + }); + }; + + const createFrequentlyAskedQuestionEntity = useCallback(async () => { + if (readonly) { + return; + } + + const createEntityResponse = await graphModule.createEntity({ + data: { + entityTypeId: frequentlyAskedQuestionType, + properties: {}, + }, + }); + + const createdEntityId = + createEntityResponse.data?.metadata.recordId.entityId; + + if (createdEntityId) { + await graphModule.createEntity({ + data: { + entityTypeId: hasFrequentlyAskedQuestion, + properties: {}, + linkData: { + leftEntityId: entityId, + rightEntityId: createdEntityId, + }, + }, + }); + } + }, [graphModule, entityId, readonly]); + + const addQuestion = useCallback(async () => { + setQuestions([...questions, { id: uuid(), properties: {} }]); + await createFrequentlyAskedQuestionEntity(); + }, [questions, createFrequentlyAskedQuestionEntity]); + + const updateQuestionField = async ( + index: number, + value: string, + field: QuestionOrAnswer, + ) => { + const questionEntity = questionEntities[index]; + + if (!questionEntity) { + return; + } + + await graphModule.updateEntity({ + data: { + entityId: questionEntity.metadata.recordId.entityId, + entityTypeId: frequentlyAskedQuestionType, + properties: { + ...questionEntity.properties, + [field]: value, + }, + }, + }); + }; + + const removeQuestion = (index: number) => { + setQuestions( + questions.map((question, questionIndex) => { + if (index === questionIndex) { + return { ...question, animatingOut: true }; + } + return question; + }), + ); + }; + + useEffect(() => { + if (!readonly && !questionEntities.length) { + void addQuestion(); + } + // We only want to run this once when the block is initiated + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const schema = useMemo(() => { + const questionsWithTitle = questionEntities.filter( + ({ properties: { [questionKey]: schemaQuestion } }) => !!schemaQuestion, + ); + + return JSON.stringify({ + "@context": "http://schema.org", + "@type": "FAQPage", + mainEntity: questionsWithTitle.map( + ({ + properties: { + [questionKey]: schemaQuestion, + [answerKey]: schemaAnswer, + }, + }) => ({ + "@type": "Question", + name: schemaQuestion, + acceptedAnswer: { + "@type": "Answer", + text: schemaAnswer ?? schemaQuestion, + }, + }), + ), + }); + }, [questionEntities]); + + const shouldDisplayIntro = !!title || !!description || !readonly; + + return ( + <> +