Skip to content
Snippets Groups Projects
os.ts 16.4 KiB
Newer Older
/*
 * SPDX-FileCopyrightText: syuilo and other misskey contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 */

// TODO: なんでもかんでもos.tsに突っ込むのやめたいのでよしなに分割する

import { Component, markRaw, Ref, ref, defineAsyncComponent } from 'vue';
syuilo's avatar
syuilo committed
import { EventEmitter } from 'eventemitter3';
import insertTextAtCursor from 'insert-text-at-cursor';
syuilo's avatar
syuilo committed
import * as Misskey from 'misskey-js';
import type { ComponentProps } from 'vue-component-type-helpers';
import { misskeyApi } from '@/scripts/misskey-api.js';
syuilo's avatar
syuilo committed
import { i18n } from '@/i18n.js';
import MkPostFormDialog from '@/components/MkPostFormDialog.vue';
import MkWaitingDialog from '@/components/MkWaitingDialog.vue';
syuilo's avatar
syuilo committed
import MkPageWindow from '@/components/MkPageWindow.vue';
import MkToast from '@/components/MkToast.vue';
import MkDialog from '@/components/MkDialog.vue';
import MkPasswordDialog from '@/components/MkPasswordDialog.vue';
import MkEmojiPickerDialog from '@/components/MkEmojiPickerDialog.vue';
import MkEmojiPickerWindow from '@/components/MkEmojiPickerWindow.vue';
import MkPopupMenu from '@/components/MkPopupMenu.vue';
import MkContextMenu from '@/components/MkContextMenu.vue';
syuilo's avatar
syuilo committed
import { MenuItem } from '@/types/menu.js';
import copyToClipboard from '@/scripts/copy-to-clipboard.js';
import { showMovedDialog } from '@/scripts/show-moved-dialog.js';
syuilo's avatar
syuilo committed

syuilo's avatar
syuilo committed
export const openingWindowsCount = ref(0);

syuilo's avatar
syuilo committed
export const apiWithDialog = ((
syuilo's avatar
syuilo committed
	endpoint: string,
	data: Record<string, any> = {},
	token?: string | null | undefined,
syuilo's avatar
syuilo committed
) => {
	promiseDialog(promise, null, async (err) => {
		let title = null;
		let text = err.message + '\n' + (err as any).id;
		if (err.code === 'INTERNAL_ERROR') {
			title = i18n.ts.internalServerError;
			text = i18n.ts.internalServerErrorDescription;
			const date = new Date().toISOString();
			const { result } = await actions({
				type: 'error',
				title,
				text,
				actions: [{
					value: 'ok',
					text: i18n.ts.gotIt,
					primary: true,
				}, {
					value: 'copy',
					text: i18n.ts.copyErrorInfo,
				}],
			});
			if (result === 'copy') {
				copyToClipboard(`Endpoint: ${endpoint}\nInfo: ${JSON.stringify(err.info)}\nDate: ${date}`);
				success();
			}
			return;
		} else if (err.code === 'RATE_LIMIT_EXCEEDED') {
			title = i18n.ts.cannotPerformTemporary;
			text = i18n.ts.cannotPerformTemporaryDescription;
		} else if (err.code === 'INVALID_PARAM') {
			title = i18n.ts.invalidParamError;
			text = i18n.ts.invalidParamErrorDescription;
		} else if (err.code === 'ROLE_PERMISSION_DENIED') {
			title = i18n.ts.permissionDeniedError;
			text = i18n.ts.permissionDeniedErrorDescription;
		} else if (err.code.startsWith('TOO_MANY')) {
			title = i18n.ts.youCannotCreateAnymore;
			text = `${i18n.ts.error}: ${err.id}`;
		} else if (err.message.startsWith('Unexpected token')) {
			title = i18n.ts.gotInvalidResponseError;
			text = i18n.ts.gotInvalidResponseErrorDescription;
syuilo's avatar
syuilo committed
		alert({
syuilo's avatar
syuilo committed
			type: 'error',
syuilo's avatar
syuilo committed
		});
	});
syuilo's avatar
syuilo committed

	return promise;
syuilo's avatar
syuilo committed

export function promiseDialog<T extends Promise<any>>(
	promise: T,
syuilo's avatar
syuilo committed
	onSuccess?: ((res: any) => void) | null,
Johann150's avatar
Johann150 committed
	onFailure?: ((err: Error) => void) | null,
syuilo's avatar
syuilo committed
	text?: string,
): T {
syuilo's avatar
syuilo committed
	const showing = ref(true);
syuilo's avatar
syuilo committed
	const success = ref(false);
syuilo's avatar
syuilo committed

	promise.then(res => {
		if (onSuccess) {
			showing.value = false;
			onSuccess(res);
		} else {
syuilo's avatar
syuilo committed
			success.value = true;
			window.setTimeout(() => {
syuilo's avatar
syuilo committed
				showing.value = false;
			}, 1000);
		}
Johann150's avatar
Johann150 committed
	}).catch(err => {
syuilo's avatar
syuilo committed
		showing.value = false;
		if (onFailure) {
Johann150's avatar
Johann150 committed
			onFailure(err);
syuilo's avatar
syuilo committed
		} else {
syuilo's avatar
syuilo committed
			alert({
syuilo's avatar
syuilo committed
				type: 'error',
Johann150's avatar
Johann150 committed
				text: err,
syuilo's avatar
syuilo committed
	// NOTE: dynamic importすると挙動がおかしくなる(showingの変更が伝播しない)
	popup(MkWaitingDialog, {
syuilo's avatar
syuilo committed
		success: success,
		showing: showing,
		text: text,
syuilo's avatar
syuilo committed
	}, {}, 'closed');

	return promise;
}

syuilo's avatar
syuilo committed
let popupIdCount = 0;
syuilo's avatar
syuilo committed
export const popups = ref([]) as Ref<{
syuilo's avatar
syuilo committed
	props: Record<string, any>;
syuilo's avatar
syuilo committed
}[]>;

syuilo's avatar
syuilo committed
const zIndexes = {
syuilo's avatar
syuilo committed
	veryLow: 500000,
syuilo's avatar
syuilo committed
	low: 1000000,
	middle: 2000000,
	high: 3000000,
};
syuilo's avatar
syuilo committed
export function claimZIndex(priority: keyof typeof zIndexes = 'low'): number {
syuilo's avatar
syuilo committed
	zIndexes[priority] += 100;
	return zIndexes[priority];
// InstanceType<typeof Component>['$emit'] だとインターセクション型が返ってきて
// 使い物にならないので、代わりに ['$props'] から色々省くことで emit の型を生成する
// FIXME: 何故か *.ts ファイルからだと型がうまく取れない?ことがあるのをなんとかしたい
type ComponentEmit<T> = T extends new () => { $props: infer Props }
	? EmitsExtractor<Props>
	: never;

type EmitsExtractor<T> = {
	[K in keyof T as K extends `onVnode${string}` ? never : K extends `on${infer E}` ? Uncapitalize<E> : K extends string ? never : K]: T[K];
};

export async function popup<T extends Component>(component: T, props: ComponentProps<T>, events: ComponentEmit<T> = {} as ComponentEmit<T>, disposeEvent?: keyof ComponentEmit<T>) {
syuilo's avatar
syuilo committed
	markRaw(component);

syuilo's avatar
syuilo committed
	const id = ++popupIdCount;
syuilo's avatar
syuilo committed
	const dispose = () => {
		// このsetTimeoutが無いと挙動がおかしくなる(autocompleteが閉じなくなる)。Vueのバグ?
		window.setTimeout(() => {
syuilo's avatar
syuilo committed
			popups.value = popups.value.filter(popup => popup.id !== id);
		}, 0);
	};
	const state = {
		component,
		props,
		events: disposeEvent ? {
			...events,
syuilo's avatar
syuilo committed
			[disposeEvent]: dispose,
syuilo's avatar
syuilo committed
		} : events,
		id,
	};

	popups.value.push(state);

	return {
		dispose,
	};
}

export function pageWindow(path: string) {
	popup(MkPageWindow, {
		initialPath: path,
syuilo's avatar
syuilo committed
	}, {}, 'closed');
}

syuilo's avatar
syuilo committed
export function toast(message: string) {
	popup(MkToast, {
syuilo's avatar
syuilo committed
		message,
syuilo's avatar
syuilo committed
}

export function alert(props: {
	type?: 'error' | 'info' | 'success' | 'warning' | 'waiting' | 'question';
syuilo's avatar
syuilo committed
	title?: string | null;
	text?: string | null;
syuilo's avatar
syuilo committed
	return new Promise((resolve, reject) => {
		popup(MkDialog, props, {
			done: result => {
				resolve();
			},
		}, 'closed');
	});
}

export function confirm(props: {
	type: 'error' | 'info' | 'success' | 'warning' | 'waiting' | 'question';
	title?: string | null;
	text?: string | null;
	okText?: string;
	cancelText?: string;
}): Promise<{ canceled: boolean }> {
	return new Promise((resolve, reject) => {
		popup(MkDialog, {
			...props,
			showCancelButton: true,
		}, {
			done: result => {
				resolve(result ? result : { canceled: true });
			},
		}, 'closed');
	});
}

// TODO: const T extends ... にしたい
// https://zenn.dev/general_link/articles/813e47b7a0eef7#const-type-parameters
export function actions<T extends {
	value: string;
	text: string;
	primary?: boolean,
}[]>(props: {
	type: 'error' | 'info' | 'success' | 'warning' | 'waiting' | 'question';
	title?: string | null;
	text?: string | null;
	actions: T;
}): Promise<{ canceled: true; result: undefined; } | {
	canceled: false; result: T[number]['value'];
}> {
	return new Promise((resolve, reject) => {
		popup(MkDialog, {
			...props,
			actions: props.actions.map(a => ({
				text: a.text,
				primary: a.primary,
				callback: () => {
					resolve({ canceled: false, result: a.value });
				},
			})),
		}, {
			done: result => {
				resolve(result ? result : { canceled: true });
			},
		}, 'closed');
	});
}

export function inputText(props: {
	type?: 'text' | 'email' | 'password' | 'url';
	title?: string | null;
	text?: string | null;
	placeholder?: string | null;
}): Promise<{ canceled: true; result: undefined; } | {
	canceled: false; result: string;
}> {
	return new Promise((resolve, reject) => {
		popup(MkDialog, {
			title: props.title,
			text: props.text,
			input: {
				type: props.type,
				placeholder: props.placeholder,
syuilo's avatar
syuilo committed
			},
		}, {
			done: result => {
				resolve(result ? result : { canceled: true });
			},
		}, 'closed');
	});
}

export function inputNumber(props: {
	title?: string | null;
	text?: string | null;
	placeholder?: string | null;
	default?: number | null;
}): Promise<{ canceled: true; result: undefined; } | {
	canceled: false; result: number;
}> {
	return new Promise((resolve, reject) => {
		popup(MkDialog, {
			title: props.title,
			text: props.text,
			input: {
				type: 'number',
				placeholder: props.placeholder,
syuilo's avatar
syuilo committed
			},
		}, {
			done: result => {
				resolve(result ? result : { canceled: true });
			},
		}, 'closed');
	});
}

export function inputDate(props: {
	title?: string | null;
	text?: string | null;
	placeholder?: string | null;
	default?: Date | null;
}): Promise<{ canceled: true; result: undefined; } | {
	canceled: false; result: Date;
}> {
	return new Promise((resolve, reject) => {
		popup(MkDialog, {
			title: props.title,
			text: props.text,
			input: {
				type: 'date',
				placeholder: props.placeholder,
				default: props.default,
syuilo's avatar
syuilo committed
			},
		}, {
			done: result => {
				resolve(result ? { result: new Date(result.result), canceled: false } : { canceled: true });
			},
		}, 'closed');
	});
}

export function authenticateDialog(): Promise<{ canceled: true; result: undefined; } | {
	canceled: false; result: { password: string; token: string | null; };
}> {
	return new Promise((resolve, reject) => {
		popup(MkPasswordDialog, {}, {
			done: result => {
				resolve(result ? { canceled: false, result } : { canceled: true, result: undefined });
			},
		}, 'closed');
	});
}

export function select<C = any>(props: {
	title?: string | null;
	text?: string | null;
	default?: string | null;
})): Promise<{ canceled: true; result: undefined; } | {
	canceled: false; result: C;
}> {
	return new Promise((resolve, reject) => {
		popup(MkDialog, {
			title: props.title,
			text: props.text,
			select: {
				items: props.items,
				groupedItems: props.groupedItems,
				default: props.default,
syuilo's avatar
syuilo committed
			},
syuilo's avatar
syuilo committed
			done: result => {
				resolve(result ? result : { canceled: true });
			},
		}, 'closed');
	});
}

syuilo's avatar
syuilo committed
	return new Promise((resolve, reject) => {
		const showing = ref(true);
		window.setTimeout(() => {
syuilo's avatar
syuilo committed
			showing.value = false;
		}, 1000);
		popup(MkWaitingDialog, {
syuilo's avatar
syuilo committed
			success: true,
syuilo's avatar
syuilo committed
			showing: showing,
syuilo's avatar
syuilo committed
		}, {
			done: () => resolve(),
		}, 'closed');
	});
}

syuilo's avatar
syuilo committed
	return new Promise((resolve, reject) => {
		const showing = ref(true);
		popup(MkWaitingDialog, {
syuilo's avatar
syuilo committed
			success: false,
syuilo's avatar
syuilo committed
			showing: showing,
syuilo's avatar
syuilo committed
		}, {
			done: () => resolve(),
		}, 'closed');
	});
}

export function form(title, form) {
	return new Promise((resolve, reject) => {
		popup(defineAsyncComponent(() => import('@/components/MkFormDialog.vue')), { title, form }, {
syuilo's avatar
syuilo committed
			done: result => {
				resolve(result);
			},
		}, 'closed');
	});
}

export async function selectUser(opts: { includeSelf?: boolean; localOnly?: boolean; } = {}): Promise<Misskey.entities.UserDetailed> {
syuilo's avatar
syuilo committed
	return new Promise((resolve, reject) => {
		popup(defineAsyncComponent(() => import('@/components/MkUserSelectDialog.vue')), {
			includeSelf: opts.includeSelf,
syuilo's avatar
syuilo committed
			ok: user => {
				resolve(user);
			},
		}, 'closed');
	});
}

syuilo's avatar
syuilo committed
export async function selectDriveFile(multiple: boolean): Promise<Misskey.entities.DriveFile[]> {
syuilo's avatar
syuilo committed
	return new Promise((resolve, reject) => {
		popup(defineAsyncComponent(() => import('@/components/MkDriveSelectDialog.vue')), {
syuilo's avatar
syuilo committed
			type: 'file',
syuilo's avatar
syuilo committed
			multiple,
syuilo's avatar
syuilo committed
		}, {
			done: files => {
				if (files) {
syuilo's avatar
syuilo committed
					resolve(files);
syuilo's avatar
syuilo committed
				}
			},
		}, 'closed');
	});
}

export async function selectDriveFolder(multiple: boolean) {
	return new Promise((resolve, reject) => {
		popup(defineAsyncComponent(() => import('@/components/MkDriveSelectDialog.vue')), {
syuilo's avatar
syuilo committed
			type: 'folder',
syuilo's avatar
syuilo committed
			multiple,
syuilo's avatar
syuilo committed
		}, {
			done: folders => {
				if (folders) {
					resolve(multiple ? folders : folders[0]);
				}
			},
		}, 'closed');
	});
}

syuilo's avatar
syuilo committed
export async function pickEmoji(src: HTMLElement | null, opts) {
syuilo's avatar
syuilo committed
	return new Promise((resolve, reject) => {
		popup(MkEmojiPickerDialog, {
syuilo's avatar
syuilo committed
			src,
syuilo's avatar
syuilo committed
			...opts,
syuilo's avatar
syuilo committed
		}, {
			done: emoji => {
				resolve(emoji);
			},
		}, 'closed');
	});
}

syuilo's avatar
syuilo committed
export async function cropImage(image: Misskey.entities.DriveFile, options: {
	aspectRatio: number;
syuilo's avatar
syuilo committed
}): Promise<Misskey.entities.DriveFile> {
	return new Promise((resolve, reject) => {
		popup(defineAsyncComponent(() => import('@/components/MkCropperDialog.vue')), {
syuilo's avatar
syuilo committed
			file: image,
			aspectRatio: options.aspectRatio,
			uploadFolder: options.uploadFolder,
syuilo's avatar
syuilo committed
		}, {
			ok: x => {
				resolve(x);
			},
		}, 'closed');
	});
}

type AwaitType<T> =
	T extends Promise<infer U> ? U :
tamaina's avatar
tamaina committed
	T extends (...args: any[]) => Promise<infer V> ? V :
	T;
let openingEmojiPicker: AwaitType<ReturnType<typeof popup>> | null = null;
let activeTextarea: HTMLTextAreaElement | HTMLInputElement | null = null;
export async function openEmojiPicker(src?: HTMLElement, opts, initialTextarea: typeof activeTextarea) {
	if (openingEmojiPicker) return;

	activeTextarea = initialTextarea;

	const textareas = document.querySelectorAll('textarea, input');
	for (const textarea of Array.from(textareas)) {
		textarea.addEventListener('focus', () => {
			activeTextarea = textarea;
		});
	}

	const observer = new MutationObserver(records => {
		for (const record of records) {
syuilo's avatar
syuilo committed
			for (const node of Array.from(record.addedNodes).filter(node => node instanceof HTMLElement) as HTMLElement[]) {
				const textareas = node.querySelectorAll('textarea, input') as NodeListOf<NonNullable<typeof activeTextarea>>;
				for (const textarea of Array.from(textareas).filter(textarea => textarea.dataset.preventEmojiInsert == null)) {
					if (document.activeElement === textarea) activeTextarea = textarea;
					textarea.addEventListener('focus', () => {
						activeTextarea = textarea;
					});
				}
			}
		}
	});

	observer.observe(document.body, {
		childList: true,
		subtree: true,
		attributes: false,
		characterData: false,
	});

	openingEmojiPicker = await popup(MkEmojiPickerWindow, {
syuilo's avatar
syuilo committed
		...opts,
	}, {
		chosen: emoji => {
			insertTextAtCursor(activeTextarea, emoji);
		},
		closed: () => {
			openingEmojiPicker!.dispose();
			openingEmojiPicker = null;
			observer.disconnect();
syuilo's avatar
syuilo committed
		},
syuilo's avatar
syuilo committed
export function popupMenu(items: MenuItem[] | Ref<MenuItem[]>, src?: HTMLElement | EventTarget | null, options?: {
syuilo's avatar
syuilo committed
	align?: string;
	width?: number;
	viaKeyboard?: boolean;
syuilo's avatar
syuilo committed
	onClosing?: () => void;
syuilo's avatar
syuilo committed
	return new Promise((resolve, reject) => {
syuilo's avatar
syuilo committed
		let dispose;
		popup(MkPopupMenu, {
syuilo's avatar
syuilo committed
			items,
			src,
syuilo's avatar
syuilo committed
			width: options?.width,
syuilo's avatar
syuilo committed
			align: options?.align,
syuilo's avatar
syuilo committed
			viaKeyboard: options?.viaKeyboard,
syuilo's avatar
syuilo committed
		}, {
			closed: () => {
				resolve();
				dispose();
			},
syuilo's avatar
syuilo committed
			closing: () => {
				if (options?.onClosing) options.onClosing();
			},
syuilo's avatar
syuilo committed
		}).then(res => {
			dispose = res.dispose;
export function contextMenu(items: MenuItem[] | Ref<MenuItem[]>, ev: MouseEvent): Promise<void> {
syuilo's avatar
syuilo committed
	ev.preventDefault();
	return new Promise((resolve, reject) => {
syuilo's avatar
syuilo committed
		let dispose;
		popup(MkContextMenu, {
syuilo's avatar
syuilo committed
			items,
			ev,
		}, {
			closed: () => {
				resolve();
				dispose();
			},
syuilo's avatar
syuilo committed
		}).then(res => {
			dispose = res.dispose;
export function post(props: Record<string, any> = {}): Promise<void> {
	showMovedDialog();

syuilo's avatar
syuilo committed
	return new Promise((resolve, reject) => {
		// NOTE: MkPostFormDialogをdynamic importするとiOSでテキストエリアに自動フォーカスできない
syuilo's avatar
syuilo committed
		// NOTE: ただ、dynamic importしない場合、MkPostFormDialogインスタンスが使いまわされ、
		//       Vueが渡されたコンポーネントに内部的に__propsというプロパティを生やす影響で、
		//       複数のpost formを開いたときに場合によってはエラーになる
		//       もちろん複数のpost formを開けること自体Misskeyサイドのバグなのだが
syuilo's avatar
syuilo committed
		let dispose;
		popup(MkPostFormDialog, props, {
syuilo's avatar
syuilo committed
			closed: () => {
				resolve();
				dispose();
			},
syuilo's avatar
syuilo committed
		}).then(res => {
			dispose = res.dispose;
syuilo's avatar
syuilo committed
		});
	});
}

export const deckGlobalEvents = new EventEmitter();

/*
export function checkExistence(fileData: ArrayBuffer): Promise<any> {
	return new Promise((resolve, reject) => {
		const data = new FormData();
		data.append('md5', getMD5(fileData));

syuilo's avatar
syuilo committed
			md5: getMD5(fileData)
		}).then(resp => {
			resolve(resp.length > 0 ? resp[0] : null);
		});
	});
}*/