This commit is contained in:
Shusui MOYATANI
2023-03-11 13:51:56 +09:00
parent fe3b1b6074
commit 0e62c4d167
20 changed files with 6378 additions and 902 deletions

View File

@@ -1,13 +0,0 @@
{
"spec": ["src/**/*.test.ts"],
"diff": true,
"extension": ["ts"],
"package": "./package.json",
"reporter": "spec",
"require": ["ts-node/register"],
"slow": 75,
"timeout": 2000,
"ui": "bdd",
"watch-files": ["src/**/*.ts", "src/**/*.test.ts"],
"watch-ignore": ["lib/vendor"]
}

199
jest.config.ts Normal file
View File

@@ -0,0 +1,199 @@
import { JestConfigWithTsJest } from 'ts-jest';
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/tmp/jest_rs",
// Automatically clear mock calls, instances, contexts and results before every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
preset: 'ts-jest',
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: 'jsdom',
testEnvironment: 'node',
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
} satisfies JestConfigWithTsJest;

6748
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,7 @@
"serve": "npm run generatePackageInfo && vite preview", "serve": "npm run generatePackageInfo && vite preview",
"lint": "eslint .", "lint": "eslint .",
"tsc": "tsc --noEmit --skipLibCheck", "tsc": "tsc --noEmit --skipLibCheck",
"test": "TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\"}' mocha", "test": "jest",
"cover": "nyc npm run test", "cover": "nyc npm run test",
"fix": "eslint --fix .", "fix": "eslint --fix .",
"prepare": "husky install", "prepare": "husky install",
@@ -19,7 +19,7 @@
"checkLicense": "node -e 'import(\"./scripts/checkLicense.mjs\").then((m) => m.default())'" "checkLicense": "node -e 'import(\"./scripts/checkLicense.mjs\").then((m) => m.default())'"
}, },
"devDependencies": { "devDependencies": {
"@types/mocha": "^10.0.1", "@jest/globals": "^29.5.0",
"@typescript-eslint/eslint-plugin": "^5.48.1", "@typescript-eslint/eslint-plugin": "^5.48.1",
"@typescript-eslint/parser": "^5.48.1", "@typescript-eslint/parser": "^5.48.1",
"autoprefixer": "^10.4.13", "autoprefixer": "^10.4.13",
@@ -33,14 +33,14 @@
"eslint-plugin-solid": "^0.9.2", "eslint-plugin-solid": "^0.9.2",
"eslint-plugin-tailwindcss": "^3.8.0", "eslint-plugin-tailwindcss": "^3.8.0",
"husky": "^8.0.3", "husky": "^8.0.3",
"jest": "^29.5.0",
"license-checker": "^25.0.1", "license-checker": "^25.0.1",
"lint-staged": "^13.1.0", "lint-staged": "^13.1.0",
"mocha": "^10.2.0",
"nyc": "^15.1.0", "nyc": "^15.1.0",
"postcss": "^8.4.21", "postcss": "^8.4.21",
"power-assert": "^1.6.1", "power-assert": "^1.6.1",
"prettier": "^2.8.3", "prettier": "^2.8.3",
"ts-node": "^10.9.1", "ts-jest": "^29.0.5",
"typescript": "^4.9.4", "typescript": "^4.9.4",
"vite": "^4.0.4", "vite": "^4.0.4",
"vite-plugin-solid": "^2.5.0", "vite-plugin-solid": "^2.5.0",

94
src/components/Config.tsx Normal file
View File

@@ -0,0 +1,94 @@
import useConfig from '@/nostr/useConfig';
import { createSignal, For, type JSX } from 'solid-js';
type ConfigProps = {
onClose: () => void;
};
const RelayConfig = () => {
const { config, setConfig } = useConfig();
const [relayUrlInput, setRelayUrlInput] = createSignal<string>('');
const addRelay = (relayUrl: string) => {
setConfig((current) => ({
...current,
relayUrls: [...current.relayUrls, relayUrl],
}));
};
const removeRelay = (relayUrl: string) => {
setConfig((current) => ({
...current,
relayUrls: current.relayUrls.filter((e) => e !== relayUrl),
}));
};
const handleClickAddRelay: JSX.EventHandler<HTMLFormElement, Event> = (ev) => {
ev.preventDefault();
const relayUrl = ev.currentTarget?.relayUrl?.value as string | undefined;
if (relayUrl == null) return;
addRelay(relayUrlInput());
};
return (
<div>
<h3 class="font-bold"></h3>
<ul>
<For each={config().relayUrls}>
{(relayUrl: string) => {
return (
<li class="flex">
<div class="flex-1">{relayUrl}</div>
<button onClick={() => removeRelay(relayUrl)}>x</button>
</li>
);
}}
</For>
</ul>
<form class="flex gap-2" onSubmit={handleClickAddRelay}>
<input
class="flex-1"
type="text"
name="relayUrl"
value={relayUrlInput()}
onChange={(ev) => setRelayUrlInput(ev.currentTarget.value)}
/>
<button type="submit" class="rounded bg-rose-300 p-2 font-bold text-white">
</button>
</form>
</div>
);
};
const Config = (props: ConfigProps) => {
let containerRef: HTMLDivElement | undefined;
const handleClickContainer: JSX.EventHandler<HTMLDivElement, MouseEvent> = (ev) => {
if (ev.target === containerRef) {
props.onClose();
}
};
return (
<div
ref={containerRef}
class="absolute top-0 left-0 flex h-screen w-screen cursor-default place-content-center place-items-center bg-black/25"
role="button"
onClick={handleClickContainer}
>
<div class="w-[480px] max-w-[100vw] rounded bg-white p-4 shadow">
<div class="relative">
<h2 class="flex-1 text-center font-bold"></h2>
<button class="absolute top-1 right-0" onClick={() => props.onClose()}>
X
</button>
</div>
<RelayConfig />
</div>
</div>
);
};
export default Config;

View File

@@ -15,7 +15,7 @@ export type DeprecatedRepostProps = {
}; };
const DeprecatedRepost: Component<DeprecatedRepostProps> = (props) => { const DeprecatedRepost: Component<DeprecatedRepostProps> = (props) => {
const [config] = useConfig(); const { config } = useConfig();
const pubkey = () => props.event.pubkey; const pubkey = () => props.event.pubkey;
const eventId = () => props.event.tags.find(([tagName]) => tagName === 'e')?.[1]; const eventId = () => props.event.tags.find(([tagName]) => tagName === 'e')?.[1];

View File

@@ -1,8 +1,10 @@
import { createSignal, Show, type JSX, Component } from 'solid-js'; import { createSignal, Show, type JSX, Component } from 'solid-js';
import MagnifyingGlass from 'heroicons/24/solid/magnifying-glass.svg'; import MagnifyingGlass from 'heroicons/24/solid/magnifying-glass.svg';
import PencilSquare from 'heroicons/24/solid/pencil-square.svg'; import PencilSquare from 'heroicons/24/solid/pencil-square.svg';
import Cog6Tooth from 'heroicons/24/outline/cog-6-tooth.svg';
import NotePostForm from '@/components/NotePostForm'; import NotePostForm from '@/components/NotePostForm';
import Config from '@/components/Config';
import useConfig from '@/nostr/useConfig'; import useConfig from '@/nostr/useConfig';
import useCommands from '@/nostr/useCommands'; import useCommands from '@/nostr/useCommands';
@@ -11,11 +13,12 @@ import { useHandleCommand } from '@/hooks/useCommandBus';
const SideBar: Component = () => { const SideBar: Component = () => {
let formTextAreaRef: HTMLTextAreaElement | undefined; let formTextAreaRef: HTMLTextAreaElement | undefined;
const [config] = useConfig(); const { config } = useConfig();
const getPubkey = usePubkey(); const getPubkey = usePubkey();
const commands = useCommands(); const commands = useCommands();
const [formOpened, setFormOpened] = createSignal(false); const [formOpened, setFormOpened] = createSignal(false);
const [configOpened, setConfigOpened] = createSignal(false);
const openForm = () => { const openForm = () => {
setFormOpened(true); setFormOpened(true);
@@ -57,22 +60,36 @@ const SideBar: Component = () => {
return ( return (
<div class="flex shrink-0 flex-row border-r bg-sidebar-bg"> <div class="flex shrink-0 flex-row border-r bg-sidebar-bg">
<div class="flex w-14 flex-auto flex-col items-center gap-3 border-r border-rose-200 py-5"> <div class="flex w-14 flex-auto flex-col items-center gap-3 border-r border-rose-200 pt-5">
<button <div class="flex flex-col items-center gap-3">
class={`h-9 w-9 rounded-full border border-primary bg-primary p-2 text-2xl font-bold text-white`} <button
onClick={() => setFormOpened((current) => !current)} class={`h-9 w-9 rounded-full border border-primary bg-primary p-2 text-2xl font-bold text-white`}
> onClick={() => setFormOpened((current) => !current)}
<PencilSquare /> >
</button> <PencilSquare />
<button class="h-9 w-9 rounded-full border border-primary p-2 text-2xl font-bold text-primary"> </button>
<MagnifyingGlass /> <button class="h-9 w-9 rounded-full border border-primary p-2 text-2xl font-bold text-primary">
</button> <MagnifyingGlass />
{/* <div>column 1</div> */} </button>
{/* <div>column 2</div> */} {/* <div>column 1</div> */}
{/* <div>column 2</div> */}
</div>
<div class="grow" />
<div>
<button
class="h-12 w-12 p-3 text-primary"
onClick={() => setConfigOpened((current) => !current)}
>
<Cog6Tooth />
</button>
</div>
</div> </div>
<Show when={formOpened()}> <Show when={formOpened()}>
<NotePostForm ref={formTextAreaRef} onPost={handlePost} onClose={closeForm} /> <NotePostForm ref={formTextAreaRef} onPost={handlePost} onClose={closeForm} />
</Show> </Show>
<Show when={configOpened()}>
<Config onClose={() => setConfigOpened(false)} />
</Show>
</div> </div>
); );
}; };

View File

@@ -23,11 +23,15 @@ import ReplyPostForm from '@/components/ReplyPostForm';
export type TextNoteProps = { export type TextNoteProps = {
event: NostrEvent; event: NostrEvent;
//
// displayinlineContent: boolean = true;
// リアクションやリポスト等の
// actions: boolean = true;
}; };
const TextNote: Component<TextNoteProps> = (props) => { const TextNote: Component<TextNoteProps> = (props) => {
const currentDate = useDatePulser(); const currentDate = useDatePulser();
const [config] = useConfig(); const { config } = useConfig();
const commands = useCommands(); const commands = useCommands();
const pubkey = usePubkey(); const pubkey = usePubkey();
const [showReplyForm, setShowReplyForm] = createSignal(false); const [showReplyForm, setShowReplyForm] = createSignal(false);

View File

@@ -8,7 +8,7 @@ type UserNameDisplayProps = {
}; };
const UserNameDisplay: Component<UserNameDisplayProps> = (props) => { const UserNameDisplay: Component<UserNameDisplayProps> = (props) => {
const [config] = useConfig(); const { config } = useConfig();
const { profile } = useProfile(() => ({ const { profile } = useProfile(() => ({
relayUrls: config().relayUrls, relayUrls: config().relayUrls,
pubkey: props.pubkey, pubkey: props.pubkey,

View File

@@ -14,7 +14,7 @@ type ReactionProps = {
}; };
const Reaction: Component<ReactionProps> = (props) => { const Reaction: Component<ReactionProps> = (props) => {
const [config] = useConfig(); const { config } = useConfig();
const eventId = () => props.event.tags.find(([tagName]) => tagName === 'e')?.[1]; const eventId = () => props.event.tags.find(([tagName]) => tagName === 'e')?.[1];
const { profile } = useProfile(() => ({ const { profile } = useProfile(() => ({
@@ -61,7 +61,10 @@ const Reaction: Component<ReactionProps> = (props) => {
</div> </div>
</div> </div>
<div class="notification-event"> <div class="notification-event">
<Show when={reactedEvent() != null} fallback={<>loading {eventId()}</>}> <Show
when={reactedEvent() != null}
fallback={<div class="truncate">loading {eventId()}</div>}
>
<TextNote event={reactedEvent()} /> <TextNote event={reactedEvent()} />
</Show> </Show>
</div> </div>

View File

@@ -8,7 +8,7 @@ export type GeneralUserMentionDisplayProps = {
}; };
const GeneralUserMentionDisplay = (props: GeneralUserMentionDisplayProps) => { const GeneralUserMentionDisplay = (props: GeneralUserMentionDisplayProps) => {
const [config] = useConfig(); const { config } = useConfig();
const { profile } = useProfile(() => ({ const { profile } = useProfile(() => ({
relayUrls: config().relayUrls, relayUrls: config().relayUrls,
pubkey: props.pubkey, pubkey: props.pubkey,

View File

@@ -1,3 +1,10 @@
import { Switch, Match } from 'solid-js';
import TextNote from '@/components/TextNote';
import useConfig from '@/nostr/useConfig';
import useEvent from '@/nostr/useEvent';
import useProfile from '@/nostr/useProfile';
import type { MentionedEvent } from '@/core/parseTextNote'; import type { MentionedEvent } from '@/core/parseTextNote';
export type MentionedEventDisplayProps = { export type MentionedEventDisplayProps = {
@@ -5,7 +12,28 @@ export type MentionedEventDisplayProps = {
}; };
const MentionedEventDisplay = (props: MentionedEventDisplayProps) => { const MentionedEventDisplay = (props: MentionedEventDisplayProps) => {
return <span class="text-blue-500 underline">#{props.mentionedEvent.eventId}</span>; const { config } = useConfig();
const { event, query: eventQuery } = useEvent(() => ({
relayUrls: config().relayUrls,
eventId: props.mentionedEvent.eventId,
}));
// return <span class="text-blue-500 underline">#{props.mentionedEvent.eventId}</span>;
return (
<div class="rounded border py-2 px-1">
{/* TODO なんかこのあたりの処理は統一したい */}
<Switch fallback="failed to load">
<Match when={event() != null}>
<TextNote event={event()} />
</Match>
<Match when={eventQuery.isLoading}>
<div class="truncate">
{'loading '}
<span>{props.mentionedEvent.eventId}</span>
</div>
</Match>
</Switch>
</div>
);
}; };
export default MentionedEventDisplay; export default MentionedEventDisplay;

View File

@@ -0,0 +1,35 @@
import assert from 'assert';
import { describe } from '@jest/globals';
import parseTextNote from './parseTextNote';
describe('parseTextNote', () => {
/*
it('should fail if the given event is not text note', () => {
parseTextNote({
kind: 0,
content: '{}',
tags: [],
});
});
*/
it('should parse text note with the url with hash', () => {
const parsed = parseTextNote({
kind: 1,
content: 'this is url\nhttps://github.com/syusui-s/rabbit/#readme #rabbit',
tags: [],
created_at: 1678377182,
pubkey: '9366708117c4a7edf9178acdce538c95059b9eb3394808cdd90564094172d972',
});
const expected = [
{ type: 'PlainText', content: 'this is url\n' },
{ type: 'URL', content: 'https://github.com/syusui-s/rabbit/#readme' },
{ type: 'PlainText', content: ' ' },
{ type: 'HashTag', content: '#rabbit' },
];
assert.deepStrictEqual(parsed, expected);
});
});

View File

@@ -38,9 +38,9 @@ export type ParsedTextNote = ParsedTextNoteNode[];
export const parseTextNote = (event: NostrEvent): ParsedTextNote => { export const parseTextNote = (event: NostrEvent): ParsedTextNote => {
const matches = [ const matches = [
...event.content.matchAll(/(?:#\[(?<idx>\d+)\])/g), ...event.content.matchAll(/(?:#\[(?<idx>\d+)\])/g),
...event.content.matchAll(/#(?<hashtag>[^[]\(\)\s]+)/g), ...event.content.matchAll(/#(?<hashtag>[^[\]()\d\s][^[\]()\s]+)/g),
...event.content.matchAll( ...event.content.matchAll(
/(?<url>https?:\/\/[-a-zA-Z0-9.]+(?:\/[-\w.%]+|\/)*(?:\?[-\w=&]*)?(?:#[-\w]*)?)/g, /(?<url>https?:\/\/[-a-zA-Z0-9.]+(?:\/[-\w.%:]+|\/)*(?:\?[-\w=.%:&]*)?(?:#[-\w=.%:&]*)?)/g,
), ),
].sort((a, b) => a?.index - b?.index); ].sort((a, b) => a?.index - b?.index);
let pos = 0; let pos = 0;
@@ -55,16 +55,11 @@ export const parseTextNote = (event: NostrEvent): ParsedTextNote => {
}; };
matches.forEach((match) => { matches.forEach((match) => {
if (match.groups?.hashtag) { if (match.groups?.url && match.index >= pos) {
pushPlainText(match.index); pushPlainText(match.index);
const tagName = match.groups?.hashtag; const url: UrlText = { type: 'URL', content: match.groups?.url };
const hashtag: HashTag = { result.push(url);
type: 'HashTag', } else if (match.groups?.idx && match.index >= pos) {
content: match[0],
tagName,
};
result.push(hashtag);
} else if (match.groups?.idx) {
const tagIndex = parseInt(match.groups.idx, 10); const tagIndex = parseInt(match.groups.idx, 10);
const tag = event.tags[tagIndex]; const tag = event.tags[tagIndex];
if (tag == null) return; if (tag == null) return;
@@ -90,10 +85,15 @@ export const parseTextNote = (event: NostrEvent): ParsedTextNote => {
}; };
result.push(mentionedEvent); result.push(mentionedEvent);
} }
} else if (match.groups?.url) { } else if (match.groups?.hashtag && match.index >= pos) {
pushPlainText(match.index); pushPlainText(match.index);
const url: UrlText = { type: 'URL', content: match.groups?.url }; const tagName = match.groups?.hashtag;
result.push(url); const hashtag: HashTag = {
type: 'HashTag',
content: match[0],
tagName,
};
result.push(hashtag);
} }
pos = match.index + match[0].length; pos = match.index + match[0].length;
}); });
@@ -104,6 +104,10 @@ export const parseTextNote = (event: NostrEvent): ParsedTextNote => {
result.push(plainText); result.push(plainText);
} }
if (result.length > 1) {
console.log(JSON.stringify(result, null, 2));
}
return result; return result;
}; };

View File

@@ -20,7 +20,7 @@ const useBatchedEvent = <TaskArgs>(propsProvider: () => UseBatchedEventProps<Tas
executor: (tasks) => { executor: (tasks) => {
const { generateKey, mergeFilters, extractKey } = props(); const { generateKey, mergeFilters, extractKey } = props();
// TODO relayUrlsを考慮する // TODO relayUrlsを考慮する
const [config] = useConfig(); const { config } = useConfig();
const keyTaskMap = new Map<string | number, Task<TaskArgs, NostrEvent>>( const keyTaskMap = new Map<string | number, Task<TaskArgs, NostrEvent>>(
tasks.map((task) => [generateKey(task.args), task]), tasks.map((task) => [generateKey(task.args), task]),

View File

@@ -39,7 +39,7 @@ const useBatchedEvents = <TaskArgs>(propsProvider: () => UseBatchedEventsProps<T
executor: (tasks) => { executor: (tasks) => {
const { generateKey, mergeFilters, extractKey } = props(); const { generateKey, mergeFilters, extractKey } = props();
// TODO relayUrlsを考慮する // TODO relayUrlsを考慮する
const [config] = useConfig(); const { config } = useConfig();
const keyTaskMap = new Map<string | number, Task<TaskArgs, Accessor<BatchedEvents>>>( const keyTaskMap = new Map<string | number, Task<TaskArgs, Accessor<BatchedEvents>>>(
tasks.map((task) => [generateKey(task.args), task]), tasks.map((task) => [generateKey(task.args), task]),

View File

@@ -1,4 +1,4 @@
import { Signal } from 'solid-js'; import { type Accessor, type Setter } from 'solid-js';
import { import {
createStorageWithSerializer, createStorageWithSerializer,
createSignalWithStorage, createSignalWithStorage,
@@ -8,13 +8,18 @@ type Config = {
relayUrls: string[]; relayUrls: string[];
}; };
type UseConfig = {
config: Accessor<Config>;
setConfig: Setter<Config>;
};
const InitialConfig: Config = { const InitialConfig: Config = {
relayUrls: [ relayUrls: [
'wss://relay-jp.nostr.wirednet.jp', 'wss://relay-jp.nostr.wirednet.jp',
'wss://nostr.h3z.jp/', 'wss://nostr.h3z.jp/',
'wss://relay.damus.io', 'wss://relay.damus.io',
'wss://nos.lol', 'wss://nos.lol',
// 'wss://relay.snort.social', 'wss://relay.snort.social',
'wss://relay.current.fyi', 'wss://relay.current.fyi',
'wss://relay.nostr.wirednet.jp', 'wss://relay.nostr.wirednet.jp',
'wss://nostr-relay.nokotaro.com', 'wss://nostr-relay.nokotaro.com',
@@ -29,8 +34,8 @@ const deserializer = (json: string): Config => JSON.parse(json) as Config;
const storage = createStorageWithSerializer(() => window.localStorage, serializer, deserializer); const storage = createStorageWithSerializer(() => window.localStorage, serializer, deserializer);
const [config, setConfig] = createSignalWithStorage('RabbitConfig', InitialConfig, storage); const [config, setConfig] = createSignalWithStorage('RabbitConfig', InitialConfig, storage);
const useConfig = (): Signal<Config> => { const useConfig = (): UseConfig => {
return [config, setConfig]; return { config, setConfig };
}; };
export default useConfig; export default useConfig;

View File

@@ -22,7 +22,7 @@ const Home: Component = () => {
const { loginStatus } = useLoginStatus(); const { loginStatus } = useLoginStatus();
const pool = usePool(); const pool = usePool();
const [config] = useConfig(); const { config } = useConfig();
const pubkey = usePubkey(); const pubkey = usePubkey();
createEffect(() => { createEffect(() => {
@@ -87,7 +87,7 @@ const Home: Component = () => {
ensureNonNull([pubkey()] as const)(([pubkeyNonNull]) => ({ ensureNonNull([pubkey()] as const)(([pubkeyNonNull]) => ({
relayUrls: [ relayUrls: [
'wss://relay-jp.nostr.wirednet.jp', 'wss://relay-jp.nostr.wirednet.jp',
'wss://nostr.h3z.jp/', 'wss://nostr.h3z.jp',
'wss://nostr.holybea.com', 'wss://nostr.holybea.com',
], ],
filters: [ filters: [
@@ -130,7 +130,7 @@ const Home: Component = () => {
<Column name="通知" columnIndex={2} width="medium"> <Column name="通知" columnIndex={2} width="medium">
<Notification events={notifications()} /> <Notification events={notifications()} />
</Column> </Column>
<Column name="日本サーバ" columnIndex={3} width="medium"> <Column name="日本リレー" columnIndex={3} width="medium">
<Timeline events={localTimeline()} /> <Timeline events={localTimeline()} />
</Column> </Column>
<Column name="自分の投稿" columnIndex={4} lastColumn width="medium"> <Column name="自分の投稿" columnIndex={4} lastColumn width="medium">

View File

@@ -1,8 +1,8 @@
import assert from 'assert'; import assert from 'assert';
import { describe } from 'mocha'; import { describe } from '@jest/globals';
describe('1 + 1', function () { describe('1 + 1', () => {
it('should be 2', function () { it('should be 2', () => {
assert(1 + 1 === 2); assert(1 + 1 === 2);
}); });
}); });

View File

@@ -1,27 +1,27 @@
type ParsedDate = type ParsedDate =
| { kind: 'abs'; value: Date } | { kind: 'now' }
| { kind: 'days'; value: number }
| { kind: 'hours'; value: number }
| { kind: 'minutes'; value: number }
| { kind: 'seconds'; value: number } | { kind: 'seconds'; value: number }
| { kind: 'now' }; | { kind: 'minutes'; value: number }
| { kind: 'hours'; value: number }
| { kind: 'days'; value: number }
| { kind: 'abs'; value: Date };
export type DateFormatter = (parsedDate: ParsedDate) => string; export type DateFormatter = (parsedDate: ParsedDate) => string;
const defaultDateFormatter = (parsedDate: ParsedDate): string => { const defaultDateFormatter = (parsedDate: ParsedDate): string => {
switch (parsedDate.kind) { switch (parsedDate.kind) {
case 'abs':
return parsedDate.value.toLocaleDateString();
case 'days':
return `${parsedDate.value}d`;
case 'hours':
return `${parsedDate.value}h`;
case 'minutes':
return `${parsedDate.value}m`;
case 'seconds':
return `${parsedDate.value}s`;
case 'now': case 'now':
return 'now'; return 'now';
case 'seconds':
return `${parsedDate.value}s`;
case 'minutes':
return `${parsedDate.value}m`;
case 'hours':
return `${parsedDate.value}h`;
case 'days':
return `${parsedDate.value}d`;
case 'abs':
return parsedDate.value.toLocaleDateString();
default: default:
return ''; return '';
} }