Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01d808381b | ||
|
|
c43278f785 |
@@ -8,16 +8,13 @@ deliberate post detail link, or manually open a valid
|
|||||||
## Scope
|
## Scope
|
||||||
|
|
||||||
- User timelines and raw X search syntax
|
- User timelines and raw X search syntax
|
||||||
- Button-driven search filters for author, period, language, content type, replies, and reposts
|
|
||||||
- Popular (`Top`) and chronological (`Latest`) search
|
- Popular (`Top`) and chronological (`Latest`) search
|
||||||
- Optional `filter:follows` search
|
- Optional `filter:follows` search
|
||||||
- Authenticated account list selection and list timelines from a deliberate URL or ID
|
- Authenticated account list selection and list timelines from a deliberate URL or ID
|
||||||
- Relay profile switching from the profiles exposed by the relay
|
|
||||||
- Infinite cursor pagination with explicit retry
|
- Infinite cursor pagination with explicit retry
|
||||||
- Deliberate post detail pages with the visible conversation
|
- Deliberate post detail pages with the visible conversation
|
||||||
- Infinite conversation loading with explicit continuation retry
|
- Infinite conversation loading with explicit continuation retry
|
||||||
- Read-only cards for text, media, quotes, articles, and quiet engagement counts
|
- Read-only cards for text, media, quotes, articles, and quiet engagement counts
|
||||||
- Experimental WebMCP tools for search, loaded-post reading, and continuation
|
|
||||||
|
|
||||||
It intentionally has no home feed, recommendations, trends, notifications,
|
It intentionally has no home feed, recommendations, trends, notifications,
|
||||||
history, account directory, or write actions.
|
history, account directory, or write actions.
|
||||||
@@ -29,9 +26,7 @@ they do not add related-post recommendations or an account-discovery surface.
|
|||||||
|
|
||||||
- `/` shows the empty user input.
|
- `/` shows the empty user input.
|
||||||
- `/:handle` shows a user timeline.
|
- `/:handle` shows a user timeline.
|
||||||
- `/search` shows search results. Its typed query parameters preserve the query,
|
- `/search?q=<query>&product=<Top|Latest>&following=<boolean>` shows search results.
|
||||||
author, period, language, content type, exclusions, ranking, and follows filter
|
|
||||||
so filtered searches can be reloaded or shared.
|
|
||||||
- `/i/lists` shows the authenticated account's lists.
|
- `/i/lists` shows the authenticated account's lists.
|
||||||
- `/i/lists/:listId` shows a list timeline.
|
- `/i/lists/:listId` shows a list timeline.
|
||||||
- `/:handle/status/:tweetId` shows one selected post and its visible conversation.
|
- `/:handle/status/:tweetId` shows one selected post and its visible conversation.
|
||||||
@@ -50,11 +45,9 @@ cp .env.example .env.local
|
|||||||
The Nix development shell installs Hallmark's agent skill for the supported
|
The Nix development shell installs Hallmark's agent skill for the supported
|
||||||
local agent targets.
|
local agent targets.
|
||||||
|
|
||||||
Set `TWITTER_RELAY_BASE_URL` in `.env.local` for Vite development.
|
Set `TWITTER_RELAY_BASE_URL` in `.env.local` for Vite development, and set
|
||||||
`BIRD_PROFILE_NAME` optionally selects the initial relay profile; the header
|
`BIRD_PROFILE_NAME` when the relay has multiple profiles. Export the same
|
||||||
selector can switch between the profiles returned by the relay's `/profiles`
|
values in the process environment before `start` or `test:live`:
|
||||||
endpoint. Export the same values in the process environment before `start` or
|
|
||||||
`test:live`:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export TWITTER_RELAY_BASE_URL=http://127.0.0.1:6900
|
export TWITTER_RELAY_BASE_URL=http://127.0.0.1:6900
|
||||||
@@ -69,7 +62,6 @@ sent to the browser.
|
|||||||
```bash
|
```bash
|
||||||
nix develop -c pnpm dev
|
nix develop -c pnpm dev
|
||||||
nix develop -c pnpm dev:tailscale
|
nix develop -c pnpm dev:tailscale
|
||||||
nix develop -c pnpm generate:e2e-openapi
|
|
||||||
nix develop -c pnpm knip
|
nix develop -c pnpm knip
|
||||||
nix develop -c pnpm test
|
nix develop -c pnpm test
|
||||||
nix develop -c pnpm test:e2e
|
nix develop -c pnpm test:e2e
|
||||||
@@ -81,39 +73,8 @@ nix develop -c pnpm start
|
|||||||
`test:e2e` is intentionally Nix-only and uses the system Chromium supplied by
|
`test:e2e` is intentionally Nix-only and uses the system Chromium supplied by
|
||||||
the dev shell. Browser tests are organized under `e2e/`: page object models
|
the dev shell. Browser tests are organized under `e2e/`: page object models
|
||||||
and fixtures are shared by integration flows and Axe checks for WCAG 2.0/2.1
|
and fixtures are shared by integration flows and Axe checks for WCAG 2.0/2.1
|
||||||
A and AA. The tests keep a standalone HTTP relay so TanStack Start server
|
A and AA. `test:live` is an explicit, opt-in smoke test that performs exactly
|
||||||
functions and SSR requests exercise the same network boundary as production.
|
one read-only Top search using the configured relay.
|
||||||
The API client and fixture types are generated with Orval from a pinned
|
|
||||||
[twitter-openapi specification](https://github.com/fa0311/twitter-openapi/commit/590dae5c9f8575abc91d3774946bfe6f23960aba);
|
|
||||||
run `generate:e2e-openapi` only when updating that pin or the selected
|
|
||||||
operations. Generated files are committed, so normal E2E runs do not require
|
|
||||||
network access. E2E fixtures use the generated response types but stay
|
|
||||||
deterministic. Runtime requests continue through Bird because its transport
|
|
||||||
differs from the upstream OpenAPI client. Relay-only endpoints, request
|
|
||||||
transport differences, cursors, and stateful failure scenarios remain in the
|
|
||||||
handwritten mock server.
|
|
||||||
`test:live` is an explicit, opt-in smoke test that performs exactly one
|
|
||||||
read-only Top search using the configured relay.
|
|
||||||
|
|
||||||
## WebMCP prototype
|
|
||||||
|
|
||||||
In a WebMCP-enabled browser, `search_posts` searches and updates the page,
|
|
||||||
`get_loaded_posts` reads a bounded slice of the active feed, and
|
|
||||||
`load_more_posts` appends a continuation and returns the new posts. The tools
|
|
||||||
share the reader's query cache and active relay profile. They do not publish
|
|
||||||
posts or change profiles.
|
|
||||||
|
|
||||||
Enable `chrome://flags/#enable-webmcp-testing`, restart Chrome, and open the
|
|
||||||
app on `http://localhost:3000` or `http://127.0.0.1:3000`. Use the
|
|
||||||
[Model Context Tool Inspector](https://developer.chrome.com/docs/ai/webmcp#imitate_agent_chat_with_the_inspector_extension)
|
|
||||||
to list and invoke tools. Try `search_posts` with
|
|
||||||
`{"q":"TypeScript","lang":"ja","product":"Latest"}`.
|
|
||||||
|
|
||||||
This prototype uses native `document.modelContext` through `usewebmcp`; it
|
|
||||||
does not initialize a polyfill or provide an external MCP transport. Browsers
|
|
||||||
without the API keep the regular reader UI. Public deployment requires the
|
|
||||||
appropriate browser support/origin trial and a secure context. See
|
|
||||||
[tool contracts and verification](docs/webmcp-prototype.md) for details.
|
|
||||||
|
|
||||||
Development binds to `127.0.0.1` by default. `dev:tailscale` binds to
|
Development binds to `127.0.0.1` by default. `dev:tailscale` binds to
|
||||||
`0.0.0.0`, so it exposes the app on LAN interfaces as well as Tailscale. Use it
|
`0.0.0.0`, so it exposes the app on LAN interfaces as well as Tailscale. Use it
|
||||||
|
|||||||
@@ -175,14 +175,10 @@ None of these functions exposes the Bird client, arbitrary method names, arbitra
|
|||||||
|
|
||||||
### Search Flow
|
### Search Flow
|
||||||
|
|
||||||
1. Keep the raw query and structured author, period, language, content, and
|
1. Trim and validate the raw query.
|
||||||
exclusion controls in typed URL search parameters.
|
2. Append `filter:follows` when the following toggle is enabled and the operator is not already present.
|
||||||
2. Compile selected controls into a deterministic advanced search expression
|
3. Fetch one page with `getAllSearchResults(query, { product, cursor, maxPages: 1 })`.
|
||||||
using `from:`, `since:`, `until:`, `lang:`, and `filter:` operators.
|
4. Return normalized tweets and the next cursor.
|
||||||
3. Trim and validate the compiled query, including its 512-character limit.
|
|
||||||
4. Append `filter:follows` when the following toggle is enabled and the operator is not already present.
|
|
||||||
5. Fetch one page with `getAllSearchResults(query, { product, cursor, maxPages: 1 })`.
|
|
||||||
6. Return normalized tweets and the next cursor.
|
|
||||||
|
|
||||||
Advanced X search grammar remains available because the raw query is otherwise passed unchanged.
|
Advanced X search grammar remains available because the raw query is otherwise passed unchanged.
|
||||||
|
|
||||||
@@ -211,11 +207,7 @@ The selected layout is **Focused Tabs**:
|
|||||||
- no content on first load;
|
- no content on first load;
|
||||||
- results directly below the submitted controls.
|
- results directly below the submitted controls.
|
||||||
|
|
||||||
The User tab contains one target input and a Display button. The Search tab
|
The User tab contains one target input and a Display button. The Search tab contains a query input, a Popular/Latest segmented control, a Following only checkbox, and a Search button.
|
||||||
contains a query input; buttons that open inline author, period, language,
|
|
||||||
content-type, and exclusion controls; removable active-condition chips; a
|
|
||||||
collapsible compiled-query preview; a Popular/Latest segmented control; a
|
|
||||||
Following only checkbox; and a Search button.
|
|
||||||
|
|
||||||
Submitting a user target normalizes it to a handle and navigates to `/:handle`.
|
Submitting a user target normalizes it to a handle and navigates to `/:handle`.
|
||||||
Submitting a search updates the route's typed search parameters. Changing tabs
|
Submitting a search updates the route's typed search parameters. Changing tabs
|
||||||
@@ -352,9 +344,7 @@ The work is complete when:
|
|||||||
target or query, following a post detail link, or manually opening a valid
|
target or query, following a post detail link, or manually opening a valid
|
||||||
status URL.
|
status URL.
|
||||||
3. A valid handle or profile URL loads that user's posts.
|
3. A valid handle or profile URL loads that user's posts.
|
||||||
4. Search supports Top, Latest, the follows filter, and button-driven author,
|
4. Search supports Top, Latest, and the follows filter.
|
||||||
period, language, content-type, reply, and repost conditions while preserving
|
|
||||||
raw advanced search syntax.
|
|
||||||
5. Infinite scrolling continues cursor pages without a fixed limit and without duplicate posts.
|
5. Infinite scrolling continues cursor pages without a fixed limit and without duplicate posts.
|
||||||
6. Relay credentials and Bird remain server-only.
|
6. Relay credentials and Bird remain server-only.
|
||||||
7. No excluded discovery or mutation feature is reachable.
|
7. No excluded discovery or mutation feature is reachable.
|
||||||
|
|||||||
@@ -1,121 +0,0 @@
|
|||||||
# WebMCP prototype
|
|
||||||
|
|
||||||
## Scope and design
|
|
||||||
|
|
||||||
Expose the existing intentional reader to agents through three React-owned
|
|
||||||
tools. Search remains available across routes. Feed tools are registered only
|
|
||||||
while a valid timeline, search, or conversation is open. Returning home or to
|
|
||||||
an empty search/list page removes the feed tools. Unsupported browsers do not
|
|
||||||
register tools or fetch posts automatically.
|
|
||||||
|
|
||||||
`usewebmcp` 5.1.0 owns browser registration and cleanup. No polyfill is
|
|
||||||
initialized. The root search tool navigates through TanStack Router and awaits
|
|
||||||
the same query options as the visible feed. Completed data is reused through
|
|
||||||
`ensureInfiniteQueryData`; an invalidated or in-progress query is awaited
|
|
||||||
through `fetchInfiniteQuery`, including refreshes after a profile change.
|
|
||||||
Reading the feed uses its current React Query result. Continuation and the
|
|
||||||
scroll observer use `fetchNextPage({ cancelRefetch: false })` to join an
|
|
||||||
existing request. A feed change during continuation returns an error instead
|
|
||||||
of reporting old results as belonging to the new feed.
|
|
||||||
|
|
||||||
## Tool contracts
|
|
||||||
|
|
||||||
### `search_posts`
|
|
||||||
|
|
||||||
Search X, show the criteria and results in the UI, and return the first slice
|
|
||||||
after retrieval. Searches use the currently selected relay profile.
|
|
||||||
|
|
||||||
Inputs match the existing search controls:
|
|
||||||
|
|
||||||
| Field | Default | Meaning |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `q` | empty | Search text, including raw X search syntax |
|
|
||||||
| `from` | empty | Author handle, optionally prefixed with `@` |
|
|
||||||
| `since` | empty | Inclusive `YYYY-MM-DD` date using X search semantics |
|
|
||||||
| `until` | empty | Exclusive `YYYY-MM-DD` date, later than `since` |
|
|
||||||
| `lang` | `all` | `all`, `ja`, or `en` |
|
|
||||||
| `content` | `all` | `all`, `images`, `videos`, or `links` |
|
|
||||||
| `excludeReplies`, `excludeReposts` | `false` | Exclusions |
|
|
||||||
| `product` | `Latest` | `Latest` or `Top` |
|
|
||||||
| `following` | `false` | Restrict to followed accounts |
|
|
||||||
|
|
||||||
Supply `q` or `from`. Unknown properties and invalid inputs fail before
|
|
||||||
navigation. Existing query construction validates dates, handles, and the
|
|
||||||
512-character compiled-query limit. A concurrent search fails with an
|
|
||||||
actionable message. Navigating elsewhere during a search prevents a stale
|
|
||||||
success response.
|
|
||||||
|
|
||||||
### `get_loaded_posts`
|
|
||||||
|
|
||||||
Return a slice of the current feed without a network request. Accepts
|
|
||||||
`offset` (default 0, nonnegative integer) and `limit` (default 20, integer
|
|
||||||
1–50). Conversation results place the selected post first, once.
|
|
||||||
|
|
||||||
The response includes `status` (`loading`, `ready`, or `error`), `loading`,
|
|
||||||
and `error` information alongside the common result. This is a snapshot of
|
|
||||||
all loaded posts, not just posts inside the viewport.
|
|
||||||
|
|
||||||
### `load_more_posts`
|
|
||||||
|
|
||||||
Accepts `{}`. Wait for one continuation, append it to the UI, and return up to
|
|
||||||
20 newly appended posts. An in-progress scroll request is shared. Initial
|
|
||||||
loading or a feed refresh must finish first. A failed continuation can be retried explicitly.
|
|
||||||
At the end of the feed the result is an empty `posts` array and `hasMore: false`.
|
|
||||||
|
|
||||||
## Results and errors
|
|
||||||
|
|
||||||
Successful tool results contain JSON in an MCP text content block:
|
|
||||||
|
|
||||||
- `request`: active feed kind and normalized criteria.
|
|
||||||
- `posts`: `id`, `author` (username/name), `text`, `textTruncated`, optional
|
|
||||||
`createdAt`, and the original X `url`.
|
|
||||||
- `loadedCount`: number of deduplicated, loaded posts.
|
|
||||||
- `offset`: start of this slice within the loaded feed.
|
|
||||||
- `nextOffset`: next unread offset within the already loaded feed, or `null`.
|
|
||||||
- `hasMore`: whether the last loaded page has an upstream continuation.
|
|
||||||
|
|
||||||
Use `get_loaded_posts` with `nextOffset` for loaded posts outside a returned
|
|
||||||
slice; use `load_more_posts` for an upstream continuation. Scrolling can load
|
|
||||||
more posts independently, so these fields describe a snapshot. Post text is
|
|
||||||
capped at 2,000 characters per post and explicitly marked when truncated;
|
|
||||||
the source URL remains available. Media, quote bodies, and article previews
|
|
||||||
are not included in this initial text-oriented tool response.
|
|
||||||
|
|
||||||
Failures use `isError: true` and JSON containing `code`, `message`, and
|
|
||||||
`retryable`. Existing relay error details are preserved. A successful empty
|
|
||||||
search is not an error.
|
|
||||||
|
|
||||||
All tools mark returned external content with `untrustedContentHint: true`.
|
|
||||||
Only `get_loaded_posts` has `readOnlyHint: true`: search and continuation
|
|
||||||
change local UI state. No tool performs X write actions. Annotations are
|
|
||||||
metadata, not authorization controls.
|
|
||||||
|
|
||||||
## Verification and limits
|
|
||||||
|
|
||||||
```sh
|
|
||||||
nix develop -c pnpm test
|
|
||||||
nix develop -c pnpm typecheck
|
|
||||||
nix develop -c pnpm test:e2e e2e/integrations/webmcp.test.ts
|
|
||||||
```
|
|
||||||
|
|
||||||
The E2E file enables native Chromium WebMCP/testing flags and uses
|
|
||||||
`navigator.modelContextTesting` to invoke actual registered tools. The
|
|
||||||
standalone mock relay supplies deterministic data through the production
|
|
||||||
server-function boundary. Tests do not contact X or a personal relay.
|
|
||||||
|
|
||||||
For interactive testing, enable Chrome's WebMCP testing flag, restart, run
|
|
||||||
`nix develop -c pnpm dev`, and open the local site with Model Context Tool
|
|
||||||
Inspector. Registration uses `document.modelContext`; availability is checked
|
|
||||||
at mount, so reload after changing browser support. No production origin-trial
|
|
||||||
token or external MCP-client bridge is configured by this prototype.
|
|
||||||
|
|
||||||
The hook does not forward the browser's execution AbortSignal to application
|
|
||||||
callbacks. Browser cancellation therefore does not guarantee cancellation of
|
|
||||||
the shared read request. Tools do detect navigation changes before returning
|
|
||||||
their asynchronous results. Agent task-selection quality still needs manual
|
|
||||||
evaluation with the consuming agent; deterministic browser tests verify the
|
|
||||||
tool contracts and UI behavior.
|
|
||||||
|
|
||||||
Design references: [Chrome best practices](https://developer.chrome.com/docs/ai/webmcp/best-practices),
|
|
||||||
[workflow design](https://developer.chrome.com/docs/ai/webmcp/build-tools),
|
|
||||||
and [usewebmcp](https://github.com/WebMCP-org/npm-packages/tree/main/packages/usewebmcp).
|
|
||||||
@@ -22,22 +22,3 @@ test('search results have no accessibility violations', async ({
|
|||||||
const result = await a11y().analyze()
|
const result = await a11y().analyze()
|
||||||
expect(result.violations).toEqual([])
|
expect(result.violations).toEqual([])
|
||||||
})
|
})
|
||||||
|
|
||||||
test('open filters and active condition chips have no accessibility violations', async ({
|
|
||||||
a11y,
|
|
||||||
page,
|
|
||||||
searchPage,
|
|
||||||
}) => {
|
|
||||||
await searchPage.goTo()
|
|
||||||
await searchPage.queryInputLocator.fill('TypeScript')
|
|
||||||
await page.getByRole('button', { name: '投稿者' }).click()
|
|
||||||
await page.getByLabel('投稿者').fill('@tan_stack')
|
|
||||||
await page.getByRole('button', { name: '言語' }).click()
|
|
||||||
await page.getByLabel('日本語').check()
|
|
||||||
await expect(
|
|
||||||
page.getByRole('button', { name: '投稿者 @tan_stack を解除' }),
|
|
||||||
).toBeVisible()
|
|
||||||
|
|
||||||
const result = await a11y().analyze()
|
|
||||||
expect(result.violations).toEqual([])
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
import type { TweetLegacy } from '../generated/twitter-openapi/client.ts'
|
|
||||||
|
|
||||||
interface TweetLegacyFixtureOptions {
|
|
||||||
conversationId?: string
|
|
||||||
inReplyTo?: string
|
|
||||||
replyCount?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export const tweetLegacyFixture = (
|
|
||||||
id: string,
|
|
||||||
text: string,
|
|
||||||
{
|
|
||||||
conversationId = id,
|
|
||||||
inReplyTo,
|
|
||||||
replyCount = 1,
|
|
||||||
}: TweetLegacyFixtureOptions = {},
|
|
||||||
): TweetLegacy => ({
|
|
||||||
bookmark_count: 0,
|
|
||||||
bookmarked: false,
|
|
||||||
conversation_id_str: conversationId,
|
|
||||||
created_at: 'Mon Jul 13 00:00:00 +0000 2026',
|
|
||||||
display_text_range: [0, text.length],
|
|
||||||
favorite_count: 3,
|
|
||||||
favorited: false,
|
|
||||||
full_text: text,
|
|
||||||
id_str: id,
|
|
||||||
...(inReplyTo ? { in_reply_to_status_id_str: inReplyTo } : {}),
|
|
||||||
is_quote_status: false,
|
|
||||||
lang: 'ja',
|
|
||||||
quote_count: 0,
|
|
||||||
reply_count: replyCount,
|
|
||||||
retweet_count: 2,
|
|
||||||
retweeted: false,
|
|
||||||
user_id_str: '42',
|
|
||||||
})
|
|
||||||
@@ -43,39 +43,6 @@ test('requires intent and infinitely loads a user timeline', async ({
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test('switches the relay profile and reloads visible content', async ({
|
|
||||||
homePage,
|
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
await homePage.goTo()
|
|
||||||
|
|
||||||
const profile = page.getByLabel('プロファイル')
|
|
||||||
await expect(profile).toHaveValue('e2e')
|
|
||||||
await homePage.displayUser('@yuta')
|
|
||||||
await expect(page.getByText('user page 1')).toBeVisible()
|
|
||||||
|
|
||||||
await profile.selectOption('alternate')
|
|
||||||
await expect(page.getByRole('status')).toHaveText('切り替えました。')
|
|
||||||
|
|
||||||
await expect(page.getByText('alternate profile page 1')).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('keeps the profile selector within narrow viewports', async ({
|
|
||||||
homePage,
|
|
||||||
page,
|
|
||||||
}) => {
|
|
||||||
for (const width of [320, 375, 414, 768]) {
|
|
||||||
await page.setViewportSize({ width, height: 900 })
|
|
||||||
await homePage.goTo()
|
|
||||||
await expect(page.getByLabel('プロファイル')).toBeVisible()
|
|
||||||
expect(
|
|
||||||
await page.evaluate(
|
|
||||||
() => document.documentElement.scrollWidth > window.innerWidth,
|
|
||||||
),
|
|
||||||
).toBe(false)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
test('selects an authenticated list and infinitely loads its timeline', async ({
|
test('selects an authenticated list and infinitely loads its timeline', async ({
|
||||||
listsPage,
|
listsPage,
|
||||||
page,
|
page,
|
||||||
@@ -185,27 +152,12 @@ test('keeps keyboard focus intentional and discovery or mutation controls absent
|
|||||||
}) => {
|
}) => {
|
||||||
await searchPage.goTo()
|
await searchPage.goTo()
|
||||||
|
|
||||||
await searchPage.tabTo(
|
|
||||||
searchPage.page.getByRole('combobox', { name: 'プロファイル' }),
|
|
||||||
)
|
|
||||||
await searchPage.tabTo(searchPage.page.getByRole('link', { name: '検索' }))
|
|
||||||
await searchPage.tabTo(
|
await searchPage.tabTo(
|
||||||
searchPage.page.getByRole('link', { name: 'ユーザー' }),
|
searchPage.page.getByRole('link', { name: 'ユーザー' }),
|
||||||
)
|
)
|
||||||
|
await searchPage.tabTo(searchPage.page.getByRole('link', { name: '検索' }))
|
||||||
await searchPage.tabTo(searchPage.page.getByRole('link', { name: 'リスト' }))
|
await searchPage.tabTo(searchPage.page.getByRole('link', { name: 'リスト' }))
|
||||||
await searchPage.tabTo(searchPage.queryInputLocator)
|
await searchPage.tabTo(searchPage.queryInputLocator)
|
||||||
await searchPage.tabTo(
|
|
||||||
searchPage.page.getByRole('button', { name: '投稿者' }),
|
|
||||||
)
|
|
||||||
await searchPage.tabTo(searchPage.page.getByRole('button', { name: '期間' }))
|
|
||||||
await searchPage.tabTo(searchPage.page.getByRole('button', { name: '言語' }))
|
|
||||||
await searchPage.tabTo(
|
|
||||||
searchPage.page.getByRole('button', { name: '投稿の種類' }),
|
|
||||||
)
|
|
||||||
await searchPage.tabTo(searchPage.page.getByRole('button', { name: '除外' }))
|
|
||||||
await searchPage.tabTo(
|
|
||||||
searchPage.page.getByText('検索式を確認', { exact: true }),
|
|
||||||
)
|
|
||||||
await expect(searchPage.latestRankingLocator).toBeChecked()
|
await expect(searchPage.latestRankingLocator).toBeChecked()
|
||||||
await searchPage.tabTo(searchPage.latestRankingLocator)
|
await searchPage.tabTo(searchPage.latestRankingLocator)
|
||||||
await searchPage.tabTo(searchPage.followingOnlyLocator)
|
await searchPage.tabTo(searchPage.followingOnlyLocator)
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 76 KiB After Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 75 KiB After Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 60 KiB After Width: | Height: | Size: 57 KiB |
@@ -1,254 +0,0 @@
|
|||||||
import type { Page } from '@playwright/test'
|
|
||||||
import { expect, test } from '../fixtures'
|
|
||||||
import { SearchPage } from '../models/SearchPage'
|
|
||||||
|
|
||||||
type NativeTesting = {
|
|
||||||
listTools(): { name: string }[]
|
|
||||||
executeTool(name: string, input: string): Promise<string | null>
|
|
||||||
}
|
|
||||||
|
|
||||||
type ToolResult = {
|
|
||||||
content: { type: string; text: string }[]
|
|
||||||
isError?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
type FeedResult = {
|
|
||||||
request: { kind: string; query: string; product: string; following: boolean }
|
|
||||||
posts: { id: string; text: string; url: string }[]
|
|
||||||
loadedCount: number
|
|
||||||
offset: number
|
|
||||||
nextOffset: number | null
|
|
||||||
hasMore: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
test.use({
|
|
||||||
launchOptions: {
|
|
||||||
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE,
|
|
||||||
args: ['--enable-blink-features=WebMCP,WebMCPTesting'],
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
async function toolNames(page: Page) {
|
|
||||||
return page.evaluate(() =>
|
|
||||||
(
|
|
||||||
navigator as Navigator & { modelContextTesting: NativeTesting }
|
|
||||||
).modelContextTesting
|
|
||||||
.listTools()
|
|
||||||
.map((tool) => tool.name)
|
|
||||||
.sort(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function executeTool(
|
|
||||||
page: Page,
|
|
||||||
name: string,
|
|
||||||
input: Record<string, unknown> = {},
|
|
||||||
): Promise<ToolResult> {
|
|
||||||
const result = await page.evaluate(
|
|
||||||
({ name, input }) =>
|
|
||||||
(
|
|
||||||
navigator as Navigator & { modelContextTesting: NativeTesting }
|
|
||||||
).modelContextTesting.executeTool(name, JSON.stringify(input)),
|
|
||||||
{ name, input },
|
|
||||||
)
|
|
||||||
expect(result, `${name} returned a result`).not.toBeNull()
|
|
||||||
if (result === null) throw new Error(`${name} returned no result`)
|
|
||||||
return JSON.parse(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function executeFeedTool(
|
|
||||||
page: Page,
|
|
||||||
name: string,
|
|
||||||
input: Record<string, unknown> = {},
|
|
||||||
): Promise<FeedResult> {
|
|
||||||
const result = await executeTool(page, name, input)
|
|
||||||
expect(result.isError, JSON.stringify(result.content)).not.toBe(true)
|
|
||||||
expect(result.content[0]?.type).toBe('text')
|
|
||||||
return JSON.parse(result.content[0]?.text ?? '')
|
|
||||||
}
|
|
||||||
|
|
||||||
let pageErrors: string[]
|
|
||||||
|
|
||||||
test.beforeEach(async ({ page }, testInfo) => {
|
|
||||||
pageErrors = []
|
|
||||||
page.on('pageerror', (error) => pageErrors.push(error.message))
|
|
||||||
if (testInfo.title === 'joins pagination already started by scrolling') return
|
|
||||||
// Keep pagination under the tool's control without replacing WebMCP itself.
|
|
||||||
await page.addInitScript(() => {
|
|
||||||
window.IntersectionObserver = class {
|
|
||||||
readonly root = null
|
|
||||||
readonly rootMargin = '0px'
|
|
||||||
readonly scrollMargin = '0px'
|
|
||||||
readonly thresholds = [0]
|
|
||||||
observe() {}
|
|
||||||
unobserve() {}
|
|
||||||
disconnect() {}
|
|
||||||
takeRecords() {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test.afterEach(() => {
|
|
||||||
expect(pageErrors, 'uncaught browser errors').toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
test('searches through native WebMCP and keeps results synchronized with the UI', async ({
|
|
||||||
homePage,
|
|
||||||
page,
|
|
||||||
searchPage,
|
|
||||||
}) => {
|
|
||||||
await homePage.goTo()
|
|
||||||
await expect.poll(() => toolNames(page)).toEqual(['search_posts'])
|
|
||||||
|
|
||||||
const first = await executeFeedTool(page, 'search_posts', {
|
|
||||||
q: 'AI',
|
|
||||||
product: 'Top',
|
|
||||||
following: true,
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(first.request).toMatchObject({
|
|
||||||
kind: 'search',
|
|
||||||
query: 'AI filter:follows',
|
|
||||||
product: 'Top',
|
|
||||||
following: true,
|
|
||||||
})
|
|
||||||
expect(first.posts.map((post) => post.text)).toEqual(['Top · follows page 1'])
|
|
||||||
expect(first).toMatchObject({ loadedCount: 1, offset: 0, hasMore: true })
|
|
||||||
await expect(page).toHaveURL(/\/search\?/)
|
|
||||||
await expect(searchPage.queryInputLocator).toHaveValue('AI')
|
|
||||||
await expect(searchPage.topRankingLocator).toBeChecked()
|
|
||||||
await expect(searchPage.followingOnlyLocator).toBeChecked()
|
|
||||||
await expect(
|
|
||||||
page.getByText(first.posts[0]?.text ?? '', { exact: true }),
|
|
||||||
).toBeVisible()
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(() => toolNames(page))
|
|
||||||
.toEqual(['get_loaded_posts', 'load_more_posts', 'search_posts'])
|
|
||||||
const more = await executeFeedTool(page, 'load_more_posts')
|
|
||||||
expect(more.posts.map((post) => post.text)).toEqual(['Top · follows page 2'])
|
|
||||||
expect(more).toMatchObject({ loadedCount: 2, offset: 1, hasMore: false })
|
|
||||||
await expect(searchPage.articlesLocator).toHaveCount(2)
|
|
||||||
await expect(searchPage.endOfFeedLocator).toBeVisible()
|
|
||||||
|
|
||||||
const slice = await executeFeedTool(page, 'get_loaded_posts', {
|
|
||||||
offset: 1,
|
|
||||||
limit: 1,
|
|
||||||
})
|
|
||||||
expect(slice.posts).toEqual(more.posts)
|
|
||||||
expect(slice).toMatchObject({ loadedCount: 2, offset: 1, hasMore: false })
|
|
||||||
|
|
||||||
const end = await executeFeedTool(page, 'load_more_posts')
|
|
||||||
expect(end).toMatchObject({ posts: [], loadedCount: 2, hasMore: false })
|
|
||||||
await expect(searchPage.articlesLocator).toHaveCount(2)
|
|
||||||
|
|
||||||
// SPA navigation must unregister the old feed's tools in the same document.
|
|
||||||
await page.getByRole('link', { name: 'ユーザー', exact: true }).click()
|
|
||||||
await expect(page).toHaveURL(/\/$/)
|
|
||||||
await expect.poll(() => toolNames(page)).toEqual(['search_posts'])
|
|
||||||
})
|
|
||||||
|
|
||||||
test('rejects invalid search conditions without navigating or dropping the active feed', async ({
|
|
||||||
homePage,
|
|
||||||
page,
|
|
||||||
searchPage,
|
|
||||||
}) => {
|
|
||||||
await homePage.goTo()
|
|
||||||
await expect.poll(() => toolNames(page)).toContain('search_posts')
|
|
||||||
const first = await executeFeedTool(page, 'search_posts', { q: 'existing' })
|
|
||||||
const previousURL = page.url()
|
|
||||||
const result = await executeTool(page, 'search_posts', {
|
|
||||||
q: 'invalid dates',
|
|
||||||
since: '2026-09-24',
|
|
||||||
until: '2026-09-23',
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(result.isError).toBe(true)
|
|
||||||
expect(result.content[0]?.type).toBe('text')
|
|
||||||
expect(() => JSON.parse(result.content[0]?.text ?? '')).not.toThrow()
|
|
||||||
await expect(page).toHaveURL(previousURL)
|
|
||||||
await expect(searchPage.queryInputLocator).toHaveValue('existing')
|
|
||||||
const current = await executeFeedTool(page, 'get_loaded_posts')
|
|
||||||
expect(current.posts).toEqual(first.posts)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('retries a failed continuation without losing the first page', async ({
|
|
||||||
homePage,
|
|
||||||
page,
|
|
||||||
searchPage,
|
|
||||||
}, testInfo) => {
|
|
||||||
await homePage.goTo()
|
|
||||||
await expect.poll(() => toolNames(page)).toContain('search_posts')
|
|
||||||
const first = await executeFeedTool(page, 'search_posts', {
|
|
||||||
q: `retry-webmcp-${testInfo.project.name}`,
|
|
||||||
})
|
|
||||||
const failed = await executeTool(page, 'load_more_posts')
|
|
||||||
expect(failed.isError, JSON.stringify(failed.content)).toBe(true)
|
|
||||||
await expect(searchPage.continuationErrorLocator).toBeVisible()
|
|
||||||
const retained = await executeFeedTool(page, 'get_loaded_posts')
|
|
||||||
expect(retained.posts).toEqual(first.posts)
|
|
||||||
|
|
||||||
const recovered = await executeFeedTool(page, 'load_more_posts')
|
|
||||||
expect(recovered.posts.map((post) => post.text)).toEqual([
|
|
||||||
'Latest · all page 2',
|
|
||||||
])
|
|
||||||
expect(recovered).toMatchObject({ loadedCount: 2, offset: 1, hasMore: false })
|
|
||||||
await expect(searchPage.continuationErrorLocator).toHaveCount(0)
|
|
||||||
await expect(searchPage.articlesLocator).toHaveCount(2)
|
|
||||||
await expect(searchPage.endOfFeedLocator).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('joins pagination already started by scrolling', async ({
|
|
||||||
homePage,
|
|
||||||
page,
|
|
||||||
searchPage,
|
|
||||||
}, testInfo) => {
|
|
||||||
await homePage.goTo()
|
|
||||||
await expect.poll(() => toolNames(page)).toContain('search_posts')
|
|
||||||
await executeFeedTool(page, 'search_posts', {
|
|
||||||
q: `slow-webmcp-${testInfo.project.name}`,
|
|
||||||
})
|
|
||||||
await expect(searchPage.loadingRailLocator).toBeVisible()
|
|
||||||
|
|
||||||
const more = await executeFeedTool(page, 'load_more_posts')
|
|
||||||
expect(more.posts.map((post) => post.text)).toEqual(['Latest · all page 2'])
|
|
||||||
expect(more).toMatchObject({ loadedCount: 2, offset: 1, hasMore: false })
|
|
||||||
await expect(searchPage.articlesLocator).toHaveCount(2)
|
|
||||||
await expect(searchPage.endOfFeedLocator).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
test('keeps the normal search form functional without native WebMCP', async ({
|
|
||||||
playwright,
|
|
||||||
baseURL,
|
|
||||||
}, testInfo) => {
|
|
||||||
const browser = await playwright.chromium.launch({
|
|
||||||
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE,
|
|
||||||
args: ['--disable-blink-features=WebMCP,WebMCPTesting'],
|
|
||||||
})
|
|
||||||
const page = await browser.newPage({ baseURL })
|
|
||||||
const searchPage = new SearchPage(page)
|
|
||||||
try {
|
|
||||||
page.on('pageerror', (error) => pageErrors.push(error.message))
|
|
||||||
await searchPage.goTo()
|
|
||||||
expect(await page.evaluate(() => Boolean(document.modelContext))).toBe(
|
|
||||||
false,
|
|
||||||
)
|
|
||||||
await searchPage.search('ordinary search')
|
|
||||||
await expect(page.getByText('Latest · all page 1')).toBeVisible()
|
|
||||||
await expect(page.getByText('Latest · all page 2')).toBeVisible()
|
|
||||||
} catch (error) {
|
|
||||||
await testInfo.attach('unsupported-browser-state', {
|
|
||||||
body: JSON.stringify({ url: page.url(), html: await page.content() }),
|
|
||||||
contentType: 'application/json',
|
|
||||||
})
|
|
||||||
await testInfo.attach('unsupported-browser-screen', {
|
|
||||||
body: await page.screenshot(),
|
|
||||||
contentType: 'image/png',
|
|
||||||
})
|
|
||||||
throw error
|
|
||||||
} finally {
|
|
||||||
await browser.close()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import { createServer } from 'node:http'
|
import { createServer } from 'node:http'
|
||||||
import { tweetLegacyFixture } from './fixtures/twitter.ts'
|
|
||||||
|
|
||||||
const portValue = process.env.TWITTER_LITE_MOCK_RELAY_PORT
|
const portValue = process.env.TWITTER_LITE_MOCK_RELAY_PORT
|
||||||
const port = Number(portValue)
|
const port = Number(portValue)
|
||||||
@@ -31,11 +30,15 @@ const tweetResult = (
|
|||||||
{ conversationId = id, inReplyTo, replyCount = 1 } = {},
|
{ conversationId = id, inReplyTo, replyCount = 1 } = {},
|
||||||
) => ({
|
) => ({
|
||||||
rest_id: id,
|
rest_id: id,
|
||||||
legacy: tweetLegacyFixture(id, text, {
|
legacy: {
|
||||||
conversationId,
|
full_text: text,
|
||||||
inReplyTo,
|
created_at: 'Mon Jul 13 00:00:00 +0000 2026',
|
||||||
replyCount,
|
reply_count: replyCount,
|
||||||
}),
|
retweet_count: 2,
|
||||||
|
favorite_count: 3,
|
||||||
|
conversation_id_str: conversationId,
|
||||||
|
...(inReplyTo ? { in_reply_to_status_id_str: inReplyTo } : {}),
|
||||||
|
},
|
||||||
core: {
|
core: {
|
||||||
user_results: {
|
user_results: {
|
||||||
result: {
|
result: {
|
||||||
@@ -96,11 +99,6 @@ const timeline = (entries) => ({ instructions: [{ entries }] })
|
|||||||
|
|
||||||
const server = createServer(async (request, response) => {
|
const server = createServer(async (request, response) => {
|
||||||
const url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`)
|
const url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`)
|
||||||
if (request.method === 'GET' && url.pathname === '/profiles') {
|
|
||||||
send(response, { profiles: ['e2e', 'alternate'] })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const operation = [
|
const operation = [
|
||||||
'UserByScreenName',
|
'UserByScreenName',
|
||||||
'UserTweets',
|
'UserTweets',
|
||||||
@@ -122,8 +120,7 @@ const server = createServer(async (request, response) => {
|
|||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const profileName = request.headers['x-profile-name']
|
if (request.headers['x-profile-name'] !== 'e2e') {
|
||||||
if (profileName !== 'e2e' && profileName !== 'alternate') {
|
|
||||||
fail(response, 403, 'invalid profile')
|
fail(response, 403, 'invalid profile')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -169,12 +166,10 @@ const server = createServer(async (request, response) => {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
const secondPage = variables.cursor === 'user-next'
|
const secondPage = variables.cursor === 'user-next'
|
||||||
const firstPageText =
|
|
||||||
profileName === 'alternate' ? 'alternate profile page 1' : 'user page 1'
|
|
||||||
const entries = secondPage
|
const entries = secondPage
|
||||||
? [tweet('1010', 'user page 2')]
|
? [tweet('1010', 'user page 2')]
|
||||||
: [
|
: [
|
||||||
tweet('1001', firstPageText, 'yuta', {
|
tweet('1001', 'user page 1', 'yuta', {
|
||||||
conversationId: '1000',
|
conversationId: '1000',
|
||||||
}),
|
}),
|
||||||
cursor('user-next'),
|
cursor('user-next'),
|
||||||
|
|||||||
@@ -74,11 +74,11 @@
|
|||||||
},
|
},
|
||||||
"nixpkgs_2": {
|
"nixpkgs_2": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1783776592,
|
"lastModified": 1784796856,
|
||||||
"narHash": "sha256-UgCQzxeWI75XM8G+hPrPh+MKzEPjG3SpAj7dtqSbksA=",
|
"narHash": "sha256-wWFrV5/Qbm+lyt5x20E/bSbfJiGKMo4RCxZV8cl/WZI=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "e7a3ca8092b61ff85b6a45bf863ea2b2d6a661b3",
|
"rev": "e2587caef70cea85dd97d7daab492899902dbf5d",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
inherit (finalAttrs) pname version src;
|
inherit (finalAttrs) pname version src;
|
||||||
pnpm = pkgs.pnpm_11;
|
pnpm = pkgs.pnpm_11;
|
||||||
fetcherVersion = 4;
|
fetcherVersion = 4;
|
||||||
hash = "sha256-rUszJwsou2NXbVwyPQQ0bk+pRFzRQIzrWs+JXBX/Q9Y=";
|
hash = "sha256-ai71NY11VUogMi8SX45LrEYRy5amSMbYbnSwko4O72A=";
|
||||||
};
|
};
|
||||||
|
|
||||||
nativeBuildInputs = with pkgs; [
|
nativeBuildInputs = with pkgs; [
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
import { defineConfig, defineTransformer } from 'orval'
|
|
||||||
|
|
||||||
const selectedTag = 'twitter-lite-e2e'
|
|
||||||
const selectedOperationIds = new Set([
|
|
||||||
'getUserByScreenName',
|
|
||||||
'getUserTweets',
|
|
||||||
'getTweetDetail',
|
|
||||||
'getSearchTimeline',
|
|
||||||
'getListLatestTweetsTimeline',
|
|
||||||
])
|
|
||||||
|
|
||||||
const selectE2eOperations = defineTransformer((document) => {
|
|
||||||
const foundOperationIds = new Set<string>()
|
|
||||||
|
|
||||||
for (const pathItem of Object.values(document.paths ?? {})) {
|
|
||||||
if (!pathItem || typeof pathItem !== 'object') continue
|
|
||||||
|
|
||||||
for (const candidate of Object.values(pathItem)) {
|
|
||||||
if (
|
|
||||||
!candidate ||
|
|
||||||
typeof candidate !== 'object' ||
|
|
||||||
Array.isArray(candidate) ||
|
|
||||||
!('operationId' in candidate)
|
|
||||||
) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
const operation = candidate as {
|
|
||||||
operationId?: string
|
|
||||||
tags?: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
operation.operationId &&
|
|
||||||
selectedOperationIds.has(operation.operationId)
|
|
||||||
) {
|
|
||||||
foundOperationIds.add(operation.operationId)
|
|
||||||
operation.tags = [...(operation.tags ?? []), selectedTag]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const missingOperationIds = [...selectedOperationIds].filter(
|
|
||||||
(operationId) => !foundOperationIds.has(operationId),
|
|
||||||
)
|
|
||||||
if (missingOperationIds.length > 0) {
|
|
||||||
throw new Error(
|
|
||||||
`twitter-openapi is missing selected operations: ${missingOperationIds.join(', ')}`,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return document
|
|
||||||
})
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
twitterOpenApi: {
|
|
||||||
input: {
|
|
||||||
target:
|
|
||||||
'https://raw.githubusercontent.com/fa0311/twitter-openapi/590dae5c9f8575abc91d3774946bfe6f23960aba/dist/docs/openapi-3.0.yaml',
|
|
||||||
filters: {
|
|
||||||
mode: 'include',
|
|
||||||
tags: [selectedTag],
|
|
||||||
},
|
|
||||||
override: {
|
|
||||||
transformer: selectE2eOperations,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
output: {
|
|
||||||
clean: true,
|
|
||||||
client: 'fetch',
|
|
||||||
mode: 'single',
|
|
||||||
target: './e2e/generated/twitter-openapi/client.ts',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
@@ -6,18 +6,12 @@
|
|||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22.12.0"
|
"node": ">=22.12.0"
|
||||||
},
|
},
|
||||||
"knip": {
|
|
||||||
"ignore": [
|
|
||||||
"e2e/generated/**"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"imports": {
|
"imports": {
|
||||||
"#/*": "./src/*"
|
"#/*": "./src/*"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev --host 127.0.0.1 --port 3000",
|
"dev": "vite dev --host 127.0.0.1 --port 3000",
|
||||||
"dev:tailscale": "vite dev --host 0.0.0.0 --port 3000",
|
"dev:tailscale": "vite dev --host 0.0.0.0 --port 3000",
|
||||||
"generate:e2e-openapi": "orval --config orval.config.ts --formatter biome --fail-on-warnings",
|
|
||||||
"generate-routes": "node scripts/generate-routes.mjs",
|
"generate-routes": "node scripts/generate-routes.mjs",
|
||||||
"check:routes": "pnpm generate-routes && git diff --exit-code -- src/routeTree.gen.ts",
|
"check:routes": "pnpm generate-routes && git diff --exit-code -- src/routeTree.gen.ts",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
@@ -40,7 +34,6 @@
|
|||||||
"nitro": "3.0.260610-beta",
|
"nitro": "3.0.260610-beta",
|
||||||
"react": "19.2.7",
|
"react": "19.2.7",
|
||||||
"react-dom": "19.2.7",
|
"react-dom": "19.2.7",
|
||||||
"usewebmcp": "5.1.0",
|
|
||||||
"zod": "4.4.3"
|
"zod": "4.4.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -56,8 +49,6 @@
|
|||||||
"@vitejs/plugin-react": "6.0.3",
|
"@vitejs/plugin-react": "6.0.3",
|
||||||
"jsdom": "29.1.1",
|
"jsdom": "29.1.1",
|
||||||
"knip": "6.27.0",
|
"knip": "6.27.0",
|
||||||
"orval": "8.24.0",
|
|
||||||
"tsx": "4.23.12",
|
|
||||||
"typescript": "7.0.2",
|
"typescript": "7.0.2",
|
||||||
"vite": "8.1.4",
|
"vite": "8.1.4",
|
||||||
"vitest": "4.1.10"
|
"vitest": "4.1.10"
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ export default defineConfig({
|
|||||||
},
|
},
|
||||||
webServer: [
|
webServer: [
|
||||||
{
|
{
|
||||||
command: `TWITTER_LITE_MOCK_RELAY_PORT=${relayPort} pnpm exec tsx e2e/mock-relay.mjs`,
|
command: `TWITTER_LITE_MOCK_RELAY_PORT=${relayPort} node e2e/mock-relay.mjs`,
|
||||||
port: relayPort,
|
port: relayPort,
|
||||||
reuseExistingServer: false,
|
reuseExistingServer: false,
|
||||||
timeout: 120_000,
|
timeout: 120_000,
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ProfileSwitcher } from '#/features/profiles/profile-switcher'
|
|
||||||
|
|
||||||
export function AppShell({
|
export function AppShell({
|
||||||
active,
|
active,
|
||||||
@@ -12,8 +11,10 @@ export function AppShell({
|
|||||||
<main className="app">
|
<main className="app">
|
||||||
<header className="app-header">
|
<header className="app-header">
|
||||||
<p className="brand">Twitter Lite</p>
|
<p className="brand">Twitter Lite</p>
|
||||||
<ProfileSwitcher />
|
|
||||||
<nav aria-label="閲覧方法" className="tabs">
|
<nav aria-label="閲覧方法" className="tabs">
|
||||||
|
<Link aria-current={active === 'user' ? 'page' : undefined} to="/">
|
||||||
|
ユーザー
|
||||||
|
</Link>
|
||||||
<Link
|
<Link
|
||||||
aria-current={active === 'search' ? 'page' : undefined}
|
aria-current={active === 'search' ? 'page' : undefined}
|
||||||
search={{ q: '', product: 'Latest', following: false }}
|
search={{ q: '', product: 'Latest', following: false }}
|
||||||
@@ -21,9 +22,6 @@ export function AppShell({
|
|||||||
>
|
>
|
||||||
検索
|
検索
|
||||||
</Link>
|
</Link>
|
||||||
<Link aria-current={active === 'user' ? 'page' : undefined} to="/">
|
|
||||||
ユーザー
|
|
||||||
</Link>
|
|
||||||
<Link
|
<Link
|
||||||
aria-current={active === 'list' ? 'page' : undefined}
|
aria-current={active === 'list' ? 'page' : undefined}
|
||||||
to="/i/lists"
|
to="/i/lists"
|
||||||
|
|||||||
@@ -1,17 +1,13 @@
|
|||||||
import { TwitterClient } from '@yuta/bird'
|
import { TwitterClient } from '@yuta/bird'
|
||||||
import type { BirdReader } from './post-service'
|
import type { BirdReader } from './post-service'
|
||||||
|
|
||||||
const clients = new Map<string | undefined, TwitterClient>()
|
let client: TwitterClient | undefined
|
||||||
|
|
||||||
export function getBirdReader(profileName?: string): BirdReader {
|
export function getBirdReader(): BirdReader {
|
||||||
const existing = clients.get(profileName)
|
client ??= new TwitterClient({
|
||||||
if (existing) return existing
|
|
||||||
|
|
||||||
const client = new TwitterClient({
|
|
||||||
relayBaseUrl: process.env.TWITTER_RELAY_BASE_URL,
|
relayBaseUrl: process.env.TWITTER_RELAY_BASE_URL,
|
||||||
profileName,
|
profileName: process.env.BIRD_PROFILE_NAME,
|
||||||
timeoutMs: 20_000,
|
timeoutMs: 20_000,
|
||||||
})
|
})
|
||||||
clients.set(profileName, client)
|
|
||||||
return client
|
return client
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,19 +4,6 @@ import { ListForm } from './list-form'
|
|||||||
import { SearchForm } from './search-form'
|
import { SearchForm } from './search-form'
|
||||||
import { UserForm } from './user-form'
|
import { UserForm } from './user-form'
|
||||||
|
|
||||||
const searchValues = {
|
|
||||||
q: '',
|
|
||||||
from: '',
|
|
||||||
since: '',
|
|
||||||
until: '',
|
|
||||||
lang: 'all' as const,
|
|
||||||
content: 'all' as const,
|
|
||||||
excludeReplies: false,
|
|
||||||
excludeReposts: false,
|
|
||||||
product: 'Latest' as const,
|
|
||||||
following: false,
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('UserForm', () => {
|
describe('UserForm', () => {
|
||||||
it('submits only after the user enters a target', () => {
|
it('submits only after the user enters a target', () => {
|
||||||
const onSubmit = vi.fn()
|
const onSubmit = vi.fn()
|
||||||
@@ -71,82 +58,40 @@ describe('ListForm', () => {
|
|||||||
|
|
||||||
describe('SearchForm', () => {
|
describe('SearchForm', () => {
|
||||||
it('uses a labelled grouping for ranking controls', () => {
|
it('uses a labelled grouping for ranking controls', () => {
|
||||||
render(<SearchForm initialValues={searchValues} onSubmit={vi.fn()} />)
|
render(
|
||||||
|
<SearchForm
|
||||||
|
initialQuery=""
|
||||||
|
initialProduct="Latest"
|
||||||
|
initialFollowing={false}
|
||||||
|
onSubmit={vi.fn()}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
expect(screen.getByRole('group', { name: '並び順' })).toBeInTheDocument()
|
expect(screen.getByRole('group', { name: '並び順' })).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('submits the selected ranking and follows filter', () => {
|
it('submits the selected ranking and follows filter', () => {
|
||||||
const onSubmit = vi.fn()
|
|
||||||
render(<SearchForm initialValues={searchValues} onSubmit={onSubmit} />)
|
|
||||||
|
|
||||||
fireEvent.change(screen.getByLabelText('検索語'), {
|
|
||||||
target: { value: ' AI lang:ja ' },
|
|
||||||
})
|
|
||||||
fireEvent.click(screen.getByLabelText('人気順'))
|
|
||||||
fireEvent.click(screen.getByLabelText('フォロー中のみ'))
|
|
||||||
expect(screen.getByText('AI lang:ja filter:follows')).toBeInTheDocument()
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '検索' }))
|
|
||||||
|
|
||||||
expect(onSubmit).toHaveBeenCalledWith({
|
|
||||||
q: 'AI lang:ja',
|
|
||||||
from: '',
|
|
||||||
since: '',
|
|
||||||
until: '',
|
|
||||||
lang: 'all',
|
|
||||||
content: 'all',
|
|
||||||
excludeReplies: false,
|
|
||||||
excludeReposts: false,
|
|
||||||
product: 'Top',
|
|
||||||
following: true,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('submits conditions selected with the filter buttons', () => {
|
|
||||||
const onSubmit = vi.fn()
|
|
||||||
render(<SearchForm initialValues={searchValues} onSubmit={onSubmit} />)
|
|
||||||
|
|
||||||
fireEvent.change(screen.getByLabelText('検索語'), {
|
|
||||||
target: { value: 'TypeScript' },
|
|
||||||
})
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '投稿者' }))
|
|
||||||
fireEvent.change(screen.getByLabelText('投稿者'), {
|
|
||||||
target: { value: '@tan_stack' },
|
|
||||||
})
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '言語' }))
|
|
||||||
fireEvent.click(screen.getByLabelText('日本語'))
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '投稿の種類' }))
|
|
||||||
fireEvent.click(screen.getByLabelText('画像'))
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '除外' }))
|
|
||||||
fireEvent.click(screen.getByLabelText('返信'))
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '検索' }))
|
|
||||||
|
|
||||||
expect(onSubmit).toHaveBeenCalledWith({
|
|
||||||
...searchValues,
|
|
||||||
q: 'TypeScript',
|
|
||||||
from: '@tan_stack',
|
|
||||||
lang: 'ja',
|
|
||||||
content: 'images',
|
|
||||||
excludeReplies: true,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('removes only the selected condition from its active chip', () => {
|
|
||||||
const onSubmit = vi.fn()
|
const onSubmit = vi.fn()
|
||||||
render(
|
render(
|
||||||
<SearchForm
|
<SearchForm
|
||||||
initialValues={{ ...searchValues, q: 'AI', from: 'yuta', lang: 'ja' }}
|
initialQuery=""
|
||||||
|
initialProduct="Latest"
|
||||||
|
initialFollowing={false}
|
||||||
onSubmit={onSubmit}
|
onSubmit={onSubmit}
|
||||||
/>,
|
/>,
|
||||||
)
|
)
|
||||||
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '投稿者 yuta を解除' }))
|
fireEvent.change(screen.getByLabelText('検索語'), {
|
||||||
|
target: { value: 'AI lang:ja' },
|
||||||
|
})
|
||||||
|
fireEvent.click(screen.getByLabelText('人気順'))
|
||||||
|
fireEvent.click(screen.getByLabelText('フォロー中のみ'))
|
||||||
fireEvent.click(screen.getByRole('button', { name: '検索' }))
|
fireEvent.click(screen.getByRole('button', { name: '検索' }))
|
||||||
|
|
||||||
expect(onSubmit).toHaveBeenCalledWith({
|
expect(onSubmit).toHaveBeenCalledWith({
|
||||||
...searchValues,
|
q: 'AI lang:ja',
|
||||||
q: 'AI',
|
product: 'Top',
|
||||||
lang: 'ja',
|
following: true,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import {
|
|||||||
} from '../page'
|
} from '../page'
|
||||||
import type { Post } from '../types'
|
import type { Post } from '../types'
|
||||||
import { type FeedRequest, PostLoadError, usePostFeed } from '../use-post-feed'
|
import { type FeedRequest, PostLoadError, usePostFeed } from '../use-post-feed'
|
||||||
import { useFeedTools } from '../webmcp-tools'
|
|
||||||
import { PostCard } from './post-card'
|
import { PostCard } from './post-card'
|
||||||
|
|
||||||
function FocalPost({ post }: { post: Post }) {
|
function FocalPost({ post }: { post: Post }) {
|
||||||
@@ -22,7 +21,6 @@ function FocalPost({ post }: { post: Post }) {
|
|||||||
|
|
||||||
export function PostFeed({ request }: { request: FeedRequest | undefined }) {
|
export function PostFeed({ request }: { request: FeedRequest | undefined }) {
|
||||||
const query = usePostFeed(request)
|
const query = usePostFeed(request)
|
||||||
useFeedTools(request, query)
|
|
||||||
const sentinel = useRef<HTMLDivElement>(null)
|
const sentinel = useRef<HTMLDivElement>(null)
|
||||||
const pages = query.data?.pages ?? []
|
const pages = query.data?.pages ?? []
|
||||||
const focalPost =
|
const focalPost =
|
||||||
@@ -46,7 +44,7 @@ export function PostFeed({ request }: { request: FeedRequest | undefined }) {
|
|||||||
([entry]) => {
|
([entry]) => {
|
||||||
if (entry?.isIntersecting && !requested) {
|
if (entry?.isIntersecting && !requested) {
|
||||||
requested = true
|
requested = true
|
||||||
void query.fetchNextPage({ cancelRefetch: false })
|
void query.fetchNextPage()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{ rootMargin: '600px 0px' },
|
{ rootMargin: '600px 0px' },
|
||||||
|
|||||||
@@ -1,57 +1,37 @@
|
|||||||
import type { SearchProduct } from '@yuta/bird'
|
import type { SearchProduct } from '@yuta/bird'
|
||||||
import { type FormEvent, useState } from 'react'
|
import { type FormEvent, useState } from 'react'
|
||||||
import { type AdvancedSearchQuery, buildFilteredSearchQuery } from '../inputs'
|
import { buildSearchQuery } from '../inputs'
|
||||||
|
|
||||||
export type SearchValues = AdvancedSearchQuery & {
|
type SearchValues = {
|
||||||
|
q: string
|
||||||
product: SearchProduct
|
product: SearchProduct
|
||||||
following: boolean
|
following: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
initialValues: SearchValues
|
initialQuery: string
|
||||||
|
initialProduct: SearchProduct
|
||||||
|
initialFollowing: boolean
|
||||||
onSubmit: (values: SearchValues) => void
|
onSubmit: (values: SearchValues) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
type FilterName = 'author' | 'period' | 'language' | 'content' | 'exclude'
|
export function SearchForm({
|
||||||
|
initialQuery,
|
||||||
const languageLabels = { all: 'すべて', ja: '日本語', en: '英語' } as const
|
initialProduct,
|
||||||
const contentLabels = {
|
initialFollowing,
|
||||||
all: 'すべて',
|
onSubmit,
|
||||||
images: '画像',
|
}: Props) {
|
||||||
videos: '動画',
|
const [q, setQuery] = useState(initialQuery)
|
||||||
links: 'リンク',
|
const [product, setProduct] = useState(initialProduct)
|
||||||
} as const
|
const [following, setFollowing] = useState(initialFollowing)
|
||||||
|
|
||||||
function localDate(daysAgo: number): string {
|
|
||||||
const date = new Date()
|
|
||||||
date.setDate(date.getDate() - daysAgo)
|
|
||||||
const year = date.getFullYear()
|
|
||||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
|
||||||
const day = String(date.getDate()).padStart(2, '0')
|
|
||||||
return `${year}-${month}-${day}`
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SearchForm({ initialValues, onSubmit }: Props) {
|
|
||||||
const [values, setValues] = useState(initialValues)
|
|
||||||
const [openFilter, setOpenFilter] = useState<FilterName>()
|
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
const update = <Key extends keyof SearchValues>(
|
|
||||||
key: Key,
|
|
||||||
value: SearchValues[Key],
|
|
||||||
) => setValues((current) => ({ ...current, [key]: value }))
|
|
||||||
|
|
||||||
const submit = (event: FormEvent) => {
|
const submit = (event: FormEvent) => {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
const normalized = {
|
|
||||||
...values,
|
|
||||||
q: values.q.trim(),
|
|
||||||
from: values.from.trim(),
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
buildFilteredSearchQuery(normalized, normalized.following)
|
const query = buildSearchQuery(q, false)
|
||||||
setError('')
|
setError('')
|
||||||
onSubmit(normalized)
|
onSubmit({ q: query, product, following })
|
||||||
} catch (cause) {
|
} catch (cause) {
|
||||||
setError(
|
setError(
|
||||||
cause instanceof Error ? cause.message : '入力内容を確認してください。',
|
cause instanceof Error ? cause.message : '入力内容を確認してください。',
|
||||||
@@ -59,337 +39,33 @@ export function SearchForm({ initialValues, onSubmit }: Props) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const toggleFilter = (filter: FilterName) => {
|
|
||||||
setOpenFilter((current) => (current === filter ? undefined : filter))
|
|
||||||
}
|
|
||||||
|
|
||||||
const setRecentPeriod = (days: number) => {
|
|
||||||
setValues((current) => ({
|
|
||||||
...current,
|
|
||||||
since: localDate(days - 1),
|
|
||||||
until: '',
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
let preview = '検索語または投稿者を入力すると表示されます。'
|
|
||||||
try {
|
|
||||||
preview = buildFilteredSearchQuery(values, values.following)
|
|
||||||
} catch {
|
|
||||||
// The submit error gives the actionable message; the preview stays quiet.
|
|
||||||
}
|
|
||||||
|
|
||||||
const filterButtons: Array<{
|
|
||||||
name: FilterName
|
|
||||||
label: string
|
|
||||||
active: boolean
|
|
||||||
}> = [
|
|
||||||
{ name: 'author', label: '投稿者', active: Boolean(values.from) },
|
|
||||||
{
|
|
||||||
name: 'period',
|
|
||||||
label: '期間',
|
|
||||||
active: Boolean(values.since || values.until),
|
|
||||||
},
|
|
||||||
{ name: 'language', label: '言語', active: values.lang !== 'all' },
|
|
||||||
{
|
|
||||||
name: 'content',
|
|
||||||
label: '投稿の種類',
|
|
||||||
active: values.content !== 'all',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'exclude',
|
|
||||||
label: '除外',
|
|
||||||
active: values.excludeReplies || values.excludeReposts,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form className="intent-form search-form" onSubmit={submit}>
|
<form className="intent-form" onSubmit={submit}>
|
||||||
<div className="field search-query">
|
<label className="field">
|
||||||
<label htmlFor="search-query">検索語</label>
|
<span>検索語</span>
|
||||||
<input
|
<input
|
||||||
aria-describedby="search-query-help"
|
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
id="search-query"
|
aria-describedby={error ? 'query-error' : undefined}
|
||||||
|
aria-invalid={Boolean(error)}
|
||||||
name="q"
|
name="q"
|
||||||
value={values.q}
|
value={q}
|
||||||
onChange={(event) => update('q', event.currentTarget.value)}
|
onChange={(event) => setQuery(event.currentTarget.value)}
|
||||||
placeholder="キーワードや高度な検索式"
|
placeholder="検索語や高度な検索演算子"
|
||||||
/>
|
/>
|
||||||
<span className="field-help" id="search-query-help">
|
{error ? (
|
||||||
演算子を直接入力することもできます。
|
<span className="field-error" id="query-error" role="alert">
|
||||||
</span>
|
{error}
|
||||||
</div>
|
</span>
|
||||||
|
|
||||||
<fieldset className="search-filter-buttons">
|
|
||||||
<legend>条件を追加</legend>
|
|
||||||
{filterButtons.map((filter) => (
|
|
||||||
<button
|
|
||||||
aria-controls={`search-filter-${filter.name}`}
|
|
||||||
aria-expanded={openFilter === filter.name}
|
|
||||||
className="filter-button"
|
|
||||||
data-active={filter.active || undefined}
|
|
||||||
key={filter.name}
|
|
||||||
onClick={() => toggleFilter(filter.name)}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
{filter.label}
|
|
||||||
{filter.active ? <span aria-hidden="true">●</span> : null}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
{openFilter ? (
|
|
||||||
<fieldset
|
|
||||||
className="search-filter-panel"
|
|
||||||
id={`search-filter-${openFilter}`}
|
|
||||||
>
|
|
||||||
<legend>
|
|
||||||
{filterButtons.find((item) => item.name === openFilter)?.label}
|
|
||||||
の条件
|
|
||||||
</legend>
|
|
||||||
{openFilter === 'author' ? (
|
|
||||||
<div className="field compact-field">
|
|
||||||
<label htmlFor="search-author">投稿者</label>
|
|
||||||
<input
|
|
||||||
aria-describedby="search-author-help"
|
|
||||||
autoComplete="off"
|
|
||||||
id="search-author"
|
|
||||||
name="from"
|
|
||||||
onChange={(event) => update('from', event.currentTarget.value)}
|
|
||||||
placeholder="@handle"
|
|
||||||
value={values.from}
|
|
||||||
/>
|
|
||||||
<span className="field-help" id="search-author-help">
|
|
||||||
@は省略できます。
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{openFilter === 'period' ? (
|
|
||||||
<>
|
|
||||||
<fieldset className="segmented search-filter-options">
|
|
||||||
<legend>すぐ選ぶ</legend>
|
|
||||||
<button onClick={() => setRecentPeriod(1)} type="button">
|
|
||||||
今日
|
|
||||||
</button>
|
|
||||||
<button onClick={() => setRecentPeriod(7)} type="button">
|
|
||||||
過去7日
|
|
||||||
</button>
|
|
||||||
<button onClick={() => setRecentPeriod(30)} type="button">
|
|
||||||
過去30日
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() =>
|
|
||||||
setValues((current) => ({
|
|
||||||
...current,
|
|
||||||
since: '',
|
|
||||||
until: '',
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
すべて
|
|
||||||
</button>
|
|
||||||
</fieldset>
|
|
||||||
<div className="date-fields">
|
|
||||||
<div className="field compact-field">
|
|
||||||
<label htmlFor="search-since">開始日</label>
|
|
||||||
<input
|
|
||||||
id="search-since"
|
|
||||||
name="since"
|
|
||||||
onChange={(event) =>
|
|
||||||
update('since', event.currentTarget.value)
|
|
||||||
}
|
|
||||||
type="date"
|
|
||||||
value={values.since}
|
|
||||||
/>
|
|
||||||
<span className="field-help" />
|
|
||||||
</div>
|
|
||||||
<div className="field compact-field">
|
|
||||||
<label htmlFor="search-until">
|
|
||||||
終了日(この日は含まない)
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="search-until"
|
|
||||||
name="until"
|
|
||||||
onChange={(event) =>
|
|
||||||
update('until', event.currentTarget.value)
|
|
||||||
}
|
|
||||||
type="date"
|
|
||||||
value={values.until}
|
|
||||||
/>
|
|
||||||
<span className="field-help" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{openFilter === 'language' ? (
|
|
||||||
<fieldset className="segmented search-filter-options">
|
|
||||||
<legend>言語</legend>
|
|
||||||
{(
|
|
||||||
Object.keys(languageLabels) as Array<
|
|
||||||
keyof typeof languageLabels
|
|
||||||
>
|
|
||||||
).map((value) => (
|
|
||||||
<label key={value}>
|
|
||||||
<input
|
|
||||||
checked={values.lang === value}
|
|
||||||
name="lang"
|
|
||||||
onChange={() => update('lang', value)}
|
|
||||||
type="radio"
|
|
||||||
value={value}
|
|
||||||
/>
|
|
||||||
{languageLabels[value]}
|
|
||||||
</label>
|
|
||||||
))}
|
|
||||||
</fieldset>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{openFilter === 'content' ? (
|
|
||||||
<fieldset className="segmented search-filter-options">
|
|
||||||
<legend>投稿の種類</legend>
|
|
||||||
{(
|
|
||||||
Object.keys(contentLabels) as Array<keyof typeof contentLabels>
|
|
||||||
).map((value) => (
|
|
||||||
<label key={value}>
|
|
||||||
<input
|
|
||||||
checked={values.content === value}
|
|
||||||
name="content"
|
|
||||||
onChange={() => update('content', value)}
|
|
||||||
type="radio"
|
|
||||||
value={value}
|
|
||||||
/>
|
|
||||||
{contentLabels[value]}
|
|
||||||
</label>
|
|
||||||
))}
|
|
||||||
</fieldset>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{openFilter === 'exclude' ? (
|
|
||||||
<fieldset className="search-exclusions">
|
|
||||||
<legend>検索結果から除外</legend>
|
|
||||||
<label className="check">
|
|
||||||
<input
|
|
||||||
checked={values.excludeReplies}
|
|
||||||
onChange={(event) =>
|
|
||||||
update('excludeReplies', event.currentTarget.checked)
|
|
||||||
}
|
|
||||||
type="checkbox"
|
|
||||||
/>
|
|
||||||
返信
|
|
||||||
</label>
|
|
||||||
<label className="check">
|
|
||||||
<input
|
|
||||||
checked={values.excludeReposts}
|
|
||||||
onChange={(event) =>
|
|
||||||
update('excludeReposts', event.currentTarget.checked)
|
|
||||||
}
|
|
||||||
type="checkbox"
|
|
||||||
/>
|
|
||||||
リポスト
|
|
||||||
</label>
|
|
||||||
</fieldset>
|
|
||||||
) : null}
|
|
||||||
</fieldset>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<ul aria-label="選択中の条件" className="active-filters">
|
|
||||||
{values.from ? (
|
|
||||||
<li>
|
|
||||||
<button
|
|
||||||
aria-label={`投稿者 ${values.from} を解除`}
|
|
||||||
onClick={() => update('from', '')}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
{values.from.startsWith('@') ? values.from : `@${values.from}`}{' '}
|
|
||||||
<span aria-hidden="true">×</span>
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
) : null}
|
) : null}
|
||||||
{values.since || values.until ? (
|
</label>
|
||||||
<li>
|
<fieldset className="segmented">
|
||||||
<button
|
|
||||||
aria-label="期間を解除"
|
|
||||||
onClick={() =>
|
|
||||||
setValues((current) => ({
|
|
||||||
...current,
|
|
||||||
since: '',
|
|
||||||
until: '',
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
{values.since || '指定なし'} → {values.until || '現在'}{' '}
|
|
||||||
<span aria-hidden="true">×</span>
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
) : null}
|
|
||||||
{values.lang !== 'all' ? (
|
|
||||||
<li>
|
|
||||||
<button
|
|
||||||
aria-label={`言語 ${languageLabels[values.lang]} を解除`}
|
|
||||||
onClick={() => update('lang', 'all')}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
{languageLabels[values.lang]} <span aria-hidden="true">×</span>
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
) : null}
|
|
||||||
{values.content !== 'all' ? (
|
|
||||||
<li>
|
|
||||||
<button
|
|
||||||
aria-label={`投稿の種類 ${contentLabels[values.content]} を解除`}
|
|
||||||
onClick={() => update('content', 'all')}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
{contentLabels[values.content]} <span aria-hidden="true">×</span>
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
) : null}
|
|
||||||
{values.excludeReplies ? (
|
|
||||||
<li>
|
|
||||||
<button
|
|
||||||
aria-label="返信の除外を解除"
|
|
||||||
onClick={() => update('excludeReplies', false)}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
返信を除外 <span aria-hidden="true">×</span>
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
) : null}
|
|
||||||
{values.excludeReposts ? (
|
|
||||||
<li>
|
|
||||||
<button
|
|
||||||
aria-label="リポストの除外を解除"
|
|
||||||
onClick={() => update('excludeReposts', false)}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
リポストを除外 <span aria-hidden="true">×</span>
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
) : null}
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<details className="search-query-preview">
|
|
||||||
<summary>検索式を確認</summary>
|
|
||||||
<code>{preview}</code>
|
|
||||||
</details>
|
|
||||||
|
|
||||||
{error ? (
|
|
||||||
<p className="field-error search-error" id="query-error" role="alert">
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<fieldset className="segmented search-ranking">
|
|
||||||
<legend>並び順</legend>
|
<legend>並び順</legend>
|
||||||
{(['Top', 'Latest'] as const).map((value) => (
|
{(['Top', 'Latest'] as const).map((value) => (
|
||||||
<label key={value}>
|
<label key={value}>
|
||||||
<input
|
<input
|
||||||
checked={values.product === value}
|
checked={product === value}
|
||||||
name="product"
|
name="product"
|
||||||
onChange={() => update('product', value)}
|
onChange={() => setProduct(value)}
|
||||||
type="radio"
|
type="radio"
|
||||||
value={value}
|
value={value}
|
||||||
/>
|
/>
|
||||||
@@ -397,17 +73,15 @@ export function SearchForm({ initialValues, onSubmit }: Props) {
|
|||||||
</label>
|
</label>
|
||||||
))}
|
))}
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<label className="check search-following">
|
<label className="check">
|
||||||
<input
|
<input
|
||||||
checked={values.following}
|
checked={following}
|
||||||
onChange={(event) => update('following', event.currentTarget.checked)}
|
onChange={(event) => setFollowing(event.currentTarget.checked)}
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
/>
|
/>
|
||||||
フォロー中のみ
|
フォロー中のみ
|
||||||
</label>
|
</label>
|
||||||
<button className="search-submit" type="submit">
|
<button type="submit">検索</button>
|
||||||
検索
|
|
||||||
</button>
|
|
||||||
</form>
|
</form>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,9 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import {
|
import {
|
||||||
buildAdvancedSearchQuery,
|
|
||||||
buildFilteredSearchQuery,
|
|
||||||
buildSearchQuery,
|
buildSearchQuery,
|
||||||
normalizeListTarget,
|
normalizeListTarget,
|
||||||
normalizeTweetId,
|
normalizeTweetId,
|
||||||
normalizeUserTarget,
|
normalizeUserTarget,
|
||||||
postSearchRouteSchema,
|
|
||||||
threadPageInputSchema,
|
threadPageInputSchema,
|
||||||
} from './inputs'
|
} from './inputs'
|
||||||
|
|
||||||
@@ -111,134 +108,3 @@ describe('buildSearchQuery', () => {
|
|||||||
expect(() => buildSearchQuery(' ', false)).toThrow()
|
expect(() => buildSearchQuery(' ', false)).toThrow()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('buildAdvancedSearchQuery', () => {
|
|
||||||
it('builds a query from button-friendly filters', () => {
|
|
||||||
expect(
|
|
||||||
buildAdvancedSearchQuery({
|
|
||||||
q: 'TypeScript',
|
|
||||||
from: '@tan_stack',
|
|
||||||
since: '2026-08-04',
|
|
||||||
until: '2026-08-11',
|
|
||||||
lang: 'ja',
|
|
||||||
content: 'images',
|
|
||||||
excludeReplies: true,
|
|
||||||
excludeReposts: true,
|
|
||||||
}),
|
|
||||||
).toBe(
|
|
||||||
'TypeScript from:tan_stack since:2026-08-04 until:2026-08-11 lang:ja filter:images -filter:replies -filter:retweets',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('allows an author search without keywords', () => {
|
|
||||||
expect(
|
|
||||||
buildAdvancedSearchQuery({
|
|
||||||
q: '',
|
|
||||||
from: 'tan_stack',
|
|
||||||
since: '',
|
|
||||||
until: '',
|
|
||||||
lang: 'all',
|
|
||||||
content: 'all',
|
|
||||||
excludeReplies: false,
|
|
||||||
excludeReposts: false,
|
|
||||||
}),
|
|
||||||
).toBe('from:tan_stack')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('rejects filters that have no keyword or author', () => {
|
|
||||||
expect(() =>
|
|
||||||
buildAdvancedSearchQuery({
|
|
||||||
q: '',
|
|
||||||
from: '',
|
|
||||||
since: '2026-08-04',
|
|
||||||
until: '',
|
|
||||||
lang: 'ja',
|
|
||||||
content: 'all',
|
|
||||||
excludeReplies: false,
|
|
||||||
excludeReposts: false,
|
|
||||||
}),
|
|
||||||
).toThrow('検索語または投稿者を入力してください。')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('rejects an invalid author and reversed dates', () => {
|
|
||||||
const base = {
|
|
||||||
q: 'TypeScript',
|
|
||||||
from: '',
|
|
||||||
since: '',
|
|
||||||
until: '',
|
|
||||||
lang: 'all' as const,
|
|
||||||
content: 'all' as const,
|
|
||||||
excludeReplies: false,
|
|
||||||
excludeReposts: false,
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(() =>
|
|
||||||
buildAdvancedSearchQuery({ ...base, from: 'not-valid!' }),
|
|
||||||
).toThrow('投稿者のハンドルを確認してください。')
|
|
||||||
expect(() =>
|
|
||||||
buildAdvancedSearchQuery({
|
|
||||||
...base,
|
|
||||||
since: '2026-08-11',
|
|
||||||
until: '2026-08-10',
|
|
||||||
}),
|
|
||||||
).toThrow('終了日は開始日より後の日付を選んでください。')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('rejects nonexistent dates and a compiled query over 512 characters', () => {
|
|
||||||
const base = {
|
|
||||||
q: 'TypeScript',
|
|
||||||
from: '',
|
|
||||||
since: '',
|
|
||||||
until: '',
|
|
||||||
lang: 'all' as const,
|
|
||||||
content: 'all' as const,
|
|
||||||
excludeReplies: false,
|
|
||||||
excludeReposts: false,
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(() =>
|
|
||||||
buildAdvancedSearchQuery({ ...base, since: '2026-02-30' }),
|
|
||||||
).toThrow('開始日を確認してください。')
|
|
||||||
expect(() =>
|
|
||||||
buildAdvancedSearchQuery({ ...base, q: 'a'.repeat(510), lang: 'ja' }),
|
|
||||||
).toThrow('検索語は 512 文字以内で入力してください。')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('buildFilteredSearchQuery', () => {
|
|
||||||
it('includes the follows filter in the final query and enforces its length', () => {
|
|
||||||
const input = {
|
|
||||||
q: 'TypeScript',
|
|
||||||
from: '',
|
|
||||||
since: '',
|
|
||||||
until: '',
|
|
||||||
lang: 'ja' as const,
|
|
||||||
content: 'all' as const,
|
|
||||||
excludeReplies: false,
|
|
||||||
excludeReposts: false,
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(buildFilteredSearchQuery(input, true)).toBe(
|
|
||||||
'TypeScript lang:ja filter:follows',
|
|
||||||
)
|
|
||||||
expect(() =>
|
|
||||||
buildFilteredSearchQuery({ ...input, q: 'a'.repeat(498) }, true),
|
|
||||||
).toThrow('検索語は 512 文字以内で入力してください。')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('postSearchRouteSchema', () => {
|
|
||||||
it('keeps omitted filter parameters optional', () => {
|
|
||||||
expect(
|
|
||||||
postSearchRouteSchema.parse({
|
|
||||||
q: 'AI',
|
|
||||||
product: 'Latest',
|
|
||||||
following: false,
|
|
||||||
}),
|
|
||||||
).toEqual({
|
|
||||||
q: 'AI',
|
|
||||||
product: 'Latest',
|
|
||||||
following: false,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
|
||||||
const HANDLE = /^[A-Za-z0-9_]{1,15}$/
|
const HANDLE = /^[A-Za-z0-9_]{1,15}$/
|
||||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/
|
|
||||||
const FOLLOWS = /(?:^|\s)filter:follows(?:\s|$)/i
|
const FOLLOWS = /(?:^|\s)filter:follows(?:\s|$)/i
|
||||||
const TWEET_ID = /^\d{1,32}$/
|
const TWEET_ID = /^\d{1,32}$/
|
||||||
const LIST_ID = /^\d{1,32}$/
|
const LIST_ID = /^\d{1,32}$/
|
||||||
@@ -12,23 +11,6 @@ const tweetIdSchema = z
|
|||||||
|
|
||||||
export class InputError extends Error {}
|
export class InputError extends Error {}
|
||||||
|
|
||||||
const searchLanguageSchema = z.enum(['all', 'ja', 'en'])
|
|
||||||
const searchContentSchema = z.enum(['all', 'images', 'videos', 'links'])
|
|
||||||
|
|
||||||
type SearchLanguage = z.infer<typeof searchLanguageSchema>
|
|
||||||
type SearchContent = z.infer<typeof searchContentSchema>
|
|
||||||
|
|
||||||
export type AdvancedSearchQuery = {
|
|
||||||
q: string
|
|
||||||
from: string
|
|
||||||
since: string
|
|
||||||
until: string
|
|
||||||
lang: SearchLanguage
|
|
||||||
content: SearchContent
|
|
||||||
excludeReplies: boolean
|
|
||||||
excludeReposts: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export const threadPageInputSchema = z.union([
|
export const threadPageInputSchema = z.union([
|
||||||
z.object({
|
z.object({
|
||||||
tweetId: tweetIdSchema,
|
tweetId: tweetIdSchema,
|
||||||
@@ -63,87 +45,10 @@ export const searchPageInputSchema = z.object({
|
|||||||
|
|
||||||
export const postSearchRouteSchema = z.object({
|
export const postSearchRouteSchema = z.object({
|
||||||
q: z.string().catch(''),
|
q: z.string().catch(''),
|
||||||
from: z
|
|
||||||
.string()
|
|
||||||
.refine((value) => !value || HANDLE.test(value.replace(/^@/, '')))
|
|
||||||
.optional()
|
|
||||||
.catch(undefined),
|
|
||||||
since: z
|
|
||||||
.string()
|
|
||||||
.refine((value) => !value || isValidDate(value))
|
|
||||||
.optional()
|
|
||||||
.catch(undefined),
|
|
||||||
until: z
|
|
||||||
.string()
|
|
||||||
.refine((value) => !value || isValidDate(value))
|
|
||||||
.optional()
|
|
||||||
.catch(undefined),
|
|
||||||
lang: searchLanguageSchema.optional().catch(undefined),
|
|
||||||
content: searchContentSchema.optional().catch(undefined),
|
|
||||||
excludeReplies: z.boolean().optional().catch(undefined),
|
|
||||||
excludeReposts: z.boolean().optional().catch(undefined),
|
|
||||||
product: z.enum(['Top', 'Latest']).catch('Latest'),
|
product: z.enum(['Top', 'Latest']).catch('Latest'),
|
||||||
following: z.boolean().catch(false),
|
following: z.boolean().catch(false),
|
||||||
})
|
})
|
||||||
|
|
||||||
function isValidDate(value: string): boolean {
|
|
||||||
if (!ISO_DATE.test(value)) return false
|
|
||||||
const [year, month, day] = value.split('-').map(Number)
|
|
||||||
const date = new Date(Date.UTC(year ?? 0, (month ?? 0) - 1, day))
|
|
||||||
return (
|
|
||||||
date.getUTCFullYear() === year &&
|
|
||||||
date.getUTCMonth() + 1 === month &&
|
|
||||||
date.getUTCDate() === day
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function requireDate(value: string, label: string): string {
|
|
||||||
if (!isValidDate(value)) {
|
|
||||||
throw new InputError(`${label}を確認してください。`)
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeSearchAuthor(raw: string): string {
|
|
||||||
const value = raw.trim().replace(/^@/, '')
|
|
||||||
if (!HANDLE.test(value)) {
|
|
||||||
throw new InputError('投稿者のハンドルを確認してください。')
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildAdvancedSearchQuery(input: AdvancedSearchQuery): string {
|
|
||||||
const query = input.q.trim()
|
|
||||||
const author = input.from.trim()
|
|
||||||
if (!query && !author) {
|
|
||||||
throw new InputError('検索語または投稿者を入力してください。')
|
|
||||||
}
|
|
||||||
|
|
||||||
const parts = [query]
|
|
||||||
if (author) parts.push(`from:${normalizeSearchAuthor(author)}`)
|
|
||||||
|
|
||||||
const since = input.since ? requireDate(input.since, '開始日') : ''
|
|
||||||
const until = input.until ? requireDate(input.until, '終了日') : ''
|
|
||||||
if (since && until && since >= until) {
|
|
||||||
throw new InputError('終了日は開始日より後の日付を選んでください。')
|
|
||||||
}
|
|
||||||
if (since) parts.push(`since:${since}`)
|
|
||||||
if (until) parts.push(`until:${until}`)
|
|
||||||
if (input.lang !== 'all') parts.push(`lang:${input.lang}`)
|
|
||||||
if (input.content !== 'all') parts.push(`filter:${input.content}`)
|
|
||||||
if (input.excludeReplies) parts.push('-filter:replies')
|
|
||||||
if (input.excludeReposts) parts.push('-filter:retweets')
|
|
||||||
|
|
||||||
return buildSearchQuery(parts.filter(Boolean).join(' '), false)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildFilteredSearchQuery(
|
|
||||||
input: AdvancedSearchQuery,
|
|
||||||
following: boolean,
|
|
||||||
): string {
|
|
||||||
return buildSearchQuery(buildAdvancedSearchQuery(input), following)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeTweetId(raw: string): string {
|
export function normalizeTweetId(raw: string): string {
|
||||||
const value = raw.trim()
|
const value = raw.trim()
|
||||||
if (!TWEET_ID.test(value)) {
|
if (!TWEET_ID.test(value)) {
|
||||||
@@ -224,10 +129,8 @@ export function buildSearchQuery(raw: string, following: boolean): string {
|
|||||||
if (!query) {
|
if (!query) {
|
||||||
throw new InputError('検索語を入力してください。')
|
throw new InputError('検索語を入力してください。')
|
||||||
}
|
}
|
||||||
const finalQuery =
|
if (query.length > 512) {
|
||||||
following && !FOLLOWS.test(query) ? `${query} filter:follows` : query
|
|
||||||
if (finalQuery.length > 512) {
|
|
||||||
throw new InputError('検索語は 512 文字以内で入力してください。')
|
throw new InputError('検索語は 512 文字以内で入力してください。')
|
||||||
}
|
}
|
||||||
return finalQuery
|
return following && !FOLLOWS.test(query) ? `${query} filter:follows` : query
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,11 +28,8 @@ const configFailure = (diagnostic: unknown): LoadFailure => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function reader() {
|
async function reader() {
|
||||||
const [{ getBirdReader }, { getSelectedProfileName }] = await Promise.all([
|
const { getBirdReader } = await import('./bird-client.server')
|
||||||
import('./bird-client.server'),
|
return getBirdReader()
|
||||||
import('../profiles/profile-service.server'),
|
|
||||||
])
|
|
||||||
return getBirdReader(getSelectedProfileName())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const loadUserPosts = createServerFn({ method: 'GET' })
|
export const loadUserPosts = createServerFn({ method: 'GET' })
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { createElement, type ReactNode } from 'react'
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
import {
|
import {
|
||||||
createPostFeedOptions,
|
createPostFeedOptions,
|
||||||
getPostFeedData,
|
|
||||||
PostLoadError,
|
PostLoadError,
|
||||||
usePostFeed,
|
usePostFeed,
|
||||||
} from './use-post-feed'
|
} from './use-post-feed'
|
||||||
@@ -230,97 +229,6 @@ describe('createPostFeedOptions', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('getPostFeedData', () => {
|
|
||||||
it('reuses the visible feed without fetching a second copy', async () => {
|
|
||||||
const loadUser = vi
|
|
||||||
.fn()
|
|
||||||
.mockResolvedValue({ ok: true, page: { tweets: [] } })
|
|
||||||
const options = createPostFeedOptions(
|
|
||||||
{ kind: 'user', target: 'yuta' },
|
|
||||||
loaders({ loadUser }),
|
|
||||||
)
|
|
||||||
const client = new QueryClient()
|
|
||||||
const visible = await client.fetchInfiniteQuery(options)
|
|
||||||
|
|
||||||
expect(await getPostFeedData(client, options)).toEqual(visible)
|
|
||||||
expect(loadUser).toHaveBeenCalledOnce()
|
|
||||||
client.clear()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('waits for the active profile refresh instead of returning old cached posts', async () => {
|
|
||||||
let release = () => {}
|
|
||||||
const gate = new Promise<void>((resolve) => {
|
|
||||||
release = resolve
|
|
||||||
})
|
|
||||||
const freshPage = {
|
|
||||||
tweets: [
|
|
||||||
{
|
|
||||||
id: 'new-profile',
|
|
||||||
text: 'fresh',
|
|
||||||
author: { username: 'new', name: 'New' },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
const loadUser = vi.fn(async () => {
|
|
||||||
await gate
|
|
||||||
return { ok: true as const, page: freshPage }
|
|
||||||
})
|
|
||||||
const options = createPostFeedOptions(
|
|
||||||
{ kind: 'user', target: 'yuta' },
|
|
||||||
loaders({ loadUser }),
|
|
||||||
)
|
|
||||||
const client = new QueryClient()
|
|
||||||
client.setQueryData(options.queryKey, {
|
|
||||||
pages: [{ tweets: [] }],
|
|
||||||
pageParams: [undefined],
|
|
||||||
})
|
|
||||||
await client.invalidateQueries({
|
|
||||||
queryKey: options.queryKey,
|
|
||||||
refetchType: 'none',
|
|
||||||
})
|
|
||||||
const refresh = client.fetchInfiniteQuery(options)
|
|
||||||
const resolved = vi.fn()
|
|
||||||
const tool = getPostFeedData(client, options).then(resolved)
|
|
||||||
await Promise.resolve()
|
|
||||||
|
|
||||||
expect(resolved).not.toHaveBeenCalled()
|
|
||||||
release()
|
|
||||||
await Promise.all([refresh, tool])
|
|
||||||
expect(resolved).toHaveBeenCalledWith({
|
|
||||||
pages: [freshPage],
|
|
||||||
pageParams: [undefined],
|
|
||||||
})
|
|
||||||
expect(loadUser).toHaveBeenCalledOnce()
|
|
||||||
client.clear()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('refreshes invalidated cached data before returning it', async () => {
|
|
||||||
const loadUser = vi.fn().mockResolvedValue({
|
|
||||||
ok: true,
|
|
||||||
page: { tweets: [], nextCursor: 'fresh' },
|
|
||||||
})
|
|
||||||
const options = createPostFeedOptions(
|
|
||||||
{ kind: 'user', target: 'yuta' },
|
|
||||||
loaders({ loadUser }),
|
|
||||||
)
|
|
||||||
const client = new QueryClient()
|
|
||||||
client.setQueryData(options.queryKey, {
|
|
||||||
pages: [{ tweets: [] }],
|
|
||||||
pageParams: [undefined],
|
|
||||||
})
|
|
||||||
await client.invalidateQueries({
|
|
||||||
queryKey: options.queryKey,
|
|
||||||
refetchType: 'none',
|
|
||||||
})
|
|
||||||
|
|
||||||
expect((await getPostFeedData(client, options)).pages[0]?.nextCursor).toBe(
|
|
||||||
'fresh',
|
|
||||||
)
|
|
||||||
expect(loadUser).toHaveBeenCalledOnce()
|
|
||||||
client.clear()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('usePostFeed', () => {
|
describe('usePostFeed', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
useServerFn.mockReset()
|
useServerFn.mockReset()
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { type QueryClient, useInfiniteQuery } from '@tanstack/react-query'
|
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||||
import { useServerFn } from '@tanstack/react-start'
|
import { useServerFn } from '@tanstack/react-start'
|
||||||
import type { SearchProduct } from '@yuta/bird'
|
import type { SearchProduct } from '@yuta/bird'
|
||||||
import {
|
import {
|
||||||
@@ -120,41 +120,23 @@ export function createPostFeedOptions(request: FeedRequest, loaders: Loaders) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function usePostFeedOptions() {
|
export function usePostFeed(request: FeedRequest | undefined) {
|
||||||
const loadUser = useServerFn(loadUserPosts)
|
const loadUser = useServerFn(loadUserPosts)
|
||||||
const loadList = useServerFn(loadListPosts)
|
const loadList = useServerFn(loadListPosts)
|
||||||
const search = useServerFn(searchPosts)
|
const search = useServerFn(searchPosts)
|
||||||
const thread = useServerFn(loadThreadPosts)
|
const thread = useServerFn(loadThreadPosts)
|
||||||
return (request: FeedRequest) =>
|
|
||||||
createPostFeedOptions(request, {
|
|
||||||
loadUser,
|
|
||||||
loadList,
|
|
||||||
search,
|
|
||||||
thread,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getPostFeedData(
|
|
||||||
client: QueryClient,
|
|
||||||
options: ReturnType<typeof createPostFeedOptions>,
|
|
||||||
) {
|
|
||||||
const state = client.getQueryState(options.queryKey)
|
|
||||||
// Profile changes invalidate and refresh an existing feed. Wait for that
|
|
||||||
// refresh instead of returning the previous profile's cached posts.
|
|
||||||
return state?.fetchStatus === 'fetching' || state?.isInvalidated
|
|
||||||
? client.fetchInfiniteQuery(options)
|
|
||||||
: client.ensureInfiniteQueryData(options)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function usePostFeed(request: FeedRequest | undefined) {
|
|
||||||
const options = usePostFeedOptions()
|
|
||||||
const disabled = {
|
const disabled = {
|
||||||
kind: 'user',
|
kind: 'user',
|
||||||
target: '',
|
target: '',
|
||||||
} satisfies FeedRequest
|
} satisfies FeedRequest
|
||||||
|
|
||||||
return useInfiniteQuery({
|
return useInfiniteQuery({
|
||||||
...options(request ?? disabled),
|
...createPostFeedOptions(request ?? disabled, {
|
||||||
|
loadUser,
|
||||||
|
loadList,
|
||||||
|
search,
|
||||||
|
thread,
|
||||||
|
}),
|
||||||
enabled: request !== undefined,
|
enabled: request !== undefined,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,241 +0,0 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import type { Post, ThreadPage } from './types'
|
|
||||||
import { type FeedRequest, PostLoadError } from './use-post-feed'
|
|
||||||
import {
|
|
||||||
feedResult,
|
|
||||||
prepareSearch,
|
|
||||||
readToolInput,
|
|
||||||
toolResult,
|
|
||||||
} from './webmcp-contracts'
|
|
||||||
|
|
||||||
const post = (id: string): Post => ({
|
|
||||||
id,
|
|
||||||
text: `Post ${id}`,
|
|
||||||
author: { username: 'reader', name: 'Reader' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const request = { kind: 'user', target: 'reader' } satisfies FeedRequest
|
|
||||||
|
|
||||||
describe('WebMCP search input', () => {
|
|
||||||
it('defaults to chronological search without adding filters', () => {
|
|
||||||
expect(prepareSearch({ q: ' hello ' })).toMatchObject({
|
|
||||||
search: { q: 'hello', product: 'Latest', following: false },
|
|
||||||
request: {
|
|
||||||
kind: 'search',
|
|
||||||
query: 'hello',
|
|
||||||
product: 'Latest',
|
|
||||||
following: false,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('compiles the same author, date, content, and exclusion filters as the UI', () => {
|
|
||||||
expect(
|
|
||||||
prepareSearch({
|
|
||||||
q: 'release',
|
|
||||||
from: '@reader',
|
|
||||||
since: '2026-09-01',
|
|
||||||
until: '2026-09-24',
|
|
||||||
lang: 'ja',
|
|
||||||
content: 'links',
|
|
||||||
excludeReplies: true,
|
|
||||||
excludeReposts: true,
|
|
||||||
product: 'Top',
|
|
||||||
following: true,
|
|
||||||
}).request,
|
|
||||||
).toEqual({
|
|
||||||
kind: 'search',
|
|
||||||
query:
|
|
||||||
'release from:reader since:2026-09-01 until:2026-09-24 lang:ja filter:links -filter:replies -filter:retweets filter:follows',
|
|
||||||
product: 'Top',
|
|
||||||
following: true,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('accepts an author as the deliberate search intent', () => {
|
|
||||||
expect(prepareSearch({ from: 'reader' }).request.query).toBe('from:reader')
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
['an impossible date', { q: 'hello', since: '2026-02-30' }],
|
|
||||||
['an invalid date format', { q: 'hello', until: 'yesterday' }],
|
|
||||||
[
|
|
||||||
'an inverted period',
|
|
||||||
{ q: 'hello', since: '2026-09-24', until: '2026-09-01' },
|
|
||||||
],
|
|
||||||
[
|
|
||||||
'an empty period',
|
|
||||||
{ q: 'hello', since: '2026-09-24', until: '2026-09-24' },
|
|
||||||
],
|
|
||||||
['missing search intent', {}],
|
|
||||||
['whitespace-only intent', { q: ' ', from: ' ' }],
|
|
||||||
['an unrecognized property', { q: 'hello', profile: 'other' }],
|
|
||||||
])('rejects %s', (_description, input) => {
|
|
||||||
expect(() => prepareSearch(input)).toThrow()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('WebMCP read input', () => {
|
|
||||||
it('defaults to the first 20 loaded posts', () => {
|
|
||||||
expect(readToolInput.parse({})).toEqual({ offset: 0, limit: 20 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('accepts the maximum batch size', () => {
|
|
||||||
expect(readToolInput.parse({ offset: 10, limit: 50 })).toEqual({
|
|
||||||
offset: 10,
|
|
||||||
limit: 50,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
{ limit: 0 },
|
|
||||||
{ limit: 51 },
|
|
||||||
{ limit: 1.5 },
|
|
||||||
{ limit: '20' },
|
|
||||||
{ offset: -1 },
|
|
||||||
{ offset: 0.5 },
|
|
||||||
{ cursor: 'upstream-cursor' },
|
|
||||||
])('rejects invalid pagination %j', (input) => {
|
|
||||||
expect(readToolInput.safeParse(input).success).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('WebMCP feed output', () => {
|
|
||||||
it('bounds post text and indicates when text was truncated', () => {
|
|
||||||
const result = feedResult(request, [
|
|
||||||
{
|
|
||||||
tweets: [
|
|
||||||
{ ...post('1'), text: 'a'.repeat(2001) },
|
|
||||||
{ ...post('2'), text: 'b'.repeat(2000) },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
])
|
|
||||||
|
|
||||||
expect(result.posts).toEqual([
|
|
||||||
{
|
|
||||||
id: '1',
|
|
||||||
author: { username: 'reader', name: 'Reader' },
|
|
||||||
text: 'a'.repeat(2000),
|
|
||||||
textTruncated: true,
|
|
||||||
createdAt: undefined,
|
|
||||||
url: 'https://x.com/reader/status/1',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '2',
|
|
||||||
author: { username: 'reader', name: 'Reader' },
|
|
||||||
text: 'b'.repeat(2000),
|
|
||||||
textTruncated: false,
|
|
||||||
createdAt: undefined,
|
|
||||||
url: 'https://x.com/reader/status/2',
|
|
||||||
},
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('deduplicates loaded pages before applying the requested offset and limit', () => {
|
|
||||||
const result = feedResult(
|
|
||||||
request,
|
|
||||||
[
|
|
||||||
{ tweets: [post('1'), post('2')], nextCursor: 'next' },
|
|
||||||
{ tweets: [post('2'), post('3'), post('4')] },
|
|
||||||
],
|
|
||||||
1,
|
|
||||||
2,
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(result.posts.map(({ id }) => id)).toEqual(['2', '3'])
|
|
||||||
expect(result).toMatchObject({
|
|
||||||
loadedCount: 4,
|
|
||||||
offset: 1,
|
|
||||||
nextOffset: 3,
|
|
||||||
hasMore: false,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('includes the focal post once before the deduplicated conversation', () => {
|
|
||||||
const focal = post('2')
|
|
||||||
const pages: ThreadPage[] = [
|
|
||||||
{
|
|
||||||
focalPost: focal,
|
|
||||||
conversationId: '1',
|
|
||||||
tweets: [post('1'), focal],
|
|
||||||
nextCursor: 'next',
|
|
||||||
},
|
|
||||||
{ conversationId: '1', tweets: [focal, post('3'), post('1')] },
|
|
||||||
]
|
|
||||||
|
|
||||||
const result = feedResult({ kind: 'thread', tweetId: '2' }, pages)
|
|
||||||
|
|
||||||
expect(result.posts.map(({ id }) => id)).toEqual(['2', '1', '3'])
|
|
||||||
expect(result.loadedCount).toBe(3)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('reports upstream continuation separately from remaining loaded posts', () => {
|
|
||||||
const result = feedResult(request, [
|
|
||||||
{ tweets: [post('1')], nextCursor: 'more-on-server' },
|
|
||||||
])
|
|
||||||
|
|
||||||
expect(result).toMatchObject({
|
|
||||||
loadedCount: 1,
|
|
||||||
nextOffset: null,
|
|
||||||
hasMore: true,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('returns an empty batch when the offset is beyond the loaded posts', () => {
|
|
||||||
expect(
|
|
||||||
feedResult(request, [{ tweets: [post('1')] }], 10, 20),
|
|
||||||
).toMatchObject({
|
|
||||||
posts: [],
|
|
||||||
loadedCount: 1,
|
|
||||||
offset: 10,
|
|
||||||
nextOffset: null,
|
|
||||||
hasMore: false,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('WebMCP execution result', () => {
|
|
||||||
it.each([
|
|
||||||
true,
|
|
||||||
false,
|
|
||||||
])('preserves a load failure with retryable=%s', async (retryable) => {
|
|
||||||
const detail = {
|
|
||||||
code: 'upstream' as const,
|
|
||||||
message: 'Relay unavailable',
|
|
||||||
retryable,
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await toolResult(() =>
|
|
||||||
Promise.reject(new PostLoadError(detail)),
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(result).toEqual({
|
|
||||||
isError: true,
|
|
||||||
content: [{ type: 'text', text: JSON.stringify(detail) }],
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('returns invalid-input for schema validation failures', async () => {
|
|
||||||
const result = await toolResult(() => readToolInput.parse({ limit: 100 }))
|
|
||||||
|
|
||||||
expect(result).toMatchObject({ isError: true })
|
|
||||||
expect(JSON.parse(result.content[0].text)).toMatchObject({
|
|
||||||
code: 'invalid-input',
|
|
||||||
retryable: false,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps successful empty results distinguishable from failures', async () => {
|
|
||||||
const result = await toolResult(() => feedResult(request, [{ tweets: [] }]))
|
|
||||||
|
|
||||||
expect(result).not.toHaveProperty('isError')
|
|
||||||
expect(JSON.parse(result.content[0].text)).toEqual({
|
|
||||||
request,
|
|
||||||
posts: [],
|
|
||||||
loadedCount: 0,
|
|
||||||
offset: 0,
|
|
||||||
nextOffset: null,
|
|
||||||
hasMore: false,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
import { z } from 'zod'
|
|
||||||
import { buildFilteredSearchQuery, InputError } from './inputs'
|
|
||||||
import {
|
|
||||||
flattenConversationPages,
|
|
||||||
flattenPostPages,
|
|
||||||
focalPostFromPages,
|
|
||||||
} from './page'
|
|
||||||
import type { Post, PostPage, ThreadPage } from './types'
|
|
||||||
import { type FeedRequest, PostLoadError } from './use-post-feed'
|
|
||||||
|
|
||||||
export const searchToolInput = z
|
|
||||||
.object({
|
|
||||||
q: z
|
|
||||||
.string()
|
|
||||||
.trim()
|
|
||||||
.max(512)
|
|
||||||
.default('')
|
|
||||||
.describe(
|
|
||||||
'Search text; raw X search operators are supported. Provide q or from.',
|
|
||||||
),
|
|
||||||
from: z
|
|
||||||
.string()
|
|
||||||
.trim()
|
|
||||||
.max(16)
|
|
||||||
.default('')
|
|
||||||
.describe('Author handle, with or without @.'),
|
|
||||||
since: z
|
|
||||||
.string()
|
|
||||||
.default('')
|
|
||||||
.describe(
|
|
||||||
'Inclusive start date, YYYY-MM-DD, using X search date semantics.',
|
|
||||||
),
|
|
||||||
until: z
|
|
||||||
.string()
|
|
||||||
.default('')
|
|
||||||
.describe('Exclusive end date, YYYY-MM-DD; must be after since.'),
|
|
||||||
lang: z.enum(['all', 'ja', 'en']).default('all'),
|
|
||||||
content: z.enum(['all', 'images', 'videos', 'links']).default('all'),
|
|
||||||
excludeReplies: z.boolean().default(false),
|
|
||||||
excludeReposts: z.boolean().default(false),
|
|
||||||
product: z
|
|
||||||
.enum(['Latest', 'Top'])
|
|
||||||
.default('Latest')
|
|
||||||
.describe('Latest is chronological; Top uses X ranking.'),
|
|
||||||
following: z
|
|
||||||
.boolean()
|
|
||||||
.default(false)
|
|
||||||
.describe('Restrict to accounts followed by the active relay profile.'),
|
|
||||||
})
|
|
||||||
.strict()
|
|
||||||
|
|
||||||
export const readToolInput = z
|
|
||||||
.object({
|
|
||||||
offset: z
|
|
||||||
.number()
|
|
||||||
.int()
|
|
||||||
.min(0)
|
|
||||||
.default(0)
|
|
||||||
.describe('Offset into the currently loaded posts, starting at zero.'),
|
|
||||||
limit: z.number().int().min(1).max(50).default(20),
|
|
||||||
})
|
|
||||||
.strict()
|
|
||||||
|
|
||||||
export const emptyToolInput = z.object({}).strict()
|
|
||||||
|
|
||||||
export function prepareSearch(input: unknown) {
|
|
||||||
const search = searchToolInput.parse(input)
|
|
||||||
const request = {
|
|
||||||
kind: 'search',
|
|
||||||
query: buildFilteredSearchQuery(search, search.following),
|
|
||||||
product: search.product,
|
|
||||||
following: search.following,
|
|
||||||
} satisfies FeedRequest
|
|
||||||
return { search, request }
|
|
||||||
}
|
|
||||||
|
|
||||||
function summarizePost(post: Post) {
|
|
||||||
return {
|
|
||||||
id: post.id,
|
|
||||||
author: { username: post.author.username, name: post.author.name },
|
|
||||||
text: post.text.slice(0, 2000),
|
|
||||||
textTruncated: post.text.length > 2000,
|
|
||||||
createdAt: post.createdAt,
|
|
||||||
url: `https://x.com/${encodeURIComponent(post.author.username)}/status/${encodeURIComponent(post.id)}`,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function loadedPosts(
|
|
||||||
request: FeedRequest,
|
|
||||||
pages: Array<PostPage | ThreadPage>,
|
|
||||||
) {
|
|
||||||
const focal =
|
|
||||||
request.kind === 'thread' ? focalPostFromPages(pages) : undefined
|
|
||||||
return focal
|
|
||||||
? [focal, ...flattenConversationPages(pages, focal.id)]
|
|
||||||
: flattenPostPages(pages)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function feedResult(
|
|
||||||
request: FeedRequest,
|
|
||||||
pages: Array<PostPage | ThreadPage>,
|
|
||||||
offset = 0,
|
|
||||||
limit = 20,
|
|
||||||
) {
|
|
||||||
const posts = loadedPosts(request, pages)
|
|
||||||
const selected = posts.slice(offset, offset + limit)
|
|
||||||
const nextOffset = offset + selected.length
|
|
||||||
return {
|
|
||||||
request,
|
|
||||||
posts: selected.map(summarizePost),
|
|
||||||
loadedCount: posts.length,
|
|
||||||
offset,
|
|
||||||
nextOffset: nextOffset < posts.length ? nextOffset : null,
|
|
||||||
hasMore: Boolean(pages.at(-1)?.nextCursor),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep the tool's failure distinguishable from a successful empty result.
|
|
||||||
export async function toolResult(run: () => unknown | Promise<unknown>) {
|
|
||||||
try {
|
|
||||||
return {
|
|
||||||
content: [
|
|
||||||
{ type: 'text' as const, text: JSON.stringify(await run()) },
|
|
||||||
] as const,
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
const detail =
|
|
||||||
error instanceof PostLoadError
|
|
||||||
? error.detail
|
|
||||||
: {
|
|
||||||
code:
|
|
||||||
error instanceof z.ZodError || error instanceof InputError
|
|
||||||
? 'invalid-input'
|
|
||||||
: 'tool-error',
|
|
||||||
message:
|
|
||||||
error instanceof Error ? error.message : 'Tool execution failed.',
|
|
||||||
retryable: false,
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
isError: true,
|
|
||||||
content: [
|
|
||||||
{ type: 'text' as const, text: JSON.stringify(detail) },
|
|
||||||
] as const,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
import { useQueryClient } from '@tanstack/react-query'
|
|
||||||
import { useRouter } from '@tanstack/react-router'
|
|
||||||
import { useEffect, useRef, useState } from 'react'
|
|
||||||
import { useWebMCP } from 'usewebmcp'
|
|
||||||
import {
|
|
||||||
type FeedRequest,
|
|
||||||
getPostFeedData,
|
|
||||||
PostLoadError,
|
|
||||||
type usePostFeed,
|
|
||||||
usePostFeedOptions,
|
|
||||||
} from './use-post-feed'
|
|
||||||
import {
|
|
||||||
emptyToolInput,
|
|
||||||
feedResult,
|
|
||||||
loadedPosts,
|
|
||||||
prepareSearch,
|
|
||||||
readToolInput,
|
|
||||||
searchToolInput,
|
|
||||||
toolResult,
|
|
||||||
} from './webmcp-contracts'
|
|
||||||
|
|
||||||
function useWebMCPSupported() {
|
|
||||||
const [supported, setSupported] = useState(false)
|
|
||||||
useEffect(() => {
|
|
||||||
setSupported(Boolean(document.modelContext))
|
|
||||||
}, [])
|
|
||||||
return supported
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SearchTool() {
|
|
||||||
const supported = useWebMCPSupported()
|
|
||||||
const router = useRouter()
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const options = usePostFeedOptions()
|
|
||||||
const searching = useRef(false)
|
|
||||||
|
|
||||||
useWebMCP({
|
|
||||||
name: 'search_posts',
|
|
||||||
description:
|
|
||||||
'Search X posts and return the first result slice. Updates the visible search page and its filters. Uses the active relay profile. Returns post text, authors, dates, source URLs and pagination information.',
|
|
||||||
inputSchema: searchToolInput,
|
|
||||||
enabled: supported,
|
|
||||||
annotations: {
|
|
||||||
readOnlyHint: false,
|
|
||||||
untrustedContentHint: true,
|
|
||||||
},
|
|
||||||
execute: (input) =>
|
|
||||||
toolResult(async () => {
|
|
||||||
const { search, request } = prepareSearch(input)
|
|
||||||
if (searching.current)
|
|
||||||
throw new Error('A search is already running. Wait for it to finish.')
|
|
||||||
searching.current = true
|
|
||||||
try {
|
|
||||||
await router.navigate({ to: '/search', search })
|
|
||||||
const href = router.buildLocation({ to: '/search', search }).href
|
|
||||||
if (router.state.location.href !== href)
|
|
||||||
throw new Error(
|
|
||||||
'The page changed. Search again from the current page.',
|
|
||||||
)
|
|
||||||
// Join the UI request (or use its completed data), rather than fetch twice.
|
|
||||||
const result = await getPostFeedData(queryClient, options(request))
|
|
||||||
if (router.state.location.href !== href)
|
|
||||||
throw new Error(
|
|
||||||
'The page changed while searching. Read the current feed or search again.',
|
|
||||||
)
|
|
||||||
return feedResult(request, result.pages)
|
|
||||||
} finally {
|
|
||||||
searching.current = false
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useFeedTools(
|
|
||||||
request: FeedRequest | undefined,
|
|
||||||
query: ReturnType<typeof usePostFeed>,
|
|
||||||
) {
|
|
||||||
const supported = useWebMCPSupported()
|
|
||||||
const generation = useRef(0)
|
|
||||||
const requestKey = JSON.stringify(request)
|
|
||||||
useEffect(() => {
|
|
||||||
// Executions belong to the feed that was visible when they started.
|
|
||||||
void requestKey
|
|
||||||
generation.current += 1
|
|
||||||
return () => {
|
|
||||||
generation.current += 1
|
|
||||||
}
|
|
||||||
}, [requestKey])
|
|
||||||
|
|
||||||
useWebMCP({
|
|
||||||
name: 'get_loaded_posts',
|
|
||||||
description:
|
|
||||||
'Read a slice of posts already loaded in the current timeline, search or conversation without a network request. Includes the selected conversation post. Returns active criteria, loading status, source URLs, nextOffset for remaining loaded posts and hasMore for upstream continuation.',
|
|
||||||
inputSchema: readToolInput,
|
|
||||||
enabled: supported && Boolean(request),
|
|
||||||
annotations: {
|
|
||||||
readOnlyHint: true,
|
|
||||||
untrustedContentHint: true,
|
|
||||||
},
|
|
||||||
execute: (input) =>
|
|
||||||
toolResult(() => {
|
|
||||||
const { offset, limit } = readToolInput.parse(input)
|
|
||||||
if (!request)
|
|
||||||
throw new Error('Open a timeline, search or conversation first.')
|
|
||||||
return {
|
|
||||||
...feedResult(request, query.data?.pages ?? [], offset, limit),
|
|
||||||
status: query.isPending
|
|
||||||
? 'loading'
|
|
||||||
: query.isError
|
|
||||||
? 'error'
|
|
||||||
: 'ready',
|
|
||||||
loading: query.isFetching,
|
|
||||||
error:
|
|
||||||
query.error instanceof PostLoadError ? query.error.detail : null,
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
|
|
||||||
useWebMCP({
|
|
||||||
name: 'load_more_posts',
|
|
||||||
description:
|
|
||||||
'Load one continuation page into the current feed and return only newly appended posts. Joins an in-progress scroll request. Returns nextOffset if additional loaded posts remain outside this response. At the end returns an empty posts array with hasMore false. Can retry a failed continuation.',
|
|
||||||
inputSchema: emptyToolInput,
|
|
||||||
enabled: supported && Boolean(request),
|
|
||||||
annotations: {
|
|
||||||
readOnlyHint: false,
|
|
||||||
untrustedContentHint: true,
|
|
||||||
},
|
|
||||||
execute: (input) =>
|
|
||||||
toolResult(async () => {
|
|
||||||
emptyToolInput.parse(input)
|
|
||||||
if (!request || query.isPending)
|
|
||||||
throw new Error(
|
|
||||||
'Wait for the initial feed to load before requesting more posts.',
|
|
||||||
)
|
|
||||||
if (query.isError && !query.isFetchNextPageError) throw query.error
|
|
||||||
if (query.isFetching && !query.isFetchingNextPage)
|
|
||||||
throw new Error(
|
|
||||||
'The feed is refreshing. Wait before requesting more posts.',
|
|
||||||
)
|
|
||||||
const pages = query.data?.pages ?? []
|
|
||||||
const offset = loadedPosts(request, pages).length
|
|
||||||
if (!query.hasNextPage) return feedResult(request, pages, offset)
|
|
||||||
const started = generation.current
|
|
||||||
const result = await query.fetchNextPage({ cancelRefetch: false })
|
|
||||||
if (generation.current !== started)
|
|
||||||
throw new Error(
|
|
||||||
'The feed changed while loading. Read the current feed before requesting more posts.',
|
|
||||||
)
|
|
||||||
if (result.isError) throw result.error
|
|
||||||
return feedResult(request, result.data?.pages ?? [], offset)
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
import {
|
|
||||||
deleteCookie,
|
|
||||||
getCookie,
|
|
||||||
setCookie,
|
|
||||||
} from '@tanstack/react-start/server'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import type { ProfileSettings } from './types'
|
|
||||||
|
|
||||||
const PROFILE_COOKIE = 'twitter-lite-profile'
|
|
||||||
const profilesSchema = z.object({
|
|
||||||
profiles: z.array(z.string().min(1)),
|
|
||||||
})
|
|
||||||
|
|
||||||
function relayBaseUrl() {
|
|
||||||
const relayBaseUrl = process.env.TWITTER_RELAY_BASE_URL
|
|
||||||
if (!relayBaseUrl) {
|
|
||||||
throw new Error('TWITTER_RELAY_BASE_URL is required')
|
|
||||||
}
|
|
||||||
return relayBaseUrl
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchProfileNames(
|
|
||||||
baseUrl = relayBaseUrl(),
|
|
||||||
request: typeof fetch = fetch,
|
|
||||||
): Promise<string[]> {
|
|
||||||
const response = await request(new URL('/profiles', baseUrl), {
|
|
||||||
signal: AbortSignal.timeout(20_000),
|
|
||||||
})
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Profiles request failed with HTTP ${response.status}`)
|
|
||||||
}
|
|
||||||
return profilesSchema.parse(await response.json()).profiles
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getSelectedProfileName(): string | undefined {
|
|
||||||
return getCookie(PROFILE_COOKIE) || process.env.BIRD_PROFILE_NAME
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadProfileSettings(): Promise<ProfileSettings> {
|
|
||||||
const profiles = await fetchProfileNames()
|
|
||||||
const selectedProfile = getSelectedProfileName()
|
|
||||||
return {
|
|
||||||
profiles,
|
|
||||||
...(selectedProfile && profiles.includes(selectedProfile)
|
|
||||||
? { selectedProfile }
|
|
||||||
: {}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function saveProfileSelection(
|
|
||||||
profileName: string | null,
|
|
||||||
): Promise<void> {
|
|
||||||
if (profileName === null) {
|
|
||||||
deleteCookie(PROFILE_COOKIE, { path: '/' })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const profiles = await fetchProfileNames()
|
|
||||||
if (!profiles.includes(profileName)) {
|
|
||||||
throw new Error(`Unknown relay profile: ${profileName}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
setCookie(PROFILE_COOKIE, profileName, {
|
|
||||||
httpOnly: true,
|
|
||||||
maxAge: 60 * 60 * 24 * 365,
|
|
||||||
path: '/',
|
|
||||||
sameSite: 'lax',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
// @vitest-environment node
|
|
||||||
|
|
||||||
import { describe, expect, it, vi } from 'vitest'
|
|
||||||
import { fetchProfileNames } from './profile-service.server'
|
|
||||||
|
|
||||||
describe('fetchProfileNames', () => {
|
|
||||||
it('loads profile names from the relay endpoint', async () => {
|
|
||||||
const request = vi.fn(async () =>
|
|
||||||
Response.json({ profiles: ['main', 'work'] }),
|
|
||||||
)
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
fetchProfileNames('https://relay.invalid/api', request),
|
|
||||||
).resolves.toEqual(['main', 'work'])
|
|
||||||
expect(request).toHaveBeenCalledWith(
|
|
||||||
new URL('https://relay.invalid/profiles'),
|
|
||||||
expect.objectContaining({ signal: expect.any(AbortSignal) }),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('rejects malformed relay responses', async () => {
|
|
||||||
const request = vi.fn(async () => Response.json({ profiles: [42] }))
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
fetchProfileNames('https://relay.invalid', request),
|
|
||||||
).rejects.toThrow()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('rejects unsuccessful relay responses', async () => {
|
|
||||||
const request = vi.fn(async () => new Response(null, { status: 503 }))
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
fetchProfileNames('https://relay.invalid', request),
|
|
||||||
).rejects.toThrow('Profiles request failed with HTTP 503')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
||||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
|
||||||
import { describe, expect, it, vi } from 'vitest'
|
|
||||||
import { ProfileSwitcher } from './profile-switcher'
|
|
||||||
|
|
||||||
const serverFns = vi.hoisted(() => ({
|
|
||||||
loadProfiles: vi.fn(),
|
|
||||||
selectProfile: vi.fn(),
|
|
||||||
}))
|
|
||||||
|
|
||||||
vi.mock('./server-functions', () => serverFns)
|
|
||||||
vi.mock('@tanstack/react-start', () => ({
|
|
||||||
useServerFn: (serverFn: unknown) => serverFn,
|
|
||||||
}))
|
|
||||||
|
|
||||||
function renderSwitcher() {
|
|
||||||
const queryClient = new QueryClient({
|
|
||||||
defaultOptions: { queries: { retry: false } },
|
|
||||||
})
|
|
||||||
render(
|
|
||||||
<QueryClientProvider client={queryClient}>
|
|
||||||
<ProfileSwitcher />
|
|
||||||
</QueryClientProvider>,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('ProfileSwitcher', () => {
|
|
||||||
it('shows relay profiles and switches the active profile', async () => {
|
|
||||||
serverFns.loadProfiles.mockResolvedValue({
|
|
||||||
profiles: ['main', 'work'],
|
|
||||||
selectedProfile: 'main',
|
|
||||||
})
|
|
||||||
serverFns.selectProfile.mockResolvedValue({ profileName: 'work' })
|
|
||||||
renderSwitcher()
|
|
||||||
|
|
||||||
const select = await screen.findByLabelText('プロファイル')
|
|
||||||
await waitFor(() => expect(select).toHaveValue('main'))
|
|
||||||
|
|
||||||
fireEvent.change(select, { target: { value: 'work' } })
|
|
||||||
|
|
||||||
await waitFor(() =>
|
|
||||||
expect(serverFns.selectProfile).toHaveBeenCalledWith({
|
|
||||||
data: { profileName: 'work' },
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
expect(await screen.findByRole('status')).toHaveTextContent(
|
|
||||||
'切り替えました。',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('reports a relay profiles failure without offering stale choices', async () => {
|
|
||||||
serverFns.loadProfiles.mockRejectedValue(new Error('relay unavailable'))
|
|
||||||
renderSwitcher()
|
|
||||||
|
|
||||||
const select = await screen.findByLabelText('プロファイル')
|
|
||||||
await waitFor(() => expect(select).toBeDisabled())
|
|
||||||
expect(select).toHaveTextContent('取得失敗')
|
|
||||||
expect(select).toHaveAttribute('aria-invalid', 'true')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
||||||
import { useServerFn } from '@tanstack/react-start'
|
|
||||||
import { loadProfiles, selectProfile } from './server-functions'
|
|
||||||
|
|
||||||
export function ProfileSwitcher() {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const load = useServerFn(loadProfiles)
|
|
||||||
const select = useServerFn(selectProfile)
|
|
||||||
const profiles = useQuery({
|
|
||||||
queryKey: ['profiles'],
|
|
||||||
queryFn: () => load(),
|
|
||||||
retry: false,
|
|
||||||
refetchOnWindowFocus: false,
|
|
||||||
refetchOnReconnect: false,
|
|
||||||
})
|
|
||||||
const selection = useMutation({
|
|
||||||
mutationFn: (profileName: string | null) =>
|
|
||||||
select({ data: { profileName } }),
|
|
||||||
onSuccess: () => queryClient.invalidateQueries(),
|
|
||||||
})
|
|
||||||
|
|
||||||
const state = profiles.isError
|
|
||||||
? 'error'
|
|
||||||
: selection.isError
|
|
||||||
? 'error'
|
|
||||||
: selection.isSuccess
|
|
||||||
? 'success'
|
|
||||||
: profiles.isPending || selection.isPending
|
|
||||||
? 'loading'
|
|
||||||
: 'default'
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="profile-switcher" data-state={state}>
|
|
||||||
<label htmlFor="relay-profile">プロファイル</label>
|
|
||||||
<select
|
|
||||||
aria-invalid={state === 'error' ? 'true' : undefined}
|
|
||||||
disabled={profiles.isPending || profiles.isError || selection.isPending}
|
|
||||||
id="relay-profile"
|
|
||||||
onChange={(event) =>
|
|
||||||
selection.mutate(
|
|
||||||
event.target.value.length ? event.target.value : null,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
value={profiles.data?.selectedProfile ?? ''}
|
|
||||||
>
|
|
||||||
<option value="">
|
|
||||||
{profiles.isPending
|
|
||||||
? '読み込み中'
|
|
||||||
: profiles.isError
|
|
||||||
? '取得失敗'
|
|
||||||
: '自動'}
|
|
||||||
</option>
|
|
||||||
{profiles.data?.profiles.map((profile) => (
|
|
||||||
<option key={profile} value={profile}>
|
|
||||||
{profile}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<span
|
|
||||||
aria-live="polite"
|
|
||||||
className="profile-switcher-status"
|
|
||||||
role={selection.isError ? 'alert' : 'status'}
|
|
||||||
>
|
|
||||||
{selection.isError
|
|
||||||
? '切り替えに失敗しました。'
|
|
||||||
: selection.isSuccess
|
|
||||||
? '切り替えました。'
|
|
||||||
: ''}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import { createServerFn } from '@tanstack/react-start'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import type { ProfileSelection } from './types'
|
|
||||||
|
|
||||||
const profileSelectionSchema = z.object({
|
|
||||||
profileName: z.string().min(1).nullable(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export const loadProfiles = createServerFn({ method: 'GET' }).handler(
|
|
||||||
async () => {
|
|
||||||
const { loadProfileSettings } = await import('./profile-service.server')
|
|
||||||
return loadProfileSettings()
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
export const selectProfile = createServerFn({ method: 'POST' })
|
|
||||||
.validator(profileSelectionSchema)
|
|
||||||
.handler(async ({ data }): Promise<ProfileSelection> => {
|
|
||||||
const { saveProfileSelection } = await import('./profile-service.server')
|
|
||||||
await saveProfileSelection(data.profileName)
|
|
||||||
return data
|
|
||||||
})
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
export type ProfileSettings = {
|
|
||||||
profiles: string[]
|
|
||||||
selectedProfile?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ProfileSelection = {
|
|
||||||
profileName: string | null
|
|
||||||
}
|
|
||||||
@@ -23,10 +23,6 @@ vi.mock('../features/posts/use-list-choices', async (importOriginal) => {
|
|||||||
return { ...original, useListChoices }
|
return { ...original, useListChoices }
|
||||||
})
|
})
|
||||||
|
|
||||||
vi.mock('../features/profiles/profile-switcher', () => ({
|
|
||||||
ProfileSwitcher: () => null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
vi.mock('./__root', async () => {
|
vi.mock('./__root', async () => {
|
||||||
const { createRootRouteWithContext, Outlet } = await import(
|
const { createRootRouteWithContext, Outlet } = await import(
|
||||||
'@tanstack/react-router'
|
'@tanstack/react-router'
|
||||||
@@ -157,42 +153,13 @@ describe('post feed route wiring', () => {
|
|||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(usePostFeed).toHaveBeenCalledWith({
|
expect(usePostFeed).toHaveBeenCalledWith({
|
||||||
kind: 'search',
|
kind: 'search',
|
||||||
query: 'AI lang:ja filter:follows',
|
query: 'AI lang:ja',
|
||||||
product: 'Top',
|
product: 'Top',
|
||||||
following: true,
|
following: true,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('compiles button-selected search conditions from the URL', async () => {
|
|
||||||
await renderRoute(
|
|
||||||
'/search?q=TypeScript&from=%40tan_stack&since=2026-08-04&until=2026-08-11&lang=ja&content=images&excludeReplies=true&excludeReposts=true&product=Latest&following=false',
|
|
||||||
)
|
|
||||||
|
|
||||||
await waitFor(() =>
|
|
||||||
expect(usePostFeed).toHaveBeenCalledWith({
|
|
||||||
kind: 'search',
|
|
||||||
query:
|
|
||||||
'TypeScript from:tan_stack since:2026-08-04 until:2026-08-11 lang:ja filter:images -filter:replies -filter:retweets',
|
|
||||||
product: 'Latest',
|
|
||||||
following: false,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
expect(
|
|
||||||
screen.getByRole('button', { name: '投稿者 @tan_stack を解除' }),
|
|
||||||
).toBeVisible()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps contradictory date parameters local and idle', async () => {
|
|
||||||
await renderRoute(
|
|
||||||
'/search?q=TypeScript&since=2026-08-11&until=2026-08-10&product=Latest&following=false',
|
|
||||||
)
|
|
||||||
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '期間' }))
|
|
||||||
expect(await screen.findByLabelText('開始日')).toHaveValue('2026-08-11')
|
|
||||||
expect(usePostFeed).toHaveBeenCalledWith(undefined)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('turns a decimal status path into a deliberate thread request', async () => {
|
it('turns a decimal status path into a deliberate thread request', async () => {
|
||||||
await renderRoute('/yuta/status/123')
|
await renderRoute('/yuta/status/123')
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,8 @@ import type { QueryClient } from '@tanstack/react-query'
|
|||||||
import {
|
import {
|
||||||
createRootRouteWithContext,
|
createRootRouteWithContext,
|
||||||
HeadContent,
|
HeadContent,
|
||||||
Outlet,
|
|
||||||
Scripts,
|
Scripts,
|
||||||
} from '@tanstack/react-router'
|
} from '@tanstack/react-router'
|
||||||
import { SearchTool } from '#/features/posts/webmcp-tools'
|
|
||||||
import appCss from '../styles.css?url'
|
import appCss from '../styles.css?url'
|
||||||
|
|
||||||
type RouterContext = { queryClient: QueryClient }
|
type RouterContext = { queryClient: QueryClient }
|
||||||
@@ -30,18 +28,8 @@ export const Route = createRootRouteWithContext<RouterContext>()({
|
|||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
shellComponent: RootDocument,
|
shellComponent: RootDocument,
|
||||||
component: RootContent,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
function RootContent() {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<SearchTool />
|
|
||||||
<Outlet />
|
|
||||||
</>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function RootDocument({ children }: { children: React.ReactNode }) {
|
function RootDocument({ children }: { children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<html lang="ja">
|
<html lang="ja">
|
||||||
|
|||||||
@@ -1,70 +1,34 @@
|
|||||||
import { createFileRoute } from '@tanstack/react-router'
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
import { AppShell } from '#/components/app-shell'
|
import { AppShell } from '#/components/app-shell'
|
||||||
import { PostFeed } from '#/features/posts/components/post-feed'
|
import { PostFeed } from '#/features/posts/components/post-feed'
|
||||||
import {
|
import { SearchForm } from '#/features/posts/components/search-form'
|
||||||
SearchForm,
|
import { postSearchRouteSchema } from '#/features/posts/inputs'
|
||||||
type SearchValues,
|
|
||||||
} from '#/features/posts/components/search-form'
|
|
||||||
import {
|
|
||||||
buildFilteredSearchQuery,
|
|
||||||
postSearchRouteSchema,
|
|
||||||
} from '#/features/posts/inputs'
|
|
||||||
|
|
||||||
export const Route = createFileRoute('/search')({
|
export const Route = createFileRoute('/search')({
|
||||||
validateSearch: (search) => postSearchRouteSchema.parse(search),
|
validateSearch: (search) => postSearchRouteSchema.parse(search),
|
||||||
component: SearchRoute,
|
component: SearchRoute,
|
||||||
})
|
})
|
||||||
|
|
||||||
function compileQuery(values: SearchValues): string | undefined {
|
|
||||||
if (!values.q && !values.from) return undefined
|
|
||||||
try {
|
|
||||||
return buildFilteredSearchQuery(values, values.following)
|
|
||||||
} catch {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function SearchRoute() {
|
function SearchRoute() {
|
||||||
const values = Route.useSearch()
|
const values = Route.useSearch()
|
||||||
const navigate = Route.useNavigate()
|
const navigate = Route.useNavigate()
|
||||||
const formValues = {
|
|
||||||
...values,
|
|
||||||
from: values.from ?? '',
|
|
||||||
since: values.since ?? '',
|
|
||||||
until: values.until ?? '',
|
|
||||||
lang: values.lang ?? 'all',
|
|
||||||
content: values.content ?? 'all',
|
|
||||||
excludeReplies: values.excludeReplies ?? false,
|
|
||||||
excludeReposts: values.excludeReposts ?? false,
|
|
||||||
} satisfies SearchValues
|
|
||||||
const query = compileQuery(formValues)
|
|
||||||
const formKey = [
|
|
||||||
formValues.q,
|
|
||||||
formValues.from,
|
|
||||||
formValues.since,
|
|
||||||
formValues.until,
|
|
||||||
formValues.lang,
|
|
||||||
formValues.content,
|
|
||||||
formValues.excludeReplies,
|
|
||||||
formValues.excludeReposts,
|
|
||||||
formValues.product,
|
|
||||||
formValues.following,
|
|
||||||
].join(':')
|
|
||||||
return (
|
return (
|
||||||
<AppShell active="search">
|
<AppShell active="search">
|
||||||
<h1>何を確認しますか?</h1>
|
<h1>何を確認しますか?</h1>
|
||||||
<p className="intro">入力した条件だけを検索します。</p>
|
<p className="intro">入力した条件だけを検索します。</p>
|
||||||
<SearchForm
|
<SearchForm
|
||||||
initialValues={formValues}
|
initialFollowing={values.following}
|
||||||
key={formKey}
|
initialProduct={values.product}
|
||||||
|
initialQuery={values.q}
|
||||||
|
key={`${values.q}:${values.product}:${values.following}`}
|
||||||
onSubmit={(search) => navigate({ search })}
|
onSubmit={(search) => navigate({ search })}
|
||||||
/>
|
/>
|
||||||
<PostFeed
|
<PostFeed
|
||||||
request={
|
request={
|
||||||
query
|
values.q
|
||||||
? {
|
? {
|
||||||
kind: 'search',
|
kind: 'search',
|
||||||
query,
|
query: values.q,
|
||||||
product: values.product,
|
product: values.product,
|
||||||
following: values.following,
|
following: values.following,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -639,9 +639,8 @@ video.media {
|
|||||||
|
|
||||||
.app-header {
|
.app-header {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: minmax(0, 1fr) minmax(8rem, 9.5rem);
|
|
||||||
align-items: start;
|
align-items: start;
|
||||||
gap: var(--space-lg) var(--space-md);
|
gap: var(--space-lg);
|
||||||
padding: var(--space-lg) var(--space-md) 0;
|
padding: var(--space-lg) var(--space-md) 0;
|
||||||
border-bottom: var(--rule-hairline) solid var(--border);
|
border-bottom: var(--rule-hairline) solid var(--border);
|
||||||
background: var(--paper);
|
background: var(--paper);
|
||||||
@@ -666,7 +665,6 @@ video.media {
|
|||||||
|
|
||||||
.tabs {
|
.tabs {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-column: 1 / -1;
|
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
gap: 0;
|
gap: 0;
|
||||||
}
|
}
|
||||||
@@ -691,72 +689,6 @@ video.media {
|
|||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Hallmark · component: select · genre: editorial · theme: Garden
|
|
||||||
* states: default · hover · focus · active · disabled · loading · error · success
|
|
||||||
* contrast: pass
|
|
||||||
*/
|
|
||||||
.profile-switcher {
|
|
||||||
position: relative;
|
|
||||||
display: grid;
|
|
||||||
width: 100%;
|
|
||||||
min-width: 0;
|
|
||||||
gap: var(--space-2xs);
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile-switcher label {
|
|
||||||
color: var(--secondary);
|
|
||||||
font-size: var(--text-xs);
|
|
||||||
font-weight: 700;
|
|
||||||
line-height: 1;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile-switcher select {
|
|
||||||
width: 100%;
|
|
||||||
min-height: 2.75rem;
|
|
||||||
padding: var(--space-xs) 1.8rem var(--space-xs) var(--space-sm);
|
|
||||||
border: var(--rule-hairline) solid var(--control-border);
|
|
||||||
border-radius: var(--radius-sm);
|
|
||||||
outline: var(--rule-active) solid transparent;
|
|
||||||
outline-offset: var(--space-3xs);
|
|
||||||
background: var(--paper);
|
|
||||||
color: var(--ink);
|
|
||||||
cursor: pointer;
|
|
||||||
font: inherit;
|
|
||||||
font-size: var(--text-sm);
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile-switcher select:active {
|
|
||||||
background: var(--color-paper-3);
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile-switcher select:disabled {
|
|
||||||
cursor: not-allowed;
|
|
||||||
opacity: 0.55;
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile-switcher[data-state="error"] select {
|
|
||||||
border-color: var(--error);
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile-switcher[data-state="success"] select {
|
|
||||||
border-color: var(--color-success);
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile-switcher-status {
|
|
||||||
position: absolute;
|
|
||||||
inset-block-start: 100%;
|
|
||||||
inset-inline-end: 0;
|
|
||||||
color: var(--error);
|
|
||||||
font-size: var(--text-xs);
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.profile-switcher[data-state="success"] .profile-switcher-status {
|
|
||||||
color: var(--color-success);
|
|
||||||
}
|
|
||||||
|
|
||||||
.reader {
|
.reader {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
@@ -805,7 +737,6 @@ video.media {
|
|||||||
letter-spacing: 0;
|
letter-spacing: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.field > label:first-child,
|
|
||||||
.field > span:first-child {
|
.field > span:first-child {
|
||||||
margin-bottom: var(--space-xs);
|
margin-bottom: var(--space-xs);
|
||||||
}
|
}
|
||||||
@@ -946,175 +877,6 @@ button[data-state="success"] {
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Hallmark · component: search filter builder · genre: editorial · theme: Garden
|
|
||||||
* states: default · hover · focus · active · disabled · loading · error · success
|
|
||||||
* contrast: pass (40–41)
|
|
||||||
*/
|
|
||||||
.search-query,
|
|
||||||
.search-filter-buttons,
|
|
||||||
.search-filter-panel,
|
|
||||||
.active-filters,
|
|
||||||
.search-query-preview,
|
|
||||||
.search-error {
|
|
||||||
grid-column: 1 / -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.field-help {
|
|
||||||
min-height: 1lh;
|
|
||||||
margin-top: var(--space-2xs);
|
|
||||||
color: var(--secondary);
|
|
||||||
font-size: var(--text-sm);
|
|
||||||
font-weight: 400;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-buttons,
|
|
||||||
.active-filters {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: var(--space-xs);
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-buttons {
|
|
||||||
min-width: 0;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
border: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-buttons legend,
|
|
||||||
.search-filter-panel > legend {
|
|
||||||
width: 100%;
|
|
||||||
margin-bottom: var(--space-xs);
|
|
||||||
color: var(--secondary);
|
|
||||||
font-size: var(--text-sm);
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-buttons .filter-button,
|
|
||||||
.active-filters button,
|
|
||||||
.search-filter-options > button {
|
|
||||||
min-height: 2.75rem;
|
|
||||||
padding: var(--space-xs) var(--space-sm);
|
|
||||||
border-color: var(--control-border);
|
|
||||||
background: var(--paper);
|
|
||||||
color: var(--ink);
|
|
||||||
font-size: var(--text-sm);
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-buttons .filter-button {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: var(--space-xs);
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-buttons .filter-button span {
|
|
||||||
color: var(--accent);
|
|
||||||
font-size: var(--text-xs);
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-buttons .filter-button[aria-expanded="true"],
|
|
||||||
.search-filter-buttons .filter-button[data-active="true"],
|
|
||||||
.active-filters button {
|
|
||||||
border-color: var(--accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-panel {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: minmax(0, 1fr);
|
|
||||||
gap: var(--space-md);
|
|
||||||
min-width: 0;
|
|
||||||
margin: 0;
|
|
||||||
padding: var(--space-md);
|
|
||||||
border-block: var(--rule-hairline) solid var(--border);
|
|
||||||
background: var(--color-paper-3);
|
|
||||||
color: var(--ink);
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-panel .field input,
|
|
||||||
.search-filter-panel .segmented label,
|
|
||||||
.search-filter-panel button {
|
|
||||||
background: var(--paper);
|
|
||||||
}
|
|
||||||
|
|
||||||
.compact-field {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.date-fields {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: minmax(0, 1fr);
|
|
||||||
gap: var(--space-md);
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-options,
|
|
||||||
.search-exclusions {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: var(--space-xs);
|
|
||||||
min-width: 0;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
border: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-filter-options legend,
|
|
||||||
.search-exclusions legend {
|
|
||||||
width: 100%;
|
|
||||||
margin-bottom: var(--space-xs);
|
|
||||||
color: var(--secondary);
|
|
||||||
font-size: var(--text-sm);
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
|
||||||
|
|
||||||
.active-filters {
|
|
||||||
min-height: 0;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
list-style: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.active-filters:empty {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.active-filters button {
|
|
||||||
color: var(--accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-query-preview {
|
|
||||||
min-width: 0;
|
|
||||||
color: var(--secondary);
|
|
||||||
font-size: var(--text-sm);
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-query-preview summary {
|
|
||||||
min-height: 2.75rem;
|
|
||||||
width: fit-content;
|
|
||||||
padding-block: var(--space-sm);
|
|
||||||
cursor: pointer;
|
|
||||||
color: var(--accent);
|
|
||||||
font-weight: 700;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-query-preview code {
|
|
||||||
display: block;
|
|
||||||
max-width: 100%;
|
|
||||||
padding: var(--space-sm) var(--space-md);
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
border-left: var(--rule-active) solid var(--border);
|
|
||||||
background: var(--paper);
|
|
||||||
color: var(--ink);
|
|
||||||
font-family: var(--font-mono);
|
|
||||||
font-size: var(--text-sm);
|
|
||||||
line-height: 1.6;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-error {
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.list-picker {
|
.list-picker {
|
||||||
margin-bottom: var(--space-xl);
|
margin-bottom: var(--space-xl);
|
||||||
padding: var(--space-lg);
|
padding: var(--space-lg);
|
||||||
@@ -1293,10 +1055,6 @@ button[data-state="success"] {
|
|||||||
color: var(--accent-hover);
|
color: var(--accent-hover);
|
||||||
}
|
}
|
||||||
|
|
||||||
.profile-switcher select:not(:disabled):hover {
|
|
||||||
background: var(--color-paper-2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.field input:hover {
|
.field input:hover {
|
||||||
background: var(--surface);
|
background: var(--surface);
|
||||||
}
|
}
|
||||||
@@ -1320,18 +1078,6 @@ button[data-state="success"] {
|
|||||||
color: var(--color-accent-ink);
|
color: var(--color-accent-ink);
|
||||||
}
|
}
|
||||||
|
|
||||||
.search-filter-buttons .filter-button:hover,
|
|
||||||
.active-filters button:hover,
|
|
||||||
.search-filter-options > button:hover {
|
|
||||||
border-color: var(--accent);
|
|
||||||
background: var(--surface);
|
|
||||||
color: var(--ink);
|
|
||||||
}
|
|
||||||
|
|
||||||
.active-filters button:hover {
|
|
||||||
color: var(--accent-hover);
|
|
||||||
}
|
|
||||||
|
|
||||||
.list-choices a:hover {
|
.list-choices a:hover {
|
||||||
border-color: var(--border);
|
border-color: var(--border);
|
||||||
background: var(--color-paper-3);
|
background: var(--color-paper-3);
|
||||||
@@ -1352,14 +1098,6 @@ button[data-state="success"] {
|
|||||||
grid-column: 1 / -1;
|
grid-column: 1 / -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.search-form .compact-field {
|
|
||||||
grid-column: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.date-fields {
|
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
||||||
}
|
|
||||||
|
|
||||||
.intent-form:not(:has(.segmented)) > button {
|
.intent-form:not(:has(.segmented)) > button {
|
||||||
align-self: start;
|
align-self: start;
|
||||||
margin-top: calc(1lh + var(--space-xs));
|
margin-top: calc(1lh + var(--space-xs));
|
||||||
@@ -1408,7 +1146,6 @@ button[data-state="success"] {
|
|||||||
.app-header {
|
.app-header {
|
||||||
position: sticky;
|
position: sticky;
|
||||||
top: var(--space-lg);
|
top: var(--space-lg);
|
||||||
grid-template-columns: minmax(0, 1fr);
|
|
||||||
grid-row: 1;
|
grid-row: 1;
|
||||||
grid-column: 1;
|
grid-column: 1;
|
||||||
align-self: start;
|
align-self: start;
|
||||||
@@ -1420,7 +1157,6 @@ button[data-state="success"] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.tabs {
|
.tabs {
|
||||||
grid-column: 1;
|
|
||||||
grid-template-columns: minmax(0, 1fr);
|
grid-template-columns: minmax(0, 1fr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,6 @@
|
|||||||
"YuMincho", "Hiragino Mincho ProN", "Noto Serif JP", ui-serif, serif;
|
"YuMincho", "Hiragino Mincho ProN", "Noto Serif JP", ui-serif, serif;
|
||||||
--font-body:
|
--font-body:
|
||||||
"Hiragino Sans", "Yu Gothic UI", "Noto Sans JP", ui-sans-serif, sans-serif;
|
"Hiragino Sans", "Yu Gothic UI", "Noto Sans JP", ui-sans-serif, sans-serif;
|
||||||
--font-mono: ui-monospace, "SFMono-Regular", Consolas, monospace;
|
|
||||||
|
|
||||||
--space-3xs: 0.125rem;
|
--space-3xs: 0.125rem;
|
||||||
--space-2xs: 0.25rem;
|
--space-2xs: 0.25rem;
|
||||||
|
|||||||