Merge branch 'develop' into feat-12997

This commit is contained in:
かっこかり 2024-09-06 16:29:20 +09:00 committed by GitHub
commit 1f6778570b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
37 changed files with 312 additions and 258 deletions

View File

@ -40,8 +40,6 @@ jobs:
needs: [pnpm_install] needs: [pnpm_install]
runs-on: ubuntu-latest runs-on: ubuntu-latest
continue-on-error: true continue-on-error: true
env:
eslint-cache-version: v1
strategy: strategy:
matrix: matrix:
workspace: workspace:
@ -49,6 +47,9 @@ jobs:
- frontend - frontend
- sw - sw
- misskey-js - misskey-js
env:
eslint-cache-version: v1
eslint-cache-path: ${{ github.workspace }}/node_modules/.cache/eslint-${{ matrix.workspace }}
steps: steps:
- uses: actions/checkout@v4.1.1 - uses: actions/checkout@v4.1.1
with: with:
@ -64,11 +65,10 @@ jobs:
- name: Restore eslint cache - name: Restore eslint cache
uses: actions/cache@v4.0.2 uses: actions/cache@v4.0.2
with: with:
path: node_modules/.cache/eslint path: ${{ env.eslint-cache-path }}
key: eslint-${{ env.eslint-cache-version }}-${{ hashFiles('/pnpm-lock.yaml') }}-${{ github.ref_name }}-${{ github.sha }} key: eslint-${{ env.eslint-cache-version }}-${{ matrix.workspace }}-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ github.ref_name }}-${{ github.sha }}
restore-keys: | restore-keys: eslint-${{ env.eslint-cache-version }}-${{ matrix.workspace }}-${{ hashFiles('**/pnpm-lock.yaml') }}-
eslint-${{ env.eslint-cache-version }}-${{ hashFiles('/pnpm-lock.yaml') }}- - run: pnpm --filter ${{ matrix.workspace }} run eslint --cache --cache-location ${{ env.eslint-cache-path }} --cache-strategy content
- run: pnpm --filter ${{ matrix.workspace }} run eslint --cache --cache-location node_modules/.cache/eslint --cache-strategy content
typecheck: typecheck:
needs: [pnpm_install] needs: [pnpm_install]
@ -78,6 +78,7 @@ jobs:
matrix: matrix:
workspace: workspace:
- backend - backend
- sw
- misskey-js - misskey-js
steps: steps:
- uses: actions/checkout@v4.1.1 - uses: actions/checkout@v4.1.1
@ -92,7 +93,7 @@ jobs:
- run: corepack enable - run: corepack enable
- run: pnpm i --frozen-lockfile - run: pnpm i --frozen-lockfile
- run: pnpm --filter misskey-js run build - run: pnpm --filter misskey-js run build
if: ${{ matrix.workspace == 'backend' }} if: ${{ matrix.workspace == 'backend' || matrix.workspace == 'sw' }}
- run: pnpm --filter misskey-reversi run build - run: pnpm --filter misskey-reversi run build
if: ${{ matrix.workspace == 'backend' }} if: ${{ matrix.workspace == 'backend' }}
- run: pnpm --filter ${{ matrix.workspace }} run typecheck - run: pnpm --filter ${{ matrix.workspace }} run typecheck

1
.gitignore vendored
View File

@ -44,6 +44,7 @@ compose.yml
/build /build
built built
built-test built-test
js-built
/data /data
/.cache-loader /.cache-loader
/db /db

View File

@ -5,6 +5,8 @@
### Client ### Client
- サイズ制限を超過するファイルをアップロードしようとした際にエラーを出すように - サイズ制限を超過するファイルをアップロードしようとした際にエラーを出すように
- Enhance: アイコンデコレーション管理画面にプレビューを追加
- Fix: サーバーメトリクスが2つ以上あるとリロード直後の表示がおかしくなる問題を修正
### Server ### Server
- ファイルがサイズの制限を超えてアップロードされた際にエラーを返さなかった問題を修正 - ファイルがサイズの制限を超えてアップロードされた際にエラーを返さなかった問題を修正

View File

@ -144,7 +144,9 @@ export interface Schema extends OfSchema {
readonly type?: TypeStringef; readonly type?: TypeStringef;
readonly nullable?: boolean; readonly nullable?: boolean;
readonly optional?: boolean; readonly optional?: boolean;
readonly prefixItems?: ReadonlyArray<Schema>;
readonly items?: Schema; readonly items?: Schema;
readonly unevaluatedItems?: Schema | boolean;
readonly properties?: Obj; readonly properties?: Obj;
readonly required?: ReadonlyArray<Extract<keyof NonNullable<this['properties']>, string>>; readonly required?: ReadonlyArray<Extract<keyof NonNullable<this['properties']>, string>>;
readonly description?: string; readonly description?: string;
@ -198,6 +200,7 @@ type UnionSchemaType<a extends readonly any[], X extends Schema = a[number]> = X
//type UnionObjectSchemaType<a extends readonly any[], X extends Schema = a[number]> = X extends any ? ObjectSchemaType<X> : never; //type UnionObjectSchemaType<a extends readonly any[], X extends Schema = a[number]> = X extends any ? ObjectSchemaType<X> : never;
type UnionObjType<s extends Obj, a extends readonly any[], X extends ReadonlyArray<keyof s> = a[number]> = X extends any ? ObjType<s, X> : never; type UnionObjType<s extends Obj, a extends readonly any[], X extends ReadonlyArray<keyof s> = a[number]> = X extends any ? ObjType<s, X> : never;
type ArrayUnion<T> = T extends any ? Array<T> : never; type ArrayUnion<T> = T extends any ? Array<T> : never;
type ArrayToTuple<X extends ReadonlyArray<Schema>> = { [K in keyof X]: SchemaType<X[K]> };
type ObjectSchemaTypeDef<p extends Schema> = type ObjectSchemaTypeDef<p extends Schema> =
p['ref'] extends keyof typeof refs ? Packed<p['ref']> : p['ref'] extends keyof typeof refs ? Packed<p['ref']> :
@ -232,6 +235,12 @@ export type SchemaTypeDef<p extends Schema> =
p['items']['allOf'] extends ReadonlyArray<Schema> ? UnionToIntersection<UnionSchemaType<NonNullable<p['items']['allOf']>>>[] : p['items']['allOf'] extends ReadonlyArray<Schema> ? UnionToIntersection<UnionSchemaType<NonNullable<p['items']['allOf']>>>[] :
never never
) : ) :
p['prefixItems'] extends ReadonlyArray<Schema> ? (
p['items'] extends NonNullable<Schema> ? [...ArrayToTuple<p['prefixItems']>, ...SchemaType<p['items']>[]] :
p['items'] extends false ? ArrayToTuple<p['prefixItems']> :
p['unevaluatedItems'] extends false ? ArrayToTuple<p['prefixItems']> :
[...ArrayToTuple<p['prefixItems']>, ...unknown[]]
) :
p['items'] extends NonNullable<Schema> ? SchemaType<p['items']>[] : p['items'] extends NonNullable<Schema> ? SchemaType<p['items']>[] :
any[] any[]
) : ) :

View File

@ -85,7 +85,7 @@ export type MiNotification = {
/** /**
* body * body
*/ */
customBody: string | null; customBody: string;
/** /**
* header * header

View File

@ -3,6 +3,7 @@
* SPDX-License-Identifier: AGPL-3.0-only * SPDX-License-Identifier: AGPL-3.0-only
*/ */
import { ACHIEVEMENT_TYPES } from '@/core/AchievementService.js';
import { notificationTypes } from '@/types.js'; import { notificationTypes } from '@/types.js';
const baseSchema = { const baseSchema = {
@ -294,6 +295,7 @@ export const packedNotificationSchema = {
achievement: { achievement: {
type: 'string', type: 'string',
optional: false, nullable: false, optional: false, nullable: false,
enum: ACHIEVEMENT_TYPES,
}, },
}, },
}, { }, {
@ -311,11 +313,11 @@ export const packedNotificationSchema = {
}, },
header: { header: {
type: 'string', type: 'string',
optional: false, nullable: false, optional: false, nullable: true,
}, },
icon: { icon: {
type: 'string', type: 'string',
optional: false, nullable: false, optional: false, nullable: true,
}, },
}, },
}, { }, {

View File

@ -21,8 +21,7 @@ export const meta = {
items: { items: {
type: 'array', type: 'array',
optional: false, nullable: false, optional: false, nullable: false,
items: { prefixItems: [
anyOf: [
{ {
type: 'string', type: 'string',
}, },
@ -30,7 +29,7 @@ export const meta = {
type: 'number', type: 'number',
}, },
], ],
}, unevaluatedItems: false,
}, },
example: [[ example: [[
'example.com', 'example.com',

View File

@ -21,8 +21,7 @@ export const meta = {
items: { items: {
type: 'array', type: 'array',
optional: false, nullable: false, optional: false, nullable: false,
items: { prefixItems: [
anyOf: [
{ {
type: 'string', type: 'string',
}, },
@ -30,7 +29,7 @@ export const meta = {
type: 'number', type: 'number',
}, },
], ],
}, unevaluatedItems: false,
}, },
example: [[ example: [[
'example.com', 'example.com',

View File

@ -166,7 +166,7 @@
if (!errorsElement) { if (!errorsElement) {
document.body.innerHTML = ` document.body.innerHTML = `
<svg class="icon-warning" xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-alert-triangle" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <svg class="icon-warning" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<path d="M12 9v2m0 4v.01"></path> <path d="M12 9v2m0 4v.01"></path>
<path d="M5 19h14a2 2 0 0 0 1.84 -2.75l-7.1 -12.25a2 2 0 0 0 -3.5 0l-7.1 12.25a2 2 0 0 0 1.75 2.75"></path> <path d="M5 19h14a2 2 0 0 0 1.84 -2.75l-7.1 -12.25a2 2 0 0 0 -3.5 0l-7.1 12.25a2 2 0 0 0 1.75 2.75"></path>
@ -320,6 +320,6 @@
#errorInfo { #errorInfo {
width: 50%; width: 50%;
} }
}`) }`);
} }
})(); })();

View File

@ -36,8 +36,6 @@ html
link(rel='prefetch' href=serverErrorImageUrl) link(rel='prefetch' href=serverErrorImageUrl)
link(rel='prefetch' href=infoImageUrl) link(rel='prefetch' href=infoImageUrl)
link(rel='prefetch' href=notFoundImageUrl) link(rel='prefetch' href=notFoundImageUrl)
//- https://github.com/misskey-dev/misskey/issues/9842
link(rel='stylesheet' href='/assets/tabler-icons/tabler-icons.min.css?v3.3.0')
link(rel='modulepreload' href=`/vite/${clientEntry.file}`) link(rel='modulepreload' href=`/vite/${clientEntry.file}`)
if !config.clientManifestExists if !config.clientManifestExists

View File

@ -6,6 +6,8 @@
// https://vitejs.dev/config/build-options.html#build-modulepreload // https://vitejs.dev/config/build-options.html#build-modulepreload
import 'vite/modulepreload-polyfill'; import 'vite/modulepreload-polyfill';
import '@tabler/icons-webfont/dist/tabler-icons.scss';
import '@/style.scss'; import '@/style.scss';
import { mainBoot } from '@/boot/main-boot.js'; import { mainBoot } from '@/boot/main-boot.js';
import { subBoot } from '@/boot/sub-boot.js'; import { subBoot } from '@/boot/sub-boot.js';

View File

@ -3,11 +3,6 @@
* SPDX-License-Identifier: AGPL-3.0-only * SPDX-License-Identifier: AGPL-3.0-only
*/ */
// devモードで起動される際index.htmlを使うときはrouterが暴発してしまってうまく読み込めない。
// よって、devモードとして起動されるときはビルド時に組み込む形としておく。
// (pnpm start時はpugファイルの中で静的リソースとして読み込むようになっており、この問題は起こっていない)
import '@tabler/icons-webfont/dist/tabler-icons.scss';
await main(); await main();
import('@/_boot_.js'); import('@/_boot_.js');

View File

@ -94,12 +94,12 @@ defineExpose({
--root-margin: 24px; --root-margin: 24px;
--headerHeight: 46px;
--headerHeightNarrow: 42px;
@media (max-width: 500px) { @media (max-width: 500px) {
--root-margin: 16px; --root-margin: 16px;
} }
--headerHeight: 46px;
--headerHeightNarrow: 42px;
} }
.header { .header {

View File

@ -100,14 +100,14 @@ defineProps<{
&.grid { &.grid {
> .group { > .group {
margin-left: 0;
margin-right: 0;
& + .group { & + .group {
padding-top: 0; padding-top: 0;
border-top: none; border-top: none;
} }
margin-left: 0;
margin-right: 0;
> .title { > .title {
font-size: 1em; font-size: 1em;
opacity: 0.7; opacity: 0.7;

View File

@ -508,10 +508,6 @@ defineExpose({
.header { .header {
--height: 39px; --height: 39px;
&.mini {
--height: 32px;
}
display: flex; display: flex;
position: relative; position: relative;
z-index: 1; z-index: 1;
@ -524,6 +520,10 @@ defineExpose({
//border-bottom: solid 1px var(--divider); //border-bottom: solid 1px var(--divider);
font-size: 90%; font-size: 90%;
font-weight: bold; font-weight: bold;
&.mini {
--height: 32px;
}
} }
.headerButton { .headerButton {

View File

@ -36,7 +36,9 @@ SPDX-License-Identifier: AGPL-3.0-only
<script lang="ts" setup> <script lang="ts" setup>
import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue'; import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue';
import * as Misskey from 'misskey-js';
import XChart from './overview.queue.chart.vue'; import XChart from './overview.queue.chart.vue';
import type { ApQueueDomain } from '@/pages/admin/queue.vue';
import number from '@/filters/number.js'; import number from '@/filters/number.js';
import { useStream } from '@/stream.js'; import { useStream } from '@/stream.js';
@ -52,10 +54,10 @@ const chartDelayed = shallowRef<InstanceType<typeof XChart>>();
const chartWaiting = shallowRef<InstanceType<typeof XChart>>(); const chartWaiting = shallowRef<InstanceType<typeof XChart>>();
const props = defineProps<{ const props = defineProps<{
domain: string; domain: ApQueueDomain;
}>(); }>();
const onStats = (stats) => { function onStats(stats: Misskey.entities.QueueStats) {
activeSincePrevTick.value = stats[props.domain].activeSincePrevTick; activeSincePrevTick.value = stats[props.domain].activeSincePrevTick;
active.value = stats[props.domain].active; active.value = stats[props.domain].active;
delayed.value = stats[props.domain].delayed; delayed.value = stats[props.domain].delayed;
@ -65,13 +67,13 @@ const onStats = (stats) => {
chartActive.value.pushData(stats[props.domain].active); chartActive.value.pushData(stats[props.domain].active);
chartDelayed.value.pushData(stats[props.domain].delayed); chartDelayed.value.pushData(stats[props.domain].delayed);
chartWaiting.value.pushData(stats[props.domain].waiting); chartWaiting.value.pushData(stats[props.domain].waiting);
}; }
const onStatsLog = (statsLog) => { function onStatsLog(statsLog: Misskey.entities.QueueStatsLog) {
const dataProcess = []; const dataProcess: Misskey.entities.QueueStats[ApQueueDomain]['activeSincePrevTick'][] = [];
const dataActive = []; const dataActive: Misskey.entities.QueueStats[ApQueueDomain]['active'][] = [];
const dataDelayed = []; const dataDelayed: Misskey.entities.QueueStats[ApQueueDomain]['delayed'][] = [];
const dataWaiting = []; const dataWaiting: Misskey.entities.QueueStats[ApQueueDomain]['waiting'][] = [];
for (const stats of [...statsLog].reverse()) { for (const stats of [...statsLog].reverse()) {
dataProcess.push(stats[props.domain].activeSincePrevTick); dataProcess.push(stats[props.domain].activeSincePrevTick);
@ -84,7 +86,7 @@ const onStatsLog = (statsLog) => {
chartActive.value.setData(dataActive); chartActive.value.setData(dataActive);
chartDelayed.value.setData(dataDelayed); chartDelayed.value.setData(dataDelayed);
chartWaiting.value.setData(dataWaiting); chartWaiting.value.setData(dataWaiting);
}; }
onMounted(() => { onMounted(() => {
connection.on('stats', onStats); connection.on('stats', onStats);

View File

@ -47,14 +47,14 @@ useInterval(fetch, 1000 * 60, {
.root { .root {
&:global { &:global {
> .users { > .users {
.chart-move {
transition: transform 1s ease;
}
display: grid; display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-gap: 12px; grid-gap: 12px;
.chart-move {
transition: transform 1s ease;
}
> .user:hover { > .user:hover {
text-decoration: none; text-decoration: none;
} }

View File

@ -49,7 +49,9 @@ SPDX-License-Identifier: AGPL-3.0-only
<script lang="ts" setup> <script lang="ts" setup>
import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue'; import { markRaw, onMounted, onUnmounted, ref, shallowRef } from 'vue';
import * as Misskey from 'misskey-js';
import XChart from './queue.chart.chart.vue'; import XChart from './queue.chart.chart.vue';
import type { ApQueueDomain } from '@/pages/admin/queue.vue';
import number from '@/filters/number.js'; import number from '@/filters/number.js';
import { misskeyApi } from '@/scripts/misskey-api.js'; import { misskeyApi } from '@/scripts/misskey-api.js';
import { useStream } from '@/stream.js'; import { useStream } from '@/stream.js';
@ -62,17 +64,17 @@ const activeSincePrevTick = ref(0);
const active = ref(0); const active = ref(0);
const delayed = ref(0); const delayed = ref(0);
const waiting = ref(0); const waiting = ref(0);
const jobs = ref<(string | number)[][]>([]); const jobs = ref<Misskey.Endpoints[`admin/queue/${ApQueueDomain}-delayed`]['res']>([]);
const chartProcess = shallowRef<InstanceType<typeof XChart>>(); const chartProcess = shallowRef<InstanceType<typeof XChart>>();
const chartActive = shallowRef<InstanceType<typeof XChart>>(); const chartActive = shallowRef<InstanceType<typeof XChart>>();
const chartDelayed = shallowRef<InstanceType<typeof XChart>>(); const chartDelayed = shallowRef<InstanceType<typeof XChart>>();
const chartWaiting = shallowRef<InstanceType<typeof XChart>>(); const chartWaiting = shallowRef<InstanceType<typeof XChart>>();
const props = defineProps<{ const props = defineProps<{
domain: string; domain: ApQueueDomain;
}>(); }>();
const onStats = (stats) => { function onStats(stats: Misskey.entities.QueueStats) {
activeSincePrevTick.value = stats[props.domain].activeSincePrevTick; activeSincePrevTick.value = stats[props.domain].activeSincePrevTick;
active.value = stats[props.domain].active; active.value = stats[props.domain].active;
delayed.value = stats[props.domain].delayed; delayed.value = stats[props.domain].delayed;
@ -82,13 +84,13 @@ const onStats = (stats) => {
chartActive.value.pushData(stats[props.domain].active); chartActive.value.pushData(stats[props.domain].active);
chartDelayed.value.pushData(stats[props.domain].delayed); chartDelayed.value.pushData(stats[props.domain].delayed);
chartWaiting.value.pushData(stats[props.domain].waiting); chartWaiting.value.pushData(stats[props.domain].waiting);
}; }
const onStatsLog = (statsLog) => { function onStatsLog(statsLog: Misskey.entities.QueueStatsLog) {
const dataProcess = []; const dataProcess: Misskey.entities.QueueStats[ApQueueDomain]['activeSincePrevTick'][] = [];
const dataActive = []; const dataActive: Misskey.entities.QueueStats[ApQueueDomain]['active'][] = [];
const dataDelayed = []; const dataDelayed: Misskey.entities.QueueStats[ApQueueDomain]['delayed'][] = [];
const dataWaiting = []; const dataWaiting: Misskey.entities.QueueStats[ApQueueDomain]['waiting'][] = [];
for (const stats of [...statsLog].reverse()) { for (const stats of [...statsLog].reverse()) {
dataProcess.push(stats[props.domain].activeSincePrevTick); dataProcess.push(stats[props.domain].activeSincePrevTick);
@ -101,14 +103,12 @@ const onStatsLog = (statsLog) => {
chartActive.value.setData(dataActive); chartActive.value.setData(dataActive);
chartDelayed.value.setData(dataDelayed); chartDelayed.value.setData(dataDelayed);
chartWaiting.value.setData(dataWaiting); chartWaiting.value.setData(dataWaiting);
}; }
onMounted(() => { onMounted(() => {
if (props.domain === 'inbox' || props.domain === 'deliver') {
misskeyApi(`admin/queue/${props.domain}-delayed`).then(result => { misskeyApi(`admin/queue/${props.domain}-delayed`).then(result => {
jobs.value = result; jobs.value = result;
}); });
}
connection.on('stats', onStats); connection.on('stats', onStats);
connection.on('statsLog', onStatsLog); connection.on('statsLog', onStatsLog);

View File

@ -16,7 +16,7 @@ SPDX-License-Identifier: AGPL-3.0-only
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref, computed } from 'vue'; import { ref, computed, type Ref } from 'vue';
import XQueue from './queue.chart.vue'; import XQueue from './queue.chart.vue';
import XHeader from './_header_.vue'; import XHeader from './_header_.vue';
import * as os from '@/os.js'; import * as os from '@/os.js';
@ -25,7 +25,9 @@ import { i18n } from '@/i18n.js';
import { definePageMetadata } from '@/scripts/page-metadata.js'; import { definePageMetadata } from '@/scripts/page-metadata.js';
import MkButton from '@/components/MkButton.vue'; import MkButton from '@/components/MkButton.vue';
const tab = ref('deliver'); export type ApQueueDomain = 'deliver' | 'inbox';
const tab: Ref<ApQueueDomain> = ref('deliver');
function clear() { function clear() {
os.confirm({ os.confirm({

View File

@ -12,6 +12,16 @@ SPDX-License-Identifier: AGPL-3.0-only
<template #label>{{ avatarDecoration.name }}</template> <template #label>{{ avatarDecoration.name }}</template>
<template #caption>{{ avatarDecoration.description }}</template> <template #caption>{{ avatarDecoration.description }}</template>
<div :class="$style.editorRoot">
<div :class="$style.editorWrapper">
<div :class="$style.preview">
<div :class="[$style.previewItem, $style.light]">
<MkAvatar style="width: 60px; height: 60px;" :user="$i" :decorations="[avatarDecoration]" forceShowDecoration/>
</div>
<div :class="[$style.previewItem, $style.dark]">
<MkAvatar style="width: 60px; height: 60px;" :user="$i" :decorations="[avatarDecoration]" forceShowDecoration/>
</div>
</div>
<div class="_gaps_m"> <div class="_gaps_m">
<MkInput v-model="avatarDecoration.name"> <MkInput v-model="avatarDecoration.name">
<template #label>{{ i18n.ts.name }}</template> <template #label>{{ i18n.ts.name }}</template>
@ -22,9 +32,11 @@ SPDX-License-Identifier: AGPL-3.0-only
<MkInput v-model="avatarDecoration.url"> <MkInput v-model="avatarDecoration.url">
<template #label>{{ i18n.ts.imageUrl }}</template> <template #label>{{ i18n.ts.imageUrl }}</template>
</MkInput> </MkInput>
<div class="buttons _buttons"> <div class="_buttons">
<MkButton class="button" inline primary @click="save(avatarDecoration)"><i class="ti ti-device-floppy"></i> {{ i18n.ts.save }}</MkButton> <MkButton inline primary @click="save(avatarDecoration)"><i class="ti ti-device-floppy"></i> {{ i18n.ts.save }}</MkButton>
<MkButton v-if="avatarDecoration.id != null" class="button" inline danger @click="del(avatarDecoration)"><i class="ti ti-trash"></i> {{ i18n.ts.delete }}</MkButton> <MkButton v-if="avatarDecoration.id != null" inline danger @click="del(avatarDecoration)"><i class="ti ti-trash"></i> {{ i18n.ts.delete }}</MkButton>
</div>
</div>
</div> </div>
</div> </div>
</MkFolder> </MkFolder>
@ -39,6 +51,7 @@ import * as Misskey from 'misskey-js';
import MkButton from '@/components/MkButton.vue'; import MkButton from '@/components/MkButton.vue';
import MkInput from '@/components/MkInput.vue'; import MkInput from '@/components/MkInput.vue';
import MkTextarea from '@/components/MkTextarea.vue'; import MkTextarea from '@/components/MkTextarea.vue';
import { signinRequired } from '@/account.js';
import * as os from '@/os.js'; import * as os from '@/os.js';
import { misskeyApi } from '@/scripts/misskey-api.js'; import { misskeyApi } from '@/scripts/misskey-api.js';
import { i18n } from '@/i18n.js'; import { i18n } from '@/i18n.js';
@ -47,6 +60,8 @@ import MkFolder from '@/components/MkFolder.vue';
const avatarDecorations = ref<Misskey.entities.AdminAvatarDecorationsListResponse>([]); const avatarDecorations = ref<Misskey.entities.AdminAvatarDecorationsListResponse>([]);
const $i = signinRequired();
function add() { function add() {
avatarDecorations.value.unshift({ avatarDecorations.value.unshift({
_id: Math.random().toString(36), _id: Math.random().toString(36),
@ -99,3 +114,55 @@ definePageMetadata(() => ({
icon: 'ti ti-sparkles', icon: 'ti ti-sparkles',
})); }));
</script> </script>
<style lang="scss" module>
.editorRoot {
container: editor / inline-size;
}
.editorWrapper {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: auto auto;
gap: var(--margin);
}
.preview {
display: grid;
place-items: center;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr;
gap: var(--margin);
}
.previewItem {
width: 100%;
height: 100%;
min-height: 160px;
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--radius);
&.light {
background: #eee;
}
&.dark {
background: #222;
}
}
@container editor (min-width: 600px) {
.editorWrapper {
grid-template-columns: 200px 1fr;
grid-template-rows: 1fr;
gap: calc(var(--margin) * 2);
}
.preview {
grid-template-columns: 1fr;
grid-template-rows: 1fr 1fr;
}
}
</style>

View File

@ -433,13 +433,12 @@ definePageMetadata(() => ({
.pageBannerTitleUser { .pageBannerTitleUser {
--height: 32px; --height: 32px;
flex-shrink: 0; flex-shrink: 0;
line-height: var(--height);
.avatar { .avatar {
height: var(--height); height: var(--height);
width: var(--height); width: var(--height);
} }
line-height: var(--height);
} }
.pageBannerTitleSubActions { .pageBannerTitleSubActions {

View File

@ -137,7 +137,6 @@ export class I18n<T extends ILocale> {
return this.tsxCache = new Proxy(this.locale, new Handler()) as unknown as Tsx<T>; return this.tsxCache = new Proxy(this.locale, new Handler()) as unknown as Tsx<T>;
} }
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (this.tsxCache) { if (this.tsxCache) {
return this.tsxCache; return this.tsxCache;
} }
@ -244,51 +243,3 @@ export class I18n<T extends ILocale> {
return str; return str;
} }
} }
if (import.meta.vitest) {
const { describe, expect, it } = import.meta.vitest;
describe('i18n', () => {
it('t', () => {
const i18n = new I18n({
foo: 'foo',
bar: {
baz: 'baz',
qux: 'qux {0}' as unknown as ParameterizedString<'0'>,
quux: 'quux {0} {1}' as unknown as ParameterizedString<'0' | '1'>,
},
});
expect(i18n.t('foo')).toBe('foo');
expect(i18n.t('bar.baz')).toBe('baz');
expect(i18n.tsx.bar.qux({ 0: 'hoge' })).toBe('qux hoge');
expect(i18n.tsx.bar.quux({ 0: 'hoge', 1: 'fuga' })).toBe('quux hoge fuga');
});
it('ts', () => {
const i18n = new I18n({
foo: 'foo',
bar: {
baz: 'baz',
qux: 'qux {0}' as unknown as ParameterizedString<'0'>,
quux: 'quux {0} {1}' as unknown as ParameterizedString<'0' | '1'>,
},
});
expect(i18n.ts.foo).toBe('foo');
expect(i18n.ts.bar.baz).toBe('baz');
});
it('tsx', () => {
const i18n = new I18n({
foo: 'foo',
bar: {
baz: 'baz',
qux: 'qux {0}' as unknown as ParameterizedString<'0'>,
quux: 'quux {0} {1}' as unknown as ParameterizedString<'0' | '1'>,
},
});
expect(i18n.tsx.bar.qux({ 0: 'hoge' })).toBe('qux hoge');
expect(i18n.tsx.bar.quux({ 0: 'hoge', 1: 'fuga' })).toBe('quux hoge fuga');
});
});
}

View File

@ -17,10 +17,6 @@
--minBottomSpacingMobile: calc(72px + max(12px, env(safe-area-inset-bottom, 0px))); --minBottomSpacingMobile: calc(72px + max(12px, env(safe-area-inset-bottom, 0px)));
--minBottomSpacing: var(--minBottomSpacingMobile); --minBottomSpacing: var(--minBottomSpacingMobile);
@media (max-width: 500px) {
--margin: var(--marginHalf);
}
//--ad: rgb(255 169 0 / 10%); //--ad: rgb(255 169 0 / 10%);
--eventFollow: #36aed2; --eventFollow: #36aed2;
--eventRenote: #36d298; --eventRenote: #36d298;
@ -29,6 +25,10 @@
--eventReaction: #e99a0b; --eventReaction: #e99a0b;
--eventAchievement: #cb9a11; --eventAchievement: #cb9a11;
--eventOther: #88a6b7; --eventOther: #88a6b7;
@media (max-width: 500px) {
--margin: var(--marginHalf);
}
} }
::selection { ::selection {

View File

@ -40,6 +40,14 @@ const XUserList = defineAsyncComponent(() => import('./statusbar-user-list.vue')
--nameMargin: 10px; --nameMargin: 10px;
font-size: 0.85em; font-size: 0.85em;
display: flex;
vertical-align: bottom;
width: 100%;
line-height: var(--height);
height: var(--height);
overflow: clip;
contain: strict;
&.verySmall { &.verySmall {
--nameMargin: 7px; --nameMargin: 7px;
--height: 16px; --height: 16px;
@ -64,14 +72,6 @@ const XUserList = defineAsyncComponent(() => import('./statusbar-user-list.vue')
font-size: 0.9em; font-size: 0.9em;
} }
display: flex;
vertical-align: bottom;
width: 100%;
line-height: var(--height);
height: var(--height);
overflow: clip;
contain: strict;
&.black { &.black {
background: #000; background: #000;
color: #fff; color: #fff;

View File

@ -324,11 +324,11 @@ function onDrop(ev) {
> .body { > .body {
background: transparent !important; background: transparent !important;
scrollbar-color: var(--scrollbarHandle) transparent;
&::-webkit-scrollbar-track { &::-webkit-scrollbar-track {
background: transparent; background: transparent;
} }
scrollbar-color: var(--scrollbarHandle) transparent;
} }
} }
@ -338,11 +338,11 @@ function onDrop(ev) {
> .body { > .body {
background: var(--bg) !important; background: var(--bg) !important;
overflow-y: scroll !important; overflow-y: scroll !important;
scrollbar-color: var(--scrollbarHandle) transparent;
&::-webkit-scrollbar-track { &::-webkit-scrollbar-track {
background: inherit; background: inherit;
} }
scrollbar-color: var(--scrollbarHandle) transparent;
} }
} }
} }
@ -423,10 +423,10 @@ function onDrop(ev) {
box-sizing: border-box; box-sizing: border-box;
container-type: size; container-type: size;
background-color: var(--bg); background-color: var(--bg);
scrollbar-color: var(--scrollbarHandle) var(--panel);
&::-webkit-scrollbar-track { &::-webkit-scrollbar-track {
background: var(--panel); background: var(--panel);
} }
scrollbar-color: var(--scrollbarHandle) var(--panel);
} }
</style> </style>

View File

@ -138,7 +138,7 @@ function onStats(connStats: Misskey.entities.ServerStats) {
} }
function onStatsLog(statsLog: Misskey.entities.ServerStatsLog) { function onStatsLog(statsLog: Misskey.entities.ServerStatsLog) {
for (const revStats of statsLog.reverse()) { for (const revStats of statsLog.toReversed()) {
onStats(revStats); onStats(revStats);
} }
} }

View File

@ -111,7 +111,7 @@ function onStats(connStats: Misskey.entities.ServerStats) {
} }
function onStatsLog(statsLog: Misskey.entities.ServerStatsLog) { function onStatsLog(statsLog: Misskey.entities.ServerStatsLog) {
for (const revStats of statsLog.reverse()) { for (const revStats of statsLog.toReversed()) {
onStats(revStats); onStats(revStats);
} }
} }

View File

@ -0,0 +1,52 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { describe, expect, it } from 'vitest';
import { I18n } from '@/scripts/i18n.js';
import { ParameterizedString } from '../../../locales/index.js';
describe('i18n', () => {
it('t', () => {
const i18n = new I18n({
foo: 'foo',
bar: {
baz: 'baz',
qux: 'qux {0}' as unknown as ParameterizedString<'0'>,
quux: 'quux {0} {1}' as unknown as ParameterizedString<'0' | '1'>,
},
});
expect(i18n.t('foo')).toBe('foo');
expect(i18n.t('bar.baz')).toBe('baz');
expect(i18n.tsx.bar.qux({ 0: 'hoge' })).toBe('qux hoge');
expect(i18n.tsx.bar.quux({ 0: 'hoge', 1: 'fuga' })).toBe('quux hoge fuga');
});
it('ts', () => {
const i18n = new I18n({
foo: 'foo',
bar: {
baz: 'baz',
qux: 'qux {0}' as unknown as ParameterizedString<'0'>,
quux: 'quux {0} {1}' as unknown as ParameterizedString<'0' | '1'>,
},
});
expect(i18n.ts.foo).toBe('foo');
expect(i18n.ts.bar.baz).toBe('baz');
});
it('tsx', () => {
const i18n = new I18n({
foo: 'foo',
bar: {
baz: 'baz',
qux: 'qux {0}' as unknown as ParameterizedString<'0'>,
quux: 'quux {0} {1}' as unknown as ParameterizedString<'0' | '1'>,
},
});
expect(i18n.tsx.bar.qux({ 0: 'hoge' })).toBe('qux hoge');
expect(i18n.tsx.bar.quux({ 0: 'hoge', 1: 'fuga' })).toBe('quux hoge fuga');
});
});

View File

@ -4245,15 +4245,16 @@ export type components = {
/** @enum {string} */ /** @enum {string} */
type: 'roleAssigned'; type: 'roleAssigned';
role: components['schemas']['Role']; role: components['schemas']['Role'];
} | { } | ({
/** Format: id */ /** Format: id */
id: string; id: string;
/** Format: date-time */ /** Format: date-time */
createdAt: string; createdAt: string;
/** @enum {string} */ /** @enum {string} */
type: 'achievementEarned'; type: 'achievementEarned';
achievement: string; /** @enum {string} */
} | { achievement: 'notes1' | 'notes10' | 'notes100' | 'notes500' | 'notes1000' | 'notes5000' | 'notes10000' | 'notes20000' | 'notes30000' | 'notes40000' | 'notes50000' | 'notes60000' | 'notes70000' | 'notes80000' | 'notes90000' | 'notes100000' | 'login3' | 'login7' | 'login15' | 'login30' | 'login60' | 'login100' | 'login200' | 'login300' | 'login400' | 'login500' | 'login600' | 'login700' | 'login800' | 'login900' | 'login1000' | 'passedSinceAccountCreated1' | 'passedSinceAccountCreated2' | 'passedSinceAccountCreated3' | 'loggedInOnBirthday' | 'loggedInOnNewYearsDay' | 'noteClipped1' | 'noteFavorited1' | 'myNoteFavorited1' | 'profileFilled' | 'markedAsCat' | 'following1' | 'following10' | 'following50' | 'following100' | 'following300' | 'followers1' | 'followers10' | 'followers50' | 'followers100' | 'followers300' | 'followers500' | 'followers1000' | 'collectAchievements30' | 'viewAchievements3min' | 'iLoveMisskey' | 'foundTreasure' | 'client30min' | 'client60min' | 'noteDeletedWithin1min' | 'postedAtLateNight' | 'postedAt0min0sec' | 'selfQuote' | 'htl20npm' | 'viewInstanceChart' | 'outputHelloWorldOnScratchpad' | 'open3windows' | 'driveFolderCircularReference' | 'reactWithoutRead' | 'clickedClickHere' | 'justPlainLucky' | 'setNameToSyuilo' | 'cookieClicked' | 'brainDiver' | 'smashTestNotificationButton' | 'tutorialCompleted' | 'bubbleGameExplodingHead' | 'bubbleGameDoubleExplodingHead';
}) | ({
/** Format: id */ /** Format: id */
id: string; id: string;
/** Format: date-time */ /** Format: date-time */
@ -4261,9 +4262,9 @@ export type components = {
/** @enum {string} */ /** @enum {string} */
type: 'app'; type: 'app';
body: string; body: string;
header: string; header: string | null;
icon: string; icon: string | null;
} | { }) | {
/** Format: id */ /** Format: id */
id: string; id: string;
/** Format: date-time */ /** Format: date-time */
@ -8219,7 +8220,7 @@ export type operations = {
/** @description OK (with results) */ /** @description OK (with results) */
200: { 200: {
content: { content: {
'application/json': ((string | number)[])[]; 'application/json': [string, number][];
}; };
}; };
/** @description Client error */ /** @description Client error */
@ -8265,7 +8266,7 @@ export type operations = {
/** @description OK (with results) */ /** @description OK (with results) */
200: { 200: {
content: { content: {
'application/json': ((string | number)[])[]; 'application/json': [string, number][];
}; };
}; };
/** @description Client error */ /** @description Client error */

View File

@ -8,10 +8,10 @@
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import * as esbuild from 'esbuild'; import * as esbuild from 'esbuild';
import locales from '../../locales/index.js'; import locales from '../../locales/index.js';
import meta from '../../package.json' with { type: "json" }; import meta from '../../package.json' with { type: 'json' };
const watch = process.argv[2]?.includes('watch'); const watch = process.argv[2]?.includes('watch');
const __dirname = fileURLToPath(new URL('.', import.meta.url)) const __dirname = fileURLToPath(new URL('.', import.meta.url));
console.log('Starting SW building...'); console.log('Starting SW building...');

View File

@ -41,11 +41,10 @@ export async function createNotification<K extends keyof PushNotificationDataMap
async function composeNotification(data: PushNotificationDataMap[keyof PushNotificationDataMap]): Promise<[string, NotificationOptions] | null> { async function composeNotification(data: PushNotificationDataMap[keyof PushNotificationDataMap]): Promise<[string, NotificationOptions] | null> {
const i18n = await (swLang.i18n ?? swLang.fetchLocale()); const i18n = await (swLang.i18n ?? swLang.fetchLocale());
const { t } = i18n;
switch (data.type) { switch (data.type) {
/* /*
case 'driveFileCreated': // TODO (Server Side) case 'driveFileCreated': // TODO (Server Side)
return [t('_notification.fileUploaded'), { return [i18n.ts._notification.fileUploaded, {
body: body.name, body: body.name,
icon: body.url, icon: body.url,
data data
@ -58,52 +57,52 @@ async function composeNotification(data: PushNotificationDataMap[keyof PushNotif
const account = await getAccountFromId(data.userId); const account = await getAccountFromId(data.userId);
if (!account) return null; if (!account) return null;
const userDetail = await cli.request('users/show', { userId: data.body.userId }, account.token); const userDetail = await cli.request('users/show', { userId: data.body.userId }, account.token);
return [t('_notification.youWereFollowed'), { return [i18n.ts._notification.youWereFollowed, {
body: getUserName(data.body.user), body: getUserName(data.body.user),
icon: data.body.user.avatarUrl, icon: data.body.user.avatarUrl ?? undefined,
badge: iconUrl('user-plus'), badge: iconUrl('user-plus'),
data, data,
actions: userDetail.isFollowing ? [] : [ actions: userDetail.isFollowing ? [] : [
{ {
action: 'follow', action: 'follow',
title: t('_notification._actions.followBack'), title: i18n.ts._notification._actions.followBack,
}, },
], ],
}]; }];
} }
case 'mention': case 'mention':
return [t('_notification.youGotMention', { name: getUserName(data.body.user) }), { return [i18n.tsx._notification.youGotMention({ name: getUserName(data.body.user) }), {
body: data.body.note.text ?? '', body: data.body.note.text ?? '',
icon: data.body.user.avatarUrl, icon: data.body.user.avatarUrl ?? undefined,
badge: iconUrl('at'), badge: iconUrl('at'),
data, data,
actions: [ actions: [
{ {
action: 'reply', action: 'reply',
title: t('_notification._actions.reply'), title: i18n.ts._notification._actions.reply,
}, },
], ],
}]; }];
case 'reply': case 'reply':
return [t('_notification.youGotReply', { name: getUserName(data.body.user) }), { return [i18n.tsx._notification.youGotReply({ name: getUserName(data.body.user) }), {
body: data.body.note.text ?? '', body: data.body.note.text ?? '',
icon: data.body.user.avatarUrl, icon: data.body.user.avatarUrl ?? undefined,
badge: iconUrl('arrow-back-up'), badge: iconUrl('arrow-back-up'),
data, data,
actions: [ actions: [
{ {
action: 'reply', action: 'reply',
title: t('_notification._actions.reply'), title: i18n.ts._notification._actions.reply,
}, },
], ],
}]; }];
case 'renote': case 'renote':
return [t('_notification.youRenoted', { name: getUserName(data.body.user) }), { return [i18n.tsx._notification.youRenoted({ name: getUserName(data.body.user) }), {
body: data.body.note.text ?? '', body: data.body.note.text ?? '',
icon: data.body.user.avatarUrl, icon: data.body.user.avatarUrl ?? undefined,
badge: iconUrl('repeat'), badge: iconUrl('repeat'),
data, data,
actions: [ actions: [
@ -115,29 +114,29 @@ async function composeNotification(data: PushNotificationDataMap[keyof PushNotif
}]; }];
case 'quote': case 'quote':
return [t('_notification.youGotQuote', { name: getUserName(data.body.user) }), { return [i18n.tsx._notification.youGotQuote({ name: getUserName(data.body.user) }), {
body: data.body.note.text ?? '', body: data.body.note.text ?? '',
icon: data.body.user.avatarUrl, icon: data.body.user.avatarUrl ?? undefined,
badge: iconUrl('quote'), badge: iconUrl('quote'),
data, data,
actions: [ actions: [
{ {
action: 'reply', action: 'reply',
title: t('_notification._actions.reply'), title: i18n.ts._notification._actions.reply,
}, },
...((data.body.note.visibility === 'public' || data.body.note.visibility === 'home') ? [ ...((data.body.note.visibility === 'public' || data.body.note.visibility === 'home') ? [
{ {
action: 'renote', action: 'renote',
title: t('_notification._actions.renote'), title: i18n.ts._notification._actions.renote,
}, },
] : []), ] : []),
], ],
}]; }];
case 'note': case 'note':
return [t('_notification.newNote') + ': ' + getUserName(data.body.user), { return [i18n.ts._notification.newNote + ': ' + getUserName(data.body.user), {
body: data.body.note.text ?? '', body: data.body.note.text ?? '',
icon: data.body.user.avatarUrl, icon: data.body.user.avatarUrl ?? undefined,
data, data,
}]; }];
@ -164,7 +163,7 @@ async function composeNotification(data: PushNotificationDataMap[keyof PushNotif
const tag = `reaction:${data.body.note.id}`; const tag = `reaction:${data.body.note.id}`;
return [`${reaction} ${getUserName(data.body.user)}`, { return [`${reaction} ${getUserName(data.body.user)}`, {
body: data.body.note.text ?? '', body: data.body.note.text ?? '',
icon: data.body.user.avatarUrl, icon: data.body.user.avatarUrl ?? undefined,
tag, tag,
badge, badge,
data, data,
@ -178,41 +177,41 @@ async function composeNotification(data: PushNotificationDataMap[keyof PushNotif
} }
case 'receiveFollowRequest': case 'receiveFollowRequest':
return [t('_notification.youReceivedFollowRequest'), { return [i18n.ts._notification.youReceivedFollowRequest, {
body: getUserName(data.body.user), body: getUserName(data.body.user),
icon: data.body.user.avatarUrl, icon: data.body.user.avatarUrl ?? undefined,
badge: iconUrl('user-plus'), badge: iconUrl('user-plus'),
data, data,
actions: [ actions: [
{ {
action: 'accept', action: 'accept',
title: t('accept'), title: i18n.ts.accept,
}, },
{ {
action: 'reject', action: 'reject',
title: t('reject'), title: i18n.ts.reject,
}, },
], ],
}]; }];
case 'followRequestAccepted': case 'followRequestAccepted':
return [t('_notification.yourFollowRequestAccepted'), { return [i18n.ts._notification.yourFollowRequestAccepted, {
body: getUserName(data.body.user), body: getUserName(data.body.user),
icon: data.body.user.avatarUrl, icon: data.body.user.avatarUrl ?? undefined,
badge: iconUrl('circle-check'), badge: iconUrl('circle-check'),
data, data,
}]; }];
case 'achievementEarned': case 'achievementEarned':
return [t('_notification.achievementEarned'), { return [i18n.ts._notification.achievementEarned, {
body: t(`_achievements._types._${data.body.achievement}.title`), body: i18n.ts._achievements._types[`_${data.body.achievement}`].title,
badge: iconUrl('medal'), badge: iconUrl('medal'),
data, data,
tag: `achievement:${data.body.achievement}`, tag: `achievement:${data.body.achievement}`,
}]; }];
case 'pollEnded': case 'pollEnded':
return [t('_notification.pollEnded'), { return [i18n.ts._notification.pollEnded, {
body: data.body.note.text ?? '', body: data.body.note.text ?? '',
badge: iconUrl('chart-arrows'), badge: iconUrl('chart-arrows'),
data, data,
@ -226,8 +225,8 @@ async function composeNotification(data: PushNotificationDataMap[keyof PushNotif
}]; }];
case 'test': case 'test':
return [t('_notification.testNotification'), { return [i18n.ts._notification.testNotification, {
body: t('_notification.notificationWillBeDisplayedLikeThis'), body: i18n.ts._notification.notificationWillBeDisplayedLikeThis,
badge: iconUrl('bell'), badge: iconUrl('bell'),
data, data,
}]; }];
@ -236,9 +235,9 @@ async function composeNotification(data: PushNotificationDataMap[keyof PushNotif
return null; return null;
} }
case 'unreadAntennaNote': case 'unreadAntennaNote':
return [t('_notification.unreadAntennaNote', { name: data.body.antenna.name }), { return [i18n.tsx._notification.unreadAntennaNote({ name: data.body.antenna.name }), {
body: `${getUserName(data.body.note.user)}: ${data.body.note.text ?? ''}`, body: `${getUserName(data.body.note.user)}: ${data.body.note.text ?? ''}`,
icon: data.body.note.user.avatarUrl, icon: data.body.note.user.avatarUrl ?? undefined,
badge: iconUrl('antenna'), badge: iconUrl('antenna'),
tag: `antenna:${data.body.antenna.id}`, tag: `antenna:${data.body.antenna.id}`,
data, data,
@ -252,7 +251,6 @@ async function composeNotification(data: PushNotificationDataMap[keyof PushNotif
export async function createEmptyNotification(): Promise<void> { export async function createEmptyNotification(): Promise<void> {
return new Promise<void>(async res => { return new Promise<void>(async res => {
const i18n = await (swLang.i18n ?? swLang.fetchLocale()); const i18n = await (swLang.i18n ?? swLang.fetchLocale());
const { t } = i18n;
await globalThis.registration.showNotification( await globalThis.registration.showNotification(
(new URL(origin)).host, (new URL(origin)).host,
@ -264,11 +262,11 @@ export async function createEmptyNotification(): Promise<void> {
actions: [ actions: [
{ {
action: 'markAllAsRead', action: 'markAllAsRead',
title: t('markAllAsRead'), title: i18n.ts.markAllAsRead,
}, },
{ {
action: 'settings', action: 'settings',
title: t('notificationSettings'), title: i18n.ts.notificationSettings,
}, },
], ],
data: {}, data: {},

View File

@ -4,9 +4,10 @@
*/ */
import { get } from 'idb-keyval'; import { get } from 'idb-keyval';
import * as Misskey from 'misskey-js';
export async function getAccountFromId(id: string): Promise<{ token: string; id: string } | void> { export async function getAccountFromId(id: string): Promise<Pick<Misskey.entities.SignupResponse, 'id' | 'token'> | undefined> {
const accounts = await get<{ token: string; id: string }[]>('accounts'); const accounts = await get<Pick<Misskey.entities.SignupResponse, 'id' | 'token'>[]>('accounts');
if (!accounts) { if (!accounts) {
console.log('Accounts are not recorded'); console.log('Accounts are not recorded');
return; return;

View File

@ -1,37 +0,0 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
export type Locale = { [key: string]: string | Locale };
export class I18n<T extends Locale = Locale> {
public ts: T;
constructor(locale: T) {
this.ts = locale;
//#region BIND
this.t = this.t.bind(this);
//#endregion
}
// string にしているのは、ドット区切りでのパス指定を許可するため
// なるべくこのメソッド使うよりもlocale直接参照の方がvueのキャッシュ効いてパフォーマンスが良いかも
public t(key: string, args?: Record<string, string>): string {
try {
let str = key.split('.').reduce<Locale | Locale[keyof Locale]>((o, i) => o[i], this.ts);
if (typeof str !== 'string') throw new Error();
if (args) {
for (const [k, v] of Object.entries(args)) {
str = str.replace(`{${k}}`, v);
}
}
return str;
} catch (err) {
console.warn(`missing localization '${key}'`);
return key;
}
}
}

View File

@ -7,7 +7,8 @@
* Language manager for SW * Language manager for SW
*/ */
import { get, set } from 'idb-keyval'; import { get, set } from 'idb-keyval';
import { I18n, type Locale } from '@/scripts/i18n.js'; import { I18n } from '../../../frontend/src/scripts/i18n.js';
import type { Locale } from '../../../../locales/index.js';
class SwLang { class SwLang {
public cacheName = `mk-cache-${_VERSION_}`; public cacheName = `mk-cache-${_VERSION_}`;
@ -23,7 +24,7 @@ class SwLang {
return this.fetchLocale(); return this.fetchLocale();
} }
public i18n: Promise<I18n> | null = null; public i18n: Promise<I18n<Locale>> | null = null;
public fetchLocale(): Promise<I18n<Locale>> { public fetchLocale(): Promise<I18n<Locale>> {
return (this.i18n = this._fetch()); return (this.i18n = this._fetch());

View File

@ -14,15 +14,22 @@ import { getUrlWithLoginId } from '@/scripts/login-id.js';
export const cli = new Misskey.api.APIClient({ origin, fetch: (...args): Promise<Response> => fetch(...args) }); export const cli = new Misskey.api.APIClient({ origin, fetch: (...args): Promise<Response> => fetch(...args) });
export async function api<E extends keyof Misskey.Endpoints, O extends Misskey.Endpoints[E]['req']>(endpoint: E, userId?: string, options?: O): Promise<void | ReturnType<typeof cli.request<E, O>>> { export async function api<
let account: { token: string; id: string } | void = undefined; E extends keyof Misskey.Endpoints,
P extends Misskey.Endpoints[E]['req']
>(endpoint: E, userId?: string, params?: P): Promise<Misskey.api.SwitchCaseResponseType<E, P> | undefined> {
let account: Pick<Misskey.entities.SignupResponse, 'id' | 'token'> | undefined;
if (userId) { if (userId) {
account = await getAccountFromId(userId); account = await getAccountFromId(userId);
if (!account) return; if (!account) return;
} }
return cli.request(endpoint, options, account?.token); return (cli.request as <E extends keyof Misskey.Endpoints, P extends Misskey.Endpoints[E]['req']>(
endpoint: E,
params: P,
credential?: string | null,
) => Promise<Misskey.api.SwitchCaseResponseType<E, P>>)(endpoint, params, account?.token);
} }
// mark-all-as-read送出を1秒間隔に制限する // mark-all-as-read送出を1秒間隔に制限する
@ -33,7 +40,7 @@ export function sendMarkAllAsRead(userId: string): Promise<null | undefined | vo
return new Promise(resolve => { return new Promise(resolve => {
setTimeout(() => { setTimeout(() => {
readBlockingStatus.set(userId, false); readBlockingStatus.set(userId, false);
api('notifications/mark-all-as-read', userId).then(resolve, resolve); (api('notifications/mark-all-as-read', userId) as Promise<void>).then(resolve, resolve);
}, 1000); }, 1000);
}); });
} }

View File

@ -6,7 +6,8 @@
import { get } from 'idb-keyval'; import { get } from 'idb-keyval';
import * as Misskey from 'misskey-js'; import * as Misskey from 'misskey-js';
import type { PushNotificationDataMap } from '@/types.js'; import type { PushNotificationDataMap } from '@/types.js';
import type { I18n, Locale } from '@/scripts/i18n.js'; import type { I18n } from '../../frontend/src/scripts/i18n.js';
import type { Locale } from '../../../locales/index.js';
import { createEmptyNotification, createNotification } from '@/scripts/create-notification.js'; import { createEmptyNotification, createNotification } from '@/scripts/create-notification.js';
import { swLang } from '@/scripts/lang.js'; import { swLang } from '@/scripts/lang.js';
import * as swos from '@/scripts/operations.js'; import * as swos from '@/scripts/operations.js';
@ -30,8 +31,8 @@ globalThis.addEventListener('activate', ev => {
async function offlineContentHTML() { async function offlineContentHTML() {
const i18n = await (swLang.i18n ?? swLang.fetchLocale()) as Partial<I18n<Locale>>; const i18n = await (swLang.i18n ?? swLang.fetchLocale()) as Partial<I18n<Locale>>;
const messages = { const messages = {
title: i18n.ts?._offlineScreen?.title ?? 'Offline - Could not connect to server', title: i18n.ts?._offlineScreen.title ?? 'Offline - Could not connect to server',
header: i18n.ts?._offlineScreen?.header ?? 'Could not connect to server', header: i18n.ts?._offlineScreen.header ?? 'Could not connect to server',
reload: i18n.ts?.reload ?? 'Reload', reload: i18n.ts?.reload ?? 'Reload',
}; };
@ -159,8 +160,8 @@ globalThis.addEventListener('notificationclick', (ev: ServiceWorkerGlobalScopeEv
case 'markAllAsRead': case 'markAllAsRead':
await globalThis.registration.getNotifications() await globalThis.registration.getNotifications()
.then(notifications => notifications.forEach(n => n.tag !== 'read_notification' && n.close())); .then(notifications => notifications.forEach(n => n.tag !== 'read_notification' && n.close()));
await get('accounts').then(accounts => { await get<Pick<Misskey.entities.SignupResponse, 'id' | 'token'>[]>('accounts').then(accounts => {
return Promise.all(accounts.map(async account => { return Promise.all((accounts ?? []).map(async account => {
await swos.sendMarkAllAsRead(account.id); await swos.sendMarkAllAsRead(account.id);
})); }));
}); });

View File

@ -2,6 +2,7 @@
"compilerOptions": { "compilerOptions": {
"allowJs": true, "allowJs": true,
"noEmitOnError": false, "noEmitOnError": false,
"noImplicitAny": false,
"noImplicitReturns": true, "noImplicitReturns": true,
"noUnusedParameters": false, "noUnusedParameters": false,
"noUnusedLocals": true, "noUnusedLocals": true,