Merge remote-tracking branch 'misskey/develop' into develop

This commit is contained in:
ThatOneCalculator 2022-08-04 13:31:54 -07:00
commit 0e7361d4b8
15 changed files with 672 additions and 34 deletions

View file

@ -2,6 +2,7 @@
## 12.x.x (unreleased)
### Improvements
- Client: Preferences Registry
### Bugfixes
-
@ -13,6 +14,7 @@ You should also include the user name that made the change.
### Improvements
- Client: Add vi-VN language support
- Client: Add unix time widget @syuilo
### Bugfixes
- Server: リモートユーザーを正しくブロックできるように修正する @xianonn

View file

@ -52,6 +52,7 @@ searchUser: "ユーザーを検索"
reply: "返信"
loadMore: "もっと見る"
showMore: "もっと見る"
showLess: "閉じる"
youGotNewFollower: "フォローされました"
receiveFollowRequest: "フォローリクエストされました"
followRequestAccepted: "フォローが承認されました"
@ -562,6 +563,7 @@ author: "作者"
leaveConfirm: "未保存の変更があります。破棄しますか?"
manage: "管理"
plugins: "プラグイン"
preferencesBackups: "設定のバックアップ"
deck: "デッキ"
undeck: "デッキ解除"
useBlurEffectForModal: "モーダルにぼかし効果を使用"
@ -970,6 +972,25 @@ _plugin:
installWarn: "信頼できないプラグインはインストールしないでください。"
manage: "プラグインの管理"
_preferencesBackups:
list: "作成したバックアップ"
saveNew: "新規保存"
loadFile: "ファイルを読み込み"
apply: "このデバイスに適用"
save: "上書き保存"
inputName: "バックアップ名を入力"
cannotSave: "保存できません"
nameAlreadyExists: "バックアップ名「{name}」は既に存在します。違う名前を指定してください。"
applyConfirm: "バックアップ「{name}」を現在のデバイスに適用しますか?現在のデバイス設定は失われます。"
saveConfirm: "{name}に上書き保存しますか?"
deleteConfirm: "{name}を削除しますか?"
renameConfirm: "「{old}」を「{new}」に変更しますか?"
noBackups: "バックアップはありません。「新規保存」で現在のクライアント設定をサーバーに保存できます。"
createdAt: "作成日時: {date} {time}"
updatedAt: "更新日時: {date} {time}"
cannotLoad: "読み込みできません"
invalidFile: "ファイル形式が違います。"
_registry:
scope: "スコープ"
key: "キー"
@ -1310,6 +1331,7 @@ _widgets:
activity: "アクティビティ"
photos: "フォト"
digitalClock: "デジタル時計"
unixClock: "UNIX時計"
federation: "連合"
instanceCloud: "インスタンスクラウド"
postForm: "投稿フォーム"

View file

@ -54,7 +54,7 @@
"devDependencies": {
"@types/gulp": "4.0.9",
"@types/gulp-rename": "2.0.1",
"@typescript-eslint/parser": "5.30.7",
"@typescript-eslint/parser": "5.31.0",
"cross-env": "7.0.3",
"cypress": "10.3.1",
"start-server-and-test": "1.14.0",

View file

@ -17,9 +17,7 @@
"@tensorflow/tfjs-node": "3.19.0"
},
"dependencies": {
"@bull-board/api": "4.0.0",
"@bull-board/koa": "4.0.0",
"@bull-board/ui": "4.0.0",
"@bull-board/koa": "4.1.1",
"@discordapp/twemoji": "14.0.2",
"@elastic/elasticsearch": "7.17.0",
"@koa/cors": "3.3.0",
@ -32,10 +30,10 @@
"archiver": "5.3.1",
"autobind-decorator": "2.4.0",
"autwh": "0.1.0",
"aws-sdk": "2.1165.0",
"aws-sdk": "2.1185.0",
"bcryptjs": "2.4.3",
"blurhash": "1.1.5",
"bull": "4.8.4",
"bull": "4.8.5",
"cacheable-lookup": "6.0.4",
"cbor": "8.1.0",
"chalk": "5.0.1",
@ -48,9 +46,9 @@
"deep-email-validator": "0.1.21",
"escape-regexp": "0.0.1",
"feed": "4.2.2",
"file-type": "17.1.3",
"file-type": "17.1.4",
"fluent-ffmpeg": "2.1.2",
"got": "12.2.0",
"got": "12.3.0",
"hpagent": "0.1.2",
"ioredis": "4.28.5",
"ip-cidr": "3.0.10",
@ -76,7 +74,7 @@
"mocha": "10.0.0",
"multer": "1.4.4",
"nested-property": "4.0.0",
"node-fetch": "3.2.9",
"node-fetch": "3.2.10",
"nodemailer": "6.7.7",
"nsfwjs": "2.4.1",
"oauth": "^0.9.15",
@ -125,9 +123,9 @@
"xev": "3.0.2"
},
"devDependencies": {
"@redocly/openapi-core": "1.0.0-beta.104",
"@redocly/openapi-core": "1.0.0-beta.105",
"@types/bcryptjs": "2.4.2",
"@types/bull": "3.15.8",
"@types/bull": "3.15.9",
"@types/cbor": "6.0.0",
"@types/escape-regexp": "0.0.1",
"@types/fluent-ffmpeg": "2.1.20",
@ -147,7 +145,7 @@
"@types/koa__multer": "2.0.4",
"@types/koa__router": "8.0.11",
"@types/mocha": "9.1.1",
"@types/node": "18.6.1",
"@types/node": "18.6.3",
"@types/node-fetch": "3.0.3",
"@types/nodemailer": "6.4.4",
"@types/oauth": "0.9.1",
@ -169,8 +167,8 @@
"@types/web-push": "3.3.2",
"@types/websocket": "1.0.5",
"@types/ws": "8.5.3",
"@typescript-eslint/eslint-plugin": "5.30.7",
"@typescript-eslint/parser": "5.30.7",
"@typescript-eslint/eslint-plugin": "5.31.0",
"@typescript-eslint/parser": "5.31.0",
"cross-env": "7.0.3",
"eslint": "8.20.0",
"eslint-plugin-import": "2.26.0",

View file

@ -51,7 +51,7 @@ html
.then(registrations => {
return Promise.all(registrations.map(registration => registration.unregister()));
})
.catch(e => { throw Error(e) });
.catch(e => { throw new Error(e) });
}
message(successText);

View file

@ -9,7 +9,7 @@
"noFallthroughCasesInSwitch": true,
"declaration": false,
"sourceMap": true,
"target": "es2017",
"target": "es2021",
"module": "es2020",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,

View file

@ -9,7 +9,7 @@
"noFallthroughCasesInSwitch": true,
"declaration": false,
"sourceMap": false,
"target": "es2017",
"target": "es2021",
"module": "es2020",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,

View file

@ -8,7 +8,7 @@
},
"dependencies": {
"@discordapp/twemoji": "14.0.2",
"@fortawesome/fontawesome-free": "6.1.1",
"@fortawesome/fontawesome-free": "6.1.2",
"@rollup/plugin-alias": "3.1.9",
"@rollup/plugin-json": "4.1.0",
"@rollup/pluginutils": "^4.2.1",
@ -48,7 +48,7 @@
"stringz": "2.1.0",
"syuilo-password-strength": "0.0.1",
"textarea-caret": "3.1.0",
"three": "0.142.0",
"three": "0.143.0",
"throttle-debounce": "5.0.0",
"tinycolor2": "1.4.2",
"tsc-alias": "1.7.0",
@ -57,7 +57,7 @@
"typescript": "4.7.4",
"uuid": "8.3.2",
"vanilla-tilt": "1.7.2",
"vite": "3.0.3",
"vite": "3.0.4",
"vue": "3.2.37",
"vue-prism-editor": "2.0.0-alpha.2",
"vuedraggable": "4.0.1"
@ -74,14 +74,14 @@
"@types/throttle-debounce": "5.0.0",
"@types/tinycolor2": "1.4.3",
"@types/uuid": "8.3.4",
"@typescript-eslint/eslint-plugin": "5.30.7",
"@typescript-eslint/parser": "5.30.7",
"@typescript-eslint/eslint-plugin": "5.31.0",
"@typescript-eslint/parser": "5.31.0",
"cross-env": "7.0.3",
"cypress": "10.3.1",
"eslint": "8.20.0",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-vue": "9.3.0",
"rollup": "2.77.0",
"rollup": "2.77.2",
"start-server-and-test": "1.14.0"
}
}

View file

@ -41,7 +41,7 @@
<Mfm v-if="appearNote.cw != ''" class="text" :text="appearNote.cw" :author="appearNote.user" :i="$i" :custom-emojis="appearNote.emojis"/>
<XCwButton v-model="showContent" :note="appearNote"/>
</p>
<div v-show="appearNote.cw == null || showContent" class="content" :class="{ collapsed }">
<div v-show="appearNote.cw == null || showContent" class="content" :class="{ collapsed, isLong }">
<div class="text">
<MkA v-if="appearNote.replyId" class="reply" :to="`/notes/${appearNote.replyId}`"><i class="fas fa-reply"></i></MkA>
<Mfm v-if="appearNote.text" :text="appearNote.text" :author="appearNote.user" :i="$i" :custom-emojis="appearNote.emojis"/>
@ -60,9 +60,12 @@
<XPoll v-if="appearNote.poll" ref="pollViewer" :note="appearNote" class="poll"/>
<MkUrlPreview v-for="url in urls" :key="url" :url="url" :compact="true" :detail="false" class="url-preview"/>
<div v-if="appearNote.renote" class="renote"><XNoteSimple :note="appearNote.renote"/></div>
<button v-if="collapsed" class="fade _button" @click="collapsed = false">
<button v-if="isLong && collapsed" class="fade _button" @click="collapsed = false">
<span>{{ i18n.ts.showMore }}</span>
</button>
<button v-else-if="isLong && !collapsed" class="showLess _button" @click="collapsed = true">
<span>{{ i18n.ts.showLess }}</span>
</button>
</div>
<MkA v-if="appearNote.channel && !inChannel" class="channel" :to="`/channels/${appearNote.channel.id}`"><i class="fas fa-satellite-dish"></i> {{ appearNote.channel.name }}</MkA>
</div>
@ -161,10 +164,11 @@ const reactButton = ref<HTMLElement>();
let appearNote = $computed(() => isRenote ? note.renote as misskey.entities.Note : note);
const isMyRenote = $i && ($i.id === note.userId);
const showContent = ref(false);
const collapsed = ref(appearNote.cw == null && appearNote.text != null && (
const isLong = (appearNote.cw == null && appearNote.text != null && (
(appearNote.text.split('\n').length > 9) ||
(appearNote.text.length > 500)
));
const collapsed = ref(appearNote.cw == null && isLong);
const isDeleted = ref(false);
const muted = ref(checkWordMute(appearNote, $i, defaultStore.state.mutedWords));
const translation = ref(null);
@ -441,6 +445,24 @@ function readPromo() {
}
> .content {
&.isLong {
> .showLess {
width: 100%;
margin-top: 1em;
position: sticky;
bottom: 1em;
> span {
display: inline-block;
background: var(--popup);
padding: 6px 10px;
font-size: 0.8em;
border-radius: 999px;
box-shadow: 0 2px 6px rgb(0 0 0 / 20%);
}
}
}
&.collapsed {
position: relative;
max-height: 9em;

View file

@ -171,6 +171,11 @@ const menuDef = computed(() => [{
}],
}, {
items: [{
icon: 'fas fa-floppy-disk',
text: i18n.ts.preferencesBackups,
to: '/settings/preferences-backups',
active: currentPage?.route.name === 'preferences-backups',
}, {
type: 'button',
icon: 'fas fa-trash',
text: i18n.ts.clearCache,

View file

@ -0,0 +1,444 @@
<template>
<div class="_formRoot">
<div :class="$style.buttons">
<MkButton inline primary @click="saveNew">{{ ts._preferencesBackups.saveNew }}</MkButton>
<MkButton inline @click="loadFile">{{ ts._preferencesBackups.loadFile }}</MkButton>
</div>
<FormSection>
<template #label>{{ ts._preferencesBackups.list }}</template>
<template v-if="profiles && Object.keys(profiles).length > 0">
<div
v-for="(profile, id) in profiles"
:key="id"
class="_formBlock _panel"
:class="$style.profile"
@click="$event => menu($event, id)"
@contextmenu.prevent.stop="$event => menu($event, id)"
>
<div :class="$style.profileName">{{ profile.name }}</div>
<div :class="$style.profileTime">{{ t('_preferencesBackups.createdAt', { date: (new Date(profile.createdAt)).toLocaleDateString(), time: (new Date(profile.createdAt)).toLocaleTimeString() }) }}</div>
<div v-if="profile.updatedAt" :class="$style.profileTime">{{ t('_preferencesBackups.updatedAt', { date: (new Date(profile.updatedAt)).toLocaleDateString(), time: (new Date(profile.updatedAt)).toLocaleTimeString() }) }}</div>
</div>
</template>
<div v-else-if="profiles">
<MkInfo>{{ ts._preferencesBackups.noBackups }}</MkInfo>
</div>
<MkLoading v-else/>
</FormSection>
</div>
</template>
<script lang="ts" setup>
import { computed, onMounted, onUnmounted, useCssModule } from 'vue';
import { v4 as uuid } from 'uuid';
import FormSection from '@/components/form/section.vue';
import MkButton from '@/components/ui/button.vue';
import MkInfo from '@/components/ui/info.vue';
import * as os from '@/os';
import { ColdDeviceStorage, defaultStore } from '@/store';
import { unisonReload } from '@/scripts/unison-reload';
import { stream } from '@/stream';
import { $i } from '@/account';
import { i18n } from '@/i18n';
import { version, host } from '@/config';
import { definePageMetadata } from '@/scripts/page-metadata';
const { t, ts } = i18n;
useCssModule();
const defaultStoreSaveKeys: (keyof typeof defaultStore['state'])[] = [
'menu',
'visibility',
'localOnly',
'statusbars',
'widgets',
'tl',
'overridedDeviceKind',
'serverDisconnectedBehavior',
'nsfw',
'animation',
'animatedMfm',
'loadRawImages',
'imageNewTab',
'disableShowingAnimatedImages',
'disablePagesScript',
'useOsNativeEmojis',
'disableDrawer',
'useBlurEffectForModal',
'useBlurEffect',
'showFixedPostForm',
'enableInfiniteScroll',
'useReactionPickerForContextMenu',
'showGapBetweenNotesInTimeline',
'instanceTicker',
'reactionPickerSize',
'reactionPickerWidth',
'reactionPickerHeight',
'reactionPickerUseDrawerForMobile',
'defaultSideView',
'menuDisplay',
'reportError',
'squareAvatars',
'numberOfPageCache',
'aiChanMode',
];
const coldDeviceStorageSaveKeys: (keyof typeof ColdDeviceStorage.default)[] = [
'lightTheme',
'darkTheme',
'syncDeviceDarkMode',
'plugins',
'mediaVolume',
'sound_masterVolume',
'sound_note',
'sound_noteMy',
'sound_notification',
'sound_chat',
'sound_chatBg',
'sound_antenna',
'sound_channel',
];
const scope = ['clientPreferencesProfiles'];
const profileProps = ['name', 'createdAt', 'updatedAt', 'misskeyVersion', 'settings'];
type Profile = {
name: string;
createdAt: string;
updatedAt: string | null;
misskeyVersion: string;
host: string;
settings: {
hot: Record<keyof typeof defaultStoreSaveKeys, unknown>;
cold: Record<keyof typeof coldDeviceStorageSaveKeys, unknown>;
fontSize: string | null;
useSystemFont: 't' | null;
wallpaper: string | null;
};
};
const connection = $i && stream.useChannel('main');
let profiles = $ref<Record<string, Profile> | null>(null);
os.api('i/registry/get-all', { scope })
.then(res => {
profiles = res || {};
});
function isObject(value: unknown): value is Record<string, unknown> {
return value != null && typeof value === 'object' && !Array.isArray(value);
}
function validate(profile: unknown): void {
if (!isObject(profile)) throw new Error('not an object');
// Check if unnecessary properties exist
if (Object.keys(profile).some(key => !profileProps.includes(key))) throw new Error('Unnecessary properties exist');
if (!profile.name) throw new Error('Missing required prop: name');
if (!profile.misskeyVersion) throw new Error('Missing required prop: misskeyVersion');
// Check if createdAt and updatedAt is Date
// https://zenn.dev/lollipop_onl/articles/eoz-judge-js-invalid-date
if (!profile.createdAt || Number.isNaN(new Date(profile.createdAt).getTime())) throw new Error('createdAt is falsy or not Date');
if (profile.updatedAt) {
if (Number.isNaN(new Date(profile.updatedAt).getTime())) {
throw new Error('updatedAt is not Date');
}
} else if (profile.updatedAt !== null) {
throw new Error('updatedAt is not null');
}
if (!profile.settings) throw new Error('Missing required prop: settings');
if (!isObject(profile.settings)) throw new Error('Invalid prop: settings');
}
function getSettings(): Profile['settings'] {
const hot = {} as Record<keyof typeof defaultStoreSaveKeys, unknown>;
for (const key of defaultStoreSaveKeys) {
hot[key] = defaultStore.state[key];
}
const cold = {} as Record<keyof typeof coldDeviceStorageSaveKeys, unknown>;
for (const key of coldDeviceStorageSaveKeys) {
cold[key] = ColdDeviceStorage.get(key);
}
return {
hot,
cold,
fontSize: localStorage.getItem('fontSize'),
useSystemFont: localStorage.getItem('useSystemFont') as 't' | null,
wallpaper: localStorage.getItem('wallpaper'),
};
}
async function saveNew(): Promise<void> {
if (!profiles) return;
const { canceled, result: name } = await os.inputText({
title: ts._preferencesBackups.inputName,
});
if (canceled) return;
if (Object.values(profiles).some(x => x.name === name)) {
return os.alert({
title: ts._preferencesBackups.cannotSave,
text: t('_preferencesBackups.nameAlreadyExists', { name }),
});
}
const id = uuid();
const profile: Profile = {
name,
createdAt: (new Date()).toISOString(),
updatedAt: null,
misskeyVersion: version,
host,
settings: getSettings(),
};
await os.apiWithDialog('i/registry/set', { scope, key: id, value: profile });
}
function loadFile(): void {
const input = document.createElement('input');
input.type = 'file';
input.multiple = false;
input.onchange = async () => {
if (!profiles) return;
if (!input.files || input.files.length === 0) return;
const file = input.files[0];
if (file.type !== 'application/json') {
return os.alert({
type: 'error',
title: ts._preferencesBackups.cannotLoad,
text: ts._preferencesBackups.invalidFile,
});
}
let profile: Profile;
try {
profile = JSON.parse(await file.text()) as unknown as Profile;
validate(profile);
} catch (err) {
return os.alert({
type: 'error',
title: ts._preferencesBackups.cannotLoad,
text: err?.message,
});
}
const id = uuid();
await os.apiWithDialog('i/registry/set', { scope, key: id, value: profile });
//
(window as any).__misskey_input_ref__ = null;
};
// https://qiita.com/fukasawah/items/b9dc732d95d99551013d
// iOS Safari
(window as any).__misskey_input_ref__ = input;
input.click();
}
async function applyProfile(id: string): Promise<void> {
if (!profiles) return;
const profile = profiles[id];
const { canceled: cancel1 } = await os.confirm({
type: 'warning',
title: ts._preferencesBackups.apply,
text: t('_preferencesBackups.applyConfirm', { name: profile.name }),
});
if (cancel1) return;
// TODO: or
const settings = profile.settings;
// defaultStore
for (const key of defaultStoreSaveKeys) {
if (settings.hot[key] !== undefined) {
defaultStore.set(key, settings.hot[key]);
}
}
// coldDeviceStorage
for (const key of coldDeviceStorageSaveKeys) {
if (settings.cold[key] !== undefined) {
ColdDeviceStorage.set(key, settings.cold[key]);
}
}
// fontSize
if (settings.fontSize) {
localStorage.setItem('fontSize', settings.fontSize);
} else {
localStorage.removeItem('fontSize');
}
// useSystemFont
if (settings.useSystemFont) {
localStorage.setItem('useSystemFont', settings.useSystemFont);
} else {
localStorage.removeItem('useSystemFont');
}
// wallpaper
if (settings.wallpaper != null) {
localStorage.setItem('wallpaper', settings.wallpaper);
} else {
localStorage.removeItem('wallpaper');
}
const { canceled: cancel2 } = await os.confirm({
type: 'info',
text: ts.reloadToApplySetting,
});
if (cancel2) return;
unisonReload();
}
async function deleteProfile(id: string): Promise<void> {
if (!profiles) return;
const { canceled } = await os.confirm({
type: 'info',
title: ts.delete,
text: t('deleteAreYouSure', { x: profiles[id].name }),
});
if (canceled) return;
await os.apiWithDialog('i/registry/remove', { scope, key: id });
delete profiles[id];
}
async function save(id: string): Promise<void> {
if (!profiles) return;
const { name, createdAt } = profiles[id];
const { canceled } = await os.confirm({
type: 'info',
title: ts._preferencesBackups.save,
text: t('_preferencesBackups.saveConfirm', { name }),
});
if (canceled) return;
const profile: Profile = {
name,
createdAt,
updatedAt: (new Date()).toISOString(),
misskeyVersion: version,
host,
settings: getSettings(),
};
await os.apiWithDialog('i/registry/set', { scope, key: id, value: profile });
}
async function rename(id: string): Promise<void> {
if (!profiles) return;
const { canceled: cancel1, result: name } = await os.inputText({
title: ts._preferencesBackups.inputName,
});
if (cancel1 || profiles[id].name === name) return;
if (Object.values(profiles).some(x => x.name === name)) {
return os.alert({
title: ts._preferencesBackups.cannotSave,
text: t('_preferencesBackups.nameAlreadyExists', { name }),
});
}
const registry = Object.assign({}, { ...profiles[id] });
const { canceled: cancel2 } = await os.confirm({
type: 'info',
title: ts._preferencesBackups.rename,
text: t('_preferencesBackups.renameConfirm', { old: registry.name, new: name }),
});
if (cancel2) return;
registry.name = name;
await os.apiWithDialog('i/registry/set', { scope, key: id, value: registry });
}
function menu(ev: MouseEvent, profileId: string) {
if (!profiles) return;
return os.popupMenu([{
text: ts._preferencesBackups.apply,
icon: 'fas fa-circle-down',
action: () => applyProfile(profileId),
}, {
type: 'a',
text: ts.download,
icon: 'fas fa-download',
href: URL.createObjectURL(new Blob([JSON.stringify(profiles[profileId], null, 2)], { type: 'application/json' })),
download: `${profiles[profileId].name}.json`,
}, null, {
text: ts.rename,
icon: 'fas fa-i-cursor',
action: () => rename(profileId),
}, {
text: ts._preferencesBackups.save,
icon: 'fas fa-floppy-disk',
action: () => save(profileId),
}, null, {
text: ts._preferencesBackups.delete,
icon: 'fas fa-trash-can',
action: () => deleteProfile(profileId),
danger: true,
}], ev.currentTarget ?? ev.target);
}
onMounted(() => {
// streaminguser storage update
connection?.on('registryUpdated', ({ scope: recievedScope, key, value }) => {
if (!recievedScope || recievedScope.length !== scope.length || recievedScope[0] !== scope[0]) return;
if (!profiles) return;
profiles[key] = value;
});
});
onUnmounted(() => {
connection?.off('registryUpdated');
});
definePageMetadata(computed(() => ({
title: ts.preferencesBackups,
icon: 'fas fa-floppy-disk',
bg: 'var(--bg)',
})));
</script>
<style lang="scss" module>
.buttons {
display: flex;
gap: var(--margin);
flex-wrap: wrap;
}
.profile {
padding: 20px;
cursor: pointer;
&Name {
font-weight: 700;
}
&Time {
font-size: .85em;
opacity: .7;
}
}
</style>

View file

@ -157,6 +157,10 @@ export const routes = [{
path: '/delete-account',
name: 'delete-account',
component: page(() => import('./pages/settings/delete-account.vue')),
}, {
path: '/preferences-backups',
name: 'preferences-backups',
component: page(() => import('./pages/settings/preferences-backups.vue')),
}, {
path: '/other',
name: 'other',

View file

@ -1,21 +1,21 @@
<template>
<div class="mkw-digitalClock _monospace" :class="{ _panel: !widgetProps.transparent }" :style="{ fontSize: `${widgetProps.fontSize}em` }">
<span>
<div class="time">
<span v-text="hh"></span>
<span :style="{ visibility: showColon ? 'visible' : 'hidden' }">:</span>
<span class="colon" :class="{ showColon }">:</span>
<span v-text="mm"></span>
<span :style="{ visibility: showColon ? 'visible' : 'hidden' }">:</span>
<span class="colon" :class="{ showColon }">:</span>
<span v-text="ss"></span>
<span v-if="widgetProps.showMs" :style="{ visibility: showColon ? 'visible' : 'hidden' }">:</span>
<span v-if="widgetProps.showMs" class="colon" :class="{ showColon }">:</span>
<span v-if="widgetProps.showMs" v-text="ms"></span>
</span>
</div>
</div>
</template>
<script lang="ts" setup>
import { onUnmounted, ref, watch } from 'vue';
import { GetFormResultType } from '@/scripts/form';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget';
import { GetFormResultType } from '@/scripts/form';
const name = 'digitalClock';
@ -54,14 +54,25 @@ const hh = ref('');
const mm = ref('');
const ss = ref('');
const ms = ref('');
const showColon = ref(true);
const showColon = ref(false);
let prevSec: number | null = null;
watch(showColon, (v) => {
if (v) {
window.setTimeout(() => {
showColon.value = false;
}, 30);
}
});
const tick = () => {
const now = new Date();
hh.value = now.getHours().toString().padStart(2, '0');
mm.value = now.getMinutes().toString().padStart(2, '0');
ss.value = now.getSeconds().toString().padStart(2, '0');
ms.value = Math.floor(now.getMilliseconds() / 10).toString().padStart(2, '0');
showColon.value = now.getSeconds() % 2 === 0;
if (now.getSeconds() !== prevSec) showColon.value = true;
prevSec = now.getSeconds();
};
tick();
@ -86,5 +97,17 @@ defineExpose<WidgetComponentExpose>({
.mkw-digitalClock {
padding: 16px 0;
text-align: center;
> .time {
> .colon {
opacity: 0;
transition: opacity 1s ease;
&.showColon {
opacity: 1;
transition: opacity 0s;
}
}
}
}
</style>

View file

@ -12,6 +12,7 @@ export default function(app: App) {
app.component('MkwActivity', defineAsyncComponent(() => import('./activity.vue')));
app.component('MkwPhotos', defineAsyncComponent(() => import('./photos.vue')));
app.component('MkwDigitalClock', defineAsyncComponent(() => import('./digital-clock.vue')));
app.component('MkwUnixClock', defineAsyncComponent(() => import('./unix-clock.vue')));
app.component('MkwFederation', defineAsyncComponent(() => import('./federation.vue')));
app.component('MkwPostForm', defineAsyncComponent(() => import('./post-form.vue')));
app.component('MkwSlideshow', defineAsyncComponent(() => import('./slideshow.vue')));
@ -36,6 +37,7 @@ export const widgets = [
'activity',
'photos',
'digitalClock',
'unixClock',
'federation',
'instanceCloud',
'postForm',

View file

@ -0,0 +1,116 @@
<template>
<div class="mkw-unixClock _monospace" :class="{ _panel: !widgetProps.transparent }" :style="{ fontSize: `${widgetProps.fontSize}em` }">
<div v-if="widgetProps.showLabel" class="label">UNIX time</div>
<div class="time">
<span v-text="ss"></span>
<span v-if="widgetProps.showMs" class="colon" :class="{ showColon }">:</span>
<span v-if="widgetProps.showMs" v-text="ms"></span>
</div>
<div v-if="widgetProps.showLabel" class="label">UTC</div>
</div>
</template>
<script lang="ts" setup>
import { onUnmounted, ref, watch } from 'vue';
import { useWidgetPropsManager, Widget, WidgetComponentEmits, WidgetComponentExpose, WidgetComponentProps } from './widget';
import { GetFormResultType } from '@/scripts/form';
const name = 'unixClock';
const widgetPropsDef = {
transparent: {
type: 'boolean' as const,
default: false,
},
fontSize: {
type: 'number' as const,
default: 1.5,
step: 0.1,
},
showMs: {
type: 'boolean' as const,
default: true,
},
showLabel: {
type: 'boolean' as const,
default: true,
},
};
type WidgetProps = GetFormResultType<typeof widgetPropsDef>;
// vueimporttype
//const props = defineProps<WidgetComponentProps<WidgetProps>>();
//const emit = defineEmits<WidgetComponentEmits<WidgetProps>>();
const props = defineProps<{ widget?: Widget<WidgetProps>; }>();
const emit = defineEmits<{ (ev: 'updateProps', props: WidgetProps); }>();
const { widgetProps, configure } = useWidgetPropsManager(name,
widgetPropsDef,
props,
emit,
);
let intervalId;
const ss = ref('');
const ms = ref('');
const showColon = ref(false);
let prevSec: string | null = null;
watch(showColon, (v) => {
if (v) {
window.setTimeout(() => {
showColon.value = false;
}, 30);
}
});
const tick = () => {
const now = new Date();
ss.value = Math.floor(now.getTime() / 1000).toString();
ms.value = Math.floor(now.getTime() % 1000 / 10).toString().padStart(2, '0');
if (ss.value !== prevSec) showColon.value = true;
prevSec = ss.value;
};
tick();
watch(() => widgetProps.showMs, () => {
if (intervalId) window.clearInterval(intervalId);
intervalId = window.setInterval(tick, widgetProps.showMs ? 10 : 1000);
}, { immediate: true });
onUnmounted(() => {
window.clearInterval(intervalId);
});
defineExpose<WidgetComponentExpose>({
name,
configure,
id: props.widget ? props.widget.id : null,
});
</script>
<style lang="scss" scoped>
.mkw-unixClock {
padding: 16px 0;
text-align: center;
> .label {
font-size: 65%;
opacity: 0.7;
}
> .time {
> .colon {
opacity: 0;
transition: opacity 1s ease;
&.showColon {
opacity: 1;
transition: opacity 0s;
}
}
}
}
</style>