Merge branch 'main' into snug.moe

This commit is contained in:
vib 2022-09-06 22:55:45 +03:00
commit 741bb2e2b4
67 changed files with 1463 additions and 1737 deletions

3
.gitignore vendored
View file

@ -59,3 +59,6 @@ ormconfig.json
packages/client/.yarn/* packages/client/.yarn/*
packages/backend/.yarn/* packages/backend/.yarn/*
packages/sw/.yarn/* packages/sw/.yarn/*
# TypeScript
tsconfig.tsbuildinfo

3
.gitmodules vendored
View file

@ -1,3 +0,0 @@
[submodule "misskey-assets"]
path = misskey-assets
url = https://github.com/misskey-dev/assets.git

View file

@ -1,7 +1,6 @@
{ {
"recommendations": [ "recommendations": [
"editorconfig.editorconfig", "editorconfig.editorconfig",
"eg2.vscode-npm-script",
"dbaeumer.vscode-eslint", "dbaeumer.vscode-eslint",
"Vue.volar", "Vue.volar",
"Vue.vscode-typescript-vue-plugin" "Vue.vscode-typescript-vue-plugin"

View file

@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
This changelog covers changes since Misskey v12.111.1, the version prior to the FoundKey fork. This changelog covers changes since Misskey v12.111.1, the version prior to the FoundKey fork.
For older Misskey versions, see [CHANGELOG-OLD.md](./CHANGELOG-OLD.md). For older Misskey versions, see [CHANGELOG-OLD.md](./CHANGELOG-OLD.md).
Unreleased changes should not be listed in this file.
Instead, run `git shortlog --format='%h %s' --group=trailer:changelog <last tag>..` to see unreleased changes; replace `<last tag>` with the tag you wish to compare from.
If you are a contributor, please read CONTRIBUTING.md, section "Changelog Trailer" on what to do instead.
## Unreleased ## Unreleased
### Added ### Added
- Client: Show instance info in ticker - Client: Show instance info in ticker
@ -37,6 +41,7 @@ For older Misskey versions, see [CHANGELOG-OLD.md](./CHANGELOG-OLD.md).
### Security ### Security
- Server: Update `multer` dependency to resolve [CVE-2022-24434](https://nvd.nist.gov/vuln/detail/CVE-2022-24434) - Server: Update `multer` dependency to resolve [CVE-2022-24434](https://nvd.nist.gov/vuln/detail/CVE-2022-24434)
- Server: Update `file-type`, `got`, and `sharp` dependencies to fix various security issues
## 13.0.0-preview1 - 2022-08-05 ## 13.0.0-preview1 - 2022-08-05
### Added ### Added

View file

@ -1,61 +1,46 @@
# Contribution guide # Contribution guide
We're glad you're interested in contributing Misskey! In this document you will find the information you need to contribute to the project. We're glad you're interested in contributing to Foundkey! In this document you will find the information you need to contribute to the project.
> **Note** The project uses English as its primary language. However due to being a fork of Misskey (which uses Japanese as its primary language) you may find things that are in Japanese.
> This project uses Japanese as its major language, **but you do not need to translate and write the Issues/PRs in Japanese.** If you make contributions (pull requests, commits, comments in newly added code etc.) we expect that these should be in English.
> Also, you might receive comments on your Issue/PR in Japanese, but you do not need to reply to them in Japanese as well.\
> The accuracy of machine translation into Japanese is not high, so it will be easier for us to understand if you write it in the original language. We won't mind if issues are not in English but we cannot guarantee we will understand you correctly.
> It will also allow the reader to use the translation tool of their preference if necessary. However it might stíll be better if you write issues in your original language if you are not confident of your English skills because we might be able to use different translators or ask people to translate if we are not sure what you mean.
Please understand that in such cases we might edit your issue to translate it, to help us avoid duplicating issues.
## Development platform
FoundKey generally assumes that it is running on a Unix-like platform (e.g. Linux or macOS). If you are using Windows for development, we highly suggest using the Windows Subsystem for Linux (WSL) as the development environment.
## Roadmap ## Roadmap
See [ROADMAP.md](./ROADMAP.md) See [ROADMAP.md](./ROADMAP.md)
## Issues ## Issues
Before creating an issue, please check the following: Issues are intended for feature requests and bug tracking.
- To avoid duplication, please search for similar issues before creating a new issue.
- Do not use Issues to ask questions or troubleshooting.
- Issues should only be used to feature requests, suggestions, and bug tracking.
- Please ask questions or troubleshooting in the [Misskey Forum](https://forum.misskey.io/) or [Discord](https://discord.gg/Wp8gVStHW3).
> **Warning** For technical support or if you are not sure if what you are experiencing is a bug you can talk to people on the [IRC server](https://irc.akkoma.dev) in the `#foundkey` channel first.
> Do not close issues that are about to be resolved. It should remain open until a commit that actually resolves it is merged.
## Before implementation Please do not close issues that are about to be resolved. It should remain open until a commit that actually resolves it is merged.
When you want to add a feature or fix a bug, **first have the design and policy reviewed in an Issue** (if it is not there, please make one). Without this step, there is a high possibility that the PR will not be merged even if it is implemented.
At this point, you also need to clarify the goals of the PR you will create, and make sure that the other members of the team are aware of them.
PRs that do not have a clear set of do's and don'ts tend to be bloated and difficult to review.
Also, when you start implementation, assign yourself to the Issue (if you cannot do it yourself, ask another member to assign you). By expressing your intention to work the Issue, you can prevent conflicts in the work.
## Well-known branches ## Well-known branches
- **`master`** branch is tracking the latest release and used for production purposes. branch|what it's for
- **`develop`** branch is where we work for the next release. ---|---
- When you create a PR, basically target it to this branch. main|development branch
- **`l10n_develop`** branch is reserved for localization management.
## Creating a PR For a production environment you might not want to follow the `main` branch directly but instead check out one of the git tags.
Thank you for your PR! Before creating a PR, please check the following:
- If possible, prefix the title with a keyword that identifies the type of this PR, as shown below.
- `fix` / `refactor` / `feat` / `enhance` / `perf` / `chore` etc
- Also, make sure that the granularity of this PR is appropriate. Please do not include more than one type of change or interest in a single PR.
- If there is an Issue which will be resolved by this PR, please include a reference to the Issue in the text.
- Please add the summary of the changes to [`CHANGELOG.md`](/CHANGELOG.md). However, this is not necessary for changes that do not affect the users, such as refactoring.
- Check if there are any documents that need to be created or updated due to this change.
- If you have added a feature or fixed a bug, please add a test case if possible.
- Please make sure that tests and Lint are passed in advance.
- You can run it with `npm run test` and `npm run lint`. [See more info](#testing)
- If this PR includes UI changes, please attach a screenshot in the text.
Thanks for your cooperation 🤗 ## Considerations to be made for all contributions
## Reviewers guide This project follows [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html).
Be willing to comment on the good points and not just the things you want fixed 💯 Significant changes should be listed in the changelog (i.e. the file called `CHANGELOG.md`, see also section "Changelog Trailer" below).
Although Semantic Versioning talks about "the API", changes to the user interface should also be tracked.
Consider if any of the existing documentation has to be updated because of your contribution.
Some more points you might want to consider are:
### Review perspective
- Scope - Scope
- Are the goals of the PR clear? - Are the goals of the PR clear?
- Is the granularity of the PR appropriate? - Is the granularity of the PR appropriate?
- Security - Security
- Does merging this PR create a vulnerability? - Does merging this PR create a vulnerability?
- Performance - Performance
@ -66,39 +51,98 @@ Be willing to comment on the good points and not just the things you want fixed
- Are there any omissions or gaps? - Are there any omissions or gaps?
- Does it check for anomalies? - Does it check for anomalies?
## Deploy ## Code contributions
The `/deploy` command by issue comment can be used to deploy the contents of a PR to the preview environment.
```
/deploy sha=<commit hash>
```
An actual domain will be assigned so you can test the federation.
## Merge There are different "rules" of how you can contribute, depending on your access privileges to the repository.
For now, basically only @syuilo has the authority to merge PRs into develop because he is most familiar with the codebase.
However, minor fixes, refactoring, and urgent changes may be merged at the discretion of a contributor. ### Without push access
If you do not have push access, you have to create a pull request to get your changes into Foundkey.
Someone with push access should review your contribution.
If they are satisfied that what you are doing seems like a good idea and the considerations from the section above are fulfilled, they can merge your pull request.
Or, they might request another member to also review your changes.
Please be patient as nobody is getting paid to do this, so it might take a bit longer.
### With push access
You can push stuff directly to any branch.
But y'know, "with great power comes great responsibility" and so on, be sensible.
We most likely will not kick you out if you made a mistake, it happens to the best.
But this of course means that the erroneous contributions may be either fixed or undone.
Alternatively, you can also proceed as for "without push access" above.
In this case it will be assumed that you wish for a review of the changes you want to make.
Instead of having someone else merge the pull request when they have approved your changes, you can also merge yourself if you think the given feedback is sufficient.
### Changelog Trailer
To keep track of changes that should go into the CHANGELOG, we use a standard [trailer](https://git-scm.com/docs/git-interpret-trailers).
For single-commits that should be included in the changeset, include the trailer directly.
For multiple commits, the merge commit (in case of a branch) or an empty final commit should include the trailer.
Valid values for the trailer are: "Added", "Changed", "Removed", "Fixed", "Security".
For breaking changes, include a "BREAKING:" in the summary.
Any additional notes should go into the commit body.
If you forget to include it, you can create an empty commit after the fact with it (`--allow-empty`).
Try not to include invalid values in the trailer.
Here is an example complete breaking commit with notes.
```
BREAKING: client: remove rooms
Rooms were removed by syuilo some time ago.
This commit is an example of what the changelog trailer usage is like.
Admins should ensure to run migrations on startup, else foundkey will fail to start.
Changelog: Removed
```
### Creating a PR
- Please prefix the title with the part of Misskey you are changing, i.e. `server:` or `client:`
- The rest of the title should roughly describe what you did.
- Make sure that the granularity of this PR is appropriate. Please do not include more than one type of change in a single PR.
- If there is an issue which will be resolved by this PR, please include a reference to the Issue in the text.
- If you have added a feature or fixed a bug, please add a test case if possible.
- Please make sure that tests and Lint are passed in advance.
- You can run it with `npm run test` and `npm run lint`. [See more info](#testing)
- Don't forget to update the changelog and/or documentation as appropriate (see above).
Thanks for your cooperation!
## Release ## Release
### Release Instructions
1. Commit version changes in the `develop` branch ([package.json](https://github.com/misskey-dev/misskey/blob/develop/package.json)) ### Fork transition
2. Create a release PR.
- Into `master` from `develop` branch. **Note:**
- The title must be in the format `Release: x.y.z`. Since Foundkey was forked from Misskey recently, there might be some breaking changes we want to make.
- `x.y.z` is the new version you are trying to release. For this purpose there will be several pre-release versions of 13.0.0 (e.g. `13.0.0-preview1`).
3. Deploy and perform a simple QA check. Also verify that the tests passed. Until major version 13 is released, the below process is not fully in effect.
4. Merge it.
5. Create a [release of GitHub](https://github.com/misskey-dev/misskey/releases) ### Release process
- The target branch must be `master` Before a stable version is released, there should be a comment period which should usually be 7 days to give everyone the chance to comment.
- The tag name must be the version If a (critical) bug or similar is found during the comment period, the release may be postponed until a fix is found.
For commenting, an issue should be created, and the comment period should also be announced in the `#foundkey-dev` [IRC](https://irc.akkoma.dev) channel.
Pre-releases do not require as much scrutiny and can be useful for "field testing" before a stable release is made.
All releases are managed as git tags.
If the released version is 1.2.3, the git tag should be "v1.2.3".
Pre-releases are marked "previewN".
The first pre-release for 1.2.3 should be tagged "v1.2.3-preview1".
The tag should be a "lightweight" tag (not annotated) of the commit that modifies the CHANGELOG and package.json version.
To generate the changelog, we use a standard shortlog command: `git shortlog --format='%h %s' --group=trailer:changelog LAST_TAG..`.
The person performing the release process should build the next CHANGELOG section based on this output, not use it as-is.
Full releases should also remove any pre-release CHANGELOG sections.
## Localization (l10n) ## Localization (l10n)
Misskey uses [Crowdin](https://crowdin.com/project/misskey) for localization management.
You can improve our translations with your Crowdin account.
Your changes in Crowdin are automatically submitted as a PR (with the title "New Crowdin translations") to the repository.
The owner [@syuilo](https://github.com/syuilo) merges the PR into the develop branch before the next release.
If your language is not listed in Crowdin, please open an issue. We have not yet set up localization management, so updating of locales can currently only be done as commits changing the respective files in the repo.
Localization files are found in `/locales/` and are YAML files using the `yml` file extension.
![Crowdin](https://d322cqt584bo4o.cloudfront.net/misskey/localized.svg) The file name consists of the [IETF BCP 47](https://www.rfc-editor.org/info/bcp47) language code.
## Development ## Development
During development, it is useful to use the `npm run dev` command. During development, it is useful to use the `npm run dev` command.
@ -132,27 +176,34 @@ npx cross-env TS_NODE_FILES=true TS_NODE_TRANSPILE_ONLY=true TS_NODE_PROJECT="./
### e2e tests ### e2e tests
TODO TODO
## Continuous integration ## Continuous integration (CI)
Misskey uses GitHub Actions for executing automated tests.
Configuration files are located in [`/.github/workflows`](/.github/workflows). Foundkey uses Woodpecker for executing automated tests and lints.
CI runs can be found at [ci.akkoma.dev](https://ci.akkoma.dev/FoundKeyGang/FoundKey)
Configuration files are located in `/.woodpecker/`.
## Vue ## Vue
Misskey uses Vue(v3) as its front-end framework. Misskey uses Vue(v3) as its front-end framework.
- Use TypeScript. - Use TypeScript functionality.
- **When creating a new component, please use the Composition API (with [setup sugar](https://v3.vuejs.org/api/sfc-script-setup.html) and [ref sugar](https://github.com/vuejs/rfcs/discussions/369)) instead of the Options API.** - Use the type only variant of `defineProps` and `defineEmits`.
- Some of the existing components are implemented in the Options API, but it is an old implementation. Refactors that migrate those components to the Composition API are also welcome. - When creating a new component, please use the Composition API (with [setup sugar](https://v3.vuejs.org/api/sfc-script-setup.html) and [ref sugar](https://github.com/vuejs/rfcs/discussions/369)) instead of the Options API.
- Some of the existing components are implemented in the Options API, but it is an old implementation. Refactors that migrate those components to the Composition API are welcome.
You might be able to use this shell command to find components that have not yet been refactored: `find packages/client/src -name '*.vue' | xargs grep '<script' | grep -v 'setup'`
## Notes ## Notes
### How to resolve conflictions occurred at yarn.lock? ### How to resolve conflictions occurred at yarn.lock?
Just execute `yarn` to fix it. Just execute `yarn` to fix it.
### INSERTするときにはsaveではなくinsertを使用する ### Use `insert` instead of `save` to create new objects
#6441 When using `save`, you may accidentally update an existing item, because `save` circumvents uniqueness constraints.
### placeholder See also <https://github.com/misskey-dev/misskey/issues/6441>.
SQLをクエリビルダで組み立てる際、使用するプレースホルダは重複してはならない
例えば ### typeorm placeholders
The names of placeholders used in queries must be unique in each query.
For example
``` ts ``` ts
query.andWhere(new Brackets(qb => { query.andWhere(new Brackets(qb => {
for (const type of ps.fileType) { for (const type of ps.fileType) {
@ -160,8 +211,8 @@ query.andWhere(new Brackets(qb => {
} }
})); }));
``` ```
と書くと、ループ中で`type`というプレースホルダが複数回使われてしまいおかしくなる would mean that `type` is used multiple times because it is used in a loop.
だから次のようにする必要がある This is incorrect. instead you would need to do something like the following:
```ts ```ts
query.andWhere(new Brackets(qb => { query.andWhere(new Brackets(qb => {
for (const type of ps.fileType) { for (const type of ps.fileType) {
@ -171,82 +222,79 @@ query.andWhere(new Brackets(qb => {
})); }));
``` ```
### Not `null` in TypeORM ### `null` (JS/TS) and `NULL` (SQL)
```ts #### in TypeORM FindOptions
const foo = await Foos.findOne({ Using the JavaScript/TypeScript `null` constant is not supported in Typeorm. Instead you need to use the special `Null()` function Typeorm provides.
bar: Not(null) It can also be combined with other similar TypeORM functions.
});
``` For example to make a condition similar to SQL `IS NOT NULL`, do the following:
のようなクエリ(`bar`が`null`ではない)は期待通りに動作しない。
次のようにします:
```ts ```ts
import { IsNull, Not } from 'typeorm';
const foo = await Foos.findOne({ const foo = await Foos.findOne({
bar: Not(IsNull()) bar: Not(IsNull())
}); });
``` ```
### `null` in SQL #### in SQL queries or `QueryBuilder`s
SQLを発行する際、パラメータが`null`になる可能性のある場合はSQL文を出し分けなければならない In SQL statements, you need to have separate statements for cases where parameters may be `null`.
例えば
Take for example this snippet:
``` ts ``` ts
query.where('file.folderId = :folderId', { folderId: ps.folderId }); query.where('file.folderId = :folderId', { folderId: ps.folderId });
``` ```
という処理で、`ps.folderId`が`null`だと結果的に`file.folderId = null`のようなクエリが発行されてしまい、これは正しいSQLではないので期待した結果が得られない If `ps.folderId === null`, the resulting query would be `file.folderId = null` which is incorrect and might produce unexpected results.
だから次のようにする必要がある
What you need to do instead is something like the following:
``` ts ``` ts
if (ps.folderId) { if (ps.folderId != null) {
query.where('file.folderId = :folderId', { folderId: ps.folderId }); query.where('file.folderId = :folderId', { folderId: ps.folderId });
} else { } else {
query.where('file.folderId IS NULL'); query.where('file.folderId IS NULL');
} }
``` ```
### `[]` in SQL ### Empty array handling in TypeORM FindOptions
SQLを発行する際、`IN`のパラメータが`[]`(空の配列)になる可能性のある場合はSQL文を出し分けなければならない If you are using the `In` function in `FindOptions`, there must be different behaviour if it may receive empty arrays.
例えば
``` ts ``` ts
const users = await Users.find({ const users = await Users.find({
id: In(userIds) id: In(userIds)
}); });
``` ```
という処理で、`userIds`が`[]`だと結果的に`user.id IN ()`のようなクエリが発行されてしまい、これは正しいSQLではないので期待した結果が得られない This would produce erroneous SQL, i.e. `user.id IN ()`.
だから次のようにする必要がある To fix this you would need separate handling for an empty array, for example like this:
``` ts ``` ts
const users = userIds.length > 0 ? await Users.find({ const users = userIds.length > 0 ? await Users.find({
id: In(userIds) id: In(userIds)
}) : []; }) : [];
``` ```
### 配列のインデックス in SQL ### Array indexing in SQL
SQLでは配列のインデックスは**1始まり**。 PostgreSQL array indices **start at 1**.
`[a, b, c]``a`にアクセスしたいなら`[0]`ではなく`[1]`と書く
### null IN ### `NULL IN ...`
nullが含まれる可能性のあるカラムにINするときは、そのままだとおかしくなるのでORなどでnullのハンドリングをしよう。 When `IN` is performed on a column that may contain `NULL` values, use `OR` or similar to handle `NULL` values.
### `undefined`にご用心 ### creating migrations
MongoDBの時とは違い、findOneでレコードを取得する時に対象レコードが存在しない場合 **`undefined`** が返ってくるので注意。 In `packages/backend`, run:
MongoDBは`null`で返してきてたので、その感覚で`if (x === null)`とか書くとバグる。代わりに`if (x == null)`と書いてください
### Migration作成方法
packages/backendで:
```sh ```sh
npx typeorm migration:generate -d ormconfig.js -o <migration name> npx typeorm migration:generate -d ormconfig.js -o <migration name>
``` ```
- 生成後、ファイルをmigration下に移してください After generating (and potentially editing) the file, move it to the `packages/backend/migration` folder.
- 作成されたスクリプトは不必要な変更を含むため除去してください
### コネクションには`markRaw`せよ ### `markRaw` for connections
**Vueのコンポーネントのdataオプションとして**misskey.jsのコネクションを設定するとき、必ず`markRaw`でラップしてください。インスタンスが不必要にリアクティブ化されることで、misskey.js内の処理で不具合が発生するとともに、パフォーマンス上の問題にも繋がる。なお、Composition APIを使う場合はこの限りではない(リアクティブ化はマニュアルなため)。 When setting up a foundkey-js streaming connection as a data option to a Vue component, be sure to wrap it in `markRaw`.
Unnecessarily reactivating a connection causes problems with processing in foundkey-js and leads to performance issues.
This does not apply when using the Composition API since reactivation is manual.
### JSONのimportに気を付けよう ### JSON imports
TypeScriptでjsonをimportすると、tscでコンパイルするときにそのjsonファイルも一緒にdistディレクトリに吐き出されてしまう。この挙動により、意図せずファイルの書き換えが発生することがあるので、jsonをimportするときは書き換えられても良いものかどうか確認すること。書き換えされて欲しくない場合は、importで読み込むのではなく、`fs.readFileSync`などの関数を使って読み込むようにすればよい。 If you import json in TypeScript, the json file will be spit out together with the TypeScript file into the dist directory when compiling with tsc. This behavior may cause unintentional rewriting of files, so when importing json files, be sure to check whether the files are allowed to be rewritten or not. If you do not want the file to be rewritten, you should make sure that the file can be rewritten by importing the json file. If you do not want the file to be rewritten, use functions such as `fs.readFileSync` to read the file instead of importing it.
### コンポーネントのスタイル定義でmarginを持たせない ### Component style definitions do not have a `margin`
コンポーネント自身がmarginを設定するのは問題の元となることはよく知られている Setting the `margin` of a component may be confusing.
marginはそのコンポーネントを使う側が設定する Instead, it should always be the user of a component that sets a `margin`.
## その他 ### Do not use the word "follow" in HTML class names
### HTMLのクラス名で follow という単語は使わない This has caused things to be blocked by an ad blocker in the past.
広告ブロッカーで誤ってブロックされる

View file

@ -1,55 +1,13 @@
<div align="center"> # FoundKey
<a href="https://misskey-hub.net"> FoundKey is a free and open source microblogging server compatible with ActivityPub. Forked from Misskey, FoundKey improves on maintainability and behaviour, while also bringing in useful features.
<img src="./assets/title_float.svg" alt="Misskey logo" style="border-radius:50%" width="400"/>
</a>
**🌎 **[Misskey](https://misskey-hub.net/)** is an open source, decentralized social media platform that's free forever! 🚀**
---
<a href="https://misskey-hub.net/instances.html"> See the [changelog](./CHANGELOG.md) and [roadmap](./ROADMAP.md) for more on what's changed and future plans.
<img src="https://custom-icon-badges.herokuapp.com/badge/find_an-instance-acea31?logoColor=acea31&style=for-the-badge&logo=misskey&labelColor=363B40" alt="find an instance"/></a>
<a href="https://misskey-hub.net/docs/install.html">
<img src="https://custom-icon-badges.herokuapp.com/badge/create_an-instance-FBD53C?logoColor=FBD53C&style=for-the-badge&logo=server&labelColor=363B40" alt="create an instance"/></a>
<a href="./CONTRIBUTING.md">
<img src="https://custom-icon-badges.herokuapp.com/badge/become_a-contributor-A371F7?logoColor=A371F7&style=for-the-badge&logo=git-merge&labelColor=363B40" alt="become a contributor"/></a>
<a href="https://discord.gg/Wp8gVStHW3">
<img src="https://custom-icon-badges.herokuapp.com/badge/join_the-community-5865F2?logoColor=5865F2&style=for-the-badge&logo=discord&labelColor=363B40" alt="join the community"/></a>
<a href="https://www.patreon.com/syuilo">
<img src="https://custom-icon-badges.herokuapp.com/badge/become_a-patron-F96854?logoColor=F96854&style=for-the-badge&logo=patreon&labelColor=363B40" alt="become a patron"/></a>
---
</div>
<div>
<a href="https://xn--931a.moe/"><img src="https://github.com/misskey-dev/misskey/blob/develop/assets/ai.png?raw=true" align="right" height="320px"/></a>
## ✨ Features
- **ActivityPub support**\
Not on Misskey? No problem! Not only can Misskey instances talk to each other, but you can make friends with people on other networks like Mastodon and Pixelfed!
- **Reactions**\
You can add emoji reactions to any post! No longer are you bound by a like button, show everyone exactly how you feel with the tap of a button.
- **Drive**\
With Misskey's built in drive, you get cloud storage right in your social media, where you can upload any files, make folders, and find media from posts you've made!
- **Rich Web UI**\
Misskey has a rich and easy to use Web UI!
It is highly customizable, from changing the layout and adding widgets to making custom themes.
Furthermore, plugins can be created using AiScript, an original programming language.
- And much more...
</div>
<div style="clear: both;"></div>
## Documentation ## Documentation
FoundKey's documentation is a work in progress. In the meantime, much of the documentation on the [Misskey Hub](https://misskey-hub.net/) will also apply to FoundKey.
Misskey Documentation can be found at [Misskey Hub](https://misskey-hub.net/), some of the links and graphics above also lead to specific portions of it. ## Contributing
If you're interested in helping out with the project, please read the [contributing guide](./CONTRIBUTING.md).
## Sponsors ## Sponsors
FoundKey is not interested in sponsorships. FoundKey is not interested in sponsorships.

View file

@ -19,7 +19,7 @@ services:
redis: redis:
restart: always restart: always
image: redis:4.0-alpine image: redis:7.0-alpine
networks: networks:
- internal_network - internal_network
volumes: volumes:
@ -27,7 +27,7 @@ services:
db: db:
restart: always restart: always
image: postgres:12.2-alpine image: postgres:14.5-alpine
networks: networks:
- internal_network - internal_network
env_file: env_file:

View file

@ -847,6 +847,7 @@ typeToConfirm: "Please enter {x} to confirm"
deleteAccount: "Delete account" deleteAccount: "Delete account"
numberOfPageCache: "Number of cached pages" numberOfPageCache: "Number of cached pages"
numberOfPageCacheDescription: "Increasing this number will improve convenience for users but cause more server load as well as more memory to be used." numberOfPageCacheDescription: "Increasing this number will improve convenience for users but cause more server load as well as more memory to be used."
document: "Document"
file: "File" file: "File"
unclip: "Unclip" unclip: "Unclip"
confirmToUnclipAlreadyClippedNote: "This note is already part of the \"{name}\" clip. Do you want to remove it from this clip instead?" confirmToUnclipAlreadyClippedNote: "This note is already part of the \"{name}\" clip. Do you want to remove it from this clip instead?"
@ -987,6 +988,10 @@ _serverDisconnectedBehavior:
reload: "Automatically reload" reload: "Automatically reload"
dialog: "Show warning dialog" dialog: "Show warning dialog"
quiet: "Show unobtrusive warning" quiet: "Show unobtrusive warning"
maxCustomEmojiPicker: "Maximum suggested custom emoji in picker"
maxCustomEmojiPickerDescription: "0 for unlimited"
maxUnicodeEmojiPicker: "Maximum suggested unicode emoji in picker"
maxUnicodeEmojiPickerDescription: "0 for unlimited"
_channel: _channel:
create: "Create channel" create: "Create channel"
edit: "Edit channel" edit: "Edit channel"

View file

@ -854,6 +854,7 @@ typeToConfirm: "この操作を行うには {x} と入力してください"
deleteAccount: "アカウント削除" deleteAccount: "アカウント削除"
numberOfPageCache: "ページキャッシュ数" numberOfPageCache: "ページキャッシュ数"
numberOfPageCacheDescription: "多くすると利便性が向上しますが、負荷とメモリ使用量が増えます。" numberOfPageCacheDescription: "多くすると利便性が向上しますが、負荷とメモリ使用量が増えます。"
document: "ドキュメント"
_emailUnavailable: _emailUnavailable:
used: "既に使用されています" used: "既に使用されています"

@ -1 +0,0 @@
Subproject commit 0179793ec891856d6f37a3be16ba4c22f67a81b5

View file

@ -10,7 +10,7 @@
"packages/*" "packages/*"
], ],
"scripts": { "scripts": {
"build": "yarn workspaces foreach --topological run build && yarn run gulp", "build": "yarn workspaces foreach --parallel --topological run build && yarn run gulp",
"start": "yarn workspace backend run start", "start": "yarn workspace backend run start",
"start:test": "yarn workspace backend run start:test", "start:test": "yarn workspace backend run start:test",
"init": "yarn migrate", "init": "yarn migrate",
@ -26,8 +26,8 @@
"mocha": "yarn workspace backend run mocha", "mocha": "yarn workspace backend run mocha",
"test": "yarn mocha", "test": "yarn mocha",
"format": "gulp format", "format": "gulp format",
"clean": "node ./scripts/clean.js", "clean": "yarn workspaces foreach run clean && rm -rf built/",
"clean-all": "node ./scripts/clean-all.js", "clean-all": "yarn workspaces foreach run clean-all && rm -rf built/ node_modules/",
"cleanall": "yarn clean-all" "cleanall": "yarn clean-all"
}, },
"dependencies": { "dependencies": {
@ -42,11 +42,11 @@
"devDependencies": { "devDependencies": {
"@types/gulp": "4.0.9", "@types/gulp": "4.0.9",
"@types/gulp-rename": "2.0.1", "@types/gulp-rename": "2.0.1",
"@typescript-eslint/parser": "5.30.0", "@typescript-eslint/parser": "^5.36.2",
"cross-env": "7.0.3", "cross-env": "7.0.3",
"cypress": "10.3.0", "cypress": "10.3.0",
"start-server-and-test": "1.14.0", "start-server-and-test": "1.14.0",
"typescript": "4.7.4" "typescript": "4.8.2"
}, },
"packageManager": "yarn@3.2.3" "packageManager": "yarn@3.2.3"
} }

View file

@ -6,6 +6,8 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"build": "tsc -p tsconfig.json || echo done. && tsc-alias -p tsconfig.json", "build": "tsc -p tsconfig.json || echo done. && tsc-alias -p tsconfig.json",
"clean": "rm -rf built/ tsconfig.tsbuildinfo",
"clean-all": "yarn clean && rm -rf node_modules/",
"watch": "node watch.mjs", "watch": "node watch.mjs",
"lint": "eslint src --ext .ts", "lint": "eslint src --ext .ts",
"mocha": "cross-env NODE_ENV=test TS_NODE_FILES=true TS_NODE_TRANSPILE_ONLY=true TS_NODE_PROJECT=\"./test/tsconfig.json\" mocha", "mocha": "cross-env NODE_ENV=test TS_NODE_FILES=true TS_NODE_TRANSPILE_ONLY=true TS_NODE_PROJECT=\"./test/tsconfig.json\" mocha",
@ -49,10 +51,10 @@
"deep-email-validator": "0.1.21", "deep-email-validator": "0.1.21",
"escape-regexp": "0.0.1", "escape-regexp": "0.0.1",
"feed": "4.2.2", "feed": "4.2.2",
"file-type": "17.1.2", "file-type": "18.0.0",
"fluent-ffmpeg": "2.1.2", "fluent-ffmpeg": "2.1.2",
"foundkey-js": "workspace:*", "foundkey-js": "workspace:*",
"got": "12.1.0", "got": "12.3.1",
"hpagent": "0.1.2", "hpagent": "0.1.2",
"ioredis": "4.28.5", "ioredis": "4.28.5",
"ip-cidr": "3.0.10", "ip-cidr": "3.0.10",
@ -88,7 +90,7 @@
"pug": "3.0.2", "pug": "3.0.2",
"punycode": "2.1.1", "punycode": "2.1.1",
"pureimage": "0.3.14", "pureimage": "0.3.14",
"qrcode": "1.5.0", "qrcode": "1.5.1",
"random-seed": "0.3.0", "random-seed": "0.3.0",
"ratelimiter": "3.4.1", "ratelimiter": "3.4.1",
"re2": "1.17.7", "re2": "1.17.7",
@ -100,7 +102,7 @@
"rss-parser": "3.12.0", "rss-parser": "3.12.0",
"sanitize-html": "2.7.0", "sanitize-html": "2.7.0",
"semver": "7.3.7", "semver": "7.3.7",
"sharp": "0.29.3", "sharp": "0.30.7",
"speakeasy": "2.0.0", "speakeasy": "2.0.0",
"strict-event-emitter-types": "2.0.0", "strict-event-emitter-types": "2.0.0",
"stringz": "2.1.0", "stringz": "2.1.0",
@ -111,8 +113,8 @@
"tinycolor2": "1.4.2", "tinycolor2": "1.4.2",
"tmp": "0.2.1", "tmp": "0.2.1",
"ts-loader": "9.3.1", "ts-loader": "9.3.1",
"ts-node": "10.8.1", "ts-node": "10.9.1",
"tsc-alias": "1.6.11", "tsc-alias": "1.7.0",
"tsconfig-paths": "4.0.0", "tsconfig-paths": "4.0.0",
"twemoji-parser": "14.0.0", "twemoji-parser": "14.0.0",
"typeorm": "0.3.7", "typeorm": "0.3.7",
@ -135,7 +137,7 @@
"@types/jsdom": "16.2.14", "@types/jsdom": "16.2.14",
"@types/jsonld": "1.5.6", "@types/jsonld": "1.5.6",
"@types/jsrsasign": "10.5.1", "@types/jsrsasign": "10.5.1",
"@types/koa": "2.13.4", "@types/koa": "2.13.5",
"@types/koa-bodyparser": "4.3.7", "@types/koa-bodyparser": "4.3.7",
"@types/koa-cors": "0.0.2", "@types/koa-cors": "0.0.2",
"@types/koa-favicon": "2.0.21", "@types/koa-favicon": "2.0.21",
@ -147,20 +149,20 @@
"@types/koa__multer": "2.0.4", "@types/koa__multer": "2.0.4",
"@types/koa__router": "8.0.11", "@types/koa__router": "8.0.11",
"@types/mocha": "9.1.1", "@types/mocha": "9.1.1",
"@types/node": "18.0.0", "@types/node": "18.7.15",
"@types/node-fetch": "3.0.3", "@types/node-fetch": "3.0.3",
"@types/nodemailer": "6.4.4", "@types/nodemailer": "6.4.5",
"@types/oauth": "^0.9.1", "@types/oauth": "^0.9.1",
"@types/pug": "2.0.6", "@types/pug": "2.0.6",
"@types/punycode": "2.1.0", "@types/punycode": "2.1.0",
"@types/qrcode": "1.4.2", "@types/qrcode": "1.5.0",
"@types/random-seed": "0.3.3", "@types/random-seed": "0.3.3",
"@types/ratelimiter": "3.4.3", "@types/ratelimiter": "3.4.3",
"@types/redis": "4.0.11", "@types/redis": "4.0.11",
"@types/rename": "1.0.4", "@types/rename": "1.0.4",
"@types/sanitize-html": "2.6.2", "@types/sanitize-html": "2.6.2",
"@types/semver": "7.3.10", "@types/semver": "7.3.12",
"@types/sharp": "0.30.4", "@types/sharp": "0.30.5",
"@types/sinonjs__fake-timers": "8.1.2", "@types/sinonjs__fake-timers": "8.1.2",
"@types/speakeasy": "2.0.7", "@types/speakeasy": "2.0.7",
"@types/tinycolor2": "1.4.3", "@types/tinycolor2": "1.4.3",
@ -169,13 +171,13 @@
"@types/web-push": "3.3.2", "@types/web-push": "3.3.2",
"@types/websocket": "1.0.5", "@types/websocket": "1.0.5",
"@types/ws": "8.5.3", "@types/ws": "8.5.3",
"@typescript-eslint/eslint-plugin": "^5.35.1", "@typescript-eslint/eslint-plugin": "^5.36.2",
"@typescript-eslint/parser": "^5.30.0", "@typescript-eslint/parser": "^5.36.2",
"cross-env": "7.0.3", "cross-env": "7.0.3",
"eslint": "^8.20.0", "eslint": "^8.20.0",
"eslint-plugin-import": "^2.26.0", "eslint-plugin-import": "^2.26.0",
"execa": "6.1.0", "execa": "6.1.0",
"form-data": "^4.0.0", "form-data": "^4.0.0",
"typescript": "^4.7.4" "typescript": "^4.8.2"
} }
} }

View file

@ -17,7 +17,7 @@ const ev = new Xev();
/** /**
* Init process * Init process
*/ */
export default async function(): void { export default async function(): Promise<void> {
process.title = `Misskey (${cluster.isPrimary ? 'master' : 'worker'})`; process.title = `Misskey (${cluster.isPrimary ? 'master' : 'worker'})`;
if (cluster.isPrimary || envOption.disableClustering) { if (cluster.isPrimary || envOption.disableClustering) {

View file

@ -49,7 +49,7 @@ function greet(): void {
/** /**
* Init master process * Init master process
*/ */
export async function masterMain(): void { export async function masterMain(): Promise<void> {
let config!: Config; let config!: Config;
// initialize app // initialize app
@ -141,7 +141,7 @@ async function connectDb(): Promise<void> {
} }
} }
async function spawnWorkers(limit = 1): void { async function spawnWorkers(limit = 1): Promise<void> {
const workers = Math.min(limit, os.cpus().length); const workers = Math.min(limit, os.cpus().length);
bootLogger.info(`Starting ${workers} worker${workers === 1 ? '' : 's'}...`); bootLogger.info(`Starting ${workers} worker${workers === 1 ? '' : 's'}...`);
await Promise.all([...Array(workers)].map(spawnWorker)); await Promise.all([...Array(workers)].map(spawnWorker));

View file

@ -4,7 +4,7 @@ import { initDb } from '@/db/postgre.js';
/** /**
* Init worker process * Init worker process
*/ */
export async function workerMain() { export async function workerMain(): Promise<void> {
await initDb(); await initDb();
// start server // start server

View file

@ -35,7 +35,7 @@ export const NoteReactionRepository = db.getRepository(NoteReaction).extend({
src: NoteReaction[], src: NoteReaction[],
me?: { id: User['id'] } | null | undefined, me?: { id: User['id'] } | null | undefined,
options?: { options?: {
withNote: booleam; withNote: boolean;
}, },
): Promise<Packed<'NoteReaction'>[]> { ): Promise<Packed<'NoteReaction'>[]> {
const reactions = await Promise.allSettled(src.map(reaction => this.pack(reaction, me, options))); const reactions = await Promise.allSettled(src.map(reaction => this.pack(reaction, me, options)));

View file

@ -35,10 +35,10 @@ export async function extractPollFromQuestion(source: string | IObject, resolver
/** /**
* Update votes of Question * Update votes of Question
* @param uri URI of AP Question object * @param value AP Question object or its id
* @returns true if updated * @returns true if updated
*/ */
export async function updateQuestion(value: any) { export async function updateQuestion(value: string | IObject) {
const uri = typeof value === 'string' ? value : value.id; const uri = typeof value === 'string' ? value : value.id;
// URIがこのサーバーを指しているならスキップ // URIがこのサーバーを指しているならスキップ

View file

@ -206,16 +206,19 @@ router.get('/emojis/:emoji', async ctx => {
// like // like
router.get('/likes/:like', async ctx => { router.get('/likes/:like', async ctx => {
const reaction = await NoteReactions.findOneBy({ id: ctx.params.like }); const note = await Notes.findOneBy({
id: reaction.noteId,
visibility: In(['public' as const, 'home' as const]),
});
if (reaction == null) { if (note == null) {
ctx.status = 404; ctx.status = 404;
return; return;
} }
const note = await Notes.findOneBy({ id: reaction.noteId }); const reaction = await NoteReactions.findOneBy({ id: ctx.params.like });
if (note == null) { if (reaction == null) {
ctx.status = 404; ctx.status = 404;
return; return;
} }

View file

@ -1,5 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"incremental": true,
"allowJs": true, "allowJs": true,
"noEmitOnError": false, "noEmitOnError": false,
"noImplicitAny": true, "noImplicitAny": true,

View file

@ -5,7 +5,9 @@
"scripts": { "scripts": {
"watch": "vite build --watch --mode development", "watch": "vite build --watch --mode development",
"build": "vite build", "build": "vite build",
"lint": "eslint src --ext .ts,.vue" "lint": "eslint src --ext .ts,.vue",
"clean": "rm -rf built/",
"clean-all": "yarn clean && rm -rf node_modules/"
}, },
"resolutions": { "resolutions": {
"chokidar": "^3.3.1", "chokidar": "^3.3.1",
@ -18,8 +20,8 @@
"@rollup/plugin-json": "4.1.0", "@rollup/plugin-json": "4.1.0",
"@rollup/pluginutils": "^4.2.1", "@rollup/pluginutils": "^4.2.1",
"@syuilo/aiscript": "0.11.1", "@syuilo/aiscript": "0.11.1",
"@vitejs/plugin-vue": "^3.0.0", "@vitejs/plugin-vue": "^3.1.0",
"@vue/compiler-sfc": "3.2.37", "@vue/compiler-sfc": "3.2.38",
"abort-controller": "3.0.0", "abort-controller": "3.0.0",
"autobind-decorator": "2.4.0", "autobind-decorator": "2.4.0",
"autosize": "5.0.1", "autosize": "5.0.1",
@ -33,7 +35,7 @@
"chartjs-plugin-zoom": "1.2.1", "chartjs-plugin-zoom": "1.2.1",
"compare-versions": "4.1.3", "compare-versions": "4.1.3",
"content-disposition": "0.5.4", "content-disposition": "0.5.4",
"cropperjs": "2.0.0-beta", "cropperjs": "2.0.0-beta.1",
"date-fns": "2.28.0", "date-fns": "2.28.0",
"escape-regexp": "0.0.1", "escape-regexp": "0.0.1",
"eventemitter3": "4.0.7", "eventemitter3": "4.0.7",
@ -54,7 +56,7 @@
"promise-limit": "2.7.0", "promise-limit": "2.7.0",
"pug": "3.0.2", "pug": "3.0.2",
"punycode": "2.1.1", "punycode": "2.1.1",
"qrcode": "1.5.0", "qrcode": "1.5.1",
"reflect-metadata": "0.1.13", "reflect-metadata": "0.1.13",
"rndstr": "1.0.0", "rndstr": "1.0.0",
"rollup": "2.75.7", "rollup": "2.75.7",
@ -67,15 +69,15 @@
"three": "0.142.0", "three": "0.142.0",
"throttle-debounce": "5.0.0", "throttle-debounce": "5.0.0",
"tinycolor2": "1.4.2", "tinycolor2": "1.4.2",
"tsc-alias": "1.6.11", "tsc-alias": "1.7.0",
"tsconfig-paths": "4.0.0", "tsconfig-paths": "4.0.0",
"twemoji-parser": "14.0.0", "twemoji-parser": "14.0.0",
"typescript": "4.7.4", "typescript": "4.8.2",
"uuid": "8.3.2", "uuid": "8.3.2",
"v-debounce": "0.1.2", "v-debounce": "0.1.2",
"vanilla-tilt": "1.7.2", "vanilla-tilt": "1.7.2",
"vite": "3.0.0", "vite": "3.1.0",
"vue": "3.2.37", "vue": "3.2.38",
"vue-prism-editor": "2.0.0-alpha.2", "vue-prism-editor": "2.0.0-alpha.2",
"vuedraggable": "4.0.1", "vuedraggable": "4.0.1",
"websocket": "1.0.34", "websocket": "1.0.34",
@ -92,15 +94,15 @@
"@types/mocha": "9.1.1", "@types/mocha": "9.1.1",
"@types/oauth": "0.9.1", "@types/oauth": "0.9.1",
"@types/punycode": "2.1.0", "@types/punycode": "2.1.0",
"@types/qrcode": "1.4.2", "@types/qrcode": "1.5.0",
"@types/seedrandom": "3.0.2", "@types/seedrandom": "3.0.2",
"@types/throttle-debounce": "5.0.0", "@types/throttle-debounce": "5.0.0",
"@types/tinycolor2": "1.4.3", "@types/tinycolor2": "1.4.3",
"@types/uuid": "8.3.4", "@types/uuid": "8.3.4",
"@types/websocket": "1.0.5", "@types/websocket": "1.0.5",
"@types/ws": "8.5.3", "@types/ws": "8.5.3",
"@typescript-eslint/eslint-plugin": "^5.35.1", "@typescript-eslint/eslint-plugin": "^5.36.2",
"@typescript-eslint/parser": "^5.30.0", "@typescript-eslint/parser": "^5.36.2",
"cross-env": "7.0.3", "cross-env": "7.0.3",
"cypress": "10.3.0", "cypress": "10.3.0",
"eslint": "^8.20.0", "eslint": "^8.20.0",

View file

@ -40,6 +40,7 @@ import bytes from '@/filters/bytes';
import * as os from '@/os'; import * as os from '@/os';
import { i18n } from '@/i18n'; import { i18n } from '@/i18n';
import { $i } from '@/account'; import { $i } from '@/account';
import { MenuItem } from '@/types/menu';
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
file: Misskey.entities.DriveFile; file: Misskey.entities.DriveFile;
@ -60,7 +61,7 @@ const isDragging = ref(false);
const title = computed(() => `${props.file.name}\n${props.file.type} ${bytes(props.file.size)}`); const title = computed(() => `${props.file.name}\n${props.file.type} ${bytes(props.file.size)}`);
function getMenu() { function getMenu(): MenuItem[] {
return [{ return [{
text: i18n.ts.rename, text: i18n.ts.rename,
icon: 'fas fa-i-cursor', icon: 'fas fa-i-cursor',
@ -92,7 +93,7 @@ function getMenu() {
}]; }];
} }
function onClick(ev: MouseEvent) { function onClick(ev: MouseEvent): void {
if (props.selectMode) { if (props.selectMode) {
emit('chosen', props.file); emit('chosen', props.file);
} else { } else {
@ -100,11 +101,11 @@ function onClick(ev: MouseEvent) {
} }
} }
function onContextmenu(ev: MouseEvent) { function onContextmenu(ev: MouseEvent): void {
os.contextMenu(getMenu(), ev); os.contextMenu(getMenu(), ev);
} }
function onDragstart(ev: DragEvent) { function onDragstart(ev: DragEvent): void {
if (ev.dataTransfer) { if (ev.dataTransfer) {
ev.dataTransfer.effectAllowed = 'move'; ev.dataTransfer.effectAllowed = 'move';
ev.dataTransfer.setData(_DATA_TRANSFER_DRIVE_FILE_, JSON.stringify(props.file)); ev.dataTransfer.setData(_DATA_TRANSFER_DRIVE_FILE_, JSON.stringify(props.file));
@ -114,12 +115,12 @@ function onDragstart(ev: DragEvent) {
emit('dragstart'); emit('dragstart');
} }
function onDragend() { function onDragend(): void {
isDragging.value = false; isDragging.value = false;
emit('dragend'); emit('dragend');
} }
function rename() { function rename(): void {
os.inputText({ os.inputText({
title: i18n.ts.renameFile, title: i18n.ts.renameFile,
placeholder: i18n.ts.inputNewFileName, placeholder: i18n.ts.inputNewFileName,
@ -133,14 +134,14 @@ function rename() {
}); });
} }
function describe() { function describe(): void {
os.popup(defineAsyncComponent(() => import('@/components/media-caption.vue')), { os.popup(defineAsyncComponent(() => import('@/components/media-caption.vue')), {
title: i18n.ts.describeFile, title: i18n.ts.describeFile,
input: { input: {
placeholder: i18n.ts.inputNewDescription, placeholder: i18n.ts.inputNewDescription,
default: props.file.comment != null ? props.file.comment : '', default: props.file.comment ?? '',
}, },
image: props.file, file: props.file,
}, { }, {
done: result => { done: result => {
if (!result || result.canceled) return; if (!result || result.canceled) return;
@ -153,23 +154,19 @@ function describe() {
}, 'closed'); }, 'closed');
} }
function toggleSensitive() { function toggleSensitive(): void {
os.api('drive/files/update', { os.api('drive/files/update', {
fileId: props.file.id, fileId: props.file.id,
isSensitive: !props.file.isSensitive, isSensitive: !props.file.isSensitive,
}); });
} }
function copyUrl() { function copyUrl(): void {
copyToClipboard(props.file.url); copyToClipboard(props.file.url);
os.success(); os.success();
} }
/*
function addApp() { async function deleteFile(): Promise<void> {
alert('not implemented yet');
}
*/
async function deleteFile() {
const { canceled } = await os.confirm({ const { canceled } = await os.confirm({
type: 'warning', type: 'warning',
text: i18n.t('driveFileDeleteConfirm', { name: props.file.name }), text: i18n.t('driveFileDeleteConfirm', { name: props.file.name }),

View file

@ -112,6 +112,8 @@ const {
reactionPickerSize, reactionPickerSize,
reactionPickerWidth, reactionPickerWidth,
reactionPickerHeight, reactionPickerHeight,
maxCustomEmojiPicker,
maxUnicodeEmojiPicker,
disableShowingAnimatedImages, disableShowingAnimatedImages,
recentlyUsedEmojis, recentlyUsedEmojis,
} = defaultStore.reactiveState; } = defaultStore.reactiveState;
@ -126,145 +128,41 @@ const searchResultCustom = ref<Misskey.entities.CustomEmoji[]>([]);
const searchResultUnicode = ref<UnicodeEmojiDef[]>([]); const searchResultUnicode = ref<UnicodeEmojiDef[]>([]);
const tab = ref<'index' | 'custom' | 'unicode' | 'tags'>('index'); const tab = ref<'index' | 'custom' | 'unicode' | 'tags'>('index');
watch(q, () => { function emojiSearch<Type>(src: Type[], max: number, query: string): Type[] {
if (emojis.value) emojis.value.scrollTop = 0; // discount fuzzy matching pattern
const re = new RegExp(query.split(' ').join('.*'), 'i');
const match = (str: string): boolean => str && re.test(str);
const matches = src.filter(emoji =>
match(emoji.name)
|| emoji.aliases?.some(match) // custom emoji
|| emoji.keywords?.some(match), // unicode emoji
);
// TODO: sort matches by distance to query
if (max <= 0 || matches.length < max) return matches;
return matches.slice(0, max);
}
if (q.value == null || q.value === '') { let queryTimeoutId = -1;
const queryCallback = (query) => {
if (emojis.value) emojis.value.scrollTop = 0;
searchResultCustom.value = emojiSearch(instance.emojis, maxCustomEmojiPicker.value, query);
searchResultUnicode.value = emojiSearch(emojilist, maxUnicodeEmojiPicker.value, query);
queryTimeoutId = -1;
};
watch(q, () => {
if (queryTimeoutId >= 0) {
clearTimeout(queryTimeoutId);
queryTimeoutId = -1;
}
const query = q.value;
if (query == null || query === '') {
searchResultCustom.value = []; searchResultCustom.value = [];
searchResultUnicode.value = []; searchResultUnicode.value = [];
return; return;
} }
const newQ = q.value.replace(/:/g, '').toLowerCase(); queryTimeoutId = setTimeout(queryCallback, 300, query);
const searchCustom = () => {
const max = 8;
const emojis = customEmojis;
const matches = new Set<Misskey.entities.CustomEmoji>();
const exactMatch = emojis.find(emoji => emoji.name === newQ);
if (exactMatch) matches.add(exactMatch);
if (newQ.includes(' ')) { // AND
const keywords = newQ.split(' ');
//
for (const emoji of emojis) {
if (keywords.every(keyword => emoji.name.includes(keyword))) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
if (matches.size >= max) return matches;
//
for (const emoji of emojis) {
if (keywords.every(keyword => emoji.name.includes(keyword) || emoji.aliases.some(alias => alias.includes(keyword)))) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
} else {
for (const emoji of emojis) {
if (emoji.name.startsWith(newQ)) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
if (matches.size >= max) return matches;
for (const emoji of emojis) {
if (emoji.aliases.some(alias => alias.startsWith(newQ))) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
if (matches.size >= max) return matches;
for (const emoji of emojis) {
if (emoji.name.includes(newQ)) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
if (matches.size >= max) return matches;
for (const emoji of emojis) {
if (emoji.aliases.some(alias => alias.includes(newQ))) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
}
return matches;
};
const searchUnicode = () => {
const max = 8;
const emojis = emojilist;
const matches = new Set<UnicodeEmojiDef>();
const exactMatch = emojis.find(emoji => emoji.name === newQ);
if (exactMatch) matches.add(exactMatch);
if (newQ.includes(' ')) { // AND
const keywords = newQ.split(' ');
//
for (const emoji of emojis) {
if (keywords.every(keyword => emoji.name.includes(keyword))) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
if (matches.size >= max) return matches;
//
for (const emoji of emojis) {
if (keywords.every(keyword => emoji.name.includes(keyword) || emoji.keywords.some(alias => alias.includes(keyword)))) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
} else {
for (const emoji of emojis) {
if (emoji.name.startsWith(newQ)) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
if (matches.size >= max) return matches;
for (const emoji of emojis) {
if (emoji.keywords.some(keyword => keyword.startsWith(newQ))) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
if (matches.size >= max) return matches;
for (const emoji of emojis) {
if (emoji.name.includes(newQ)) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
if (matches.size >= max) return matches;
for (const emoji of emojis) {
if (emoji.keywords.some(keyword => keyword.includes(newQ))) {
matches.add(emoji);
if (matches.size >= max) break;
}
}
}
return matches;
};
searchResultCustom.value = Array.from(searchCustom());
searchResultUnicode.value = Array.from(searchUnicode());
}); });
function focus() { function focus() {

View file

@ -16,13 +16,13 @@
</template> </template>
</div> </div>
<div class="sub"> <div class="sub">
<a v-click-anime href="https://misskey-hub.net/help.html" target="_blank" @click.passive="close()"> <button v-click-anime class="_button" @click="help">
<i class="fas fa-question-circle icon"></i> <i class="fas fa-question-circle icon"></i>
<div class="text">{{ i18n.ts.help }}</div> <div class="text">{{ i18n.ts.help }}</div>
</a> </button>
<MkA v-click-anime to="/about" @click.passive="close()"> <MkA v-click-anime to="/about" @click.passive="close()">
<i class="fas fa-info-circle icon"></i> <i class="fas fa-info-circle icon"></i>
<div class="text">{{ i18n.t('aboutX', { x: instanceName }) }}</div> <div class="text">{{ i18n.ts.instanceInfo }}</div>
</MkA> </MkA>
<MkA v-click-anime to="/about-misskey" @click.passive="close()"> <MkA v-click-anime to="/about-misskey" @click.passive="close()">
<img src="/static-assets/favicon.png" class="icon"/> <img src="/static-assets/favicon.png" class="icon"/>
@ -40,6 +40,7 @@ import { instanceName } from '@/config';
import { defaultStore } from '@/store'; import { defaultStore } from '@/store';
import { i18n } from '@/i18n'; import { i18n } from '@/i18n';
import { deviceKind } from '@/scripts/device-kind'; import { deviceKind } from '@/scripts/device-kind';
import * as os from '@/os';
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
src?: HTMLElement; src?: HTMLElement;
@ -72,6 +73,28 @@ const items = Object.keys(menuDef).filter(k => !menu.includes(k)).map(k => menuD
function close() { function close() {
modal.close(); modal.close();
} }
function help(ev: MouseEvent) {
os.popupMenu([{
type: 'link',
to: '/mfm-cheat-sheet',
text: i18n.ts._mfm.cheatSheet,
icon: 'fas fa-code',
}, {
type: 'link',
to: '/scratchpad',
text: i18n.ts.scratchpad,
icon: 'fas fa-terminal',
}, null, {
text: i18n.ts.document,
icon: 'fas fa-question-circle',
action: () => {
window.open('https://misskey-hub.net/help.html', '_blank');
},
}], ev.currentTarget ?? ev.target);
close();
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View file

@ -15,12 +15,19 @@
</div> </div>
</div> </div>
<div class="hdrwpsaf fullwidth"> <div class="hdrwpsaf fullwidth">
<header>{{ image.name }}</header> <header>{{ file.name }}</header>
<img :src="image.url" :alt="image.comment" :title="image.comment" @click="modal.close()"/> <img v-if="file.type.startsWith('image/')" :src="file.url" @click="modal.close()"/>
<video v-else-if="file.type.startsWith('video/')" controls>
<source :src="file.url" :type="file.type">
</video>
<audio v-else-if="file.type.startsWith('audio/')" controls>
<source :src="file.url" :type="file.type">
</audio>
<a v-else :href="file.url">{{ file.url }}</a>
<footer> <footer>
<span>{{ image.type }}</span> <span>{{ file.type }}</span>
<span>{{ bytes(image.size) }}</span> <span>{{ bytes(file.size) }}</span>
<span v-if="image.properties && image.properties.width">{{ number(image.properties.width) }}px × {{ number(image.properties.height) }}px</span> <span v-if="file.properties?.width">{{ number(file.properties.width) }}px × {{ number(file.properties.height) }}px</span>
</footer> </footer>
</div> </div>
</div> </div>
@ -43,7 +50,7 @@ type Input = {
}; };
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
image: misskey.entities.DriveFile; file: misskey.entities.DriveFile;
title?: string; title?: string;
input: Input; input: Input;
showOkButton: boolean; showOkButton: boolean;

View file

@ -1,5 +1,5 @@
<template> <template>
<MkA v-if="url.startsWith('/')" v-user-preview="canonical" :class="[$style.root, { isMe }]" :to="url" :style="{ background: bgCss }"> <MkA v-if="url.startsWith('/')" v-user-preview="canonical" :class="[$style.root, { [$style.isMe]: isMe }]" :to="url" :style="{ background: bgCss }">
<img :class="$style.icon" :src="`/avatar/@${username}@${host}`" alt=""> <img :class="$style.icon" :src="`/avatar/@${username}@${host}`" alt="">
<span class="main"> <span class="main">
<span class="username">@{{ username }}</span> <span class="username">@{{ username }}</span>

View file

@ -14,21 +14,12 @@
</MkA> </MkA>
</template> </template>
<script lang="ts"> <script lang="ts" setup>
import { defineComponent } from 'vue';
import { userName } from '@/filters/user'; import { userName } from '@/filters/user';
export default defineComponent({ defineProps<{
props: { page: Record<string, any>;
page: { }>();
type: Object,
required: true,
},
},
methods: {
userName,
},
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View file

@ -82,9 +82,9 @@ async function describe(file: DriveFile): Promise<void> {
title: i18n.ts.describeFile, title: i18n.ts.describeFile,
input: { input: {
placeholder: i18n.ts.inputNewDescription, placeholder: i18n.ts.inputNewDescription,
default: file.comment !== null ? file.comment : '', default: file.comment ?? '',
}, },
image: file, file,
}, { }, {
done: result => { done: result => {
if (!result || result.canceled) return; if (!result || result.canceled) return;
@ -117,7 +117,7 @@ function showFileMenu(file: DriveFile, ev: MouseEvent): void {
text: i18n.ts.attachCancel, text: i18n.ts.attachCancel,
icon: 'fas fa-times-circle', icon: 'fas fa-times-circle',
action: () => { detachMedia(file.id); }, action: () => { detachMedia(file.id); },
}], ev.currentTarget ?? ev.target).then(() => menu = null); }], ev.currentTarget as HTMLElement | null ?? ev.target as HTMLElement).then(() => menu = null);
} }
</script> </script>

View file

@ -1,52 +1,34 @@
<template> <template>
<div class="fgmtyycl" :style="{ zIndex, top: top + 'px', left: left + 'px' }"> <div class="fgmtyycl" :style="{ zIndex, top: top + 'px', left: left + 'px' }">
<transition :name="$store.state.animation ? 'zoom' : ''" @after-leave="$emit('closed')"> <transition :name="$store.state.animation ? 'zoom' : ''" @after-leave="emit('closed')">
<MkUrlPreview v-if="showing" class="_popup _shadow" :url="url"/> <MkUrlPreview v-if="showing" class="_popup _shadow" :url="url"/>
</transition> </transition>
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts" setup>
import { defineComponent } from 'vue'; import { onMounted } from 'vue';
import MkUrlPreview from './url-preview.vue'; import MkUrlPreview from '@/components/url-preview.vue';
import * as os from '@/os'; import * as os from '@/os';
export default defineComponent({ const emit = defineEmits<{
components: { (ev: 'closed'): void;
MkUrlPreview, }>();
},
props: { const props = defineProps<{
url: { url: string;
type: String, source: HTMLElement;
required: true, showing: boolean;
}, }>();
source: {
required: true,
},
showing: {
type: Boolean,
required: true,
},
},
data() { let top = $ref(0);
return { let left = $ref(0);
u: null, const zIndex = os.claimZIndex('middle');
top: 0,
left: 0,
zIndex: os.claimZIndex('middle'),
};
},
mounted() { onMounted((): void => {
const rect = this.source.getBoundingClientRect(); const rect = props.source.getBoundingClientRect();
const x = Math.max((rect.left + (this.source.offsetWidth / 2)) - (300 / 2), 6) + window.pageXOffset; top = Math.max((rect.left + (props.source.offsetWidth / 2)) - (300 / 2), 6) + window.pageXOffset;
const y = rect.top + this.source.offsetHeight + window.pageYOffset; left = rect.top + props.source.offsetHeight + window.pageYOffset;
this.top = y;
this.left = x;
},
}); });
</script> </script>

View file

@ -1,6 +1,6 @@
<template> <template>
<transition :name="$store.state.animation ? 'popup' : ''" appear @after-leave="$emit('closed')"> <transition :name="$store.state.animation ? 'popup' : ''" appear @after-leave="$emit('closed')">
<div v-if="showing" class="fxxzrfni _popup _shadow" :style="{ zIndex, top: top + 'px', left: left + 'px' }" @mouseover="() => { $emit('mouseover'); }" @mouseleave="() => { $emit('mouseleave'); }"> <div v-if="showing" class="fxxzrfni _popup _shadow" :style="{ zIndex, top: top + 'px', left: left + 'px' }" @mouseover="() => { emit('mouseover'); }" @mouseleave="() => { emit('mouseleave'); }">
<div v-if="fetched" class="info"> <div v-if="fetched" class="info">
<div class="banner" :style="user.bannerUrl ? `background-image: url(${user.bannerUrl})` : ''"></div> <div class="banner" :style="user.bannerUrl ? `background-image: url(${user.bannerUrl})` : ''"></div>
<MkAvatar class="avatar" :user="user" :disable-preview="true" :show-indicator="true"/> <MkAvatar class="avatar" :user="user" :disable-preview="true" :show-indicator="true"/>
@ -31,71 +31,55 @@
</transition> </transition>
</template> </template>
<script lang="ts"> <script lang="ts" setup>
import { defineComponent } from 'vue'; import { onMounted } from 'vue';
import * as Acct from 'foundkey-js/built/acct'; import * as Acct from 'foundkey-js/built/acct';
import { UserDetailed } from 'foundkey-js/built/entities';
import MkFollowButton from './follow-button.vue'; import MkFollowButton from './follow-button.vue';
import { userPage } from '@/filters/user'; import { userPage } from '@/filters/user';
import * as os from '@/os'; import * as os from '@/os';
import { $i } from '@/account';
export default defineComponent({ const props = defineProps<{
components: { showing: boolean;
MkFollowButton, q: UserDetailed | string;
}, source: HTMLElement;
}>();
props: { const emit = defineEmits<{
showing: { (ev: 'closed'): void;
type: Boolean, (ev: 'mouseover'): void;
required: true, (ev: 'mouseleave'): void;
}, }>();
q: {
type: String,
required: true,
},
source: {
required: true,
},
},
emits: ['closed', 'mouseover', 'mouseleave'], let user: UserDetailed = $ref();
let fetched = $ref(false);
let top = $ref(0);
let left = $ref(0);
let zIndex = $ref(os.claimZIndex('middle'));
data() { onMounted(() => {
return { if (typeof props.q === 'object') {
user: null, user = props.q;
fetched: false, fetched = true;
top: 0, } else {
left: 0, const query = props.q.startsWith('@') ?
zIndex: os.claimZIndex('middle'), Acct.parse(props.q.slice(1)) :
}; { userId: props.q };
},
mounted() { os.api('users/show', query).then(result => {
if (typeof this.q === 'object') { if (!props.showing) return;
this.user = this.q; user = result;
this.fetched = true; fetched = true;
} else { });
const query = this.q.startsWith('@') ? }
Acct.parse(this.q.substr(1)) :
{ userId: this.q };
os.api('users/show', query).then(user => { const rect = props.source.getBoundingClientRect();
if (!this.showing) return; const x = ((rect.left + (props.source.offsetWidth / 2)) - (300 / 2)) + window.pageXOffset;
this.user = user; const y = rect.top + props.source.offsetHeight + window.pageYOffset;
this.fetched = true;
});
}
const rect = this.source.getBoundingClientRect(); top = y;
const x = ((rect.left + (this.source.offsetWidth / 2)) - (300 / 2)) + window.pageXOffset; left = x;
const y = rect.top + this.source.offsetHeight + window.pageYOffset;
this.top = y;
this.left = x;
},
methods: {
userPage,
},
}); });
</script> </script>

View file

@ -12,7 +12,7 @@ export const instance: Misskey.entities.InstanceMetadata = reactive(instanceData
// TODO: set default values // TODO: set default values
}); });
export async function fetchInstance() { export async function fetchInstance(): Promise<void> {
const meta = await api('meta', { const meta = await api('meta', {
detail: false, detail: false,
}); });

View file

@ -112,14 +112,14 @@ export const menuDef = reactive({
icon: 'fas fa-at', icon: 'fas fa-at',
show: computed(() => $i != null), show: computed(() => $i != null),
indicated: computed(() => $i != null && $i.hasUnreadMentions), indicated: computed(() => $i != null && $i.hasUnreadMentions),
to: '/my/mentions', to: '/my/notifications#mentions',
}, },
messages: { messages: {
title: 'directNotes', title: 'directNotes',
icon: 'fas fa-envelope', icon: 'fas fa-envelope',
show: computed(() => $i != null), show: computed(() => $i != null),
indicated: computed(() => $i != null && $i.hasUnreadSpecifiedNotes), indicated: computed(() => $i != null && $i.hasUnreadSpecifiedNotes),
to: '/my/messages', to: '/my/notifications#directNotes',
}, },
favorites: { favorites: {
title: 'favorites', title: 'favorites',
@ -151,17 +151,12 @@ export const menuDef = reactive({
federation: { federation: {
title: 'federation', title: 'federation',
icon: 'fas fa-globe', icon: 'fas fa-globe',
to: '/federation', to: '/about#federation',
}, },
emojis: { emojis: {
title: 'emojis', title: 'emojis',
icon: 'fas fa-laugh', icon: 'fas fa-laugh',
to: '/emojis', to: '/about#emojis',
},
scratchpad: {
title: 'scratchpad',
icon: 'fas fa-terminal',
to: '/scratchpad',
}, },
ui: { ui: {
title: 'switchUi', title: 'switchUi',

View file

@ -163,7 +163,7 @@ export class Router extends EventEmitter<{
return null; return null;
} }
private navigate(path: string, key: string | null | undefined, initial = false) { private navigate(path: string, key: string | null | undefined, initial = false): void {
const beforePath = this.currentPath; const beforePath = this.currentPath;
this.currentPath = path; this.currentPath = path;
@ -195,23 +195,23 @@ export class Router extends EventEmitter<{
} }
} }
public getCurrentComponent() { public getCurrentComponent(): Component | null {
return this.currentComponent; return this.currentComponent;
} }
public getCurrentProps() { public getCurrentProps(): Map<string, string> | null {
return this.currentProps; return this.currentProps;
} }
public getCurrentPath() { public getCurrentPath(): string {
return this.currentPath; return this.currentPath;
} }
public getCurrentKey() { public getCurrentKey(): string {
return this.currentKey; return this.currentKey;
} }
public push(path: string) { public push(path: string): void {
const beforePath = this.currentPath; const beforePath = this.currentPath;
if (path === beforePath) { if (path === beforePath) {
this.emit('same'); this.emit('same');
@ -231,7 +231,7 @@ export class Router extends EventEmitter<{
}); });
} }
public change(path: string, key?: string | null) { public change(path: string, key?: string | null): void {
this.navigate(path, key); this.navigate(path, key);
} }
} }

View file

@ -0,0 +1,106 @@
<template>
<div class="taeiyria">
<div class="query">
<MkInput v-model="host" :debounce="true" class="">
<template #prefix><i class="fas fa-search"></i></template>
<template #label>{{ $ts.host }}</template>
</MkInput>
<FormSplit style="margin-top: var(--margin);">
<MkSelect v-model="state">
<template #label>{{ $ts.state }}</template>
<option value="all">{{ $ts.all }}</option>
<option value="federating">{{ $ts.federating }}</option>
<option value="subscribing">{{ $ts.subscribing }}</option>
<option value="publishing">{{ $ts.publishing }}</option>
<option value="suspended">{{ $ts.suspended }}</option>
<option value="blocked">{{ $ts.blocked }}</option>
<option value="notResponding">{{ $ts.notResponding }}</option>
</MkSelect>
<MkSelect v-model="sort">
<template #label>{{ $ts.sort }}</template>
<option value="+pubSub">{{ $ts.pubSub }} ({{ $ts.descendingOrder }})</option>
<option value="-pubSub">{{ $ts.pubSub }} ({{ $ts.ascendingOrder }})</option>
<option value="+notes">{{ $ts.notes }} ({{ $ts.descendingOrder }})</option>
<option value="-notes">{{ $ts.notes }} ({{ $ts.ascendingOrder }})</option>
<option value="+users">{{ $ts.users }} ({{ $ts.descendingOrder }})</option>
<option value="-users">{{ $ts.users }} ({{ $ts.ascendingOrder }})</option>
<option value="+following">{{ $ts.following }} ({{ $ts.descendingOrder }})</option>
<option value="-following">{{ $ts.following }} ({{ $ts.ascendingOrder }})</option>
<option value="+followers">{{ $ts.followers }} ({{ $ts.descendingOrder }})</option>
<option value="-followers">{{ $ts.followers }} ({{ $ts.ascendingOrder }})</option>
<option value="+caughtAt">{{ $ts.registeredAt }} ({{ $ts.descendingOrder }})</option>
<option value="-caughtAt">{{ $ts.registeredAt }} ({{ $ts.ascendingOrder }})</option>
<option value="+lastCommunicatedAt">{{ $ts.lastCommunication }} ({{ $ts.descendingOrder }})</option>
<option value="-lastCommunicatedAt">{{ $ts.lastCommunication }} ({{ $ts.ascendingOrder }})</option>
</MkSelect>
</FormSplit>
</div>
<MkPagination v-slot="{items}" ref="instances" :key="host + state" :pagination="pagination">
<div class="dqokceoi">
<MkA v-for="instance in items" :key="instance.id" v-tooltip.mfm="`Last communicated: ${new Date(instance.lastCommunicatedAt).toLocaleString()}\nStatus: ${getStatus(instance)}`" class="instance" :to="`/instance-info/${instance.host}`">
<MkInstanceCardMini :instance="instance"/>
</MkA>
</div>
</MkPagination>
</div>
</template>
<script lang="ts" setup>
import { computed } from 'vue';
import MkButton from '@/components/ui/button.vue';
import MkInput from '@/components/form/input.vue';
import MkSelect from '@/components/form/select.vue';
import MkPagination from '@/components/ui/pagination.vue';
import MkInstanceCardMini from '@/components/instance-card-mini.vue';
import FormSplit from '@/components/form/split.vue';
import * as os from '@/os';
import { i18n } from '@/i18n';
let host = $ref('');
let state = $ref('federating');
let sort = $ref('+pubSub');
const pagination = {
endpoint: 'federation/instances' as const,
limit: 10,
offsetMode: true,
params: computed(() => ({
sort,
host: host !== '' ? host : null,
...(
state === 'federating' ? { federating: true } :
state === 'subscribing' ? { subscribing: true } :
state === 'publishing' ? { publishing: true } :
state === 'suspended' ? { suspended: true } :
state === 'blocked' ? { blocked: true } :
state === 'notResponding' ? { notResponding: true } :
{}),
})),
};
function getStatus(instance) {
if (instance.isSuspended) return 'Suspended';
if (instance.isBlocked) return 'Blocked';
if (instance.isNotResponding) return 'Error';
return 'Alive';
}
</script>
<style lang="scss" scoped>
.taeiyria {
> .query {
background: var(--bg);
margin-bottom: 16px;
}
}
.dqokceoi {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
grid-gap: 12px;
> .instance:hover {
text-decoration: none;
}
}
</style>

View file

@ -73,7 +73,7 @@
<MkSpacer v-else-if="tab === 'federation'" :content-max="1000" :margin-min="20"> <MkSpacer v-else-if="tab === 'federation'" :content-max="1000" :margin-min="20">
<XFederation/> <XFederation/>
</MkSpacer> </MkSpacer>
<MkSpacer v-else-if="tab === 'charts'" :content-max="1000" :margin-min="20"> <MkSpacer v-else-if="tab === 'charts'" :content-max="1200" :margin-min="20">
<MkInstanceStats :chart-limit="500" :detailed="true"/> <MkInstanceStats :chart-limit="500" :detailed="true"/>
</MkSpacer> </MkSpacer>
</MkStickyContainer> </MkStickyContainer>
@ -81,6 +81,8 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed } from 'vue'; import { computed } from 'vue';
import XEmojis from './about.emojis.vue';
import XFederation from './about.federation.vue';
import { version, host } from '@/config'; import { version, host } from '@/config';
import FormLink from '@/components/form/link.vue'; import FormLink from '@/components/form/link.vue';
import FormSection from '@/components/form/section.vue'; import FormSection from '@/components/form/section.vue';
@ -93,6 +95,23 @@ import number from '@/filters/number';
import { i18n } from '@/i18n'; import { i18n } from '@/i18n';
import { definePageMetadata } from '@/scripts/page-metadata'; import { definePageMetadata } from '@/scripts/page-metadata';
const headerTabs = $computed(() => [{
key: 'overview',
title: i18n.ts.overview,
}, {
key: 'emojis',
title: i18n.ts.customEmojis,
icon: 'fas fa-laugh',
}, {
key: 'federation',
title: i18n.ts.federation,
icon: 'fas fa-globe',
}, {
key: 'charts',
title: i18n.ts.charts,
icon: 'fas fa-chart-simple',
}]);
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
initialTab?: string; initialTab?: string;
}>(), { }>(), {
@ -100,7 +119,7 @@ const props = withDefaults(defineProps<{
}); });
let stats = $ref(null); let stats = $ref(null);
let tab = $ref(props.initialTab); let tab = $ref(headerTabs.some(({ key }) => key === props.initialTab) ? props.initialTab : 'overview');
const initStats = () => os.api('stats', { const initStats = () => os.api('stats', {
}).then((res) => { }).then((res) => {
@ -109,15 +128,6 @@ const initStats = () => os.api('stats', {
const headerActions = $computed(() => []); const headerActions = $computed(() => []);
const headerTabs = $computed(() => [{
key: 'overview',
title: i18n.ts.overview,
}, {
key: 'charts',
title: i18n.ts.charts,
icon: 'fas fa-chart-bar',
}]);
definePageMetadata(computed(() => ({ definePageMetadata(computed(() => ({
title: i18n.ts.instanceInfo, title: i18n.ts.instanceInfo,
icon: 'fas fa-info-circle', icon: 'fas fa-info-circle',

View file

@ -185,12 +185,10 @@ const menuDef = $computed(() => [{
}]); }]);
const component = $computed(() => { const component = $computed(() => {
if (props.initialPage == null) return null;
switch (props.initialPage) { switch (props.initialPage) {
case 'overview': return defineAsyncComponent(() => import('./overview.vue')); case 'overview': return defineAsyncComponent(() => import('./overview.vue'));
case 'users': return defineAsyncComponent(() => import('./users.vue')); case 'users': return defineAsyncComponent(() => import('./users.vue'));
case 'emojis': return defineAsyncComponent(() => import('./emojis.vue')); case 'emojis': return defineAsyncComponent(() => import('./emojis.vue'));
case 'federation': return defineAsyncComponent(() => import('../federation.vue'));
case 'queue': return defineAsyncComponent(() => import('./queue.vue')); case 'queue': return defineAsyncComponent(() => import('./queue.vue'));
case 'files': return defineAsyncComponent(() => import('./files.vue')); case 'files': return defineAsyncComponent(() => import('./files.vue'));
case 'announcements': return defineAsyncComponent(() => import('./announcements.vue')); case 'announcements': return defineAsyncComponent(() => import('./announcements.vue'));
@ -204,6 +202,7 @@ const component = $computed(() => {
case 'integrations': return defineAsyncComponent(() => import('./integrations.vue')); case 'integrations': return defineAsyncComponent(() => import('./integrations.vue'));
case 'instance-block': return defineAsyncComponent(() => import('./instance-block.vue')); case 'instance-block': return defineAsyncComponent(() => import('./instance-block.vue'));
case 'proxy-account': return defineAsyncComponent(() => import('./proxy-account.vue')); case 'proxy-account': return defineAsyncComponent(() => import('./proxy-account.vue'));
default: return null;
} }
}); });

View file

@ -1,58 +0,0 @@
<template>
<MkStickyContainer>
<template #header><MkPageHeader :actions="headerActions" :tabs="headerTabs"/></template>
<div :class="$style.root">
<XCategory/>
</div>
</MkStickyContainer>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue';
import XCategory from './emojis.category.vue';
import * as os from '@/os';
import { i18n } from '@/i18n';
import { definePageMetadata } from '@/scripts/page-metadata';
function menu(ev) {
os.popupMenu([{
icon: 'fas fa-download',
text: i18n.ts.export,
action: async () => {
os.api('export-custom-emojis', {
})
.then(() => {
os.alert({
type: 'info',
text: i18n.ts.exportRequested,
});
}).catch((err) => {
os.alert({
type: 'error',
text: err.message,
});
});
},
}], ev.currentTarget ?? ev.target);
}
const headerActions = $computed(() => [{
icon: 'fas fa-ellipsis-h',
handler: menu,
}]);
const headerTabs = $computed(() => []);
definePageMetadata({
title: i18n.ts.customEmojis,
icon: 'fas fa-laugh',
bg: 'var(--bg)',
});
</script>
<style lang="scss" module>
.root {
max-width: 1000px;
margin: 0 auto;
}
</style>

View file

@ -1,122 +0,0 @@
<template>
<MkStickyContainer>
<template #header><MkPageHeader :actions="headerActions" :tabs="headerTabs"/></template>
<MkSpacer :content-max="1000">
<div class="taeiyria">
<div class="query">
<MkInput v-model="host" :debounce="true" class="">
<template #prefix><i class="fas fa-search"></i></template>
<template #label>{{ i18n.ts.host }}</template>
</MkInput>
<FormSplit style="margin-top: var(--margin);">
<MkSelect v-model="state">
<template #label>{{ i18n.ts.state }}</template>
<option value="all">{{ i18n.ts.all }}</option>
<option value="federating">{{ i18n.ts.federating }}</option>
<option value="subscribing">{{ i18n.ts.subscribing }}</option>
<option value="publishing">{{ i18n.ts.publishing }}</option>
<option value="suspended">{{ i18n.ts.suspended }}</option>
<option value="blocked">{{ i18n.ts.blocked }}</option>
<option value="notResponding">{{ i18n.ts.notResponding }}</option>
</MkSelect>
<MkSelect v-model="sort">
<template #label>{{ i18n.ts.sort }}</template>
<option value="+pubSub">{{ i18n.ts.pubSub }} ({{ i18n.ts.descendingOrder }})</option>
<option value="-pubSub">{{ i18n.ts.pubSub }} ({{ i18n.ts.ascendingOrder }})</option>
<option value="+notes">{{ i18n.ts.notes }} ({{ i18n.ts.descendingOrder }})</option>
<option value="-notes">{{ i18n.ts.notes }} ({{ i18n.ts.ascendingOrder }})</option>
<option value="+users">{{ i18n.ts.users }} ({{ i18n.ts.descendingOrder }})</option>
<option value="-users">{{ i18n.ts.users }} ({{ i18n.ts.ascendingOrder }})</option>
<option value="+following">{{ i18n.ts.following }} ({{ i18n.ts.descendingOrder }})</option>
<option value="-following">{{ i18n.ts.following }} ({{ i18n.ts.ascendingOrder }})</option>
<option value="+followers">{{ i18n.ts.followers }} ({{ i18n.ts.descendingOrder }})</option>
<option value="-followers">{{ i18n.ts.followers }} ({{ i18n.ts.ascendingOrder }})</option>
<option value="+caughtAt">{{ i18n.ts.registeredAt }} ({{ i18n.ts.descendingOrder }})</option>
<option value="-caughtAt">{{ i18n.ts.registeredAt }} ({{ i18n.ts.ascendingOrder }})</option>
<option value="+lastCommunicatedAt">{{ i18n.ts.lastCommunication }} ({{ i18n.ts.descendingOrder }})</option>
<option value="-lastCommunicatedAt">{{ i18n.ts.lastCommunication }} ({{ i18n.ts.ascendingOrder }})</option>
</MkSelect>
</FormSplit>
</div>
<MkPagination v-slot="{items}" ref="instances" :key="host + state" :pagination="pagination">
<div class="dqokceoi">
<MkA v-for="instance in items" :key="instance.id" v-tooltip.mfm="`Last communicated: ${new Date(instance.lastCommunicatedAt).toLocaleString()}\nStatus: ${getStatus(instance)}`" class="instance" :to="`/instance-info/${instance.host}`">
<MkInstanceCardMini :instance="instance"/>
</MkA>
</div>
</MkPagination>
</div>
</MkSpacer>
</MkStickyContainer>
</template>
<script lang="ts" setup>
import { computed } from 'vue';
import MkButton from '@/components/ui/button.vue';
import MkInput from '@/components/form/input.vue';
import MkSelect from '@/components/form/select.vue';
import MkPagination from '@/components/ui/pagination.vue';
import MkInstanceCardMini from '@/components/instance-card-mini.vue';
import FormSplit from '@/components/form/split.vue';
import * as os from '@/os';
import { i18n } from '@/i18n';
import { definePageMetadata } from '@/scripts/page-metadata';
let host = $ref('');
let state = $ref('federating');
let sort = $ref('+pubSub');
const pagination = {
endpoint: 'federation/instances' as const,
limit: 10,
offsetMode: true,
params: computed(() => ({
sort,
host: host !== '' ? host : null,
...(
state === 'federating' ? { federating: true } :
state === 'subscribing' ? { subscribing: true } :
state === 'publishing' ? { publishing: true } :
state === 'suspended' ? { suspended: true } :
state === 'blocked' ? { blocked: true } :
state === 'notResponding' ? { notResponding: true } :
{}),
})),
};
function getStatus(instance) {
if (instance.isSuspended) return 'Suspended';
if (instance.isBlocked) return 'Blocked';
if (instance.isNotResponding) return 'Error';
return 'Alive';
}
const headerActions = $computed(() => []);
const headerTabs = $computed(() => []);
definePageMetadata({
title: i18n.ts.federation,
icon: 'fas fa-globe',
bg: 'var(--bg)',
});
</script>
<style lang="scss" scoped>
.taeiyria {
> .query {
background: var(--bg);
margin-bottom: 16px;
}
}
.dqokceoi {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
grid-gap: 12px;
> .instance:hover {
text-decoration: none;
}
}
</style>

View file

@ -1,29 +0,0 @@
<template>
<MkStickyContainer>
<template #header><MkPageHeader :actions="headerActions" :tabs="headerTabs"/></template>
<MkSpacer :content-max="800">
<XNotes :pagination="pagination"/>
</MkSpacer>
</MkStickyContainer>
</template>
<script lang="ts" setup>
import XNotes from '@/components/notes.vue';
import { i18n } from '@/i18n';
import { definePageMetadata } from '@/scripts/page-metadata';
const pagination = {
endpoint: 'notes/mentions' as const,
limit: 10,
};
const headerActions = $computed(() => []);
const headerTabs = $computed(() => []);
definePageMetadata({
title: i18n.ts.mentions,
icon: 'fas fa-at',
bg: 'var(--bg)',
});
</script>

View file

@ -1,32 +0,0 @@
<template>
<MkStickyContainer>
<template #header><MkPageHeader :actions="headerActions" :tabs="headerTabs"/></template>
<MkSpacer :content-max="800">
<XNotes :pagination="pagination"/>
</MkSpacer>
</MkStickyContainer>
</template>
<script lang="ts" setup>
import XNotes from '@/components/notes.vue';
import { i18n } from '@/i18n';
import { definePageMetadata } from '@/scripts/page-metadata';
const pagination = {
endpoint: 'notes/mentions' as const,
limit: 10,
params: {
visibility: 'specified',
},
};
const headerActions = $computed(() => []);
const headerTabs = $computed(() => []);
definePageMetadata({
title: i18n.ts.directNotes,
icon: 'fas fa-envelope',
bg: 'var(--bg)',
});
</script>

View file

@ -2,8 +2,14 @@
<MkStickyContainer> <MkStickyContainer>
<template #header><MkPageHeader v-model:tab="tab" :actions="headerActions" :tabs="headerTabs"/></template> <template #header><MkPageHeader v-model:tab="tab" :actions="headerActions" :tabs="headerTabs"/></template>
<MkSpacer :content-max="800"> <MkSpacer :content-max="800">
<div class="clupoqwt"> <div v-if="tab === 'mentions'">
<XNotifications class="notifications" :include-types="includeTypes" :unread-only="tab === 'unread'"/> <XNotes :pagination="mentionsPagination"/>
</div>
<div v-else-if="tab === 'directNotes'">
<XNotes :pagination="directNotesPagination"/>
</div>
<div v-else>
<XNotifications class="notifications" :include-types="includeTypes" :unread-only="unreadOnly"/>
</div> </div>
</MkSpacer> </MkSpacer>
</MkStickyContainer> </MkStickyContainer>
@ -13,14 +19,51 @@
import { computed } from 'vue'; import { computed } from 'vue';
import { notificationTypes } from 'foundkey-js'; import { notificationTypes } from 'foundkey-js';
import XNotifications from '@/components/notifications.vue'; import XNotifications from '@/components/notifications.vue';
import XNotes from '@/components/notes.vue';
import * as os from '@/os'; import * as os from '@/os';
import { i18n } from '@/i18n'; import { i18n } from '@/i18n';
import { definePageMetadata } from '@/scripts/page-metadata'; import { definePageMetadata } from '@/scripts/page-metadata';
let tab = $ref('all'); const headerTabs = $computed(() => [{
let includeTypes = $ref<string[] | null>(null); key: 'all',
title: i18n.ts.all,
}, {
key: 'unread',
title: i18n.ts.unread,
}, {
key: 'mentions',
title: i18n.ts.mentions,
icon: 'fas fa-at',
}, {
key: 'directNotes',
title: i18n.ts.directNotes,
icon: 'fas fa-envelope',
}]);
function setFilter(ev) { const props = withDefaults(defineProps<{
initialTab?: string;
}>(), {
initialTab: 'all',
});
let tab = $ref(headerTabs.some(({ key }) => key === props.initialTab) ? props.initialTab : 'all');
let includeTypes = $ref<string[] | null>(null);
let unreadOnly = $computed(() => tab === 'unread');
const mentionsPagination = {
endpoint: 'notes/mentions' as const,
limit: 10,
};
const directNotesPagination = {
endpoint: 'notes/mentions' as const,
limit: 10,
params: {
visibility: 'specified',
},
};
function setFilter(ev: Event): void {
const typeItems = notificationTypes.map(t => ({ const typeItems = notificationTypes.map(t => ({
text: i18n.t(`_notification._types.${t}`), text: i18n.t(`_notification._types.${t}`),
active: includeTypes && includeTypes.includes(t), active: includeTypes && includeTypes.includes(t),
@ -38,34 +81,21 @@ function setFilter(ev) {
os.popupMenu(items, ev.currentTarget ?? ev.target); os.popupMenu(items, ev.currentTarget ?? ev.target);
} }
const headerActions = $computed(() => [{ const headerActions = $computed(() => tab === 'all' ? [{
text: i18n.ts.filter, text: i18n.ts.filter,
icon: 'fas fa-filter', icon: 'fas fa-filter',
highlighted: includeTypes != null, highlighted: includeTypes != null,
handler: setFilter, handler: setFilter,
}, { },{
text: i18n.ts.markAllAsRead, text: i18n.ts.markAllAsRead,
icon: 'fas fa-check', icon: 'fas fa-check',
handler: () => { handler: () => {
os.apiWithDialog('notifications/mark-all-as-read'); os.apiWithDialog('notifications/mark-all-as-read');
}, },
}]); }] : []);
const headerTabs = $computed(() => [{
key: 'all',
title: i18n.ts.all,
}, {
key: 'unread',
title: i18n.ts.unread,
}]);
definePageMetadata(computed(() => ({ definePageMetadata(computed(() => ({
title: i18n.ts.notifications, title: i18n.ts.notifications,
icon: 'fas fa-bell', icon: 'fas fa-bell',
}))); })));
</script> </script>
<style lang="scss" scoped>
.clupoqwt {
}
</style>

View file

@ -35,6 +35,15 @@
<option value="dialog">{{ i18n.ts._serverDisconnectedBehavior.dialog }}</option> <option value="dialog">{{ i18n.ts._serverDisconnectedBehavior.dialog }}</option>
<option value="quiet">{{ i18n.ts._serverDisconnectedBehavior.quiet }}</option> <option value="quiet">{{ i18n.ts._serverDisconnectedBehavior.quiet }}</option>
</FormSelect> </FormSelect>
<FormRange v-model="maxCustomEmojiPicker" :min="0" :max="24" :step="1" class="_formBlock">
<template #label>{{ i18n.ts.maxCustomEmojiPicker }}</template>
<template #caption>{{ i18n.ts.maxCustomEmojiPickerDescription }}</template>
</FormRange>
<FormRange v-model="maxUnicodeEmojiPicker" :min="0" :max="24" :step="1" class="_formBlock">
<template #label>{{ i18n.ts.maxUnicodeEmojiPicker }}</template>
<template #caption>{{ i18n.ts.maxUnicodeEmojiPickerDescription }}</template>
</FormRange>
</FormSection> </FormSection>
<FormSection> <FormSection>
@ -124,6 +133,8 @@ async function reloadAsk() {
const overridedDeviceKind = computed(defaultStore.makeGetterSetter('overridedDeviceKind')); const overridedDeviceKind = computed(defaultStore.makeGetterSetter('overridedDeviceKind'));
const serverDisconnectedBehavior = computed(defaultStore.makeGetterSetter('serverDisconnectedBehavior')); const serverDisconnectedBehavior = computed(defaultStore.makeGetterSetter('serverDisconnectedBehavior'));
const maxCustomEmojiPicker = computed(defaultStore.makeGetterSetter('maxCustomEmojiPicker'));
const maxUnicodeEmojiPicker = computed(defaultStore.makeGetterSetter('maxUnicodeEmojiPicker'));
const reduceAnimation = computed(defaultStore.makeGetterSetter('animation', v => !v, v => !v)); const reduceAnimation = computed(defaultStore.makeGetterSetter('animation', v => !v, v => !v));
const useBlurEffectForModal = computed(defaultStore.makeGetterSetter('useBlurEffectForModal')); const useBlurEffectForModal = computed(defaultStore.makeGetterSetter('useBlurEffectForModal'));
const useBlurEffect = computed(defaultStore.makeGetterSetter('useBlurEffect')); const useBlurEffect = computed(defaultStore.makeGetterSetter('useBlurEffect'));

View file

@ -1,6 +1,6 @@
<template> <template>
<MkContainer> <MkContainer>
<template #header><i class="fas fa-chart-bar" style="margin-right: 0.5em;"></i>{{ $ts.activity }}</template> <template #header><i class="fas fa-chart-simple" style="margin-right: 0.5em;"></i>{{ $ts.activity }}</template>
<template #func> <template #func>
<button class="_button" @click="showMenu"> <button class="_button" @click="showMenu">
<i class="fas fa-ellipsis-h"></i> <i class="fas fa-ellipsis-h"></i>

View file

@ -130,7 +130,7 @@ export class Storage<T extends StateDef> {
this.set(key, [...currentState, value]); this.set(key, [...currentState, value]);
} }
public reset(key: keyof T) { public reset(key: keyof T): void {
this.set(key, this.def[key].default); this.set(key, this.def[key].default);
} }

View file

@ -70,12 +70,6 @@ export const routes = [{
}, { }, {
path: '/explore', path: '/explore',
component: page(() => import('./pages/explore.vue')), component: page(() => import('./pages/explore.vue')),
}, {
path: '/federation',
component: page(() => import('./pages/federation.vue')),
}, {
path: '/emojis',
component: page(() => import('./pages/emojis.vue')),
}, { }, {
path: '/search', path: '/search',
component: page(() => import('./pages/search.vue')), component: page(() => import('./pages/search.vue')),
@ -167,17 +161,12 @@ export const routes = [{
}, { }, {
path: '/my/notifications', path: '/my/notifications',
component: page(() => import('./pages/notifications.vue')), component: page(() => import('./pages/notifications.vue')),
hash: 'initialTab',
loginRequired: true, loginRequired: true,
}, { }, {
path: '/my/favorites', path: '/my/favorites',
component: page(() => import('./pages/favorites.vue')), component: page(() => import('./pages/favorites.vue')),
loginRequired: true, loginRequired: true,
}, {
path: '/my/messages',
component: page(() => import('./pages/messages.vue')),
}, {
path: '/my/mentions',
component: page(() => import('./pages/mentions.vue')),
}, { }, {
name: 'messaging', name: 'messaging',
path: '/my/messaging', path: '/my/messaging',

View file

@ -108,6 +108,14 @@ export const defaultStore = markRaw(new Storage('base', {
where: 'device', where: 'device',
default: 'quiet' as 'quiet' | 'reload' | 'dialog', default: 'quiet' as 'quiet' | 'reload' | 'dialog',
}, },
maxCustomEmojiPicker: {
where: 'device',
default: 10,
},
maxUnicodeEmojiPicker: {
where: 'device',
default: 10,
},
nsfw: { nsfw: {
where: 'device', where: 'device',
default: 'respect' as 'respect' | 'force' | 'ignore', default: 'respect' as 'respect' | 'force' | 'ignore',

View file

@ -7,13 +7,13 @@
</MkA> </MkA>
<template v-for="item in menu"> <template v-for="item in menu">
<div v-if="item === '-'" class="divider"></div> <div v-if="item === '-'" class="divider"></div>
<component :is="menuDef[item].to ? 'MkA' : 'button'" v-else-if="menuDef[item] && (menuDef[item].show !== false)" v-click-anime v-tooltip="$ts[menuDef[item].title]" class="item _button" :class="item" active-class="active" :to="menuDef[item].to" v-on="menuDef[item].action ? { click: menuDef[item].action } : {}"> <component :is="menuDef[item].to ? 'MkA' : 'button'" v-else-if="menuDef[item] && (menuDef[item].show !== false)" v-click-anime v-tooltip="i18n.ts[menuDef[item].title]" class="item _button" :class="item" active-class="active" :to="menuDef[item].to" v-on="menuDef[item].action ? { click: menuDef[item].action } : {}">
<i class="fa-fw" :class="menuDef[item].icon"></i> <i class="fa-fw" :class="menuDef[item].icon"></i>
<span v-if="menuDef[item].indicated" class="indicator"><i class="fas fa-circle"></i></span> <span v-if="menuDef[item].indicated" class="indicator"><i class="fas fa-circle"></i></span>
</component> </component>
</template> </template>
<div class="divider"></div> <div class="divider"></div>
<MkA v-if="$i.isAdmin || $i.isModerator" v-click-anime v-tooltip="$ts.controlPanel" class="item" active-class="active" to="/admin" :behavior="settingsWindowed ? 'modalWindow' : null"> <MkA v-if="iAmModerator" v-click-anime v-tooltip="i18n.ts.controlPanel" class="item" active-class="active" to="/admin" :behavior="settingsWindowed ? 'modalWindow' : null">
<i class="fas fa-door-open fa-fw"></i> <i class="fas fa-door-open fa-fw"></i>
</MkA> </MkA>
<button v-click-anime class="item _button" @click="more"> <button v-click-anime class="item _button" @click="more">
@ -25,7 +25,7 @@
<MkA v-click-anime v-tooltip="$ts.settings" class="item" active-class="active" to="/settings" :behavior="settingsWindowed ? 'modalWindow' : null"> <MkA v-click-anime v-tooltip="$ts.settings" class="item" active-class="active" to="/settings" :behavior="settingsWindowed ? 'modalWindow' : null">
<i class="fas fa-cog fa-fw"></i> <i class="fas fa-cog fa-fw"></i>
</MkA> </MkA>
<button v-click-anime class="item _button account" @click="openAccountMenu"> <button v-click-anime class="item _button account" @click="openAccountMenuWrapper">
<MkAvatar :user="$i" class="avatar"/><MkAcct class="acct" :user="$i"/> <MkAvatar :user="$i" class="avatar"/><MkAcct class="acct" :user="$i"/>
</button> </button>
<div class="post" @click="post"> <div class="post" @click="post">
@ -38,83 +38,52 @@
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts" setup>
import { defineAsyncComponent, defineComponent } from 'vue'; import { defineAsyncComponent, watch } from 'vue';
import { host } from '@/config';
import { search } from '@/scripts/search';
import * as os from '@/os'; import * as os from '@/os';
import { menuDef } from '@/menu'; import { menuDef } from '@/menu';
import { openAccountMenu } from '@/account'; import { openAccountMenu, $i, iAmModerator } from '@/account';
import MkButton from '@/components/ui/button.vue'; import MkButton from '@/components/ui/button.vue';
import { defaultStore } from '@/store';
import { i18n } from '@/i18n';
export default defineComponent({ let settingsWindowed = $ref(false);
components: {
MkButton,
},
data() { const menu = $computed(() => defaultStore.state.menu);
return { const otherNavItemIndicated = $computed((): boolean => {
host, for (const def in menuDef) {
accounts: [], if (menu.includes(def)) continue;
connection: null, if (menuDef[def].indicated) return true;
menuDef, }
settingsWindowed: false, return false;
};
},
computed: {
menu(): string[] {
return this.$store.state.menu;
},
otherNavItemIndicated(): boolean {
for (const def in this.menuDef) {
if (this.menu.includes(def)) continue;
if (this.menuDef[def].indicated) return true;
}
return false;
},
},
watch: {
'$store.reactiveState.menuDisplay.value'() {
this.calcViewState();
},
},
created() {
window.addEventListener('resize', this.calcViewState);
this.calcViewState();
},
methods: {
calcViewState() {
this.settingsWindowed = (window.innerWidth > 1400);
},
post() {
os.post();
},
search() {
search();
},
more(ev) {
os.popup(defineAsyncComponent(() => import('@/components/launch-pad.vue')), {
src: ev.currentTarget ?? ev.target,
anchor: { x: 'center', y: 'bottom' },
}, {
}, 'closed');
},
openAccountMenu: (ev) => {
openAccountMenu({
withExtraOperation: true,
}, ev);
},
},
}); });
function calcViewState(): void {
settingsWindowed = (window.innerWidth > 1400);
}
watch(defaultStore.reactiveState.menuDisplay, calcViewState);
window.addEventListener('resize', calcViewState);
calcViewState();
function post(): void {
os.post();
}
function more(ev: MouseEvent | TouchEvent): void {
os.popup(defineAsyncComponent(() => import('@/components/launch-pad.vue')), {
src: ev.currentTarget ?? ev.target,
anchor: { x: 'center', y: 'bottom' },
}, {
}, 'closed');
}
function openAccountMenuWrapper(ev: MouseEvent): void {
openAccountMenu({
withExtraOperation: true,
}, ev);
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View file

@ -1,12 +1,12 @@
<template> <template>
<MkContainer :naked="widgetProps.transparent" :show-header="false" class="mkw-aichan"> <MkContainer :naked="widgetProps.transparent" :show-header="false" class="mkw-aichan">
<iframe ref="live2d" class="dedjhjmo" src="https://misskey-dev.github.io/mascot-web/?scale=1.5&y=1.1&eyeY=100" @click="touched"></iframe> <iframe ref="live2d" class="dedjhjmo" src="https://misskey-dev.github.io/mascot-web/?scale=1.5&y=1.1&eyeY=100"></iframe>
</MkContainer> </MkContainer>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue'; import { onMounted, onUnmounted } from 'vue';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget'; import { useWidgetPropsManager, Widget, WidgetComponentExpose } from './widget';
import { GetFormResultType } from '@/scripts/form'; import { GetFormResultType } from '@/scripts/form';
const name = 'ai'; const name = 'ai';
@ -23,8 +23,12 @@ type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
// vueimporttype // vueimporttype
//const props = defineProps<WidgetComponentProps<WidgetProps>>(); //const props = defineProps<WidgetComponentProps<WidgetProps>>();
//const emit = defineEmits<WidgetComponentEmits<WidgetProps>>(); //const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const props = defineProps<{ widget?: Widget<WidgetProps>; }>(); const props = defineProps<{
const emit = defineEmits<{ (ev: 'updateProps', props: WidgetProps); }>(); widget?: Widget<WidgetProps>;
}>();
const emit = defineEmits<{
(ev: 'updateProps', widgetProps: WidgetProps);
}>();
const { widgetProps, configure } = useWidgetPropsManager(name, const { widgetProps, configure } = useWidgetPropsManager(name,
widgetPropsDef, widgetPropsDef,
@ -32,15 +36,11 @@ const { widgetProps, configure } = useWidgetPropsManager(name,
emit, emit,
); );
const live2d = ref<HTMLIFrameElement>(); const live2d: HTMLIFrameElement = $ref();
const touched = () => { const onMousemove = (ev: MouseEvent): void => {
//if (this.live2d) this.live2d.changeExpression('gurugurume'); const iframeRect = live2d.getBoundingClientRect();
}; live2d.contentWindow?.postMessage({
const onMousemove = (ev: MouseEvent) => {
const iframeRect = live2d.value.getBoundingClientRect();
live2d.value.contentWindow.postMessage({
type: 'moveCursor', type: 'moveCursor',
body: { body: {
x: ev.clientX - iframeRect.left, x: ev.clientX - iframeRect.left,

View file

@ -13,9 +13,9 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'; import { ref } from 'vue';
import { AiScript, parse, utils } from '@syuilo/aiscript'; import { AiScript, parse, utils } from '@syuilo/aiscript';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget'; import { useWidgetPropsManager, Widget, WidgetComponentExpose } from './widget';
import { GetFormResultType } from '@/scripts/form'; import { GetFormResultType } from '@/scripts/form';
import * as os from '@/os'; import * as os from '@/os';
import MkContainer from '@/components/ui/container.vue'; import MkContainer from '@/components/ui/container.vue';
@ -43,8 +43,12 @@ type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
// vueimporttype // vueimporttype
//const props = defineProps<WidgetComponentProps<WidgetProps>>(); //const props = defineProps<WidgetComponentProps<WidgetProps>>();
//const emit = defineEmits<WidgetComponentEmits<WidgetProps>>(); //const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const props = defineProps<{ widget?: Widget<WidgetProps>; }>(); const props = defineProps<{
const emit = defineEmits<{ (ev: 'updateProps', props: WidgetProps); }>(); widget?: Widget<WidgetProps>;
}>();
const emit = defineEmits<{
(ev: 'updateProps', widgetProps: WidgetProps): void;
}>();
const { widgetProps, configure } = useWidgetPropsManager(name, const { widgetProps, configure } = useWidgetPropsManager(name,
widgetPropsDef, widgetPropsDef,
@ -58,7 +62,7 @@ const logs = ref<{
print: boolean; print: boolean;
}[]>([]); }[]>([]);
const run = async () => { const run = async (): Promise<void> => {
logs.value = []; logs.value = [];
const aiscript = new AiScript(createAiScriptEnv({ const aiscript = new AiScript(createAiScriptEnv({
storageKey: 'widget', storageKey: 'widget',
@ -68,7 +72,7 @@ const run = async () => {
return new Promise(ok => { return new Promise(ok => {
os.inputText({ os.inputText({
title: q, title: q,
}).then(({ canceled, result: a }) => { }).then(({ result: a }) => {
ok(a); ok(a);
}); });
}); });

View file

@ -7,9 +7,8 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'; import { AiScript, parse } from '@syuilo/aiscript';
import { AiScript, parse, utils } from '@syuilo/aiscript'; import { useWidgetPropsManager, Widget, WidgetComponentExpose } from './widget';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget';
import { GetFormResultType } from '@/scripts/form'; import { GetFormResultType } from '@/scripts/form';
import * as os from '@/os'; import * as os from '@/os';
import { createAiScriptEnv } from '@/scripts/aiscript/api'; import { createAiScriptEnv } from '@/scripts/aiscript/api';
@ -39,8 +38,12 @@ type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
// vueimporttype // vueimporttype
//const props = defineProps<WidgetComponentProps<WidgetProps>>(); //const props = defineProps<WidgetComponentProps<WidgetProps>>();
//const emit = defineEmits<WidgetComponentEmits<WidgetProps>>(); //const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const props = defineProps<{ widget?: Widget<WidgetProps>; }>(); const props = defineProps<{
const emit = defineEmits<{ (ev: 'updateProps', props: WidgetProps); }>(); widget?: Widget<WidgetProps>;
}>();
const emit = defineEmits<{
(ev: 'updateProps', widgetProps: WidgetProps): void;
}>();
const { widgetProps, configure } = useWidgetPropsManager(name, const { widgetProps, configure } = useWidgetPropsManager(name,
widgetPropsDef, widgetPropsDef,
@ -48,7 +51,7 @@ const { widgetProps, configure } = useWidgetPropsManager(name,
emit, emit,
); );
const run = async () => { const run = async (): Promise<void> => {
const aiscript = new AiScript(createAiScriptEnv({ const aiscript = new AiScript(createAiScriptEnv({
storageKey: 'widget', storageKey: 'widget',
token: $i?.token, token: $i?.token,
@ -57,15 +60,15 @@ const run = async () => {
return new Promise(ok => { return new Promise(ok => {
os.inputText({ os.inputText({
title: q, title: q,
}).then(({ canceled, result: a }) => { }).then(({ result: a }) => {
ok(a); ok(a);
}); });
}); });
}, },
out: (value) => { out: (_value) => {
// nop // nop
}, },
log: (type, params) => { log: (_type, _params) => {
// nop // nop
}, },
}); });
@ -96,8 +99,3 @@ defineExpose<WidgetComponentExpose>({
id: props.widget ? props.widget.id : null, id: props.widget ? props.widget.id : null,
}); });
</script> </script>
<style lang="scss" scoped>
.mkw-button {
}
</style>

View file

@ -10,10 +10,9 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref, watch } from 'vue'; import { ref, watch } from 'vue';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget'; import { useWidgetPropsManager, Widget, WidgetComponentExpose } from './widget';
import { GetFormResultType } from '@/scripts/form'; import { GetFormResultType } from '@/scripts/form';
import * as os from '@/os';
import MkContainer from '@/components/ui/container.vue'; import MkContainer from '@/components/ui/container.vue';
import { defaultStore } from '@/store'; import { defaultStore } from '@/store';
import { i18n } from '@/i18n'; import { i18n } from '@/i18n';
@ -33,7 +32,9 @@ type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
//const props = defineProps<WidgetComponentProps<WidgetProps>>(); //const props = defineProps<WidgetComponentProps<WidgetProps>>();
//const emit = defineEmits<WidgetComponentEmits<WidgetProps>>(); //const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const props = defineProps<{ widget?: Widget<WidgetProps>; }>(); const props = defineProps<{ widget?: Widget<WidgetProps>; }>();
const emit = defineEmits<{ (ev: 'updateProps', props: WidgetProps); }>(); const emit = defineEmits<{
(ev: 'updateProps', widgetProps: WidgetProps): void;
}>();
const { widgetProps, configure } = useWidgetPropsManager(name, const { widgetProps, configure } = useWidgetPropsManager(name,
widgetPropsDef, widgetPropsDef,
@ -43,14 +44,14 @@ const { widgetProps, configure } = useWidgetPropsManager(name,
const text = ref<string | null>(defaultStore.state.memo); const text = ref<string | null>(defaultStore.state.memo);
const changed = ref(false); const changed = ref(false);
let timeoutId; let timeoutId: number;
const saveMemo = () => { const saveMemo = (): void => {
defaultStore.set('memo', text.value); defaultStore.set('memo', text.value);
changed.value = false; changed.value = false;
}; };
const onChange = () => { const onChange = (): void => {
changed.value = true; changed.value = true;
window.clearTimeout(timeoutId); window.clearTimeout(timeoutId);
timeoutId = window.setTimeout(saveMemo, 1000); timeoutId = window.setTimeout(saveMemo, 1000);

View file

@ -11,7 +11,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { defineAsyncComponent } from 'vue'; import { defineAsyncComponent } from 'vue';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget'; import { useWidgetPropsManager, Widget, WidgetComponentExpose } from './widget';
import { GetFormResultType } from '@/scripts/form'; import { GetFormResultType } from '@/scripts/form';
import MkContainer from '@/components/ui/container.vue'; import MkContainer from '@/components/ui/container.vue';
import XNotifications from '@/components/notifications.vue'; import XNotifications from '@/components/notifications.vue';

View file

@ -16,8 +16,9 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue'; import { onUnmounted } from 'vue';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget'; import { DriveFile } from 'foundkey-js/built/entities';
import { useWidgetPropsManager, Widget, WidgetComponentExpose } from './widget';
import { GetFormResultType } from '@/scripts/form'; import { GetFormResultType } from '@/scripts/form';
import { stream } from '@/stream'; import { stream } from '@/stream';
import { getStaticImageUrl } from '@/scripts/get-static-image-url'; import { getStaticImageUrl } from '@/scripts/get-static-image-url';
@ -44,8 +45,12 @@ type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
// vueimporttype // vueimporttype
//const props = defineProps<WidgetComponentProps<WidgetProps>>(); //const props = defineProps<WidgetComponentProps<WidgetProps>>();
//const emit = defineEmits<WidgetComponentEmits<WidgetProps>>(); //const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const props = defineProps<{ widget?: Widget<WidgetProps>; }>(); const props = defineProps<{
const emit = defineEmits<{ (ev: 'updateProps', props: WidgetProps); }>(); widget?: Widget<WidgetProps>;
}>();
const emit = defineEmits<{
(ev: 'updateProps', widgetProps: WidgetProps);
}>();
const { widgetProps, configure } = useWidgetPropsManager(name, const { widgetProps, configure } = useWidgetPropsManager(name,
widgetPropsDef, widgetPropsDef,
@ -54,17 +59,17 @@ const { widgetProps, configure } = useWidgetPropsManager(name,
); );
const connection = stream.useChannel('main'); const connection = stream.useChannel('main');
const images = ref([]); let images: DriveFile[] = $ref([]);
const fetching = ref(true); let fetching = $ref(true);
const onDriveFileCreated = (file) => { const onDriveFileCreated = (file: DriveFile): void => {
if (/^image\/.+$/.test(file.type)) { if (/^image\/.+$/.test(file.type)) {
images.value.unshift(file); images.unshift(file);
if (images.value.length > 9) images.value.pop(); if (images.length > 9) images.pop();
} }
}; };
const thumbnail = (image: any): string => { const thumbnail = (image: DriveFile): string => {
return defaultStore.state.disableShowingAnimatedImages return defaultStore.state.disableShowingAnimatedImages
? getStaticImageUrl(image.thumbnailUrl) ? getStaticImageUrl(image.thumbnailUrl)
: image.thumbnailUrl; : image.thumbnailUrl;
@ -74,8 +79,8 @@ os.api('drive/stream', {
type: 'image/*', type: 'image/*',
limit: 9, limit: 9,
}).then(res => { }).then(res => {
images.value = res; images = res;
fetching.value = false; fetching = false;
}); });
connection.on('driveFileCreated', onDriveFileCreated); connection.on('driveFileCreated', onDriveFileCreated);

View file

@ -19,11 +19,10 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'; import { ref, watch } from 'vue';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget'; import { useWidgetPropsManager, Widget, WidgetComponentExpose } from './widget';
import MarqueeText from '@/components/marquee.vue'; import MarqueeText from '@/components/marquee.vue';
import { GetFormResultType } from '@/scripts/form'; import { GetFormResultType } from '@/scripts/form';
import * as os from '@/os';
import MkContainer from '@/components/ui/container.vue'; import MkContainer from '@/components/ui/container.vue';
import { useInterval } from '@/scripts/use-interval'; import { useInterval } from '@/scripts/use-interval';
@ -77,7 +76,7 @@ const items = ref([]);
const fetching = ref(true); const fetching = ref(true);
let key = $ref(0); let key = $ref(0);
const tick = () => { const tick = (): void => {
fetch(`/api/fetch-rss?url=${widgetProps.url}`, {}).then(res => { fetch(`/api/fetch-rss?url=${widgetProps.url}`, {}).then(res => {
res.json().then(feed => { res.json().then(feed => {
items.value = feed.items; items.value = feed.items;

View file

@ -14,8 +14,9 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue'; import { onUnmounted } from 'vue';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from '../widget'; import { ServerInfo } from 'foundkey-js/built/entities';
import { useWidgetPropsManager, Widget, WidgetComponentExpose } from '../widget';
import XCpuMemory from './cpu-mem.vue'; import XCpuMemory from './cpu-mem.vue';
import XNet from './net.vue'; import XNet from './net.vue';
import XCpu from './cpu.vue'; import XCpu from './cpu.vue';
@ -50,8 +51,12 @@ type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
// vueimporttype // vueimporttype
//const props = defineProps<WidgetComponentProps<WidgetProps>>(); //const props = defineProps<WidgetComponentProps<WidgetProps>>();
//const emit = defineEmits<WidgetComponentEmits<WidgetProps>>(); //const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const props = defineProps<{ widget?: Widget<WidgetProps>; }>(); const props = defineProps<{
const emit = defineEmits<{ (ev: 'updateProps', props: WidgetProps); }>(); widget?: Widget<WidgetProps>;
}>();
const emit = defineEmits<{
(ev: 'updateProps', widgetProps: WidgetProps);
}>();
const { widgetProps, configure, save } = useWidgetPropsManager(name, const { widgetProps, configure, save } = useWidgetPropsManager(name,
widgetPropsDef, widgetPropsDef,
@ -59,13 +64,13 @@ const { widgetProps, configure, save } = useWidgetPropsManager(name,
emit, emit,
); );
const meta = ref(null); let meta = $ref<ServerInfo | null>(null);
os.api('server-info', {}).then(res => { os.api('server-info', {}).then(res => {
meta.value = res; meta = res;
}); });
const toggleView = () => { const toggleView = (): void => {
if (widgetProps.view === 4) { if (widgetProps.view === 4) {
widgetProps.view = 0; widgetProps.view = 0;
} else { } else {

View file

@ -12,8 +12,8 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'; import { onMounted, ref } from 'vue';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget'; import { useWidgetPropsManager, Widget, WidgetComponentExpose } from './widget';
import { GetFormResultType } from '@/scripts/form'; import { GetFormResultType } from '@/scripts/form';
import * as os from '@/os'; import * as os from '@/os';
import { useInterval } from '@/scripts/use-interval'; import { useInterval } from '@/scripts/use-interval';
@ -38,8 +38,12 @@ type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
// vueimporttype // vueimporttype
//const props = defineProps<WidgetComponentProps<WidgetProps>>(); //const props = defineProps<WidgetComponentProps<WidgetProps>>();
//const emit = defineEmits<WidgetComponentEmits<WidgetProps>>(); //const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const props = defineProps<{ widget?: Widget<WidgetProps>; }>(); const props = defineProps<{
const emit = defineEmits<{ (ev: 'updateProps', props: WidgetProps); }>(); widget?: Widget<WidgetProps>;
}>();
const emit = defineEmits<{
(ev: 'updateProps', widgetProps: WidgetProps): void;
}>();
const { widgetProps, configure, save } = useWidgetPropsManager(name, const { widgetProps, configure, save } = useWidgetPropsManager(name,
widgetPropsDef, widgetPropsDef,
@ -52,7 +56,7 @@ const fetching = ref(true);
const slideA = ref<HTMLElement>(); const slideA = ref<HTMLElement>();
const slideB = ref<HTMLElement>(); const slideB = ref<HTMLElement>();
const change = () => { const change = (): void => {
if (images.value.length === 0) return; if (images.value.length === 0) return;
const index = Math.floor(Math.random() * images.value.length); const index = Math.floor(Math.random() * images.value.length);
@ -71,7 +75,7 @@ const change = () => {
}, 1000); }, 1000);
}; };
const fetch = () => { const fetch = (): void => {
fetching.value = true; fetching.value = true;
os.api('drive/files', { os.api('drive/files', {
@ -87,7 +91,7 @@ const fetch = () => {
}); });
}; };
const choose = () => { const choose = (): void => {
os.selectDriveFolder(false).then(folder => { os.selectDriveFolder(false).then(folder => {
if (folder == null) { if (folder == null) {
return; return;

View file

@ -1,5 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"incremental": true,
"allowJs": true, "allowJs": true,
"noEmitOnError": false, "noEmitOnError": false,
"noImplicitAny": false, "noImplicitAny": false,

View file

@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed ### Changed
- foundkey-js is now part of the main FoundKey repo - foundkey-js is now part of the main FoundKey repo
- BREAKING: foundkey-js now uses ES2020 modules. Ensure that your version of Node supports them. - BREAKING: foundkey-js now uses ES2020 modules. Ensure that your version of Node supports them.
- The `comment` property of `DriveFile` is now nullable. Make sure to check that this property is not `null` before accessing it.
## 0.0.15 - 2022-07-22 ## 0.0.15 - 2022-07-22
### Changed ### Changed

View file

@ -1,47 +1,37 @@
# misskey.js # foundkey-js
**Strongly-typed official Misskey SDK for browsers/Node.js.** `foundkey-js` is a fork of [misskey-js](https://github.com/misskey-dev/misskey.js) that is more up to date.
[![Test](https://github.com/misskey-dev/misskey.js/actions/workflows/test.yml/badge.svg)](https://github.com/misskey-dev/misskey.js/actions/workflows/test.yml) The following is provided:
[![codecov](https://codecov.io/gh/misskey-dev/misskey.js/branch/develop/graph/badge.svg?token=PbrTtk3nVD)](https://codecov.io/gh/misskey-dev/misskey.js) - User authentication
- API requests
- Streaming
- Utility functions
- Various Misskey type definitions
[![NPM](https://nodei.co/npm/misskey-js.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/misskey-js) This library is designed to work with FoundKey. It should also work with Misskey 12+ but compatibility is not guaranteed.
JavaScript(TypeScript)用の公式MisskeySDKです。ブラウザ/Node.js上で動作します。
以下が提供されています:
- ユーザー認証
- APIリクエスト
- ストリーミング
- ユーティリティ関数
- Misskeyの各種型定義
対応するMisskeyのバージョンは12以上です。
## Install ## Install
``` This package is not currently published to npmjs.
npm i misskey-js
```
# Usage # Usage
インポートは以下のようにまとめて行うと便利です。 To use `foundkey-js` in your code, use the following import:
``` ts ``` ts
import * as Misskey from 'misskey-js'; import * as Misskey from 'foundkey-js';
``` ```
便宜上、以後のコード例は上記のように`* as Misskey`としてインポートしている前提のものになります。 For convenience, the following code examples are based on the assumption that the code is imported as `* as Misskey` as shown above.
ただし、このインポート方法だとTree-Shakingできなくなるので、コードサイズが重要なユースケースでは以下のような個別インポートをお勧めします。 However, since tree-shaking is not possible with this import method, we recommend the following individual import for use cases where code size is important.
``` ts ``` ts
import { api as misskeyApi } from 'misskey-js'; import { api as misskeyApi } from 'foundkey-js';
``` ```
## Authenticate ## Authenticate
todo todo
## API request ## API request
APIを利用する際は、利用するサーバーの情報とアクセストークンを与えて`APIClient`クラスのインスタンスを初期化し、そのインスタンスの`request`メソッドを呼び出してリクエストを行います。 When using the API, initialize an instance of the `APIClient` class by providing information on the server to be used and an access token, and make a request by calling the `request` method of the instance.
``` ts ``` ts
const cli = new Misskey.api.APIClient({ const cli = new Misskey.api.APIClient({
@ -52,12 +42,14 @@ const cli = new Misskey.api.APIClient({
const meta = await cli.request('meta', { detail: true }); const meta = await cli.request('meta', { detail: true });
``` ```
`request`の第一引数には呼び出すエンドポイント名、第二引数にはパラメータオブジェクトを渡します。レスポンスはPromiseとして返ります。 The first argument of `request` is the name of the endpoint to call, and the second argument is a parameter object. The response is returned as a Promise.
## Streaming ## Streaming
misskey.jsのストリーミングでは、二つのクラスが提供されます。 Two classes are provided for streaming in `foundkey-js`.
ひとつは、ストリーミングのコネクション自体を司る`Stream`クラスと、もうひとつはストリーミング上のチャンネルの概念を表す`Channel`クラスです。
ストリーミングを利用する際は、まず`Stream`クラスのインスタンスを初期化し、その後で`Stream`インスタンスのメソッドを利用して`Channel`クラスのインスタンスを取得する形になります。 One is the `Stream` class, which handles the streaming connection itself, and the other is the `Channel` class, which represents the concept of a channel on the streaming.
When using streaming, you first initialize an instance of the `Stream` class, and then use the methods of the `Stream` instance to get an instance of the `Channel` class.
``` ts ``` ts
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' }); const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
@ -67,19 +59,19 @@ mainChannel.on('notification', notification => {
}); });
``` ```
コネクションが途切れても自動で再接続されます。 If a connection is lost, it is automatically reconnected.
### チャンネルへの接続 ### Connecting to a channel
チャンネルへの接続は`Stream`クラスの`useChannel`メソッドを使用します。 Connection to a channel is made using the `useChannel` method of the `Stream` class.
パラメータなし No parameters
``` ts ``` ts
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' }); const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
const mainChannel = stream.useChannel('main'); const mainChannel = stream.useChannel('main');
``` ```
パラメータあり With parameters
``` ts ``` ts
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' }); const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
@ -88,8 +80,8 @@ const messagingChannel = stream.useChannel('messaging', {
}); });
``` ```
### チャンネルから切断 ### Disconnect from a channel
`Channel`クラスの`dispose`メソッドを呼び出します。 Call the `dispose` method of the `Channel` class.
``` ts ``` ts
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' }); const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
@ -99,8 +91,8 @@ const mainChannel = stream.useChannel('main');
mainChannel.dispose(); mainChannel.dispose();
``` ```
### メッセージの受信 ### Receiving messages
`Channel`クラスはEventEmitterを継承しており、メッセージがサーバーから受信されると受け取ったイベント名でペイロードをemitします。 The `Channel` class inherits from EventEmitter and when a message is received from the server, it emits a payload with the name of the event received.
``` ts ``` ts
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' }); const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
@ -110,8 +102,8 @@ mainChannel.on('notification', notification => {
}); });
``` ```
### メッセージの送信 ### Sending messages
`Channel`クラスの`send`メソッドを使用してメッセージをサーバーに送信することができます。 Messages can be sent to the server using the `send` method of the `Channel` class.
``` ts ``` ts
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' }); const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
@ -124,8 +116,8 @@ messagingChannel.send('read', {
}); });
``` ```
### コネクション確立イベント ### `_connected_` event
`Stream`クラスの`_connected_`イベントが利用可能です。 The `_connected_` event of the `Stream` class is available.
``` ts ``` ts
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' }); const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
@ -134,8 +126,8 @@ stream.on('_connected_', () => {
}); });
``` ```
### コネクション切断イベント ### `_disconnected_` event
`Stream`クラスの`_disconnected_`イベントが利用可能です。 The `_disconnected_` event of the `Stream` class is available.
``` ts ``` ts
const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' }); const stream = new Misskey.Stream('https://misskey.test', { token: 'TOKEN' });
@ -144,15 +136,9 @@ stream.on('_disconnected_', () => {
}); });
``` ```
### コネクションの状態 ### Connection state
`Stream`クラスの`state`プロパティで確認できます。 You can check the `state` property of the `Stream` class.
- `initializing`: 接続確立前 - `initializing`: before connection is established
- `connected`: 接続完了 - `connected`: connected.
- `reconnecting`: 再接続中 - `reconnecting`: reconnecting.
---
<div align="center">
<a href="https://github.com/misskey-dev/misskey/blob/develop/CONTRIBUTING.md"><img src="https://raw.githubusercontent.com/misskey-dev/assets/main/i-want-you.png" width="300"></a>
</div>

View file

@ -14,23 +14,25 @@
"api-prod": "npx api-extractor run --verbose", "api-prod": "npx api-extractor run --verbose",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx", "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"jest": "jest --coverage --detectOpenHandles", "jest": "jest --coverage --detectOpenHandles",
"test": "yarn jest && yarn tsd" "test": "yarn jest && yarn tsd",
"clean": "rm -rf built/",
"clean-all": "yarn clean && rm -rf node_modules/"
}, },
"devDependencies": { "devDependencies": {
"@microsoft/api-extractor": "^7.19.3", "@microsoft/api-extractor": "^7.19.3",
"@types/jest": "^27.4.0", "@types/jest": "^27.4.0",
"@types/node": "17.0.5", "@types/node": "18.7.15",
"@typescript-eslint/eslint-plugin": "5.8.1", "@typescript-eslint/eslint-plugin": "5.36.2",
"@typescript-eslint/parser": "5.8.1", "@typescript-eslint/parser": "^5.36.2",
"eslint": "8.6.0", "eslint": "^8.23.0",
"jest": "^27.4.5", "jest": "^27.4.5",
"jest-fetch-mock": "^3.0.3", "jest-fetch-mock": "^3.0.3",
"jest-websocket-mock": "^2.2.1", "jest-websocket-mock": "^2.2.1",
"mock-socket": "^9.0.8", "mock-socket": "^9.0.8",
"ts-jest": "^27.1.2", "ts-jest": "^27.1.5",
"ts-node": "10.4.0", "ts-node": "10.9.1",
"tsd": "^0.19.1", "tsd": "^0.23.0",
"typescript": "4.5.4" "typescript": "4.8.2"
}, },
"files": [ "files": [
"built" "built"

View file

@ -4,8 +4,8 @@ export type Acct = {
}; };
export function parse(acct: string): Acct { export function parse(acct: string): Acct {
if (acct.startsWith('@')) acct = acct.substr(1); const acct_ = acct.startsWith('@') ? acct.slice(1) : acct;
const split = acct.split('@', 2); const split = acct_.split('@', 2);
return { username: split[0], host: split[1] || null }; return { username: split[0], host: split[1] || null };
} }

View file

@ -117,7 +117,7 @@ export type DriveFile = {
size: number; size: number;
md5: string; md5: string;
blurhash: string; blurhash: string;
comment: string; comment: string | null;
properties: Record<string, any>; properties: Record<string, any>;
}; };

View file

@ -3,10 +3,10 @@ module.exports = {
env: { env: {
"node": false "node": false
}, },
parser: "@typescript-eslint/parser",
parserOptions: { parserOptions: {
"parser": "@typescript-eslint/parser",
tsconfigRootDir: __dirname, tsconfigRootDir: __dirname,
//project: ['./tsconfig.json'], project: ['./tsconfig.json'],
}, },
extends: [ extends: [
//"../shared/.eslintrc.js", //"../shared/.eslintrc.js",

View file

@ -5,7 +5,9 @@
"scripts": { "scripts": {
"watch": "node build.js watch", "watch": "node build.js watch",
"build": "node build.js", "build": "node build.js",
"lint": "eslint src --ext .ts" "lint": "eslint src --ext .ts",
"clean": "rm -rf built/",
"clean-all": "yarn clean && rm -rf node_modules/"
}, },
"dependencies": { "dependencies": {
"esbuild": "^0.14.13", "esbuild": "^0.14.13",

View file

@ -1,18 +0,0 @@
const fs = require('fs');
(async () => {
fs.rmSync(__dirname + '/../packages/backend/built', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/backend/node_modules', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/client/built', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/client/node_modules', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/foundkey-js/built', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/foundkey-js/node_modules', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/sw/built', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/sw/node_modules', { recursive: true, force: true });
fs.rmSync(__dirname + '/../built', { recursive: true, force: true });
fs.rmSync(__dirname + '/../node_modules', { recursive: true, force: true });
})();

View file

@ -1,9 +0,0 @@
const fs = require('fs');
(async () => {
fs.rmSync(__dirname + '/../packages/backend/built', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/client/built', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/foundkey-js/built', { recursive: true, force: true });
fs.rmSync(__dirname + '/../packages/sw/built', { recursive: true, force: true });
fs.rmSync(__dirname + '/../built', { recursive: true, force: true });
})();

1360
yarn.lock

File diff suppressed because it is too large Load diff