初始化
This commit is contained in:
1 parent
34474bd5fc
commit
b638b541d0
3008 files changed
+837699
No files matched your search
@@ -0,0 +1,67 @@
|
||||
"""LangGraph-compatible runtime — runs, streaming, and lifecycle management.
|
||||
|
||||
Re-exports the public API of :mod:`~deerflow.runtime.runs` and
|
||||
:mod:`~deerflow.runtime.stream_bridge` so that consumers can import
|
||||
directly from ``deerflow.runtime``.
|
||||
"""
|
||||
|
||||
from .checkpointer import checkpointer_context, get_checkpointer, make_checkpointer, reset_checkpointer
|
||||
from .runs import (
|
||||
AcquireDecision,
|
||||
AcquireResult,
|
||||
ActiveLease,
|
||||
ConflictError,
|
||||
DisconnectMode,
|
||||
ModelConcurrencyLimitError,
|
||||
RedisConcurrencyGate,
|
||||
RunContext,
|
||||
RunManager,
|
||||
RunRecord,
|
||||
RunStatus,
|
||||
UnsupportedStrategyError,
|
||||
make_redis_concurrency_gate,
|
||||
run_agent,
|
||||
)
|
||||
from .serialization import serialize, serialize_channel_values, serialize_lc_object, serialize_messages_tuple
|
||||
from .store import get_store, make_store, reset_store, store_context
|
||||
from .stream_bridge import END_SENTINEL, HEARTBEAT_SENTINEL, MemoryStreamBridge, StreamBridge, StreamEvent, make_stream_bridge
|
||||
|
||||
__all__ = [
|
||||
# checkpointer
|
||||
"checkpointer_context",
|
||||
"get_checkpointer",
|
||||
"make_checkpointer",
|
||||
"reset_checkpointer",
|
||||
# runs
|
||||
"AcquireDecision",
|
||||
"AcquireResult",
|
||||
"ActiveLease",
|
||||
"ConflictError",
|
||||
"DisconnectMode",
|
||||
"ModelConcurrencyLimitError",
|
||||
"RedisConcurrencyGate",
|
||||
"RunContext",
|
||||
"RunManager",
|
||||
"RunRecord",
|
||||
"RunStatus",
|
||||
"UnsupportedStrategyError",
|
||||
"make_redis_concurrency_gate",
|
||||
"run_agent",
|
||||
# serialization
|
||||
"serialize",
|
||||
"serialize_channel_values",
|
||||
"serialize_lc_object",
|
||||
"serialize_messages_tuple",
|
||||
# store
|
||||
"get_store",
|
||||
"make_store",
|
||||
"reset_store",
|
||||
"store_context",
|
||||
# stream_bridge
|
||||
"END_SENTINEL",
|
||||
"HEARTBEAT_SENTINEL",
|
||||
"MemoryStreamBridge",
|
||||
"StreamBridge",
|
||||
"StreamEvent",
|
||||
"make_stream_bridge",
|
||||
]
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
from .async_provider import make_checkpointer
|
||||
from .provider import checkpointer_context, get_checkpointer, reset_checkpointer
|
||||
|
||||
__all__ = [
|
||||
"get_checkpointer",
|
||||
"reset_checkpointer",
|
||||
"checkpointer_context",
|
||||
"make_checkpointer",
|
||||
]
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
"""Async checkpointer factory.
|
||||
|
||||
Provides an **async context manager** for long-running async servers that need
|
||||
proper resource cleanup.
|
||||
|
||||
Supported backends: memory, sqlite, postgres.
|
||||
|
||||
Usage (e.g. FastAPI lifespan)::
|
||||
|
||||
from deerflow.runtime.checkpointer.async_provider import make_checkpointer
|
||||
|
||||
async with make_checkpointer() as checkpointer:
|
||||
app.state.checkpointer = checkpointer # InMemorySaver if not configured
|
||||
|
||||
For sync usage see :mod:`deerflow.runtime.checkpointer.provider`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from langgraph.types import Checkpointer
|
||||
|
||||
from deerflow.config.app_config import AppConfig, get_app_config
|
||||
from deerflow.runtime.checkpointer.provider import (
|
||||
POSTGRES_CONN_REQUIRED,
|
||||
POSTGRES_INSTALL,
|
||||
SQLITE_INSTALL,
|
||||
)
|
||||
from deerflow.runtime.store._sqlite_utils import ensure_sqlite_parent_dir, resolve_sqlite_conn_str
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _csv_env(name: str) -> list[str]:
|
||||
raw = os.getenv(name, "")
|
||||
return [part.strip() for part in raw.split(",") if part.strip()]
|
||||
|
||||
|
||||
def _dual_read_enabled(config) -> bool:
|
||||
if getattr(config, "dual_read_enabled", False):
|
||||
return True
|
||||
return os.getenv("DEER_FLOW_CHECKPOINT_DUAL_READ", "").strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _use_postgres_enabled(config) -> bool:
|
||||
raw = os.getenv("DEER_FLOW_USE_PG_CHECKPOINTER")
|
||||
if raw:
|
||||
return raw.strip().lower() not in {"0", "false", "no", "off"}
|
||||
return bool(getattr(config, "use_postgres", True))
|
||||
|
||||
|
||||
def _dual_read_paths(config) -> list[str]:
|
||||
paths = list(getattr(config, "dual_read_sqlite_paths", []) or [])
|
||||
paths.extend(_csv_env("DEER_FLOW_CHECKPOINT_SQLITE_PATHS"))
|
||||
resolved: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for path in paths:
|
||||
conn_str = resolve_sqlite_conn_str(path)
|
||||
if conn_str == ":memory:" or conn_str.startswith("file:"):
|
||||
logger.warning("Skipping unsupported checkpoint migration SQLite path: %s", path)
|
||||
continue
|
||||
if conn_str not in seen:
|
||||
resolved.append(conn_str)
|
||||
seen.add(conn_str)
|
||||
return resolved
|
||||
|
||||
|
||||
def _sqlite_conn_str_for_postgres_fallback(config) -> str:
|
||||
configured = getattr(config, "sqlite_connection_string", None)
|
||||
if configured:
|
||||
return configured
|
||||
paths = _dual_read_paths(config)
|
||||
return paths[0] if paths else "store.db"
|
||||
|
||||
|
||||
def _pool_size_env(name: str, default: int) -> int:
|
||||
raw = os.getenv(name, "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
return max(0, int(raw))
|
||||
except ValueError:
|
||||
logger.warning("Invalid %s=%r; using default %d", name, raw, default)
|
||||
return default
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def _postgres_saver_from_pool(conn_string: str) -> AsyncIterator[Checkpointer]:
|
||||
"""Yield an ``AsyncPostgresSaver`` backed by a self-healing connection pool.
|
||||
|
||||
``AsyncPostgresSaver.from_conn_string`` opens a *single* long-lived
|
||||
connection. If that one connection dies (Postgres restart, idle timeout,
|
||||
network blip, or a prior broken pipeline), every later checkpointer call
|
||||
fails permanently with "the connection is closed" until the process is
|
||||
restarted. A pool with ``check=check_connection`` validates each connection
|
||||
on checkout and transparently replaces dead ones, so the runtime recovers
|
||||
on its own.
|
||||
"""
|
||||
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
|
||||
pool = AsyncConnectionPool(
|
||||
conninfo=conn_string,
|
||||
min_size=_pool_size_env("DEER_FLOW_PG_POOL_MIN", 1),
|
||||
max_size=_pool_size_env("DEER_FLOW_PG_POOL_MAX", 10),
|
||||
max_idle=300.0,
|
||||
max_lifetime=3600.0,
|
||||
check=AsyncConnectionPool.check_connection,
|
||||
kwargs={"autocommit": True, "prepare_threshold": 0, "row_factory": dict_row},
|
||||
open=False,
|
||||
)
|
||||
await pool.open(wait=True)
|
||||
try:
|
||||
saver = AsyncPostgresSaver(pool)
|
||||
await saver.setup()
|
||||
yield saver
|
||||
finally:
|
||||
await pool.close()
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def _sqlite_checkpointer_from_conn_str(raw: str) -> AsyncIterator[Checkpointer]:
|
||||
try:
|
||||
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
|
||||
except ImportError as exc:
|
||||
raise ImportError(SQLITE_INSTALL) from exc
|
||||
|
||||
conn_str = resolve_sqlite_conn_str(raw)
|
||||
await asyncio.to_thread(ensure_sqlite_parent_dir, conn_str)
|
||||
async with AsyncSqliteSaver.from_conn_string(conn_str) as saver:
|
||||
await saver.setup()
|
||||
yield saver
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Async factory
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def _async_checkpointer(config) -> AsyncIterator[Checkpointer]:
|
||||
"""Async context manager that constructs and tears down a checkpointer."""
|
||||
if config.type == "memory":
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
yield InMemorySaver()
|
||||
return
|
||||
|
||||
if config.type == "sqlite":
|
||||
async with _sqlite_checkpointer_from_conn_str(config.connection_string or "store.db") as saver:
|
||||
yield saver
|
||||
return
|
||||
|
||||
if config.type == "postgres":
|
||||
if not _use_postgres_enabled(config):
|
||||
conn_str = _sqlite_conn_str_for_postgres_fallback(config)
|
||||
logger.info("Checkpointer: use_postgres=false; using SQLite fallback (%s)", conn_str)
|
||||
async with _sqlite_checkpointer_from_conn_str(conn_str) as saver:
|
||||
yield saver
|
||||
return
|
||||
|
||||
try:
|
||||
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver # noqa: F401
|
||||
except ImportError as exc:
|
||||
raise ImportError(POSTGRES_INSTALL) from exc
|
||||
|
||||
if not config.connection_string:
|
||||
raise ValueError(POSTGRES_CONN_REQUIRED)
|
||||
|
||||
async with _postgres_saver_from_pool(config.connection_string) as saver:
|
||||
if not _dual_read_enabled(config):
|
||||
yield saver
|
||||
return
|
||||
|
||||
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
|
||||
|
||||
from deerflow.runtime.checkpointer.checkpoint_migration import (
|
||||
DualReadCheckpointer,
|
||||
SQLiteCheckpointSource,
|
||||
)
|
||||
|
||||
sources: list[SQLiteCheckpointSource] = []
|
||||
for sqlite_path in _dual_read_paths(config):
|
||||
if not Path(sqlite_path).exists():
|
||||
logger.info("Checkpoint dual-read source does not exist, skipping: %s", sqlite_path)
|
||||
continue
|
||||
ctx = AsyncSqliteSaver.from_conn_string(sqlite_path)
|
||||
source_saver = await ctx.__aenter__()
|
||||
await source_saver.setup()
|
||||
sources.append(
|
||||
SQLiteCheckpointSource(
|
||||
path=sqlite_path,
|
||||
saver=source_saver,
|
||||
context=ctx,
|
||||
progress_path=Path(sqlite_path).with_suffix(Path(sqlite_path).suffix + ".pg-migration.json"),
|
||||
)
|
||||
)
|
||||
|
||||
if not sources:
|
||||
logger.info("Checkpoint dual-read enabled but no SQLite sources were opened; using Postgres only")
|
||||
yield saver
|
||||
return
|
||||
|
||||
proxy = DualReadCheckpointer(
|
||||
saver,
|
||||
sources,
|
||||
)
|
||||
try:
|
||||
yield proxy
|
||||
finally:
|
||||
await proxy.aclose_sources()
|
||||
return
|
||||
|
||||
raise ValueError(f"Unknown checkpointer type: {config.type!r}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public async context manager
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def _async_checkpointer_from_database(db_config) -> AsyncIterator[Checkpointer]:
|
||||
"""Async context manager that constructs a checkpointer from unified DatabaseConfig."""
|
||||
if db_config.backend == "memory":
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
yield InMemorySaver()
|
||||
return
|
||||
|
||||
if db_config.backend == "sqlite":
|
||||
try:
|
||||
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
|
||||
except ImportError as exc:
|
||||
raise ImportError(SQLITE_INSTALL) from exc
|
||||
|
||||
conn_str = db_config.checkpointer_sqlite_path
|
||||
ensure_sqlite_parent_dir(conn_str)
|
||||
async with AsyncSqliteSaver.from_conn_string(conn_str) as saver:
|
||||
await saver.setup()
|
||||
yield saver
|
||||
return
|
||||
|
||||
if db_config.backend == "postgres":
|
||||
try:
|
||||
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver # noqa: F401
|
||||
except ImportError as exc:
|
||||
raise ImportError(POSTGRES_INSTALL) from exc
|
||||
|
||||
if not db_config.postgres_url:
|
||||
raise ValueError("database.postgres_url is required for the postgres backend")
|
||||
|
||||
async with _postgres_saver_from_pool(db_config.postgres_url) as saver:
|
||||
yield saver
|
||||
return
|
||||
|
||||
raise ValueError(f"Unknown database backend: {db_config.backend!r}")
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def make_checkpointer(app_config: AppConfig | None = None) -> AsyncIterator[Checkpointer]:
|
||||
"""Async context manager that yields a checkpointer for the caller's lifetime.
|
||||
Resources are opened on enter and closed on exit -- no global state::
|
||||
|
||||
async with make_checkpointer(app_config) as checkpointer:
|
||||
app.state.checkpointer = checkpointer
|
||||
|
||||
Yields an ``InMemorySaver`` when no checkpointer is configured in *config.yaml*.
|
||||
|
||||
Priority:
|
||||
1. Legacy ``checkpointer:`` config section (backward compatible)
|
||||
2. Unified ``database:`` config section
|
||||
3. Default InMemorySaver
|
||||
"""
|
||||
|
||||
if app_config is None:
|
||||
app_config = get_app_config()
|
||||
|
||||
# Legacy: standalone checkpointer config takes precedence
|
||||
if app_config.checkpointer is not None:
|
||||
async with _async_checkpointer(app_config.checkpointer) as saver:
|
||||
yield saver
|
||||
return
|
||||
|
||||
# Unified database config
|
||||
db_config = getattr(app_config, "database", None)
|
||||
if db_config is not None and db_config.backend != "memory":
|
||||
async with _async_checkpointer_from_database(db_config) as saver:
|
||||
yield saver
|
||||
return
|
||||
|
||||
# Default: in-memory
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
yield InMemorySaver()
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
"""SQLite-to-Postgres checkpoint migration and read fallback helpers.
|
||||
|
||||
The live gateway can wrap a Postgres checkpointer with ``DualReadCheckpointer``.
|
||||
New writes go to Postgres, reads prefer Postgres and fall back to legacy SQLite.
|
||||
Manual migration scripts reuse the copy helpers in this module.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SQLiteCheckpointSource:
|
||||
path: str
|
||||
saver: Any
|
||||
context: Any
|
||||
progress_path: Path
|
||||
closed: bool = False
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.closed:
|
||||
return
|
||||
self.closed = True
|
||||
try:
|
||||
await self.context.__aexit__(None, None, None)
|
||||
except Exception:
|
||||
logger.warning("Failed to close legacy SQLite checkpointer: %s", self.path, exc_info=True)
|
||||
|
||||
|
||||
def _sqlite_db_exists(path: str) -> bool:
|
||||
return Path(path).exists()
|
||||
|
||||
|
||||
def _sqlite_threads(path: str) -> list[str]:
|
||||
with sqlite3.connect(path) as conn:
|
||||
rows = conn.execute("SELECT DISTINCT thread_id FROM checkpoints ORDER BY thread_id").fetchall()
|
||||
return [str(row[0]) for row in rows if row and row[0]]
|
||||
|
||||
|
||||
def _sqlite_has_table(path: str, table: str) -> bool:
|
||||
with sqlite3.connect(path) as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",
|
||||
(table,),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def sqlite_recent_threads(path: str, *, since: str | None = None, until: str | None = None) -> list[str]:
|
||||
"""Return threads updated since an ISO timestamp when ``threads_meta`` exists."""
|
||||
|
||||
if not _sqlite_has_table(path, "threads_meta"):
|
||||
return []
|
||||
query = "SELECT thread_id FROM threads_meta"
|
||||
where: list[str] = []
|
||||
params: list[str] = []
|
||||
if since:
|
||||
where.append("updated_at >= ?")
|
||||
params.append(since)
|
||||
if until:
|
||||
where.append("updated_at <= ?")
|
||||
params.append(until)
|
||||
if where:
|
||||
query += " WHERE " + " AND ".join(where)
|
||||
query += " ORDER BY updated_at DESC"
|
||||
with sqlite3.connect(path) as conn:
|
||||
rows = conn.execute(query, tuple(params)).fetchall()
|
||||
return [str(row[0]) for row in rows if row and row[0]]
|
||||
|
||||
|
||||
def _sqlite_thread_checkpoint_count(path: str, thread_id: str) -> int:
|
||||
with sqlite3.connect(path) as conn:
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(*) FROM checkpoints WHERE thread_id = ?",
|
||||
(thread_id,),
|
||||
).fetchone()
|
||||
return int(row[0] if row else 0)
|
||||
|
||||
|
||||
def _load_progress(path: Path) -> set[str]:
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return set()
|
||||
except Exception:
|
||||
logger.warning("Ignoring unreadable checkpoint migration progress file: %s", path, exc_info=True)
|
||||
return set()
|
||||
migrated = payload.get("migrated_threads", [])
|
||||
return {str(x) for x in migrated if x}
|
||||
|
||||
|
||||
def _save_progress(path: Path, migrated: set[str]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_text(
|
||||
json.dumps({"migrated_threads": sorted(migrated)}, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
async def _copy_thread_state(source, target, thread_id: str) -> bool:
|
||||
"""Copy one thread through the public LangGraph checkpointer API."""
|
||||
|
||||
config = {"configurable": {"thread_id": thread_id}}
|
||||
tuples = [t async for t in source.alist(config)]
|
||||
if not tuples:
|
||||
return False
|
||||
|
||||
for tup in reversed(tuples):
|
||||
configurable = (tup.config or {}).get("configurable", {}) or {}
|
||||
checkpoint_ns = configurable.get("checkpoint_ns", "") or ""
|
||||
parent_id = ((tup.parent_config or {}).get("configurable", {}) or {}).get("checkpoint_id")
|
||||
|
||||
put_config: dict[str, Any] = {"configurable": {"thread_id": thread_id, "checkpoint_ns": checkpoint_ns}}
|
||||
if parent_id:
|
||||
put_config["configurable"]["checkpoint_id"] = parent_id
|
||||
|
||||
new_versions = (tup.checkpoint or {}).get("channel_versions", {}) or {}
|
||||
await target.aput(put_config, tup.checkpoint, tup.metadata or {}, new_versions)
|
||||
|
||||
if tup.pending_writes:
|
||||
by_task: dict[str, list] = {}
|
||||
for task_id, channel, value in tup.pending_writes:
|
||||
by_task.setdefault(task_id, []).append((channel, value))
|
||||
checkpoint_id = (tup.checkpoint or {}).get("id")
|
||||
for task_id, writes in by_task.items():
|
||||
writes_config = {
|
||||
"configurable": {
|
||||
"thread_id": thread_id,
|
||||
"checkpoint_ns": checkpoint_ns,
|
||||
"checkpoint_id": checkpoint_id,
|
||||
}
|
||||
}
|
||||
await target.aput_writes(writes_config, writes, task_id)
|
||||
return True
|
||||
|
||||
|
||||
async def copy_thread_state(source, target, thread_id: str) -> bool:
|
||||
return await _copy_thread_state(source, target, thread_id)
|
||||
|
||||
|
||||
async def _target_thread_checkpoint_count(target, thread_id: str) -> int:
|
||||
config = {"configurable": {"thread_id": thread_id}}
|
||||
count = 0
|
||||
async for _ in target.alist(config):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
async def target_has_thread(target, thread_id: str) -> bool:
|
||||
config = {"configurable": {"thread_id": thread_id}}
|
||||
async for _ in target.alist(config, limit=1):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class DualReadCheckpointer:
|
||||
"""Postgres-first checkpointer with SQLite read fallback."""
|
||||
|
||||
def __init__(self, primary, sources: list[SQLiteCheckpointSource], *, sleep_seconds: float = 0.05):
|
||||
self.primary = primary
|
||||
self.sources = sources
|
||||
self.sleep_seconds = max(0.0, sleep_seconds)
|
||||
self._closed = False
|
||||
|
||||
def __getattr__(self, name: str):
|
||||
return getattr(self.primary, name)
|
||||
|
||||
async def aclose_sources(self) -> None:
|
||||
self._closed = True
|
||||
for source in self.sources:
|
||||
await source.close()
|
||||
|
||||
async def aget_tuple(self, config):
|
||||
found = await self.primary.aget_tuple(config)
|
||||
if found is not None:
|
||||
return found
|
||||
for source in self.sources:
|
||||
if source.closed:
|
||||
continue
|
||||
found = await source.saver.aget_tuple(config)
|
||||
if found is not None:
|
||||
return found
|
||||
return None
|
||||
|
||||
async def aget(self, config):
|
||||
found = await self.primary.aget(config)
|
||||
if found is not None:
|
||||
return found
|
||||
for source in self.sources:
|
||||
if source.closed:
|
||||
continue
|
||||
found = await source.saver.aget(config)
|
||||
if found is not None:
|
||||
return found
|
||||
return None
|
||||
|
||||
async def alist(self, config, *, filter=None, before=None, limit=None):
|
||||
seen: set[tuple[str, str, str]] = set()
|
||||
yielded = 0
|
||||
|
||||
async for tup in self.primary.alist(config, filter=filter, before=before, limit=limit):
|
||||
key = self._tuple_key(tup)
|
||||
seen.add(key)
|
||||
yield tup
|
||||
yielded += 1
|
||||
if limit is not None and yielded >= limit:
|
||||
return
|
||||
|
||||
remaining = None if limit is None else max(0, limit - yielded)
|
||||
for source in self.sources:
|
||||
if source.closed:
|
||||
continue
|
||||
async for tup in source.saver.alist(config, filter=filter, before=before, limit=remaining):
|
||||
key = self._tuple_key(tup)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
yield tup
|
||||
yielded += 1
|
||||
if limit is not None:
|
||||
remaining = max(0, limit - yielded)
|
||||
if remaining <= 0:
|
||||
return
|
||||
|
||||
async def aput(self, *args, **kwargs):
|
||||
return await self.primary.aput(*args, **kwargs)
|
||||
|
||||
async def aput_writes(self, *args, **kwargs):
|
||||
return await self.primary.aput_writes(*args, **kwargs)
|
||||
|
||||
async def adelete_thread(self, thread_id: str) -> None:
|
||||
delete = getattr(self.primary, "adelete_thread", None)
|
||||
if delete is not None:
|
||||
await delete(thread_id)
|
||||
for source in self.sources:
|
||||
if source.closed:
|
||||
continue
|
||||
delete = getattr(source.saver, "adelete_thread", None)
|
||||
if delete is not None:
|
||||
await delete(thread_id)
|
||||
|
||||
@staticmethod
|
||||
def _tuple_key(tup) -> tuple[str, str, str]:
|
||||
configurable = (tup.config or {}).get("configurable", {}) or {}
|
||||
return (
|
||||
str(configurable.get("thread_id", "")),
|
||||
str(configurable.get("checkpoint_ns", "") or ""),
|
||||
str(configurable.get("checkpoint_id", "") or (tup.checkpoint or {}).get("id", "")),
|
||||
)
|
||||
|
||||
async def _verify_source(self, source: SQLiteCheckpointSource, threads: list[str]) -> bool:
|
||||
for thread_id in threads:
|
||||
source_count = await asyncio.to_thread(_sqlite_thread_checkpoint_count, source.path, thread_id)
|
||||
target_count = await _target_thread_checkpoint_count(self.primary, thread_id)
|
||||
if target_count < source_count:
|
||||
logger.warning(
|
||||
"Checkpoint migration verification failed: source=%s thread_id=%s source_count=%d target_count=%d",
|
||||
source.path,
|
||||
thread_id,
|
||||
source_count,
|
||||
target_count,
|
||||
)
|
||||
return False
|
||||
return True
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
"""Sync checkpointer factory.
|
||||
|
||||
Provides a **sync singleton** and a **sync context manager** for LangGraph
|
||||
graph compilation and CLI tools.
|
||||
|
||||
Supported backends: memory, sqlite, postgres.
|
||||
|
||||
Usage::
|
||||
|
||||
from deerflow.runtime.checkpointer.provider import get_checkpointer, checkpointer_context
|
||||
|
||||
# Singleton — reused across calls, closed on process exit
|
||||
cp = get_checkpointer()
|
||||
|
||||
# One-shot — fresh connection, closed on block exit
|
||||
with checkpointer_context() as cp:
|
||||
graph.invoke(input, config={"configurable": {"thread_id": "1"}})
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
from collections.abc import Iterator
|
||||
|
||||
from langgraph.types import Checkpointer
|
||||
|
||||
from deerflow.config.app_config import get_app_config
|
||||
from deerflow.config.checkpointer_config import CheckpointerConfig
|
||||
from deerflow.runtime.store._sqlite_utils import ensure_sqlite_parent_dir, resolve_sqlite_conn_str
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Error message constants — imported by aio.provider too
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SQLITE_INSTALL = "langgraph-checkpoint-sqlite is required for the SQLite checkpointer. Install it with: uv add langgraph-checkpoint-sqlite"
|
||||
POSTGRES_INSTALL = "langgraph-checkpoint-postgres is required for the PostgreSQL checkpointer. Install it with: uv add langgraph-checkpoint-postgres psycopg[binary] psycopg-pool"
|
||||
POSTGRES_CONN_REQUIRED = "checkpointer.connection_string is required for the postgres backend"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sync factory
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _sync_checkpointer_cm(config: CheckpointerConfig) -> Iterator[Checkpointer]:
|
||||
"""Context manager that creates and tears down a sync checkpointer.
|
||||
|
||||
Returns a configured ``Checkpointer`` instance. Resource cleanup for any
|
||||
underlying connections or pools is handled by higher-level helpers in
|
||||
this module (such as the singleton factory or context manager); this
|
||||
function does not return a separate cleanup callback.
|
||||
"""
|
||||
if config.type == "memory":
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
logger.info("Checkpointer: using InMemorySaver (in-process, not persistent)")
|
||||
yield InMemorySaver()
|
||||
return
|
||||
|
||||
if config.type == "sqlite":
|
||||
try:
|
||||
from langgraph.checkpoint.sqlite import SqliteSaver
|
||||
except ImportError as exc:
|
||||
raise ImportError(SQLITE_INSTALL) from exc
|
||||
|
||||
conn_str = resolve_sqlite_conn_str(config.connection_string or "store.db")
|
||||
ensure_sqlite_parent_dir(conn_str)
|
||||
with SqliteSaver.from_conn_string(conn_str) as saver:
|
||||
saver.setup()
|
||||
logger.info("Checkpointer: using SqliteSaver (%s)", conn_str)
|
||||
yield saver
|
||||
return
|
||||
|
||||
if config.type == "postgres":
|
||||
try:
|
||||
from langgraph.checkpoint.postgres import PostgresSaver
|
||||
except ImportError as exc:
|
||||
raise ImportError(POSTGRES_INSTALL) from exc
|
||||
|
||||
if not config.connection_string:
|
||||
raise ValueError(POSTGRES_CONN_REQUIRED)
|
||||
|
||||
with PostgresSaver.from_conn_string(config.connection_string) as saver:
|
||||
saver.setup()
|
||||
logger.info("Checkpointer: using PostgresSaver")
|
||||
yield saver
|
||||
return
|
||||
|
||||
raise ValueError(f"Unknown checkpointer type: {config.type!r}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sync singleton
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_checkpointer: Checkpointer | None = None
|
||||
_checkpointer_ctx = None # open context manager keeping the connection alive
|
||||
|
||||
|
||||
def get_checkpointer() -> Checkpointer:
|
||||
"""Return the global sync checkpointer singleton, creating it on first call.
|
||||
|
||||
Returns an ``InMemorySaver`` when no checkpointer is configured in *config.yaml*.
|
||||
|
||||
Raises:
|
||||
ImportError: If the required package for the configured backend is not installed.
|
||||
ValueError: If ``connection_string`` is missing for a backend that requires it.
|
||||
"""
|
||||
global _checkpointer, _checkpointer_ctx
|
||||
|
||||
if _checkpointer is not None:
|
||||
return _checkpointer
|
||||
|
||||
# Ensure app config is loaded before checking checkpointer config
|
||||
# This prevents returning InMemorySaver when config.yaml actually has a checkpointer section
|
||||
# but hasn't been loaded yet
|
||||
from deerflow.config.app_config import _app_config
|
||||
from deerflow.config.checkpointer_config import get_checkpointer_config
|
||||
|
||||
config = get_checkpointer_config()
|
||||
|
||||
if config is None and _app_config is None:
|
||||
# Only load app config lazily when neither the app config nor an explicit
|
||||
# checkpointer config has been initialized yet. This keeps tests that
|
||||
# intentionally set the global checkpointer config isolated from any
|
||||
# ambient config.yaml on disk.
|
||||
try:
|
||||
get_app_config()
|
||||
except FileNotFoundError:
|
||||
# In test environments without config.yaml, this is expected.
|
||||
pass
|
||||
config = get_checkpointer_config()
|
||||
if config is None:
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
logger.info("Checkpointer: using InMemorySaver (in-process, not persistent)")
|
||||
_checkpointer = InMemorySaver()
|
||||
return _checkpointer
|
||||
|
||||
_checkpointer_ctx = _sync_checkpointer_cm(config)
|
||||
_checkpointer = _checkpointer_ctx.__enter__()
|
||||
|
||||
return _checkpointer
|
||||
|
||||
|
||||
def reset_checkpointer() -> None:
|
||||
"""Reset the sync singleton, forcing recreation on the next call.
|
||||
|
||||
Closes any open backend connections and clears the cached instance.
|
||||
Useful in tests or after a configuration change.
|
||||
"""
|
||||
global _checkpointer, _checkpointer_ctx
|
||||
if _checkpointer_ctx is not None:
|
||||
try:
|
||||
_checkpointer_ctx.__exit__(None, None, None)
|
||||
except Exception:
|
||||
logger.warning("Error during checkpointer cleanup", exc_info=True)
|
||||
_checkpointer_ctx = None
|
||||
_checkpointer = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sync context manager
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def checkpointer_context() -> Iterator[Checkpointer]:
|
||||
"""Sync context manager that yields a checkpointer and cleans up on exit.
|
||||
|
||||
Unlike :func:`get_checkpointer`, this does **not** cache the instance —
|
||||
each ``with`` block creates and destroys its own connection. Use it in
|
||||
CLI scripts or tests where you want deterministic cleanup::
|
||||
|
||||
with checkpointer_context() as cp:
|
||||
graph.invoke(input, config={"configurable": {"thread_id": "1"}})
|
||||
|
||||
Yields an ``InMemorySaver`` when no checkpointer is configured in *config.yaml*.
|
||||
"""
|
||||
|
||||
config = get_app_config()
|
||||
if config.checkpointer is None:
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
|
||||
yield InMemorySaver()
|
||||
return
|
||||
|
||||
with _sync_checkpointer_cm(config.checkpointer) as saver:
|
||||
yield saver
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Pure functions to convert LangChain message objects to OpenAI Chat Completions format.
|
||||
|
||||
Utility for translating LangChain message types to OpenAI-compatible dicts.
|
||||
Not currently wired into RunJournal (which uses message.model_dump() directly),
|
||||
but available for consumers that need the OpenAI wire format.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
_ROLE_MAP = {
|
||||
"human": "user",
|
||||
"ai": "assistant",
|
||||
"system": "system",
|
||||
"tool": "tool",
|
||||
}
|
||||
|
||||
|
||||
def langchain_to_openai_message(message: Any) -> dict:
|
||||
"""Convert a single LangChain BaseMessage to an OpenAI message dict.
|
||||
|
||||
Handles:
|
||||
- HumanMessage → {"role": "user", "content": "..."}
|
||||
- AIMessage (text only) → {"role": "assistant", "content": "..."}
|
||||
- AIMessage (with tool_calls) → {"role": "assistant", "content": null, "tool_calls": [...]}
|
||||
- AIMessage (text + tool_calls) → both content and tool_calls present
|
||||
- AIMessage (list content / multimodal) → content preserved as list
|
||||
- SystemMessage → {"role": "system", "content": "..."}
|
||||
- ToolMessage → {"role": "tool", "tool_call_id": "...", "content": "..."}
|
||||
"""
|
||||
msg_type = getattr(message, "type", "")
|
||||
role = _ROLE_MAP.get(msg_type, msg_type)
|
||||
content = getattr(message, "content", "")
|
||||
|
||||
if role == "tool":
|
||||
return {
|
||||
"role": "tool",
|
||||
"tool_call_id": getattr(message, "tool_call_id", ""),
|
||||
"content": content,
|
||||
}
|
||||
|
||||
if role == "assistant":
|
||||
tool_calls = getattr(message, "tool_calls", None) or []
|
||||
result: dict = {"role": "assistant"}
|
||||
|
||||
if tool_calls:
|
||||
openai_tool_calls = []
|
||||
for tc in tool_calls:
|
||||
args = tc.get("args", {})
|
||||
openai_tool_calls.append(
|
||||
{
|
||||
"id": tc.get("id", ""),
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.get("name", ""),
|
||||
"arguments": json.dumps(args) if not isinstance(args, str) else args,
|
||||
},
|
||||
}
|
||||
)
|
||||
# If no text content, set content to null per OpenAI spec
|
||||
result["content"] = content if (isinstance(content, list) and content) or (isinstance(content, str) and content) else None
|
||||
result["tool_calls"] = openai_tool_calls
|
||||
else:
|
||||
result["content"] = content
|
||||
|
||||
return result
|
||||
|
||||
# user / system / unknown
|
||||
return {"role": role, "content": content}
|
||||
|
||||
|
||||
def _infer_finish_reason(message: Any) -> str:
|
||||
"""Infer OpenAI finish_reason from an AIMessage.
|
||||
|
||||
Returns "tool_calls" if tool_calls present, else looks in
|
||||
response_metadata.finish_reason, else returns "stop".
|
||||
"""
|
||||
tool_calls = getattr(message, "tool_calls", None) or []
|
||||
if tool_calls:
|
||||
return "tool_calls"
|
||||
resp_meta = getattr(message, "response_metadata", None) or {}
|
||||
if isinstance(resp_meta, dict):
|
||||
finish = resp_meta.get("finish_reason")
|
||||
if finish:
|
||||
return finish
|
||||
return "stop"
|
||||
|
||||
|
||||
def langchain_to_openai_completion(message: Any) -> dict:
|
||||
"""Convert an AIMessage and its metadata to an OpenAI completion response dict.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"id": message.id,
|
||||
"model": message.response_metadata.get("model_name"),
|
||||
"choices": [{"index": 0, "message": <openai_message>, "finish_reason": <inferred>}],
|
||||
"usage": {"prompt_tokens": ..., "completion_tokens": ..., "total_tokens": ...} or None,
|
||||
}
|
||||
"""
|
||||
resp_meta = getattr(message, "response_metadata", None) or {}
|
||||
model_name = resp_meta.get("model_name") if isinstance(resp_meta, dict) else None
|
||||
|
||||
openai_msg = langchain_to_openai_message(message)
|
||||
finish_reason = _infer_finish_reason(message)
|
||||
|
||||
usage_metadata = getattr(message, "usage_metadata", None)
|
||||
if usage_metadata is not None:
|
||||
input_tokens = usage_metadata.get("input_tokens", 0) or 0
|
||||
output_tokens = usage_metadata.get("output_tokens", 0) or 0
|
||||
usage: dict | None = {
|
||||
"prompt_tokens": input_tokens,
|
||||
"completion_tokens": output_tokens,
|
||||
"total_tokens": input_tokens + output_tokens,
|
||||
}
|
||||
else:
|
||||
usage = None
|
||||
|
||||
return {
|
||||
"id": getattr(message, "id", None),
|
||||
"model": model_name,
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": openai_msg,
|
||||
"finish_reason": finish_reason,
|
||||
}
|
||||
],
|
||||
"usage": usage,
|
||||
}
|
||||
|
||||
|
||||
def langchain_messages_to_openai(messages: list) -> list[dict]:
|
||||
"""Convert a list of LangChain BaseMessages to OpenAI message dicts."""
|
||||
return [langchain_to_openai_message(m) for m in messages]
|
||||
@@ -0,0 +1,4 @@
|
||||
from deerflow.runtime.events.store.base import RunEventStore
|
||||
from deerflow.runtime.events.store.memory import MemoryRunEventStore
|
||||
|
||||
__all__ = ["MemoryRunEventStore", "RunEventStore"]
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
from deerflow.runtime.events.store.base import RunEventStore
|
||||
from deerflow.runtime.events.store.memory import MemoryRunEventStore
|
||||
|
||||
|
||||
def make_run_event_store(config=None) -> RunEventStore:
|
||||
"""Create a RunEventStore based on run_events.backend configuration."""
|
||||
if config is None or config.backend == "memory":
|
||||
return MemoryRunEventStore()
|
||||
if config.backend == "db":
|
||||
from deerflow.persistence.engine import get_session_factory
|
||||
|
||||
sf = get_session_factory()
|
||||
if sf is None:
|
||||
# database.backend=memory but run_events.backend=db -> fallback
|
||||
return MemoryRunEventStore()
|
||||
from deerflow.runtime.events.store.db import DbRunEventStore
|
||||
|
||||
return DbRunEventStore(sf, max_trace_content=config.max_trace_content)
|
||||
if config.backend == "jsonl":
|
||||
from deerflow.runtime.events.store.jsonl import JsonlRunEventStore
|
||||
|
||||
return JsonlRunEventStore()
|
||||
raise ValueError(f"Unknown run_events backend: {config.backend!r}")
|
||||
|
||||
|
||||
__all__ = ["MemoryRunEventStore", "RunEventStore", "make_run_event_store"]
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
"""Abstract interface for run event storage.
|
||||
|
||||
RunEventStore is the unified storage interface for run event streams.
|
||||
Messages (frontend display) and execution traces (debugging/audit) go
|
||||
through the same interface, distinguished by the ``category`` field.
|
||||
|
||||
Implementations:
|
||||
- MemoryRunEventStore: in-memory dict (development, tests)
|
||||
- Future: DB-backed store (SQLAlchemy ORM), JSONL file store
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
|
||||
|
||||
class RunEventStore(abc.ABC):
|
||||
"""Run event stream storage interface.
|
||||
|
||||
All implementations must guarantee:
|
||||
1. put() events are retrievable in subsequent queries
|
||||
2. seq is strictly increasing within the same thread
|
||||
3. list_messages() only returns category="message" events
|
||||
4. list_events() returns all events for the specified run
|
||||
5. Returned dicts match the RunEvent field structure
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def put(
|
||||
self,
|
||||
*,
|
||||
thread_id: str,
|
||||
run_id: str,
|
||||
event_type: str,
|
||||
category: str,
|
||||
content: str | dict = "",
|
||||
metadata: dict | None = None,
|
||||
created_at: str | None = None,
|
||||
) -> dict:
|
||||
"""Write an event, auto-assign seq, return the complete record."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def put_batch(self, events: list[dict]) -> list[dict]:
|
||||
"""Batch-write events. Used by RunJournal flush buffer.
|
||||
|
||||
Each dict's keys match put()'s keyword arguments.
|
||||
Returns complete records with seq assigned.
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def list_messages(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
limit: int = 50,
|
||||
before_seq: int | None = None,
|
||||
after_seq: int | None = None,
|
||||
) -> list[dict]:
|
||||
"""Return displayable messages (category=message) for a thread, ordered by seq ascending.
|
||||
|
||||
Supports bidirectional cursor pagination:
|
||||
- before_seq: return the last ``limit`` records with seq < before_seq (ascending)
|
||||
- after_seq: return the first ``limit`` records with seq > after_seq (ascending)
|
||||
- neither: return the latest ``limit`` records (ascending)
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def list_events(
|
||||
self,
|
||||
thread_id: str,
|
||||
run_id: str,
|
||||
*,
|
||||
event_types: list[str] | None = None,
|
||||
limit: int = 500,
|
||||
) -> list[dict]:
|
||||
"""Return the full event stream for a run, ordered by seq ascending.
|
||||
|
||||
Optionally filter by event_types.
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def list_messages_by_run(
|
||||
self,
|
||||
thread_id: str,
|
||||
run_id: str,
|
||||
*,
|
||||
limit: int = 50,
|
||||
before_seq: int | None = None,
|
||||
after_seq: int | None = None,
|
||||
user_id: str | None = None,
|
||||
) -> list[dict]:
|
||||
"""Return displayable messages (category=message) for a specific run, ordered by seq ascending.
|
||||
|
||||
Supports bidirectional cursor pagination:
|
||||
- after_seq: return the first ``limit`` records with seq > after_seq (ascending)
|
||||
- before_seq: return the last ``limit`` records with seq < before_seq (ascending)
|
||||
- neither: return the latest ``limit`` records (ascending)
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def count_messages(self, thread_id: str) -> int:
|
||||
"""Count displayable messages (category=message) in a thread."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def delete_by_thread(self, thread_id: str) -> int:
|
||||
"""Delete all events for a thread. Return the number of deleted events."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def delete_by_run(self, thread_id: str, run_id: str) -> int:
|
||||
"""Delete all events for a specific run. Return the number of deleted events."""
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
"""SQLAlchemy-backed RunEventStore implementation.
|
||||
|
||||
Persists events to the ``run_events`` table. Trace content is truncated
|
||||
at ``max_trace_content`` bytes to avoid bloating the database.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.models.run_event import RunEventRow
|
||||
from deerflow.runtime.events.store.base import RunEventStore
|
||||
from deerflow.runtime.user_context import AUTO, _AutoSentinel, get_current_user, resolve_user_id
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DbRunEventStore(RunEventStore):
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession], *, max_trace_content: int = 10240):
|
||||
self._sf = session_factory
|
||||
self._max_trace_content = max_trace_content
|
||||
|
||||
@staticmethod
|
||||
def _row_to_dict(row: RunEventRow) -> dict:
|
||||
d = row.to_dict()
|
||||
d["metadata"] = d.pop("event_metadata", {})
|
||||
val = d.get("created_at")
|
||||
if isinstance(val, datetime):
|
||||
d["created_at"] = val.isoformat()
|
||||
d.pop("id", None)
|
||||
# Restore dict content that was JSON-serialized on write
|
||||
raw = d.get("content", "")
|
||||
if isinstance(raw, str) and d.get("metadata", {}).get("content_is_dict"):
|
||||
try:
|
||||
d["content"] = json.loads(raw)
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
# Content looked like JSON (content_is_dict flag) but failed to parse;
|
||||
# keep the raw string as-is.
|
||||
logger.debug("Failed to deserialize content as JSON for event seq=%s", d.get("seq"))
|
||||
return d
|
||||
|
||||
def _truncate_trace(self, category: str, content: str | dict, metadata: dict | None) -> tuple[str | dict, dict]:
|
||||
if category == "trace":
|
||||
text = json.dumps(content, default=str, ensure_ascii=False) if isinstance(content, dict) else content
|
||||
encoded = text.encode("utf-8")
|
||||
if len(encoded) > self._max_trace_content:
|
||||
# Truncate by bytes, then decode back (may cut a multi-byte char, so use errors="ignore")
|
||||
content = encoded[: self._max_trace_content].decode("utf-8", errors="ignore")
|
||||
metadata = {**(metadata or {}), "content_truncated": True, "original_byte_length": len(encoded)}
|
||||
return content, metadata or {}
|
||||
|
||||
@staticmethod
|
||||
def _user_id_from_context() -> str | None:
|
||||
"""Soft read of user_id from contextvar for write paths.
|
||||
|
||||
Returns ``None`` (no filter / no stamp) if contextvar is unset,
|
||||
which is the expected case for background worker writes. HTTP
|
||||
request writes will have the contextvar set by auth middleware
|
||||
and get their user_id stamped automatically.
|
||||
|
||||
Coerces ``user.id`` to ``str`` at the boundary: ``User.id`` is
|
||||
typed as ``UUID`` by the auth layer, but ``run_events.user_id``
|
||||
is ``VARCHAR(64)`` and aiosqlite cannot bind a raw UUID object
|
||||
to a VARCHAR column ("type 'UUID' is not supported") — the
|
||||
INSERT would silently roll back and the worker would hang.
|
||||
"""
|
||||
user = get_current_user()
|
||||
return str(user.id) if user is not None else None
|
||||
|
||||
async def put(self, *, thread_id, run_id, event_type, category, content="", metadata=None, created_at=None): # noqa: D401
|
||||
"""Write a single event — low-frequency path only.
|
||||
|
||||
This opens a dedicated transaction with a FOR UPDATE lock to
|
||||
assign a monotonic *seq*. For high-throughput writes use
|
||||
:meth:`put_batch`, which acquires the lock once for the whole
|
||||
batch. Currently the only caller is ``worker.run_agent`` for
|
||||
the initial ``human_message`` event (once per run).
|
||||
"""
|
||||
content, metadata = self._truncate_trace(category, content, metadata)
|
||||
if isinstance(content, dict):
|
||||
db_content = json.dumps(content, default=str, ensure_ascii=False)
|
||||
metadata = {**(metadata or {}), "content_is_dict": True}
|
||||
else:
|
||||
db_content = content
|
||||
user_id = self._user_id_from_context()
|
||||
async with self._sf() as session:
|
||||
async with session.begin():
|
||||
# Use FOR UPDATE to serialize seq assignment within a thread.
|
||||
# NOTE: with_for_update() on aggregates is a no-op on SQLite;
|
||||
# the UNIQUE(thread_id, seq) constraint catches races there.
|
||||
max_seq = await session.scalar(select(func.max(RunEventRow.seq)).where(RunEventRow.thread_id == thread_id).with_for_update())
|
||||
seq = (max_seq or 0) + 1
|
||||
row = RunEventRow(
|
||||
thread_id=thread_id,
|
||||
run_id=run_id,
|
||||
user_id=user_id,
|
||||
event_type=event_type,
|
||||
category=category,
|
||||
content=db_content,
|
||||
event_metadata=metadata,
|
||||
seq=seq,
|
||||
created_at=datetime.fromisoformat(created_at) if created_at else datetime.now(UTC),
|
||||
)
|
||||
session.add(row)
|
||||
return self._row_to_dict(row)
|
||||
|
||||
async def put_batch(self, events):
|
||||
if not events:
|
||||
return []
|
||||
user_id = self._user_id_from_context()
|
||||
async with self._sf() as session:
|
||||
async with session.begin():
|
||||
# Get max seq for the thread (assume all events in batch belong to same thread).
|
||||
# NOTE: with_for_update() on aggregates is a no-op on SQLite;
|
||||
# the UNIQUE(thread_id, seq) constraint catches races there.
|
||||
thread_id = events[0]["thread_id"]
|
||||
max_seq = await session.scalar(select(func.max(RunEventRow.seq)).where(RunEventRow.thread_id == thread_id).with_for_update())
|
||||
seq = max_seq or 0
|
||||
rows = []
|
||||
for e in events:
|
||||
seq += 1
|
||||
content = e.get("content", "")
|
||||
category = e.get("category", "trace")
|
||||
metadata = e.get("metadata")
|
||||
content, metadata = self._truncate_trace(category, content, metadata)
|
||||
if isinstance(content, dict):
|
||||
db_content = json.dumps(content, default=str, ensure_ascii=False)
|
||||
metadata = {**(metadata or {}), "content_is_dict": True}
|
||||
else:
|
||||
db_content = content
|
||||
row = RunEventRow(
|
||||
thread_id=e["thread_id"],
|
||||
run_id=e["run_id"],
|
||||
user_id=e.get("user_id", user_id),
|
||||
event_type=e["event_type"],
|
||||
category=category,
|
||||
content=db_content,
|
||||
event_metadata=metadata,
|
||||
seq=seq,
|
||||
created_at=datetime.fromisoformat(e["created_at"]) if e.get("created_at") else datetime.now(UTC),
|
||||
)
|
||||
session.add(row)
|
||||
rows.append(row)
|
||||
return [self._row_to_dict(r) for r in rows]
|
||||
|
||||
async def list_messages(
|
||||
self,
|
||||
thread_id,
|
||||
*,
|
||||
limit=50,
|
||||
before_seq=None,
|
||||
after_seq=None,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
):
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="DbRunEventStore.list_messages")
|
||||
stmt = select(RunEventRow).where(RunEventRow.thread_id == thread_id, RunEventRow.category == "message")
|
||||
if resolved_user_id is not None:
|
||||
stmt = stmt.where(RunEventRow.user_id == resolved_user_id)
|
||||
if before_seq is not None:
|
||||
stmt = stmt.where(RunEventRow.seq < before_seq)
|
||||
if after_seq is not None:
|
||||
stmt = stmt.where(RunEventRow.seq > after_seq)
|
||||
|
||||
if after_seq is not None:
|
||||
# Forward pagination: first `limit` records after cursor
|
||||
stmt = stmt.order_by(RunEventRow.seq.asc()).limit(limit)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [self._row_to_dict(r) for r in result.scalars()]
|
||||
else:
|
||||
# before_seq or default (latest): take last `limit` records, return ascending
|
||||
stmt = stmt.order_by(RunEventRow.seq.desc()).limit(limit)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
rows = list(result.scalars())
|
||||
return [self._row_to_dict(r) for r in reversed(rows)]
|
||||
|
||||
async def list_events(
|
||||
self,
|
||||
thread_id,
|
||||
run_id,
|
||||
*,
|
||||
event_types=None,
|
||||
limit=500,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
):
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="DbRunEventStore.list_events")
|
||||
stmt = select(RunEventRow).where(RunEventRow.thread_id == thread_id, RunEventRow.run_id == run_id)
|
||||
if resolved_user_id is not None:
|
||||
stmt = stmt.where(RunEventRow.user_id == resolved_user_id)
|
||||
if event_types:
|
||||
stmt = stmt.where(RunEventRow.event_type.in_(event_types))
|
||||
stmt = stmt.order_by(RunEventRow.seq.asc()).limit(limit)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [self._row_to_dict(r) for r in result.scalars()]
|
||||
|
||||
async def list_messages_by_run(
|
||||
self,
|
||||
thread_id,
|
||||
run_id,
|
||||
*,
|
||||
limit=50,
|
||||
before_seq=None,
|
||||
after_seq=None,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
):
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="DbRunEventStore.list_messages_by_run")
|
||||
stmt = select(RunEventRow).where(
|
||||
RunEventRow.thread_id == thread_id,
|
||||
RunEventRow.run_id == run_id,
|
||||
RunEventRow.category == "message",
|
||||
)
|
||||
if resolved_user_id is not None:
|
||||
stmt = stmt.where(RunEventRow.user_id == resolved_user_id)
|
||||
if before_seq is not None:
|
||||
stmt = stmt.where(RunEventRow.seq < before_seq)
|
||||
if after_seq is not None:
|
||||
stmt = stmt.where(RunEventRow.seq > after_seq)
|
||||
|
||||
if after_seq is not None:
|
||||
stmt = stmt.order_by(RunEventRow.seq.asc()).limit(limit)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [self._row_to_dict(r) for r in result.scalars()]
|
||||
else:
|
||||
stmt = stmt.order_by(RunEventRow.seq.desc()).limit(limit)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
rows = list(result.scalars())
|
||||
return [self._row_to_dict(r) for r in reversed(rows)]
|
||||
|
||||
async def count_messages(
|
||||
self,
|
||||
thread_id,
|
||||
*,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
):
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="DbRunEventStore.count_messages")
|
||||
stmt = select(func.count()).select_from(RunEventRow).where(RunEventRow.thread_id == thread_id, RunEventRow.category == "message")
|
||||
if resolved_user_id is not None:
|
||||
stmt = stmt.where(RunEventRow.user_id == resolved_user_id)
|
||||
async with self._sf() as session:
|
||||
return await session.scalar(stmt) or 0
|
||||
|
||||
async def delete_by_thread(
|
||||
self,
|
||||
thread_id,
|
||||
*,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
):
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="DbRunEventStore.delete_by_thread")
|
||||
async with self._sf() as session:
|
||||
count_conditions = [RunEventRow.thread_id == thread_id]
|
||||
if resolved_user_id is not None:
|
||||
count_conditions.append(RunEventRow.user_id == resolved_user_id)
|
||||
count_stmt = select(func.count()).select_from(RunEventRow).where(*count_conditions)
|
||||
count = await session.scalar(count_stmt) or 0
|
||||
if count > 0:
|
||||
await session.execute(delete(RunEventRow).where(*count_conditions))
|
||||
await session.commit()
|
||||
return count
|
||||
|
||||
async def delete_by_run(
|
||||
self,
|
||||
thread_id,
|
||||
run_id,
|
||||
*,
|
||||
user_id: str | None | _AutoSentinel = AUTO,
|
||||
):
|
||||
resolved_user_id = resolve_user_id(user_id, method_name="DbRunEventStore.delete_by_run")
|
||||
async with self._sf() as session:
|
||||
count_conditions = [RunEventRow.thread_id == thread_id, RunEventRow.run_id == run_id]
|
||||
if resolved_user_id is not None:
|
||||
count_conditions.append(RunEventRow.user_id == resolved_user_id)
|
||||
count_stmt = select(func.count()).select_from(RunEventRow).where(*count_conditions)
|
||||
count = await session.scalar(count_stmt) or 0
|
||||
if count > 0:
|
||||
await session.execute(delete(RunEventRow).where(*count_conditions))
|
||||
await session.commit()
|
||||
return count
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
"""JSONL file-backed RunEventStore implementation.
|
||||
|
||||
Each run's events are stored in a single file:
|
||||
``.deer-flow/threads/{thread_id}/runs/{run_id}.jsonl``
|
||||
|
||||
All categories (message, trace, lifecycle) are in the same file.
|
||||
This backend is suitable for lightweight single-node deployments.
|
||||
|
||||
Known trade-off: ``list_messages()`` must scan all run files for a
|
||||
thread since messages from multiple runs need unified seq ordering.
|
||||
``list_events()`` reads only one file -- the fast path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from deerflow.runtime.events.store.base import RunEventStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SAFE_ID_PATTERN = re.compile(r"^[A-Za-z0-9_\-]+$")
|
||||
|
||||
|
||||
class JsonlRunEventStore(RunEventStore):
|
||||
def __init__(self, base_dir: str | Path | None = None):
|
||||
self._base_dir = Path(base_dir) if base_dir else Path(".deer-flow")
|
||||
self._seq_counters: dict[str, int] = {} # thread_id -> current max seq
|
||||
|
||||
@staticmethod
|
||||
def _validate_id(value: str, label: str) -> str:
|
||||
"""Validate that an ID is safe for use in filesystem paths."""
|
||||
if not value or not _SAFE_ID_PATTERN.match(value):
|
||||
raise ValueError(f"Invalid {label}: must be alphanumeric/dash/underscore, got {value!r}")
|
||||
return value
|
||||
|
||||
def _thread_dir(self, thread_id: str) -> Path:
|
||||
self._validate_id(thread_id, "thread_id")
|
||||
return self._base_dir / "threads" / thread_id / "runs"
|
||||
|
||||
def _run_file(self, thread_id: str, run_id: str) -> Path:
|
||||
self._validate_id(run_id, "run_id")
|
||||
return self._thread_dir(thread_id) / f"{run_id}.jsonl"
|
||||
|
||||
def _next_seq(self, thread_id: str) -> int:
|
||||
self._seq_counters[thread_id] = self._seq_counters.get(thread_id, 0) + 1
|
||||
return self._seq_counters[thread_id]
|
||||
|
||||
def _ensure_seq_loaded(self, thread_id: str) -> None:
|
||||
"""Load max seq from existing files if not yet cached."""
|
||||
if thread_id in self._seq_counters:
|
||||
return
|
||||
max_seq = 0
|
||||
thread_dir = self._thread_dir(thread_id)
|
||||
if thread_dir.exists():
|
||||
for f in thread_dir.glob("*.jsonl"):
|
||||
for line in f.read_text(encoding="utf-8").strip().splitlines():
|
||||
try:
|
||||
record = json.loads(line)
|
||||
max_seq = max(max_seq, record.get("seq", 0))
|
||||
except json.JSONDecodeError:
|
||||
logger.debug("Skipping malformed JSONL line in %s", f)
|
||||
continue
|
||||
self._seq_counters[thread_id] = max_seq
|
||||
|
||||
def _write_record(self, record: dict) -> None:
|
||||
path = self._run_file(record["thread_id"], record["run_id"])
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(record, default=str, ensure_ascii=False) + "\n")
|
||||
|
||||
def _read_thread_events(self, thread_id: str) -> list[dict]:
|
||||
"""Read all events for a thread, sorted by seq."""
|
||||
events = []
|
||||
thread_dir = self._thread_dir(thread_id)
|
||||
if not thread_dir.exists():
|
||||
return events
|
||||
for f in sorted(thread_dir.glob("*.jsonl")):
|
||||
for line in f.read_text(encoding="utf-8").strip().splitlines():
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
events.append(json.loads(line))
|
||||
except json.JSONDecodeError:
|
||||
logger.debug("Skipping malformed JSONL line in %s", f)
|
||||
continue
|
||||
events.sort(key=lambda e: e.get("seq", 0))
|
||||
return events
|
||||
|
||||
def _read_run_events(self, thread_id: str, run_id: str) -> list[dict]:
|
||||
"""Read events for a specific run file."""
|
||||
path = self._run_file(thread_id, run_id)
|
||||
if not path.exists():
|
||||
return []
|
||||
events = []
|
||||
for line in path.read_text(encoding="utf-8").strip().splitlines():
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
events.append(json.loads(line))
|
||||
except json.JSONDecodeError:
|
||||
logger.debug("Skipping malformed JSONL line in %s", path)
|
||||
continue
|
||||
events.sort(key=lambda e: e.get("seq", 0))
|
||||
return events
|
||||
|
||||
async def put(self, *, thread_id, run_id, event_type, category, content="", metadata=None, created_at=None):
|
||||
self._ensure_seq_loaded(thread_id)
|
||||
seq = self._next_seq(thread_id)
|
||||
record = {
|
||||
"thread_id": thread_id,
|
||||
"run_id": run_id,
|
||||
"event_type": event_type,
|
||||
"category": category,
|
||||
"content": content,
|
||||
"metadata": metadata or {},
|
||||
"seq": seq,
|
||||
"created_at": created_at or datetime.now(UTC).isoformat(),
|
||||
}
|
||||
self._write_record(record)
|
||||
return record
|
||||
|
||||
async def put_batch(self, events):
|
||||
if not events:
|
||||
return []
|
||||
results = []
|
||||
for ev in events:
|
||||
record = await self.put(**ev)
|
||||
results.append(record)
|
||||
return results
|
||||
|
||||
async def list_messages(self, thread_id, *, limit=50, before_seq=None, after_seq=None):
|
||||
all_events = self._read_thread_events(thread_id)
|
||||
messages = [e for e in all_events if e.get("category") == "message"]
|
||||
|
||||
if before_seq is not None:
|
||||
messages = [e for e in messages if e["seq"] < before_seq]
|
||||
return messages[-limit:]
|
||||
elif after_seq is not None:
|
||||
messages = [e for e in messages if e["seq"] > after_seq]
|
||||
return messages[:limit]
|
||||
else:
|
||||
return messages[-limit:]
|
||||
|
||||
async def list_events(self, thread_id, run_id, *, event_types=None, limit=500):
|
||||
events = self._read_run_events(thread_id, run_id)
|
||||
if event_types is not None:
|
||||
events = [e for e in events if e.get("event_type") in event_types]
|
||||
return events[:limit]
|
||||
|
||||
async def list_messages_by_run(self, thread_id, run_id, *, limit=50, before_seq=None, after_seq=None, user_id=None):
|
||||
# JSONL events carry no per-event owner; user_id is accepted for
|
||||
# interface parity with DbRunEventStore but ignored.
|
||||
events = self._read_run_events(thread_id, run_id)
|
||||
filtered = [e for e in events if e.get("category") == "message"]
|
||||
if before_seq is not None:
|
||||
filtered = [e for e in filtered if e.get("seq", 0) < before_seq]
|
||||
if after_seq is not None:
|
||||
filtered = [e for e in filtered if e.get("seq", 0) > after_seq]
|
||||
if after_seq is not None:
|
||||
return filtered[:limit]
|
||||
else:
|
||||
return filtered[-limit:] if len(filtered) > limit else filtered
|
||||
|
||||
async def count_messages(self, thread_id):
|
||||
all_events = self._read_thread_events(thread_id)
|
||||
return sum(1 for e in all_events if e.get("category") == "message")
|
||||
|
||||
async def delete_by_thread(self, thread_id):
|
||||
all_events = self._read_thread_events(thread_id)
|
||||
count = len(all_events)
|
||||
thread_dir = self._thread_dir(thread_id)
|
||||
if thread_dir.exists():
|
||||
for f in thread_dir.glob("*.jsonl"):
|
||||
f.unlink()
|
||||
self._seq_counters.pop(thread_id, None)
|
||||
return count
|
||||
|
||||
async def delete_by_run(self, thread_id, run_id):
|
||||
events = self._read_run_events(thread_id, run_id)
|
||||
count = len(events)
|
||||
path = self._run_file(thread_id, run_id)
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
return count
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
"""In-memory RunEventStore. Used when run_events.backend=memory (default) and in tests.
|
||||
|
||||
Thread-safe for single-process async usage (no threading locks needed
|
||||
since all mutations happen within the same event loop).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from deerflow.runtime.events.store.base import RunEventStore
|
||||
|
||||
|
||||
class MemoryRunEventStore(RunEventStore):
|
||||
def __init__(self) -> None:
|
||||
self._events: dict[str, list[dict]] = {} # thread_id -> sorted event list
|
||||
self._seq_counters: dict[str, int] = {} # thread_id -> last assigned seq
|
||||
|
||||
def _next_seq(self, thread_id: str) -> int:
|
||||
current = self._seq_counters.get(thread_id, 0)
|
||||
next_val = current + 1
|
||||
self._seq_counters[thread_id] = next_val
|
||||
return next_val
|
||||
|
||||
def _put_one(
|
||||
self,
|
||||
*,
|
||||
thread_id: str,
|
||||
run_id: str,
|
||||
event_type: str,
|
||||
category: str,
|
||||
content: str | dict = "",
|
||||
metadata: dict | None = None,
|
||||
created_at: str | None = None,
|
||||
) -> dict:
|
||||
seq = self._next_seq(thread_id)
|
||||
record = {
|
||||
"thread_id": thread_id,
|
||||
"run_id": run_id,
|
||||
"event_type": event_type,
|
||||
"category": category,
|
||||
"content": content,
|
||||
"metadata": metadata or {},
|
||||
"seq": seq,
|
||||
"created_at": created_at or datetime.now(UTC).isoformat(),
|
||||
}
|
||||
self._events.setdefault(thread_id, []).append(record)
|
||||
return record
|
||||
|
||||
async def put(
|
||||
self,
|
||||
*,
|
||||
thread_id,
|
||||
run_id,
|
||||
event_type,
|
||||
category,
|
||||
content="",
|
||||
metadata=None,
|
||||
created_at=None,
|
||||
):
|
||||
return self._put_one(
|
||||
thread_id=thread_id,
|
||||
run_id=run_id,
|
||||
event_type=event_type,
|
||||
category=category,
|
||||
content=content,
|
||||
metadata=metadata,
|
||||
created_at=created_at,
|
||||
)
|
||||
|
||||
async def put_batch(self, events):
|
||||
results = []
|
||||
for ev in events:
|
||||
record = self._put_one(**ev)
|
||||
results.append(record)
|
||||
return results
|
||||
|
||||
async def list_messages(self, thread_id, *, limit=50, before_seq=None, after_seq=None):
|
||||
all_events = self._events.get(thread_id, [])
|
||||
messages = [e for e in all_events if e["category"] == "message"]
|
||||
|
||||
if before_seq is not None:
|
||||
messages = [e for e in messages if e["seq"] < before_seq]
|
||||
# Take the last `limit` records
|
||||
return messages[-limit:]
|
||||
elif after_seq is not None:
|
||||
messages = [e for e in messages if e["seq"] > after_seq]
|
||||
return messages[:limit]
|
||||
else:
|
||||
# Return the latest `limit` records, ascending
|
||||
return messages[-limit:]
|
||||
|
||||
async def list_events(self, thread_id, run_id, *, event_types=None, limit=500):
|
||||
all_events = self._events.get(thread_id, [])
|
||||
filtered = [e for e in all_events if e["run_id"] == run_id]
|
||||
if event_types is not None:
|
||||
filtered = [e for e in filtered if e["event_type"] in event_types]
|
||||
return filtered[:limit]
|
||||
|
||||
async def list_messages_by_run(self, thread_id, run_id, *, limit=50, before_seq=None, after_seq=None, user_id=None):
|
||||
# The in-memory store keeps no per-event owner, so user_id is accepted
|
||||
# for interface parity with DbRunEventStore but ignored.
|
||||
all_events = self._events.get(thread_id, [])
|
||||
filtered = [e for e in all_events if e["run_id"] == run_id and e["category"] == "message"]
|
||||
if before_seq is not None:
|
||||
filtered = [e for e in filtered if e["seq"] < before_seq]
|
||||
if after_seq is not None:
|
||||
filtered = [e for e in filtered if e["seq"] > after_seq]
|
||||
if after_seq is not None:
|
||||
return filtered[:limit]
|
||||
else:
|
||||
return filtered[-limit:] if len(filtered) > limit else filtered
|
||||
|
||||
async def count_messages(self, thread_id):
|
||||
all_events = self._events.get(thread_id, [])
|
||||
return sum(1 for e in all_events if e["category"] == "message")
|
||||
|
||||
async def delete_by_thread(self, thread_id):
|
||||
events = self._events.pop(thread_id, [])
|
||||
self._seq_counters.pop(thread_id, None)
|
||||
return len(events)
|
||||
|
||||
async def delete_by_run(self, thread_id, run_id):
|
||||
all_events = self._events.get(thread_id, [])
|
||||
if not all_events:
|
||||
return 0
|
||||
remaining = [e for e in all_events if e["run_id"] != run_id]
|
||||
removed = len(all_events) - len(remaining)
|
||||
self._events[thread_id] = remaining
|
||||
return removed
|
||||
@@ -0,0 +1,410 @@
|
||||
"""Run event capture via LangChain callbacks.
|
||||
|
||||
RunJournal sits between LangChain's callback mechanism and the pluggable
|
||||
RunEventStore. It standardizes callback data into RunEvent records and
|
||||
handles token usage accumulation.
|
||||
|
||||
Key design decisions:
|
||||
- on_llm_new_token is NOT implemented -- only complete messages via on_llm_end
|
||||
- on_chat_model_start captures structured prompts as llm_request (OpenAI format) and
|
||||
extracts the first human message for run.input, because it is more reliable than
|
||||
on_chain_start (fires on every node) — messages here are fully structured.
|
||||
- on_chain_start with parent_run_id=None emits a run.start trace marking root invocation.
|
||||
- on_llm_end emits llm_response in OpenAI Chat Completions format
|
||||
- Token usage accumulated in memory, written to RunRow on run completion
|
||||
- Caller identification via tags injection (lead_agent / subagent:{name} / middleware:{name})
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
from uuid import UUID
|
||||
|
||||
from langchain_core.callbacks import BaseCallbackHandler
|
||||
from langchain_core.messages import AnyMessage, BaseMessage, HumanMessage, ToolMessage
|
||||
from langgraph.types import Command
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from deerflow.runtime.events.store.base import RunEventStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Flush the buffer at least this often (seconds) even when it never fills up.
|
||||
# Live consumers — notably the scheduled-task run-detail page, which polls
|
||||
# ``GET /runs/{rid}/messages`` every 4s — would otherwise see nothing until a
|
||||
# run ends, because a short run can finish before the buffer reaches
|
||||
# ``flush_threshold``.
|
||||
_FLUSH_INTERVAL_SECONDS = 3.0
|
||||
|
||||
|
||||
class RunJournal(BaseCallbackHandler):
|
||||
"""LangChain callback handler that captures events to RunEventStore."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
run_id: str,
|
||||
thread_id: str,
|
||||
event_store: RunEventStore,
|
||||
*,
|
||||
track_token_usage: bool = True,
|
||||
flush_threshold: int = 20,
|
||||
):
|
||||
super().__init__()
|
||||
self.run_id = run_id
|
||||
self.thread_id = thread_id
|
||||
self._store = event_store
|
||||
self._track_tokens = track_token_usage
|
||||
self._flush_threshold = flush_threshold
|
||||
|
||||
# Write buffer
|
||||
self._buffer: list[dict] = []
|
||||
self._pending_flush_tasks: set[asyncio.Task[None]] = set()
|
||||
# Monotonic timestamp of the last flush attempt — drives time-based
|
||||
# flushing so incremental progress is visible to live pollers.
|
||||
self._last_flush_at: float = time.monotonic()
|
||||
|
||||
# Token accumulators
|
||||
self._total_input_tokens = 0
|
||||
self._total_output_tokens = 0
|
||||
self._total_tokens = 0
|
||||
self._llm_call_count = 0
|
||||
|
||||
# Convenience fields
|
||||
self._last_ai_msg: str | None = None
|
||||
self._first_human_msg: str | None = None
|
||||
self._msg_count = 0
|
||||
|
||||
# Latency tracking
|
||||
self._llm_start_times: dict[str, float] = {} # langchain run_id -> start time
|
||||
|
||||
# LLM request/response tracking
|
||||
self._llm_call_index = 0
|
||||
self._seen_llm_starts: set[str] = set() # langchain run_ids that fired on_chat_model_start
|
||||
|
||||
# -- Lifecycle callbacks --
|
||||
|
||||
def on_chain_start(
|
||||
self,
|
||||
serialized: dict[str, Any],
|
||||
inputs: dict[str, Any],
|
||||
*,
|
||||
run_id: UUID,
|
||||
parent_run_id: UUID | None = None,
|
||||
tags: list[str] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
caller = self._identify_caller(tags)
|
||||
if parent_run_id is None:
|
||||
# Root graph invocation — emit a single trace event for the run start.
|
||||
chain_name = (serialized or {}).get("name", "unknown")
|
||||
self._put(
|
||||
event_type="run.start",
|
||||
category="trace",
|
||||
content={"chain": chain_name},
|
||||
metadata={"caller": caller, **(metadata or {})},
|
||||
)
|
||||
|
||||
def on_chain_end(self, outputs: Any, *, run_id: UUID, **kwargs: Any) -> None:
|
||||
self._put(event_type="run.end", category="outputs", content=outputs, metadata={"status": "success"})
|
||||
self._flush_sync()
|
||||
|
||||
def on_chain_error(self, error: BaseException, *, run_id: UUID, **kwargs: Any) -> None:
|
||||
self._put(
|
||||
event_type="run.error",
|
||||
category="error",
|
||||
content=str(error),
|
||||
metadata={"error_type": type(error).__name__},
|
||||
)
|
||||
self._flush_sync()
|
||||
|
||||
# -- LLM callbacks --
|
||||
|
||||
def on_chat_model_start(
|
||||
self,
|
||||
serialized: dict,
|
||||
messages: list[list[BaseMessage]],
|
||||
*,
|
||||
run_id: UUID,
|
||||
tags: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Capture structured prompt messages for llm_request event.
|
||||
|
||||
This is also the canonical place to extract the first human message:
|
||||
messages are fully structured here, it fires only on real LLM calls,
|
||||
and the content is never compressed by checkpoint trimming.
|
||||
"""
|
||||
rid = str(run_id)
|
||||
self._llm_start_times[rid] = time.monotonic()
|
||||
self._llm_call_index += 1
|
||||
self._seen_llm_starts.add(rid)
|
||||
|
||||
logger.debug(
|
||||
"on_chat_model_start %s: tags=%s num_batches=%d message_counts=%s",
|
||||
run_id,
|
||||
tags,
|
||||
len(messages),
|
||||
[len(batch) for batch in messages],
|
||||
)
|
||||
|
||||
# Capture the first human message sent to any LLM in this run.
|
||||
if not self._first_human_msg and messages:
|
||||
for batch in reversed(messages):
|
||||
for m in reversed(batch):
|
||||
if isinstance(m, HumanMessage) and m.name != "summary":
|
||||
caller = self._identify_caller(tags)
|
||||
self.set_first_human_message(m.text)
|
||||
self._put(
|
||||
event_type="llm.human.input",
|
||||
category="message",
|
||||
content=m.model_dump(),
|
||||
metadata={"caller": caller},
|
||||
)
|
||||
break
|
||||
if self._first_human_msg:
|
||||
break
|
||||
|
||||
def on_llm_start(self, serialized: dict, prompts: list[str], *, run_id: UUID, parent_run_id: UUID | None = None, tags: list[str] | None = None, metadata: dict[str, Any] | None = None, **kwargs: Any) -> None:
|
||||
# Fallback: on_chat_model_start is preferred. This just tracks latency.
|
||||
self._llm_start_times[str(run_id)] = time.monotonic()
|
||||
|
||||
def on_llm_end(
|
||||
self,
|
||||
response: Any,
|
||||
*,
|
||||
run_id: UUID,
|
||||
parent_run_id: UUID | None = None,
|
||||
tags: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
messages: list[AnyMessage] = []
|
||||
logger.debug("on_llm_end %s: tags=%s", run_id, tags)
|
||||
for generation in response.generations:
|
||||
for gen in generation:
|
||||
if hasattr(gen, "message"):
|
||||
messages.append(gen.message)
|
||||
else:
|
||||
logger.warning(f"on_llm_end {run_id}: generation has no message attribute: {gen}")
|
||||
|
||||
for message in messages:
|
||||
caller = self._identify_caller(tags)
|
||||
|
||||
# Latency
|
||||
rid = str(run_id)
|
||||
start = self._llm_start_times.pop(rid, None)
|
||||
latency_ms = int((time.monotonic() - start) * 1000) if start else None
|
||||
|
||||
# Token usage from message
|
||||
usage = getattr(message, "usage_metadata", None)
|
||||
usage_dict = dict(usage) if usage else {}
|
||||
|
||||
# Resolve call index
|
||||
call_index = self._llm_call_index
|
||||
if rid not in self._seen_llm_starts:
|
||||
# Fallback: on_chat_model_start was not called
|
||||
self._llm_call_index += 1
|
||||
call_index = self._llm_call_index
|
||||
self._seen_llm_starts.add(rid)
|
||||
|
||||
# Trace event: llm_response (OpenAI completion format)
|
||||
self._put(
|
||||
event_type="llm.ai.response",
|
||||
category="message",
|
||||
content=message.model_dump(),
|
||||
metadata={
|
||||
"caller": caller,
|
||||
"usage": usage_dict,
|
||||
"latency_ms": latency_ms,
|
||||
"llm_call_index": call_index,
|
||||
},
|
||||
)
|
||||
|
||||
# Token accumulation
|
||||
if self._track_tokens:
|
||||
input_tk = usage_dict.get("input_tokens", 0) or 0
|
||||
output_tk = usage_dict.get("output_tokens", 0) or 0
|
||||
total_tk = usage_dict.get("total_tokens", 0) or 0
|
||||
if total_tk == 0:
|
||||
total_tk = input_tk + output_tk
|
||||
if total_tk > 0:
|
||||
self._total_input_tokens += input_tk
|
||||
self._total_output_tokens += output_tk
|
||||
self._total_tokens += total_tk
|
||||
self._llm_call_count += 1
|
||||
|
||||
def on_llm_error(self, error: BaseException, *, run_id: UUID, **kwargs: Any) -> None:
|
||||
self._llm_start_times.pop(str(run_id), None)
|
||||
self._put(event_type="llm.error", category="trace", content=str(error))
|
||||
|
||||
def on_tool_start(self, serialized, input_str, *, run_id, parent_run_id=None, tags=None, metadata=None, inputs=None, **kwargs):
|
||||
"""Handle tool start event, cache tool call ID for later correlation"""
|
||||
tool_call_id = str(run_id)
|
||||
logger.debug("Tool start for node %s, tool_call_id=%s, tags=%s", run_id, tool_call_id, tags)
|
||||
|
||||
def on_tool_end(self, output, *, run_id, parent_run_id=None, **kwargs):
|
||||
"""Handle tool end event, append message and clear node data"""
|
||||
try:
|
||||
if isinstance(output, ToolMessage):
|
||||
msg = cast(ToolMessage, output)
|
||||
self._put(event_type="llm.tool.result", category="message", content=msg.model_dump())
|
||||
elif isinstance(output, Command):
|
||||
cmd = cast(Command, output)
|
||||
messages = cmd.update.get("messages", [])
|
||||
for message in messages:
|
||||
if isinstance(message, BaseMessage):
|
||||
self._put(event_type="llm.tool.result", category="message", content=message.model_dump())
|
||||
else:
|
||||
logger.warning(f"on_tool_end {run_id}: command update message is not BaseMessage: {type(message)}")
|
||||
else:
|
||||
logger.warning(f"on_tool_end {run_id}: output is not ToolMessage: {type(output)}")
|
||||
finally:
|
||||
logger.debug("Tool end for node %s", run_id)
|
||||
|
||||
# -- Internal methods --
|
||||
|
||||
def _put(self, *, event_type: str, category: str, content: str | dict = "", metadata: dict | None = None) -> None:
|
||||
self._buffer.append(
|
||||
{
|
||||
"thread_id": self.thread_id,
|
||||
"run_id": self.run_id,
|
||||
"event_type": event_type,
|
||||
"category": category,
|
||||
"content": content,
|
||||
"metadata": metadata or {},
|
||||
"created_at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
)
|
||||
# Flush on a full buffer, or once enough time has elapsed since the
|
||||
# last flush. The time-based path lets live consumers (the
|
||||
# scheduled-task run-detail page polls every 4s) see incremental
|
||||
# progress even when a run ends before the buffer fills up.
|
||||
if len(self._buffer) >= self._flush_threshold:
|
||||
self._flush_sync()
|
||||
elif time.monotonic() - self._last_flush_at >= _FLUSH_INTERVAL_SECONDS:
|
||||
self._flush_sync()
|
||||
|
||||
def _flush_sync(self) -> None:
|
||||
"""Best-effort flush of buffer to RunEventStore.
|
||||
|
||||
BaseCallbackHandler methods are synchronous. If an event loop is
|
||||
running we schedule an async ``put_batch``; otherwise the events
|
||||
stay in the buffer and are flushed later by the async ``flush()``
|
||||
call in the worker's ``finally`` block.
|
||||
"""
|
||||
if not self._buffer:
|
||||
return
|
||||
# Skip if a flush is already in flight — avoids concurrent writes
|
||||
# to the same SQLite file from multiple fire-and-forget tasks.
|
||||
if self._pending_flush_tasks:
|
||||
return
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
# No event loop — keep events in buffer for later async flush.
|
||||
return
|
||||
batch = self._buffer.copy()
|
||||
self._buffer.clear()
|
||||
self._last_flush_at = time.monotonic()
|
||||
task = loop.create_task(self._flush_async(batch))
|
||||
self._pending_flush_tasks.add(task)
|
||||
task.add_done_callback(self._on_flush_done)
|
||||
|
||||
async def _flush_async(self, batch: list[dict]) -> None:
|
||||
try:
|
||||
await self._store.put_batch(batch)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Failed to flush %d events for run %s — returning to buffer",
|
||||
len(batch),
|
||||
self.run_id,
|
||||
exc_info=True,
|
||||
)
|
||||
# Return failed events to buffer for retry on next flush, then
|
||||
# re-raise so _on_flush_done can tell success from failure.
|
||||
self._buffer = batch + self._buffer
|
||||
raise
|
||||
|
||||
def _on_flush_done(self, task: asyncio.Task) -> None:
|
||||
self._pending_flush_tasks.discard(task)
|
||||
if task.cancelled():
|
||||
return
|
||||
exc = task.exception()
|
||||
if exc:
|
||||
# The batch was already returned to the buffer by _flush_async.
|
||||
# Don't retry here — that would busy-loop on a persistent DB
|
||||
# outage; the next _put (or the final flush()) retries instead.
|
||||
logger.warning("Journal flush task failed: %s", exc)
|
||||
return
|
||||
# Events may have accumulated while this flush was in flight — drain
|
||||
# them now so incremental progress keeps reaching the store without
|
||||
# waiting for the next _put to cross a threshold.
|
||||
if self._buffer:
|
||||
self._flush_sync()
|
||||
|
||||
def _identify_caller(self, tags: list[str] | None) -> str:
|
||||
_tags = tags or []
|
||||
for tag in _tags:
|
||||
if isinstance(tag, str) and (tag.startswith("subagent:") or tag.startswith("middleware:") or tag == "lead_agent"):
|
||||
return tag
|
||||
# Default to lead_agent: the main agent graph does not inject
|
||||
# callback tags, while subagents and middleware explicitly tag
|
||||
# themselves.
|
||||
return "lead_agent"
|
||||
|
||||
# -- Public methods (called by worker) --
|
||||
|
||||
def set_first_human_message(self, content: str) -> None:
|
||||
"""Record the first human message for convenience fields."""
|
||||
self._first_human_msg = content[:2000] if content else None
|
||||
|
||||
def record_middleware(self, tag: str, *, name: str, hook: str, action: str, changes: dict) -> None:
|
||||
"""Record a middleware state-change event.
|
||||
|
||||
Called by middleware implementations when they perform a meaningful
|
||||
state change (e.g., title generation, summarization, HITL approval).
|
||||
Pure-observation middleware should not call this.
|
||||
|
||||
Args:
|
||||
tag: Short identifier for the middleware (e.g., "title", "summarize",
|
||||
"guardrail"). Used to form event_type="middleware:{tag}".
|
||||
name: Full middleware class name.
|
||||
hook: Lifecycle hook that triggered the action (e.g., "after_model").
|
||||
action: Specific action performed (e.g., "generate_title").
|
||||
changes: Dict describing the state changes made.
|
||||
"""
|
||||
self._put(
|
||||
event_type=f"middleware:{tag}",
|
||||
category="middleware",
|
||||
content={"name": name, "hook": hook, "action": action, "changes": changes},
|
||||
)
|
||||
|
||||
async def flush(self) -> None:
|
||||
"""Force flush remaining buffer. Called in worker's finally block."""
|
||||
if self._pending_flush_tasks:
|
||||
await asyncio.gather(*tuple(self._pending_flush_tasks), return_exceptions=True)
|
||||
|
||||
while self._buffer:
|
||||
batch = self._buffer[: self._flush_threshold]
|
||||
del self._buffer[: self._flush_threshold]
|
||||
try:
|
||||
await self._store.put_batch(batch)
|
||||
except Exception:
|
||||
self._buffer = batch + self._buffer
|
||||
raise
|
||||
|
||||
def get_completion_data(self) -> dict:
|
||||
"""Return accumulated token and message data for run completion."""
|
||||
return {
|
||||
"total_input_tokens": self._total_input_tokens,
|
||||
"total_output_tokens": self._total_output_tokens,
|
||||
"total_tokens": self._total_tokens,
|
||||
"llm_call_count": self._llm_call_count,
|
||||
"message_count": self._msg_count,
|
||||
"last_ai_message": self._last_ai_msg,
|
||||
"first_human_message": self._first_human_msg,
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
"""Run lifecycle management for LangGraph Platform API compatibility."""
|
||||
|
||||
from .manager import ConflictError, ModelConcurrencyLimitError, RunManager, RunRecord, UnsupportedStrategyError
|
||||
from .schemas import DisconnectMode, RunStatus
|
||||
from .concurrency_gate import AcquireDecision, AcquireResult, ActiveLease, RedisConcurrencyGate, make_redis_concurrency_gate
|
||||
from .worker import RunContext, run_agent
|
||||
|
||||
__all__ = [
|
||||
"AcquireDecision",
|
||||
"AcquireResult",
|
||||
"ActiveLease",
|
||||
"ConflictError",
|
||||
"DisconnectMode",
|
||||
"ModelConcurrencyLimitError",
|
||||
"RedisConcurrencyGate",
|
||||
"RunContext",
|
||||
"RunManager",
|
||||
"RunRecord",
|
||||
"RunStatus",
|
||||
"UnsupportedStrategyError",
|
||||
"make_redis_concurrency_gate",
|
||||
"run_agent",
|
||||
]
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
"""Optional cross-worker run concurrency gates.
|
||||
|
||||
The Redis gate is deliberately fail-open by default: Redis coordinates global
|
||||
limits when it is fast and healthy, but it must not block the chat path when it
|
||||
is slow or unavailable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
from deerflow.config.concurrency_config import RedisConcurrencyConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AcquireDecision(str, Enum):
|
||||
ACQUIRED = "acquired"
|
||||
REJECTED = "rejected"
|
||||
DEGRADED = "degraded"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AcquireResult:
|
||||
decision: AcquireDecision
|
||||
reason: str = ""
|
||||
source: str = "redis"
|
||||
|
||||
@property
|
||||
def acquired(self) -> bool:
|
||||
return self.decision == AcquireDecision.ACQUIRED
|
||||
|
||||
@property
|
||||
def rejected(self) -> bool:
|
||||
return self.decision == AcquireDecision.REJECTED
|
||||
|
||||
@property
|
||||
def degraded(self) -> bool:
|
||||
return self.decision == AcquireDecision.DEGRADED
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ActiveLease:
|
||||
run_id: str
|
||||
thread_id: str = ""
|
||||
model_name: str = ""
|
||||
user_id: str = ""
|
||||
assistant_id: str = ""
|
||||
created_at: float = 0.0
|
||||
expires_at: float = 0.0
|
||||
|
||||
|
||||
class CircuitBreaker:
|
||||
"""Tiny in-process circuit breaker for Redis failures."""
|
||||
|
||||
def __init__(self, *, failure_threshold: int, cooldown_seconds: int) -> None:
|
||||
self._failure_threshold = max(1, int(failure_threshold))
|
||||
self._cooldown_seconds = max(1, int(cooldown_seconds))
|
||||
self._failures = 0
|
||||
self._opened_until = 0.0
|
||||
|
||||
def allow(self) -> bool:
|
||||
return time.monotonic() >= self._opened_until
|
||||
|
||||
def record_success(self) -> None:
|
||||
self._failures = 0
|
||||
self._opened_until = 0.0
|
||||
|
||||
def record_failure(self) -> None:
|
||||
self._failures += 1
|
||||
if self._failures >= self._failure_threshold:
|
||||
self._opened_until = time.monotonic() + self._cooldown_seconds
|
||||
|
||||
@property
|
||||
def open(self) -> bool:
|
||||
return not self.allow()
|
||||
|
||||
|
||||
class RedisConcurrencyGate:
|
||||
"""Redis lease-based global concurrency limiter."""
|
||||
|
||||
_ACQUIRE_SCRIPT = """
|
||||
local now = tonumber(ARGV[1])
|
||||
local expires_at = tonumber(ARGV[2])
|
||||
local run_id = ARGV[3]
|
||||
local model_limit = tonumber(ARGV[4])
|
||||
local user_model_limit = tonumber(ARGV[5])
|
||||
local reject_thread = tonumber(ARGV[6])
|
||||
local payload = ARGV[7]
|
||||
local ttl_ms = tonumber(ARGV[8])
|
||||
|
||||
for i = 1, 4 do
|
||||
redis.call('ZREMRANGEBYSCORE', KEYS[i], '-inf', now)
|
||||
end
|
||||
|
||||
if reject_thread == 1 and redis.call('ZCARD', KEYS[4]) > 0 then
|
||||
return {'rejected', 'thread'}
|
||||
end
|
||||
if model_limit > 0 and redis.call('ZCARD', KEYS[2]) >= model_limit then
|
||||
return {'rejected', 'model'}
|
||||
end
|
||||
if user_model_limit > 0 and redis.call('ZCARD', KEYS[3]) >= user_model_limit then
|
||||
return {'rejected', 'user_model'}
|
||||
end
|
||||
|
||||
redis.call('ZADD', KEYS[1], expires_at, run_id)
|
||||
redis.call('ZADD', KEYS[2], expires_at, run_id)
|
||||
if user_model_limit > 0 then
|
||||
redis.call('ZADD', KEYS[3], expires_at, run_id)
|
||||
end
|
||||
redis.call('ZADD', KEYS[4], expires_at, run_id)
|
||||
redis.call('SET', KEYS[5], payload, 'PX', ttl_ms)
|
||||
return {'acquired', ''}
|
||||
"""
|
||||
|
||||
def __init__(self, config: RedisConcurrencyConfig) -> None:
|
||||
self.config = config
|
||||
self._client: Any | None = None
|
||||
self._breaker = CircuitBreaker(
|
||||
failure_threshold=config.circuit_breaker_failures,
|
||||
cooldown_seconds=config.circuit_breaker_cooldown_seconds,
|
||||
)
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return bool(self.config.enabled and self.config.url)
|
||||
|
||||
def health(self) -> dict[str, Any]:
|
||||
return {
|
||||
"enabled": self.enabled,
|
||||
"source": "redis",
|
||||
"circuit_open": self._breaker.open,
|
||||
"fail_open": self.config.fail_open,
|
||||
}
|
||||
|
||||
async def aclose(self) -> None:
|
||||
client = self._client
|
||||
self._client = None
|
||||
if client is not None:
|
||||
try:
|
||||
await client.aclose()
|
||||
except Exception:
|
||||
logger.debug("Failed to close Redis concurrency client", exc_info=True)
|
||||
|
||||
def _ns(self) -> str:
|
||||
return self.config.namespace.strip().rstrip(":") or "cmzs_deerflow:concurrency"
|
||||
|
||||
def _keys(self, *, run_id: str, model_name: str, user_id: str, thread_id: str) -> list[str]:
|
||||
ns = self._ns()
|
||||
return [
|
||||
f"{ns}:all",
|
||||
f"{ns}:model:{model_name}",
|
||||
f"{ns}:user_model:{model_name}:{user_id}",
|
||||
f"{ns}:thread:{thread_id}",
|
||||
f"{ns}:run:{run_id}",
|
||||
]
|
||||
|
||||
async def _redis(self) -> Any:
|
||||
if self._client is not None:
|
||||
return self._client
|
||||
try:
|
||||
from redis.asyncio import Redis
|
||||
except Exception as exc: # pragma: no cover - exercised when dependency is absent
|
||||
raise RuntimeError("redis package is not installed") from exc
|
||||
|
||||
timeout = max(0.001, self.config.socket_timeout_ms / 1000)
|
||||
connect_timeout = max(0.001, self.config.socket_connect_timeout_ms / 1000)
|
||||
self._client = Redis.from_url(
|
||||
self.config.url,
|
||||
password=self.config.password,
|
||||
socket_timeout=timeout,
|
||||
socket_connect_timeout=connect_timeout,
|
||||
decode_responses=True,
|
||||
)
|
||||
return self._client
|
||||
|
||||
async def _with_timeout(self, coro, timeout_ms: int) -> Any:
|
||||
return await asyncio.wait_for(coro, timeout=max(0.001, timeout_ms / 1000))
|
||||
|
||||
def _degraded(self, reason: str) -> AcquireResult:
|
||||
return AcquireResult(AcquireDecision.DEGRADED, reason=reason)
|
||||
|
||||
def _on_failure(self, action: str, exc: BaseException) -> None:
|
||||
self._breaker.record_failure()
|
||||
logger.warning(
|
||||
"Redis concurrency %s failed; fail_open=%s circuit_open=%s: %s",
|
||||
action,
|
||||
self.config.fail_open,
|
||||
self._breaker.open,
|
||||
exc,
|
||||
)
|
||||
|
||||
async def try_acquire(
|
||||
self,
|
||||
*,
|
||||
run_id: str,
|
||||
thread_id: str,
|
||||
model_name: str,
|
||||
user_id: str,
|
||||
assistant_id: str = "",
|
||||
model_limit: int | None = None,
|
||||
user_model_limit: int | None = None,
|
||||
reject_thread: bool = True,
|
||||
) -> AcquireResult:
|
||||
if not self.enabled:
|
||||
return self._degraded("disabled")
|
||||
if not self._breaker.allow():
|
||||
return self._degraded("circuit_open")
|
||||
|
||||
now = time.time()
|
||||
expires_at = now + self.config.lease_ttl_seconds
|
||||
payload = {
|
||||
"run_id": run_id,
|
||||
"thread_id": thread_id,
|
||||
"model_name": model_name,
|
||||
"user_id": user_id,
|
||||
"assistant_id": assistant_id,
|
||||
"created_at": now,
|
||||
"expires_at": expires_at,
|
||||
}
|
||||
import json
|
||||
|
||||
keys = self._keys(run_id=run_id, model_name=model_name, user_id=user_id, thread_id=thread_id)
|
||||
ttl_ms = int(self.config.lease_ttl_seconds * 1000)
|
||||
try:
|
||||
client = await self._redis()
|
||||
raw = await self._with_timeout(
|
||||
client.eval(
|
||||
self._ACQUIRE_SCRIPT,
|
||||
len(keys),
|
||||
*keys,
|
||||
str(now),
|
||||
str(expires_at),
|
||||
run_id,
|
||||
str(max(0, int(model_limit or 0))),
|
||||
str(max(0, int(user_model_limit or 0))),
|
||||
"1" if reject_thread else "0",
|
||||
json.dumps(payload, ensure_ascii=False),
|
||||
str(ttl_ms),
|
||||
),
|
||||
self.config.acquire_timeout_ms,
|
||||
)
|
||||
self._breaker.record_success()
|
||||
except Exception as exc:
|
||||
self._on_failure("acquire", exc)
|
||||
if self.config.fail_open:
|
||||
return self._degraded(type(exc).__name__)
|
||||
raise
|
||||
|
||||
status = raw[0] if isinstance(raw, list) and raw else ""
|
||||
reason = raw[1] if isinstance(raw, list) and len(raw) > 1 else ""
|
||||
if status == "acquired":
|
||||
return AcquireResult(AcquireDecision.ACQUIRED)
|
||||
return AcquireResult(AcquireDecision.REJECTED, reason=str(reason or "limit"))
|
||||
|
||||
async def heartbeat(
|
||||
self,
|
||||
*,
|
||||
run_id: str,
|
||||
thread_id: str,
|
||||
model_name: str,
|
||||
user_id: str,
|
||||
user_model_accounted: bool = True,
|
||||
) -> None:
|
||||
if not self.enabled or not self._breaker.allow():
|
||||
return
|
||||
now = time.time()
|
||||
expires_at = now + self.config.lease_ttl_seconds
|
||||
keys = self._keys(run_id=run_id, model_name=model_name, user_id=user_id, thread_id=thread_id)
|
||||
try:
|
||||
client = await self._redis()
|
||||
pipe = client.pipeline(transaction=False)
|
||||
refresh_keys = [keys[0], keys[1], keys[3]]
|
||||
if user_model_accounted:
|
||||
refresh_keys.append(keys[2])
|
||||
for key in refresh_keys:
|
||||
pipe.zadd(key, {run_id: expires_at})
|
||||
pipe.expire(keys[4], self.config.lease_ttl_seconds)
|
||||
await self._with_timeout(pipe.execute(), self.config.operation_timeout_ms)
|
||||
self._breaker.record_success()
|
||||
except Exception as exc:
|
||||
self._on_failure("heartbeat", exc)
|
||||
|
||||
async def release(
|
||||
self,
|
||||
*,
|
||||
run_id: str,
|
||||
thread_id: str,
|
||||
model_name: str,
|
||||
user_id: str,
|
||||
user_model_accounted: bool = True,
|
||||
) -> None:
|
||||
if not self.enabled or not self._breaker.allow():
|
||||
return
|
||||
keys = self._keys(run_id=run_id, model_name=model_name, user_id=user_id, thread_id=thread_id)
|
||||
try:
|
||||
client = await self._redis()
|
||||
pipe = client.pipeline(transaction=False)
|
||||
release_keys = [keys[0], keys[1], keys[3]]
|
||||
if user_model_accounted:
|
||||
release_keys.append(keys[2])
|
||||
for key in release_keys:
|
||||
pipe.zrem(key, run_id)
|
||||
pipe.delete(keys[4])
|
||||
await self._with_timeout(pipe.execute(), self.config.operation_timeout_ms)
|
||||
self._breaker.record_success()
|
||||
except Exception as exc:
|
||||
self._on_failure("release", exc)
|
||||
|
||||
async def count_active(self) -> int | None:
|
||||
if not self.enabled or not self._breaker.allow():
|
||||
return None
|
||||
key = f"{self._ns()}:all"
|
||||
now = time.time()
|
||||
try:
|
||||
client = await self._redis()
|
||||
pipe = client.pipeline(transaction=False)
|
||||
pipe.zremrangebyscore(key, "-inf", now)
|
||||
pipe.zcard(key)
|
||||
result = await self._with_timeout(pipe.execute(), self.config.operation_timeout_ms)
|
||||
self._breaker.record_success()
|
||||
return int(result[-1] or 0)
|
||||
except Exception as exc:
|
||||
self._on_failure("count", exc)
|
||||
return None
|
||||
|
||||
async def list_active(self, *, limit: int = 1000) -> list[ActiveLease] | None:
|
||||
if not self.enabled or not self._breaker.allow():
|
||||
return None
|
||||
import json
|
||||
|
||||
all_key = f"{self._ns()}:all"
|
||||
now = time.time()
|
||||
try:
|
||||
client = await self._redis()
|
||||
await self._with_timeout(client.zremrangebyscore(all_key, "-inf", now), self.config.operation_timeout_ms)
|
||||
run_ids = await self._with_timeout(client.zrange(all_key, 0, max(0, limit - 1)), self.config.operation_timeout_ms)
|
||||
if not run_ids:
|
||||
self._breaker.record_success()
|
||||
return []
|
||||
keys = [f"{self._ns()}:run:{run_id}" for run_id in run_ids]
|
||||
payloads = await self._with_timeout(client.mget(keys), self.config.operation_timeout_ms)
|
||||
leases: list[ActiveLease] = []
|
||||
for run_id, payload in zip(run_ids, payloads, strict=False):
|
||||
if not payload:
|
||||
continue
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
except Exception:
|
||||
continue
|
||||
leases.append(
|
||||
ActiveLease(
|
||||
run_id=str(data.get("run_id") or run_id),
|
||||
thread_id=str(data.get("thread_id") or ""),
|
||||
model_name=str(data.get("model_name") or ""),
|
||||
user_id=str(data.get("user_id") or ""),
|
||||
assistant_id=str(data.get("assistant_id") or ""),
|
||||
created_at=float(data.get("created_at") or 0),
|
||||
expires_at=float(data.get("expires_at") or 0),
|
||||
)
|
||||
)
|
||||
self._breaker.record_success()
|
||||
return leases
|
||||
except Exception as exc:
|
||||
self._on_failure("list", exc)
|
||||
return None
|
||||
|
||||
|
||||
def make_redis_concurrency_gate(config: Any) -> RedisConcurrencyGate | None:
|
||||
concurrency = getattr(config, "concurrency", None)
|
||||
redis_config = getattr(concurrency, "redis", None)
|
||||
if redis_config is None or not getattr(redis_config, "enabled", False) or not getattr(redis_config, "url", None):
|
||||
return None
|
||||
return RedisConcurrencyGate(redis_config)
|
||||
@@ -0,0 +1,343 @@
|
||||
"""In-memory run registry with optional persistent RunStore backing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from deerflow.utils.time import now_iso as _now_iso
|
||||
|
||||
from .schemas import DisconnectMode, RunStatus
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from deerflow.runtime.runs.store.base import RunStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RunRecord:
|
||||
"""Mutable record for a single run."""
|
||||
|
||||
run_id: str
|
||||
thread_id: str
|
||||
assistant_id: str | None
|
||||
status: RunStatus
|
||||
on_disconnect: DisconnectMode
|
||||
multitask_strategy: str = "reject"
|
||||
metadata: dict = field(default_factory=dict)
|
||||
kwargs: dict = field(default_factory=dict)
|
||||
created_at: str = ""
|
||||
updated_at: str = ""
|
||||
task: asyncio.Task | None = field(default=None, repr=False)
|
||||
abort_event: asyncio.Event = field(default_factory=asyncio.Event, repr=False)
|
||||
abort_action: str = "interrupt"
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class RunManager:
|
||||
"""In-memory run registry with optional persistent RunStore backing.
|
||||
|
||||
All mutations are protected by an asyncio lock. When a ``store`` is
|
||||
provided, serializable metadata is also persisted to the store so
|
||||
that run history survives process restarts.
|
||||
"""
|
||||
|
||||
def __init__(self, store: RunStore | None = None) -> None:
|
||||
self._runs: dict[str, RunRecord] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
self._store = store
|
||||
|
||||
async def _persist_to_store(self, record: RunRecord) -> None:
|
||||
"""Best-effort persist run record to backing store."""
|
||||
if self._store is None:
|
||||
return
|
||||
try:
|
||||
await self._store.put(
|
||||
record.run_id,
|
||||
thread_id=record.thread_id,
|
||||
assistant_id=record.assistant_id,
|
||||
status=record.status.value,
|
||||
multitask_strategy=record.multitask_strategy,
|
||||
metadata=record.metadata or {},
|
||||
kwargs=record.kwargs or {},
|
||||
created_at=record.created_at,
|
||||
)
|
||||
except Exception:
|
||||
logger.warning("Failed to persist run %s to store", record.run_id, exc_info=True)
|
||||
|
||||
async def update_run_completion(self, run_id: str, **kwargs) -> None:
|
||||
"""Persist token usage and completion data to the backing store."""
|
||||
if self._store is not None:
|
||||
try:
|
||||
await self._store.update_run_completion(run_id, **kwargs)
|
||||
except Exception:
|
||||
logger.warning("Failed to persist run completion for %s", run_id, exc_info=True)
|
||||
|
||||
async def create(
|
||||
self,
|
||||
thread_id: str,
|
||||
assistant_id: str | None = None,
|
||||
*,
|
||||
on_disconnect: DisconnectMode = DisconnectMode.cancel,
|
||||
metadata: dict | None = None,
|
||||
kwargs: dict | None = None,
|
||||
multitask_strategy: str = "reject",
|
||||
) -> RunRecord:
|
||||
"""Create a new pending run and register it."""
|
||||
run_id = str(uuid.uuid4())
|
||||
now = _now_iso()
|
||||
record = RunRecord(
|
||||
run_id=run_id,
|
||||
thread_id=thread_id,
|
||||
assistant_id=assistant_id,
|
||||
status=RunStatus.pending,
|
||||
on_disconnect=on_disconnect,
|
||||
multitask_strategy=multitask_strategy,
|
||||
metadata=metadata or {},
|
||||
kwargs=kwargs or {},
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
async with self._lock:
|
||||
self._runs[run_id] = record
|
||||
await self._persist_to_store(record)
|
||||
logger.info("Run created: run_id=%s thread_id=%s", run_id, thread_id)
|
||||
return record
|
||||
|
||||
def get(self, run_id: str) -> RunRecord | None:
|
||||
"""Return a run record by ID, or ``None``."""
|
||||
return self._runs.get(run_id)
|
||||
|
||||
def _record_from_store(self, data: dict) -> RunRecord:
|
||||
"""Rebuild a :class:`RunRecord` from a persisted store row.
|
||||
|
||||
The reconstructed record has no live ``task``/``abort_event`` wired to a
|
||||
running coroutine — it represents *history*, not an in-flight run.
|
||||
"""
|
||||
try:
|
||||
status = RunStatus(data.get("status") or RunStatus.success.value)
|
||||
except ValueError:
|
||||
status = RunStatus.success
|
||||
return RunRecord(
|
||||
run_id=data["run_id"],
|
||||
thread_id=data["thread_id"],
|
||||
assistant_id=data.get("assistant_id"),
|
||||
status=status,
|
||||
# Disconnect mode is irrelevant for a store-only record (no task to
|
||||
# cancel); ``continue_`` keeps sse_consumer's finally block a no-op.
|
||||
on_disconnect=DisconnectMode.continue_,
|
||||
multitask_strategy=data.get("multitask_strategy", "reject"),
|
||||
metadata=data.get("metadata") or {},
|
||||
kwargs=data.get("kwargs") or {},
|
||||
created_at=data.get("created_at") or "",
|
||||
updated_at=data.get("updated_at") or "",
|
||||
error=data.get("error"),
|
||||
)
|
||||
|
||||
async def get_persisted(self, run_id: str) -> RunRecord | None:
|
||||
"""Load a run from the backing store (process-restart fallback).
|
||||
|
||||
The in-memory registry is wiped on every Gateway restart, but the
|
||||
``RunStore`` row survives. When :meth:`get` misses, callers fall back
|
||||
here so a stale ``joinStream``/``GET run`` can report the run's final
|
||||
status instead of 404ing. Returns ``None`` when there is no store, no
|
||||
matching row, or the lookup fails (e.g. no user context).
|
||||
"""
|
||||
if self._store is None:
|
||||
return None
|
||||
try:
|
||||
data = await self._store.get(run_id)
|
||||
except Exception:
|
||||
logger.warning("Failed to load run %s from store", run_id, exc_info=True)
|
||||
return None
|
||||
if not data:
|
||||
return None
|
||||
return self._record_from_store(data)
|
||||
|
||||
async def list_by_thread(self, thread_id: str) -> list[RunRecord]:
|
||||
"""Return all runs for a given thread, newest first."""
|
||||
async with self._lock:
|
||||
# Dict insertion order matches creation order, so reversing it gives
|
||||
# us deterministic newest-first results even when timestamps tie.
|
||||
return [r for r in self._runs.values() if r.thread_id == thread_id]
|
||||
|
||||
async def set_status(self, run_id: str, status: RunStatus, *, error: str | None = None) -> None:
|
||||
"""Transition a run to a new status."""
|
||||
async with self._lock:
|
||||
record = self._runs.get(run_id)
|
||||
if record is None:
|
||||
logger.warning("set_status called for unknown run %s", run_id)
|
||||
return
|
||||
record.status = status
|
||||
record.updated_at = _now_iso()
|
||||
if error is not None:
|
||||
record.error = error
|
||||
if self._store is not None:
|
||||
try:
|
||||
await self._store.update_status(run_id, status.value, error=error)
|
||||
except Exception:
|
||||
logger.warning("Failed to persist status update for run %s", run_id, exc_info=True)
|
||||
logger.info("Run %s -> %s", run_id, status.value)
|
||||
|
||||
async def cancel(self, run_id: str, *, action: str = "interrupt") -> bool:
|
||||
"""Request cancellation of a run.
|
||||
|
||||
Args:
|
||||
run_id: The run ID to cancel.
|
||||
action: "interrupt" keeps checkpoint, "rollback" reverts to pre-run state.
|
||||
|
||||
Sets the abort event with the action reason and cancels the asyncio task.
|
||||
Returns ``True`` if cancellation was initiated or the run was already stopped.
|
||||
"""
|
||||
async with self._lock:
|
||||
record = self._runs.get(run_id)
|
||||
if record is None:
|
||||
return True
|
||||
if record.status not in (RunStatus.pending, RunStatus.running):
|
||||
return True
|
||||
record.abort_action = action
|
||||
record.abort_event.set()
|
||||
if record.task is not None and not record.task.done():
|
||||
record.task.cancel()
|
||||
record.status = RunStatus.interrupted
|
||||
record.updated_at = _now_iso()
|
||||
logger.info("Run %s cancelled (action=%s)", run_id, action)
|
||||
return True
|
||||
|
||||
async def create_or_reject(
|
||||
self,
|
||||
thread_id: str,
|
||||
assistant_id: str | None = None,
|
||||
*,
|
||||
on_disconnect: DisconnectMode = DisconnectMode.cancel,
|
||||
metadata: dict | None = None,
|
||||
kwargs: dict | None = None,
|
||||
multitask_strategy: str = "reject",
|
||||
model_concurrency_limit: tuple[str, int] | None = None,
|
||||
user_model_concurrency_limit: tuple[str, str, int] | None = None,
|
||||
run_id: str | None = None,
|
||||
) -> RunRecord:
|
||||
"""Atomically check for inflight runs and create a new one.
|
||||
|
||||
For ``reject`` strategy, raises ``ConflictError`` if thread
|
||||
already has a pending/running run. For ``interrupt``/``rollback``,
|
||||
cancels inflight runs before creating.
|
||||
|
||||
This method holds the lock across both the check and the insert,
|
||||
eliminating the TOCTOU race in separate ``has_inflight`` + ``create``.
|
||||
"""
|
||||
run_id = run_id or str(uuid.uuid4())
|
||||
now = _now_iso()
|
||||
|
||||
_supported_strategies = ("reject", "interrupt", "rollback")
|
||||
|
||||
async with self._lock:
|
||||
if multitask_strategy not in _supported_strategies:
|
||||
raise UnsupportedStrategyError(f"Multitask strategy '{multitask_strategy}' is not yet supported. Supported strategies: {', '.join(_supported_strategies)}")
|
||||
|
||||
inflight = [r for r in self._runs.values() if r.thread_id == thread_id and r.status in (RunStatus.pending, RunStatus.running)]
|
||||
|
||||
if multitask_strategy == "reject" and inflight:
|
||||
raise ConflictError(f"Thread {thread_id} already has an active run")
|
||||
|
||||
if multitask_strategy in ("interrupt", "rollback") and inflight:
|
||||
for r in inflight:
|
||||
r.abort_action = multitask_strategy
|
||||
r.abort_event.set()
|
||||
if r.task is not None and not r.task.done():
|
||||
r.task.cancel()
|
||||
r.status = RunStatus.interrupted
|
||||
r.updated_at = now
|
||||
logger.info(
|
||||
"Cancelled %d inflight run(s) on thread %s (strategy=%s)",
|
||||
len(inflight),
|
||||
thread_id,
|
||||
multitask_strategy,
|
||||
)
|
||||
|
||||
if model_concurrency_limit is not None:
|
||||
model_name, limit = model_concurrency_limit
|
||||
active_for_model = sum(1 for r in self._runs.values() if r.status in (RunStatus.pending, RunStatus.running) and str((r.metadata or {}).get("model_name") or "").strip() == model_name)
|
||||
if active_for_model >= max(1, int(limit)):
|
||||
raise ModelConcurrencyLimitError(model_name, limit, scope="model")
|
||||
|
||||
if user_model_concurrency_limit is not None:
|
||||
model_name, user_id, limit = user_model_concurrency_limit
|
||||
active_for_user_model = sum(
|
||||
1
|
||||
for r in self._runs.values()
|
||||
if r.status in (RunStatus.pending, RunStatus.running)
|
||||
and str((r.metadata or {}).get("model_name") or "").strip() == model_name
|
||||
and str((r.metadata or {}).get("user_id") or "").strip() == user_id
|
||||
and str((r.metadata or {}).get("run_scope") or "external_root").strip() == "external_root"
|
||||
)
|
||||
if active_for_user_model >= max(1, int(limit)):
|
||||
raise ModelConcurrencyLimitError(model_name, limit, scope="user_model", user_id=user_id)
|
||||
|
||||
record = RunRecord(
|
||||
run_id=run_id,
|
||||
thread_id=thread_id,
|
||||
assistant_id=assistant_id,
|
||||
status=RunStatus.pending,
|
||||
on_disconnect=on_disconnect,
|
||||
multitask_strategy=multitask_strategy,
|
||||
metadata=metadata or {},
|
||||
kwargs=kwargs or {},
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
self._runs[run_id] = record
|
||||
|
||||
await self._persist_to_store(record)
|
||||
logger.info("Run created: run_id=%s thread_id=%s", run_id, thread_id)
|
||||
return record
|
||||
|
||||
async def has_inflight(self, thread_id: str) -> bool:
|
||||
"""Return ``True`` if *thread_id* has a pending or running run."""
|
||||
async with self._lock:
|
||||
return any(r.thread_id == thread_id and r.status in (RunStatus.pending, RunStatus.running) for r in self._runs.values())
|
||||
|
||||
async def list_active(self) -> list[RunRecord]:
|
||||
"""Return every in-flight run (status pending/running), oldest first.
|
||||
|
||||
Powers the admin concurrency monitor: each record represents one live
|
||||
call into the model runtime (interactive chat, agent chat, roundtable
|
||||
seat, …), so ``len(list_active())`` is the current concurrent-call count
|
||||
and each record can be cancelled to relieve model pressure. Completed
|
||||
records linger in ``_runs`` until :meth:`cleanup`, so we filter by status
|
||||
rather than returning the whole registry.
|
||||
"""
|
||||
async with self._lock:
|
||||
# Dict insertion order == creation order, so this is oldest-first.
|
||||
return [r for r in self._runs.values() if r.status in (RunStatus.pending, RunStatus.running)]
|
||||
|
||||
async def cleanup(self, run_id: str, *, delay: float = 300) -> None:
|
||||
"""Remove a run record after an optional delay."""
|
||||
if delay > 0:
|
||||
await asyncio.sleep(delay)
|
||||
async with self._lock:
|
||||
self._runs.pop(run_id, None)
|
||||
logger.debug("Run record %s cleaned up", run_id)
|
||||
|
||||
|
||||
class ConflictError(Exception):
|
||||
"""Raised when multitask_strategy=reject and thread has inflight runs."""
|
||||
|
||||
|
||||
class ModelConcurrencyLimitError(Exception):
|
||||
"""Raised when a model-specific in-flight run limit has been reached."""
|
||||
|
||||
def __init__(self, model_name: str, limit: int, *, scope: str = "model", user_id: str | None = None) -> None:
|
||||
self.model_name = model_name
|
||||
self.limit = limit
|
||||
self.scope = scope
|
||||
self.user_id = user_id
|
||||
super().__init__(f"Model {model_name} has reached its concurrency limit")
|
||||
|
||||
|
||||
class UnsupportedStrategyError(Exception):
|
||||
"""Raised when a multitask_strategy value is not yet implemented."""
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
"""Small in-memory gate used by legacy model-concurrency tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
|
||||
class ModelConcurrencyGate:
|
||||
"""Track per-model active counts with atomic try-acquire semantics."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = asyncio.Lock()
|
||||
self._counts: dict[str, int] = {}
|
||||
|
||||
async def try_acquire(self, model_name: str, limit: int) -> bool:
|
||||
key = str(model_name).strip()
|
||||
if not key:
|
||||
return True
|
||||
async with self._lock:
|
||||
current = self._counts.get(key, 0)
|
||||
if current >= max(1, int(limit)):
|
||||
return False
|
||||
self._counts[key] = current + 1
|
||||
return True
|
||||
|
||||
async def release(self, model_name: str) -> None:
|
||||
key = str(model_name).strip()
|
||||
if not key:
|
||||
return
|
||||
async with self._lock:
|
||||
current = self._counts.get(key, 0)
|
||||
if current <= 1:
|
||||
self._counts.pop(key, None)
|
||||
else:
|
||||
self._counts[key] = current - 1
|
||||
|
||||
async def snapshot(self) -> dict[str, int]:
|
||||
async with self._lock:
|
||||
return dict(self._counts)
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Run status and disconnect mode enums."""
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class RunStatus(StrEnum):
|
||||
"""Lifecycle status of a single run."""
|
||||
|
||||
pending = "pending"
|
||||
running = "running"
|
||||
success = "success"
|
||||
error = "error"
|
||||
timeout = "timeout"
|
||||
interrupted = "interrupted"
|
||||
|
||||
|
||||
class DisconnectMode(StrEnum):
|
||||
"""Behaviour when the SSE consumer disconnects."""
|
||||
|
||||
cancel = "cancel"
|
||||
continue_ = "continue"
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
from deerflow.runtime.runs.store.base import RunStore
|
||||
from deerflow.runtime.runs.store.memory import MemoryRunStore
|
||||
|
||||
__all__ = ["MemoryRunStore", "RunStore"]
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
"""Abstract interface for run metadata storage.
|
||||
|
||||
RunManager depends on this interface. Implementations:
|
||||
- MemoryRunStore: in-memory dict (development, tests)
|
||||
- Future: RunRepository backed by SQLAlchemy ORM
|
||||
|
||||
All methods accept an optional user_id for user isolation.
|
||||
When user_id is None, no user filtering is applied (single-user mode).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
from typing import Any
|
||||
|
||||
|
||||
class RunStore(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
async def put(
|
||||
self,
|
||||
run_id: str,
|
||||
*,
|
||||
thread_id: str,
|
||||
assistant_id: str | None = None,
|
||||
user_id: str | None = None,
|
||||
status: str = "pending",
|
||||
multitask_strategy: str = "reject",
|
||||
metadata: dict[str, Any] | None = None,
|
||||
kwargs: dict[str, Any] | None = None,
|
||||
error: str | None = None,
|
||||
created_at: str | None = None,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get(self, run_id: str) -> dict[str, Any] | None:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
async def list_by_thread(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
user_id: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> list[dict[str, Any]]:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
async def update_status(
|
||||
self,
|
||||
run_id: str,
|
||||
status: str,
|
||||
*,
|
||||
error: str | None = None,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
async def delete(self, run_id: str) -> None:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
async def update_run_completion(
|
||||
self,
|
||||
run_id: str,
|
||||
*,
|
||||
status: str,
|
||||
total_input_tokens: int = 0,
|
||||
total_output_tokens: int = 0,
|
||||
total_tokens: int = 0,
|
||||
llm_call_count: int = 0,
|
||||
lead_agent_tokens: int = 0,
|
||||
subagent_tokens: int = 0,
|
||||
middleware_tokens: int = 0,
|
||||
message_count: int = 0,
|
||||
last_ai_message: str | None = None,
|
||||
first_human_message: str | None = None,
|
||||
error: str | None = None,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
async def list_pending(self, *, before: str | None = None) -> list[dict[str, Any]]:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
async def aggregate_tokens_by_thread(self, thread_id: str) -> dict[str, Any]:
|
||||
"""Aggregate token usage for completed runs in a thread.
|
||||
|
||||
Returns a dict with keys: total_tokens, total_input_tokens,
|
||||
total_output_tokens, total_runs, by_model (model_name → {tokens, runs}),
|
||||
by_caller ({lead_agent, subagent, middleware}).
|
||||
"""
|
||||
pass
|
||||
|
||||
async def count_by_user(self) -> dict[str, int]:
|
||||
"""Return ``{user_id: run_count}`` across all runs.
|
||||
|
||||
One run corresponds to one user submission, so this backs the admin
|
||||
user center's 问答次数 (Q&A count) column — each question counts once.
|
||||
Non-overriding stores return an empty mapping (treated as 0 per user).
|
||||
"""
|
||||
return {}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
"""In-memory RunStore. Used when database.backend=memory (default) and in tests.
|
||||
|
||||
Equivalent to the original RunManager._runs dict behavior.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from deerflow.runtime.runs.store.base import RunStore
|
||||
|
||||
|
||||
class MemoryRunStore(RunStore):
|
||||
def __init__(self) -> None:
|
||||
self._runs: dict[str, dict[str, Any]] = {}
|
||||
|
||||
async def put(
|
||||
self,
|
||||
run_id,
|
||||
*,
|
||||
thread_id,
|
||||
assistant_id=None,
|
||||
user_id=None,
|
||||
status="pending",
|
||||
multitask_strategy="reject",
|
||||
metadata=None,
|
||||
kwargs=None,
|
||||
error=None,
|
||||
created_at=None,
|
||||
):
|
||||
now = datetime.now(UTC).isoformat()
|
||||
self._runs[run_id] = {
|
||||
"run_id": run_id,
|
||||
"thread_id": thread_id,
|
||||
"assistant_id": assistant_id,
|
||||
"user_id": user_id,
|
||||
"status": status,
|
||||
"multitask_strategy": multitask_strategy,
|
||||
"metadata": metadata or {},
|
||||
"kwargs": kwargs or {},
|
||||
"error": error,
|
||||
"created_at": created_at or now,
|
||||
"updated_at": now,
|
||||
}
|
||||
|
||||
async def get(self, run_id):
|
||||
return self._runs.get(run_id)
|
||||
|
||||
async def list_by_thread(self, thread_id, *, user_id=None, limit=100):
|
||||
results = [r for r in self._runs.values() if r["thread_id"] == thread_id and (user_id is None or r.get("user_id") == user_id)]
|
||||
results.sort(key=lambda r: r["created_at"], reverse=True)
|
||||
return results[:limit]
|
||||
|
||||
async def update_status(self, run_id, status, *, error=None):
|
||||
if run_id in self._runs:
|
||||
self._runs[run_id]["status"] = status
|
||||
if error is not None:
|
||||
self._runs[run_id]["error"] = error
|
||||
self._runs[run_id]["updated_at"] = datetime.now(UTC).isoformat()
|
||||
|
||||
async def delete(self, run_id):
|
||||
self._runs.pop(run_id, None)
|
||||
|
||||
async def update_run_completion(self, run_id, *, status, **kwargs):
|
||||
if run_id in self._runs:
|
||||
self._runs[run_id]["status"] = status
|
||||
for key, value in kwargs.items():
|
||||
if value is not None:
|
||||
self._runs[run_id][key] = value
|
||||
self._runs[run_id]["updated_at"] = datetime.now(UTC).isoformat()
|
||||
|
||||
async def list_pending(self, *, before=None):
|
||||
now = before or datetime.now(UTC).isoformat()
|
||||
results = [r for r in self._runs.values() if r["status"] == "pending" and r["created_at"] <= now]
|
||||
results.sort(key=lambda r: r["created_at"])
|
||||
return results
|
||||
|
||||
async def aggregate_tokens_by_thread(self, thread_id: str) -> dict[str, Any]:
|
||||
completed = [r for r in self._runs.values() if r["thread_id"] == thread_id and r.get("status") in ("success", "error")]
|
||||
by_model: dict[str, dict] = {}
|
||||
for r in completed:
|
||||
model = r.get("model_name") or "unknown"
|
||||
entry = by_model.setdefault(model, {"tokens": 0, "runs": 0})
|
||||
entry["tokens"] += r.get("total_tokens", 0)
|
||||
entry["runs"] += 1
|
||||
return {
|
||||
"total_tokens": sum(r.get("total_tokens", 0) for r in completed),
|
||||
"total_input_tokens": sum(r.get("total_input_tokens", 0) for r in completed),
|
||||
"total_output_tokens": sum(r.get("total_output_tokens", 0) for r in completed),
|
||||
"total_runs": len(completed),
|
||||
"by_model": by_model,
|
||||
"by_caller": {
|
||||
"lead_agent": sum(r.get("lead_agent_tokens", 0) for r in completed),
|
||||
"subagent": sum(r.get("subagent_tokens", 0) for r in completed),
|
||||
"middleware": sum(r.get("middleware_tokens", 0) for r in completed),
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,737 @@
|
||||
"""Background agent execution.
|
||||
|
||||
Runs an agent graph inside an ``asyncio.Task``, publishing events to
|
||||
a :class:`StreamBridge` as they are produced.
|
||||
|
||||
Uses ``graph.astream(stream_mode=[...])`` which gives correct full-state
|
||||
snapshots for ``values`` mode, proper ``{node: writes}`` for ``updates``,
|
||||
and ``(chunk, metadata)`` tuples for ``messages`` mode.
|
||||
|
||||
Note: ``events`` mode is not supported through the gateway — it requires
|
||||
``graph.astream_events()`` which cannot simultaneously produce ``values``
|
||||
snapshots. The JS open-source LangGraph API server works around this via
|
||||
internal checkpoint callbacks that are not exposed in the Python public API.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import inspect
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from functools import lru_cache
|
||||
from typing import TYPE_CHECKING, Any, Literal, cast
|
||||
|
||||
from langgraph.checkpoint.base import empty_checkpoint
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from langchain_core.messages import HumanMessage
|
||||
|
||||
from deerflow.agents.middlewares.title_middleware import (
|
||||
finalize_thread_title,
|
||||
log_title_debug,
|
||||
)
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.runtime.serialization import serialize
|
||||
from deerflow.runtime.stream_bridge import StreamBridge
|
||||
|
||||
from .manager import RunManager, RunRecord
|
||||
from .schemas import RunStatus
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Valid stream_mode values for LangGraph's graph.astream()
|
||||
_VALID_LG_MODES = {"values", "updates", "checkpoints", "tasks", "debug", "messages", "custom"}
|
||||
|
||||
|
||||
def _log_background_title_finalize_failure(thread_id: str):
|
||||
def _done(task: asyncio.Task[bool]) -> None:
|
||||
try:
|
||||
task.result()
|
||||
except Exception:
|
||||
logger.debug("Failed to finalize background title for thread %s", thread_id, exc_info=True)
|
||||
|
||||
return _done
|
||||
|
||||
|
||||
def _build_runtime_context(
|
||||
thread_id: str,
|
||||
run_id: str,
|
||||
caller_context: Any | None,
|
||||
app_config: AppConfig | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build the dict that becomes ``ToolRuntime.context`` for the run.
|
||||
|
||||
Always includes ``thread_id`` and ``run_id``. Additional keys from the caller's
|
||||
``config['context']`` (e.g. ``agent_name`` for the bootstrap flow — issue #2677)
|
||||
are merged in but never override ``thread_id``/``run_id``. The resolved
|
||||
``AppConfig`` is added by the worker so tools can consume it without ambient
|
||||
global lookups.
|
||||
|
||||
langgraph 1.1+ surfaces this as ``runtime.context`` via the parent runtime stored
|
||||
under ``config['configurable']['__pregel_runtime']`` — see
|
||||
``langgraph.pregel.main`` where ``parent_runtime.merge(...)`` is invoked.
|
||||
"""
|
||||
runtime_ctx: dict[str, Any] = {"thread_id": thread_id, "run_id": run_id}
|
||||
if isinstance(caller_context, dict):
|
||||
for key, value in caller_context.items():
|
||||
runtime_ctx.setdefault(key, value)
|
||||
if app_config is not None:
|
||||
runtime_ctx["app_config"] = app_config
|
||||
return runtime_ctx
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RunContext:
|
||||
"""Infrastructure dependencies for a single agent run.
|
||||
|
||||
Groups checkpointer, store, and persistence-related singletons so that
|
||||
``run_agent`` (and any future callers) receive one object instead of a
|
||||
growing list of keyword arguments.
|
||||
"""
|
||||
|
||||
checkpointer: Any
|
||||
store: Any | None = field(default=None)
|
||||
event_store: Any | None = field(default=None)
|
||||
run_events_config: Any | None = field(default=None)
|
||||
thread_store: Any | None = field(default=None)
|
||||
app_config: AppConfig | None = field(default=None)
|
||||
|
||||
|
||||
def _install_runtime_context(config: dict, runtime_context: dict[str, Any]) -> None:
|
||||
existing_context = config.get("context")
|
||||
if isinstance(existing_context, dict):
|
||||
existing_context.setdefault("thread_id", runtime_context["thread_id"])
|
||||
existing_context.setdefault("run_id", runtime_context["run_id"])
|
||||
if "app_config" in runtime_context:
|
||||
existing_context["app_config"] = runtime_context["app_config"]
|
||||
return
|
||||
|
||||
config["context"] = dict(runtime_context)
|
||||
|
||||
|
||||
def _compute_agent_factory_supports_app_config(agent_factory: Any) -> bool:
|
||||
try:
|
||||
return "app_config" in inspect.signature(agent_factory).parameters
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
@lru_cache(maxsize=128)
|
||||
def _cached_agent_factory_supports_app_config(agent_factory: Any) -> bool:
|
||||
return _compute_agent_factory_supports_app_config(agent_factory)
|
||||
|
||||
|
||||
def _agent_factory_supports_app_config(agent_factory: Any) -> bool:
|
||||
try:
|
||||
return _cached_agent_factory_supports_app_config(agent_factory)
|
||||
except TypeError:
|
||||
# Some callable instances are unhashable; fall back to a direct check.
|
||||
return _compute_agent_factory_supports_app_config(agent_factory)
|
||||
|
||||
|
||||
async def run_agent(
|
||||
bridge: StreamBridge,
|
||||
run_manager: RunManager,
|
||||
record: RunRecord,
|
||||
*,
|
||||
ctx: RunContext,
|
||||
agent_factory: Any,
|
||||
graph_input: dict,
|
||||
config: dict,
|
||||
stream_modes: list[str] | None = None,
|
||||
stream_subgraphs: bool = False,
|
||||
interrupt_before: list[str] | Literal["*"] | None = None,
|
||||
interrupt_after: list[str] | Literal["*"] | None = None,
|
||||
command: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""Execute an agent in the background, publishing events to *bridge*.
|
||||
|
||||
``command`` 来自 LangGraph SDK 的 ``Command`` 协议(``{resume, update, goto}``)。
|
||||
存在时把它翻译成 ``langgraph.types.Command`` 并作为 ``astream`` 的入参 ——
|
||||
Pregel 检查到 Command 输入会从最近 checkpoint 处恢复(典型场景:interrupt 之后
|
||||
的 ``Command(resume=user_input)``);不存在时仍按 ``graph_input`` dict 起新 run。
|
||||
AI 写作的 4 个干预卡就靠这个把 user_input 传回 ``pause_*_confirm`` 节点。
|
||||
"""
|
||||
|
||||
# Unpack infrastructure dependencies from RunContext.
|
||||
checkpointer = ctx.checkpointer
|
||||
store = ctx.store
|
||||
event_store = ctx.event_store
|
||||
run_events_config = ctx.run_events_config
|
||||
thread_store = ctx.thread_store
|
||||
|
||||
run_id = record.run_id
|
||||
thread_id = record.thread_id
|
||||
requested_modes: set[str] = set(stream_modes or ["values"])
|
||||
pre_run_checkpoint_id: str | None = None
|
||||
pre_run_snapshot: dict[str, Any] | None = None
|
||||
snapshot_capture_failed = False
|
||||
|
||||
journal = None
|
||||
|
||||
journal = None
|
||||
|
||||
# Track whether "events" was requested but skipped
|
||||
if "events" in requested_modes:
|
||||
logger.info(
|
||||
"Run %s: 'events' stream_mode not supported in gateway (requires astream_events + checkpoint callbacks). Skipping.",
|
||||
run_id,
|
||||
)
|
||||
|
||||
try:
|
||||
# Initialize RunJournal + write human_message event.
|
||||
# These are inside the try block so any exception (e.g. a DB
|
||||
# error writing the event) flows through the except/finally
|
||||
# path that publishes an "end" event to the SSE bridge —
|
||||
# otherwise a failure here would leave the stream hanging
|
||||
# with no terminator.
|
||||
if event_store is not None:
|
||||
from deerflow.runtime.journal import RunJournal
|
||||
|
||||
journal = RunJournal(
|
||||
run_id=run_id,
|
||||
thread_id=thread_id,
|
||||
event_store=event_store,
|
||||
track_token_usage=getattr(run_events_config, "track_token_usage", True),
|
||||
)
|
||||
|
||||
# 1. Mark running
|
||||
await run_manager.set_status(run_id, RunStatus.running)
|
||||
|
||||
# Snapshot the latest pre-run checkpoint so rollback can restore it.
|
||||
if checkpointer is not None:
|
||||
try:
|
||||
config_for_check = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
|
||||
ckpt_tuple = await checkpointer.aget_tuple(config_for_check)
|
||||
if ckpt_tuple is not None:
|
||||
ckpt_config = getattr(ckpt_tuple, "config", {}).get("configurable", {})
|
||||
pre_run_checkpoint_id = ckpt_config.get("checkpoint_id")
|
||||
pre_run_snapshot = {
|
||||
"checkpoint_ns": ckpt_config.get("checkpoint_ns", ""),
|
||||
"checkpoint": copy.deepcopy(getattr(ckpt_tuple, "checkpoint", {})),
|
||||
"metadata": copy.deepcopy(getattr(ckpt_tuple, "metadata", {})),
|
||||
"pending_writes": copy.deepcopy(getattr(ckpt_tuple, "pending_writes", []) or []),
|
||||
}
|
||||
except Exception:
|
||||
snapshot_capture_failed = True
|
||||
logger.warning("Could not capture pre-run checkpoint snapshot for run %s", run_id, exc_info=True)
|
||||
|
||||
# 2. Publish metadata — useStream needs both run_id AND thread_id
|
||||
await bridge.publish(
|
||||
run_id,
|
||||
"metadata",
|
||||
{
|
||||
"run_id": run_id,
|
||||
"thread_id": thread_id,
|
||||
},
|
||||
)
|
||||
|
||||
# 3. Build the agent
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
from langgraph.runtime import Runtime
|
||||
|
||||
# Inject runtime context so middlewares and tools (via ToolRuntime.context) can
|
||||
# access thread-level data. langgraph-cli does this automatically; we must do it
|
||||
# manually here because we drive the graph through ``agent.astream(config=...)``
|
||||
# without passing the official ``context=`` parameter.
|
||||
runtime_ctx = _build_runtime_context(thread_id, run_id, config.get("context"), ctx.app_config)
|
||||
_install_runtime_context(config, runtime_ctx)
|
||||
runtime = Runtime(context=cast(Any, runtime_ctx), store=store)
|
||||
config.setdefault("configurable", {})["__pregel_runtime"] = runtime
|
||||
|
||||
# Inject RunJournal as a LangChain callback handler.
|
||||
# on_llm_end captures token usage; on_chain_start/end captures lifecycle.
|
||||
if journal is not None:
|
||||
config.setdefault("callbacks", []).append(journal)
|
||||
|
||||
runnable_config = RunnableConfig(**config)
|
||||
if ctx.app_config is not None and _agent_factory_supports_app_config(agent_factory):
|
||||
agent = agent_factory(config=runnable_config, app_config=ctx.app_config)
|
||||
else:
|
||||
agent = agent_factory(config=runnable_config)
|
||||
|
||||
# 4. Attach checkpointer and store
|
||||
if checkpointer is not None:
|
||||
agent.checkpointer = checkpointer
|
||||
if store is not None:
|
||||
agent.store = store
|
||||
|
||||
# 5. Set interrupt nodes
|
||||
if interrupt_before:
|
||||
agent.interrupt_before_nodes = interrupt_before
|
||||
if interrupt_after:
|
||||
agent.interrupt_after_nodes = interrupt_after
|
||||
|
||||
# 6. Build LangGraph stream_mode list
|
||||
# "events" is NOT a valid astream mode — skip it
|
||||
# "messages-tuple" maps to LangGraph's "messages" mode
|
||||
lg_modes: list[str] = []
|
||||
for m in requested_modes:
|
||||
if m == "messages-tuple":
|
||||
lg_modes.append("messages")
|
||||
elif m == "events":
|
||||
# Skipped — see log above
|
||||
continue
|
||||
elif m in _VALID_LG_MODES:
|
||||
lg_modes.append(m)
|
||||
if not lg_modes:
|
||||
lg_modes = ["values"]
|
||||
|
||||
# Deduplicate while preserving order
|
||||
seen: set[str] = set()
|
||||
deduped: list[str] = []
|
||||
for m in lg_modes:
|
||||
if m not in seen:
|
||||
seen.add(m)
|
||||
deduped.append(m)
|
||||
lg_modes = deduped
|
||||
|
||||
logger.info("Run %s: streaming with modes %s (requested: %s)", run_id, lg_modes, requested_modes)
|
||||
|
||||
# 7. Stream using graph.astream
|
||||
# 如果客户端传了 Command(典型:interrupt 后续提的 ``Command(resume=...)``),
|
||||
# 把它翻译成 langgraph.types.Command 作为 astream 输入;否则按 graph_input dict
|
||||
# 起新一轮。Pregel 检查到 Command 会从最近 checkpoint 处恢复,而不是重头跑。
|
||||
stream_input: Any = graph_input
|
||||
if command is not None:
|
||||
# 有 resume/update/goto(如 AI 写作 4 个干预卡的 Command(resume=user_input))→
|
||||
# 构造 langgraph.types.Command,Pregel 从 interrupt 处恢复。
|
||||
# **空 command(无任何指令)= "从最近 checkpoint 继续执行挂起的任务"**:AI 写作
|
||||
# "暂停后继续" —— 暂停时硬取消了活跃节点(非 interrupt),continue 要让该阶段节点
|
||||
# 从 checkpoint 续跑。此时必须用 **None 输入**让 Pregel resume pending tasks;
|
||||
# 既不能用 graph_input={}(空 dict 被当新一轮输入 → 从图入口 intent 重跑),也不能
|
||||
# 构造 Command()(没有挂起的 interrupt 可消费,LangGraph 内部会抛
|
||||
# "cannot access local variable 'resume_is_map'")。
|
||||
has_directive = any(command.get(k) is not None for k in ("resume", "update", "goto"))
|
||||
if has_directive:
|
||||
from langgraph.types import Command as _LGCommand
|
||||
|
||||
stream_input = _LGCommand(
|
||||
resume=command.get("resume"),
|
||||
update=command.get("update"),
|
||||
goto=command.get("goto"),
|
||||
)
|
||||
else:
|
||||
stream_input = None
|
||||
|
||||
if len(lg_modes) == 1 and not stream_subgraphs:
|
||||
# Single mode, no subgraphs: astream yields raw chunks
|
||||
single_mode = lg_modes[0]
|
||||
async for chunk in agent.astream(stream_input, config=runnable_config, stream_mode=single_mode):
|
||||
if record.abort_event.is_set():
|
||||
logger.info("Run %s abort requested — stopping", run_id)
|
||||
break
|
||||
sse_event = _lg_mode_to_sse_event(single_mode)
|
||||
await bridge.publish(run_id, sse_event, serialize(chunk, mode=single_mode))
|
||||
else:
|
||||
# Multiple modes or subgraphs: astream yields tuples
|
||||
async for item in agent.astream(
|
||||
stream_input,
|
||||
config=runnable_config,
|
||||
stream_mode=lg_modes,
|
||||
subgraphs=stream_subgraphs,
|
||||
):
|
||||
if record.abort_event.is_set():
|
||||
logger.info("Run %s abort requested — stopping", run_id)
|
||||
break
|
||||
|
||||
mode, chunk = _unpack_stream_item(item, lg_modes, stream_subgraphs)
|
||||
if mode is None:
|
||||
continue
|
||||
|
||||
sse_event = _lg_mode_to_sse_event(mode)
|
||||
await bridge.publish(run_id, sse_event, serialize(chunk, mode=mode))
|
||||
|
||||
# 8. Final status
|
||||
if record.abort_event.is_set():
|
||||
action = record.abort_action
|
||||
if action == "rollback":
|
||||
await run_manager.set_status(run_id, RunStatus.error, error="Rolled back by user")
|
||||
try:
|
||||
await _rollback_to_pre_run_checkpoint(
|
||||
checkpointer=checkpointer,
|
||||
thread_id=thread_id,
|
||||
run_id=run_id,
|
||||
pre_run_checkpoint_id=pre_run_checkpoint_id,
|
||||
pre_run_snapshot=pre_run_snapshot,
|
||||
snapshot_capture_failed=snapshot_capture_failed,
|
||||
)
|
||||
logger.info("Run %s rolled back to pre-run checkpoint %s", run_id, pre_run_checkpoint_id)
|
||||
except Exception:
|
||||
logger.warning("Failed to rollback checkpoint for run %s", run_id, exc_info=True)
|
||||
else:
|
||||
await run_manager.set_status(run_id, RunStatus.interrupted)
|
||||
else:
|
||||
# LLMErrorHandlingMiddleware intentionally converts an exhausted
|
||||
# provider failure into a user-safe AIMessage instead of raising.
|
||||
# That keeps a malformed upstream response out of the SSE transport,
|
||||
# but previously made this worker record the run as ``success``.
|
||||
# The UI consequently had no error event to show and looked as if
|
||||
# generation had silently stopped halfway through. Inspect the
|
||||
# terminal checkpoint before declaring success so the persisted run
|
||||
# state and the user-visible SSE outcome stay consistent.
|
||||
terminal_llm_error = await _terminal_llm_error_reason(
|
||||
checkpointer=checkpointer,
|
||||
thread_id=thread_id,
|
||||
)
|
||||
if terminal_llm_error is not None:
|
||||
error_message = "本轮模型生成未能完成,已保留当前对话内容,请稍后重试。"
|
||||
logger.warning(
|
||||
"Run %s ended with LLM fallback message (reason=%s)",
|
||||
run_id,
|
||||
terminal_llm_error,
|
||||
)
|
||||
await run_manager.set_status(
|
||||
run_id,
|
||||
RunStatus.error,
|
||||
error=error_message,
|
||||
)
|
||||
await bridge.publish(
|
||||
run_id,
|
||||
"error",
|
||||
{
|
||||
"message": error_message,
|
||||
"name": "ModelGenerationError",
|
||||
},
|
||||
)
|
||||
else:
|
||||
await run_manager.set_status(run_id, RunStatus.success)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
action = record.abort_action
|
||||
if action == "rollback":
|
||||
await run_manager.set_status(run_id, RunStatus.error, error="Rolled back by user")
|
||||
try:
|
||||
await _rollback_to_pre_run_checkpoint(
|
||||
checkpointer=checkpointer,
|
||||
thread_id=thread_id,
|
||||
run_id=run_id,
|
||||
pre_run_checkpoint_id=pre_run_checkpoint_id,
|
||||
pre_run_snapshot=pre_run_snapshot,
|
||||
snapshot_capture_failed=snapshot_capture_failed,
|
||||
)
|
||||
logger.info("Run %s was cancelled and rolled back", run_id)
|
||||
except Exception:
|
||||
logger.warning("Run %s cancellation rollback failed", run_id, exc_info=True)
|
||||
else:
|
||||
await run_manager.set_status(run_id, RunStatus.interrupted)
|
||||
logger.info("Run %s was cancelled", run_id)
|
||||
|
||||
except Exception as exc:
|
||||
error_msg = f"{exc}"
|
||||
logger.exception("Run %s failed: %s", run_id, error_msg)
|
||||
await run_manager.set_status(run_id, RunStatus.error, error=error_msg)
|
||||
await bridge.publish(
|
||||
run_id,
|
||||
"error",
|
||||
{
|
||||
"message": error_msg,
|
||||
"name": type(exc).__name__,
|
||||
},
|
||||
)
|
||||
|
||||
finally:
|
||||
# Flush any buffered journal events and persist completion data
|
||||
if journal is not None:
|
||||
try:
|
||||
await journal.flush()
|
||||
except Exception:
|
||||
logger.warning("Failed to flush journal for run %s", run_id, exc_info=True)
|
||||
|
||||
try:
|
||||
# Persist token usage + convenience fields to RunStore
|
||||
completion = journal.get_completion_data()
|
||||
await run_manager.update_run_completion(run_id, status=record.status.value, **completion)
|
||||
except Exception:
|
||||
logger.warning("Failed to persist run completion for %s (non-fatal)", run_id, exc_info=True)
|
||||
|
||||
# Sync title from checkpoint to threads_meta.display_name
|
||||
if checkpointer is not None and thread_store is not None:
|
||||
try:
|
||||
ckpt_config = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
|
||||
ckpt_tuple = await checkpointer.aget_tuple(ckpt_config)
|
||||
if ckpt_tuple is not None:
|
||||
ckpt = getattr(ckpt_tuple, "checkpoint", {}) or {}
|
||||
channel_values = ckpt.get("channel_values", {}) or {}
|
||||
title = channel_values.get("title")
|
||||
if title:
|
||||
await thread_store.update_display_name(thread_id, title)
|
||||
if (
|
||||
record.status == RunStatus.success
|
||||
and channel_values.get("title_provisional") is True
|
||||
):
|
||||
log_title_debug(
|
||||
"Run %s: scheduling background title generation for thread %s",
|
||||
run_id,
|
||||
thread_id,
|
||||
)
|
||||
title_task = asyncio.create_task(
|
||||
finalize_thread_title(
|
||||
checkpointer=checkpointer,
|
||||
thread_store=thread_store,
|
||||
thread_id=thread_id,
|
||||
source_state=copy.deepcopy(channel_values),
|
||||
app_config=ctx.app_config,
|
||||
),
|
||||
name=f"title-finalize:{thread_id}",
|
||||
)
|
||||
title_task.add_done_callback(_log_background_title_finalize_failure(thread_id))
|
||||
elif record.status == RunStatus.success:
|
||||
log_title_debug(
|
||||
"Run %s: background title generation not scheduled for thread %s because title_provisional=%r title=%r",
|
||||
run_id,
|
||||
thread_id,
|
||||
channel_values.get("title_provisional"),
|
||||
channel_values.get("title"),
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Failed to sync title for thread %s (non-fatal)", thread_id)
|
||||
|
||||
# Update threads_meta status based on run outcome
|
||||
if thread_store is not None:
|
||||
try:
|
||||
final_status = "idle" if record.status == RunStatus.success else record.status.value
|
||||
await thread_store.update_status(thread_id, final_status)
|
||||
except Exception:
|
||||
logger.debug("Failed to update thread_meta status for %s (non-fatal)", thread_id)
|
||||
|
||||
await bridge.publish_end(run_id)
|
||||
asyncio.create_task(bridge.cleanup(run_id, delay=60))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _call_checkpointer_method(checkpointer: Any, async_name: str, sync_name: str, *args: Any, **kwargs: Any) -> Any:
|
||||
"""Call a checkpointer method, supporting async and sync variants."""
|
||||
method = getattr(checkpointer, async_name, None) or getattr(checkpointer, sync_name, None)
|
||||
if method is None:
|
||||
raise AttributeError(f"Missing checkpointer method: {async_name}/{sync_name}")
|
||||
result = method(*args, **kwargs)
|
||||
if inspect.isawaitable(result):
|
||||
return await result
|
||||
return result
|
||||
|
||||
|
||||
async def _terminal_llm_error_reason(
|
||||
*,
|
||||
checkpointer: Any | None,
|
||||
thread_id: str,
|
||||
) -> str | None:
|
||||
"""Return the terminal LLM fallback reason, if this run ended in one.
|
||||
|
||||
``LLMErrorHandlingMiddleware`` persists its fallback as an AI message with
|
||||
an internal marker. A normal agent graph treats that message as a valid
|
||||
result and completes without an exception, so the worker must check the
|
||||
saved conversation rather than relying solely on ``astream`` raising.
|
||||
"""
|
||||
if checkpointer is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
checkpoint_config = {
|
||||
"configurable": {
|
||||
"thread_id": thread_id,
|
||||
"checkpoint_ns": "",
|
||||
}
|
||||
}
|
||||
checkpoint_tuple = await _call_checkpointer_method(
|
||||
checkpointer,
|
||||
"aget_tuple",
|
||||
"get_tuple",
|
||||
checkpoint_config,
|
||||
)
|
||||
if checkpoint_tuple is None:
|
||||
return None
|
||||
checkpoint = getattr(checkpoint_tuple, "checkpoint", {}) or {}
|
||||
channel_values = checkpoint.get("channel_values", {})
|
||||
messages = channel_values.get("messages", []) if isinstance(channel_values, dict) else []
|
||||
if not isinstance(messages, list):
|
||||
return None
|
||||
|
||||
# Walk backwards to the latest assistant message. Tool/human messages
|
||||
# may be appended around it by middleware, but an older fallback should
|
||||
# never turn a later successful response into an error.
|
||||
for message in reversed(messages):
|
||||
message_type = message.get("type") if isinstance(message, dict) else getattr(message, "type", None)
|
||||
if message_type not in {"ai", "assistant"}:
|
||||
continue
|
||||
from deerflow.agents.middlewares.llm_error_handling_middleware import (
|
||||
is_llm_error_message,
|
||||
)
|
||||
|
||||
return is_llm_error_message(message)
|
||||
except Exception:
|
||||
# A status check must never turn a completed answer into a failed run
|
||||
# merely because a custom checkpointer cannot expose its latest tuple.
|
||||
logger.debug(
|
||||
"Could not inspect terminal LLM state for thread %s",
|
||||
thread_id,
|
||||
exc_info=True,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
async def _rollback_to_pre_run_checkpoint(
|
||||
*,
|
||||
checkpointer: Any,
|
||||
thread_id: str,
|
||||
run_id: str,
|
||||
pre_run_checkpoint_id: str | None,
|
||||
pre_run_snapshot: dict[str, Any] | None,
|
||||
snapshot_capture_failed: bool,
|
||||
) -> None:
|
||||
"""Restore thread state to the checkpoint snapshot captured before run start."""
|
||||
if checkpointer is None:
|
||||
logger.info("Run %s rollback requested but no checkpointer is configured", run_id)
|
||||
return
|
||||
|
||||
if snapshot_capture_failed:
|
||||
logger.warning("Run %s rollback skipped: pre-run checkpoint snapshot capture failed", run_id)
|
||||
return
|
||||
|
||||
if pre_run_snapshot is None:
|
||||
await _call_checkpointer_method(checkpointer, "adelete_thread", "delete_thread", thread_id)
|
||||
logger.info("Run %s rollback reset thread %s to empty state", run_id, thread_id)
|
||||
return
|
||||
|
||||
checkpoint_to_restore = None
|
||||
metadata_to_restore: dict[str, Any] = {}
|
||||
checkpoint_ns = ""
|
||||
checkpoint = pre_run_snapshot.get("checkpoint")
|
||||
if not isinstance(checkpoint, dict):
|
||||
logger.warning("Run %s rollback skipped: invalid pre-run checkpoint snapshot", run_id)
|
||||
return
|
||||
checkpoint_to_restore = checkpoint
|
||||
if checkpoint_to_restore.get("id") is None and pre_run_checkpoint_id is not None:
|
||||
checkpoint_to_restore = {**checkpoint_to_restore, "id": pre_run_checkpoint_id}
|
||||
if checkpoint_to_restore.get("id") is None:
|
||||
logger.warning("Run %s rollback skipped: pre-run checkpoint has no checkpoint id", run_id)
|
||||
return
|
||||
restore_marker = _new_checkpoint_marker()
|
||||
checkpoint_to_restore = {
|
||||
**checkpoint_to_restore,
|
||||
"id": restore_marker["id"],
|
||||
"ts": restore_marker["ts"],
|
||||
}
|
||||
metadata = pre_run_snapshot.get("metadata", {})
|
||||
metadata_to_restore = metadata if isinstance(metadata, dict) else {}
|
||||
raw_checkpoint_ns = pre_run_snapshot.get("checkpoint_ns")
|
||||
checkpoint_ns = raw_checkpoint_ns if isinstance(raw_checkpoint_ns, str) else ""
|
||||
|
||||
channel_versions = checkpoint_to_restore.get("channel_versions")
|
||||
new_versions = dict(channel_versions) if isinstance(channel_versions, dict) else {}
|
||||
|
||||
restore_config = {"configurable": {"thread_id": thread_id, "checkpoint_ns": checkpoint_ns}}
|
||||
restored_config = await _call_checkpointer_method(
|
||||
checkpointer,
|
||||
"aput",
|
||||
"put",
|
||||
restore_config,
|
||||
checkpoint_to_restore,
|
||||
metadata_to_restore if isinstance(metadata_to_restore, dict) else {},
|
||||
new_versions,
|
||||
)
|
||||
if not isinstance(restored_config, dict):
|
||||
raise RuntimeError(f"Run {run_id} rollback restore returned invalid config: expected dict")
|
||||
restored_configurable = restored_config.get("configurable", {})
|
||||
if not isinstance(restored_configurable, dict):
|
||||
raise RuntimeError(f"Run {run_id} rollback restore returned invalid config payload")
|
||||
restored_checkpoint_id = restored_configurable.get("checkpoint_id")
|
||||
if not restored_checkpoint_id:
|
||||
raise RuntimeError(f"Run {run_id} rollback restore did not return checkpoint_id")
|
||||
|
||||
pending_writes = pre_run_snapshot.get("pending_writes", [])
|
||||
if not pending_writes:
|
||||
return
|
||||
|
||||
writes_by_task: dict[str, list[tuple[str, Any]]] = {}
|
||||
for item in pending_writes:
|
||||
if not isinstance(item, (tuple, list)) or len(item) != 3:
|
||||
raise RuntimeError(f"Run {run_id} rollback failed: pending_write is not a 3-tuple: {item!r}")
|
||||
task_id, channel, value = item
|
||||
if not isinstance(channel, str):
|
||||
raise RuntimeError(f"Run {run_id} rollback failed: pending_write has non-string channel: task_id={task_id!r}, channel={channel!r}")
|
||||
writes_by_task.setdefault(str(task_id), []).append((channel, value))
|
||||
|
||||
for task_id, writes in writes_by_task.items():
|
||||
await _call_checkpointer_method(
|
||||
checkpointer,
|
||||
"aput_writes",
|
||||
"put_writes",
|
||||
restored_config,
|
||||
writes,
|
||||
task_id=task_id,
|
||||
)
|
||||
|
||||
|
||||
def _new_checkpoint_marker() -> dict[str, str]:
|
||||
marker = empty_checkpoint()
|
||||
return {"id": marker["id"], "ts": marker["ts"]}
|
||||
|
||||
|
||||
def _lg_mode_to_sse_event(mode: str) -> str:
|
||||
"""Map LangGraph internal stream_mode name to SSE event name.
|
||||
|
||||
LangGraph's ``astream(stream_mode="messages")`` produces message
|
||||
tuples. The SSE protocol calls this ``messages-tuple`` when the
|
||||
client explicitly requests it, but the default SSE event name used
|
||||
by LangGraph Platform is simply ``"messages"``.
|
||||
"""
|
||||
# All LG modes map 1:1 to SSE event names — "messages" stays "messages"
|
||||
return mode
|
||||
|
||||
|
||||
def _extract_human_message(graph_input: dict) -> HumanMessage | None:
|
||||
"""Extract or construct a HumanMessage from graph_input for event recording.
|
||||
|
||||
Returns a LangChain HumanMessage so callers can use .model_dump() to get
|
||||
the checkpoint-aligned serialization format.
|
||||
"""
|
||||
from langchain_core.messages import HumanMessage
|
||||
|
||||
messages = graph_input.get("messages")
|
||||
if not messages:
|
||||
return None
|
||||
last = messages[-1] if isinstance(messages, list) else messages
|
||||
if isinstance(last, HumanMessage):
|
||||
return last
|
||||
if isinstance(last, str):
|
||||
return HumanMessage(content=last) if last else None
|
||||
if hasattr(last, "content"):
|
||||
content = last.content
|
||||
return HumanMessage(content=content)
|
||||
if isinstance(last, dict):
|
||||
content = last.get("content", "")
|
||||
return HumanMessage(content=content) if content else None
|
||||
return None
|
||||
|
||||
|
||||
def _unpack_stream_item(
|
||||
item: Any,
|
||||
lg_modes: list[str],
|
||||
stream_subgraphs: bool,
|
||||
) -> tuple[str | None, Any]:
|
||||
"""Unpack a multi-mode or subgraph stream item into (mode, chunk).
|
||||
|
||||
Returns ``(None, None)`` if the item cannot be parsed.
|
||||
"""
|
||||
if stream_subgraphs:
|
||||
if isinstance(item, tuple) and len(item) == 3:
|
||||
_ns, mode, chunk = item
|
||||
return str(mode), chunk
|
||||
if isinstance(item, tuple) and len(item) == 2:
|
||||
mode, chunk = item
|
||||
return str(mode), chunk
|
||||
return None, None
|
||||
|
||||
if isinstance(item, tuple) and len(item) == 2:
|
||||
mode, chunk = item
|
||||
return str(mode), chunk
|
||||
|
||||
# Fallback: single-element output from first mode
|
||||
return lg_modes[0] if lg_modes else None, item
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
from .registry import get_scheduled_task_service, set_scheduled_task_service
|
||||
from .service import (
|
||||
DuplicateFavoriteError,
|
||||
DuplicateTaskNameError,
|
||||
HtmlGenerationError,
|
||||
MarkdownRequirementError,
|
||||
ScheduledTaskService,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"DuplicateFavoriteError",
|
||||
"DuplicateTaskNameError",
|
||||
"HtmlGenerationError",
|
||||
"MarkdownRequirementError",
|
||||
"ScheduledTaskService",
|
||||
"get_scheduled_task_service",
|
||||
"set_scheduled_task_service",
|
||||
]
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
"""Element / Matrix delivery helpers for scheduled task results."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ElementDeliveryClient:
|
||||
def __init__(self, *, homeserver_url: str, access_token: str) -> None:
|
||||
self.homeserver_url = homeserver_url.rstrip("/")
|
||||
self.access_token = access_token
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> ElementDeliveryClient | None:
|
||||
enabled = os.environ.get("ELEMENT_ENABLED", "true").strip().lower()
|
||||
if enabled in {"0", "false", "no", "off"}:
|
||||
return None
|
||||
|
||||
homeserver_url = os.environ.get("ELEMENT_HOMESERVER_URL", "").strip()
|
||||
if not homeserver_url:
|
||||
return None
|
||||
|
||||
access_token = os.environ.get("ELEMENT_ACCESS_TOKEN", "").strip()
|
||||
if not access_token:
|
||||
access_token = _load_cached_access_token()
|
||||
if not access_token:
|
||||
try:
|
||||
access_token = _bootstrap_access_token(homeserver_url)
|
||||
except Exception:
|
||||
logger.exception("Failed to bootstrap Element bot access token")
|
||||
return None
|
||||
if not access_token:
|
||||
return None
|
||||
return cls(homeserver_url=homeserver_url, access_token=access_token)
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {self.access_token}"}
|
||||
|
||||
async def send_direct_message(self, element_user_id: str, body: str, *, room_id: str | None = None) -> str:
|
||||
if not room_id:
|
||||
room_id = await self._create_dm_room(element_user_id)
|
||||
await self._send_message(room_id, body)
|
||||
return room_id
|
||||
|
||||
async def _create_dm_room(self, element_user_id: str) -> str:
|
||||
url = f"{self.homeserver_url}/_matrix/client/v3/createRoom"
|
||||
payload = {
|
||||
"preset": "trusted_private_chat",
|
||||
"is_direct": True,
|
||||
"invite": [element_user_id],
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=20) as client:
|
||||
response = await client.post(url, headers=self._headers(), json=payload)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
room_id = data.get("room_id")
|
||||
if not isinstance(room_id, str) or not room_id:
|
||||
raise RuntimeError("Matrix createRoom response did not include room_id")
|
||||
return room_id
|
||||
|
||||
async def _send_message(self, room_id: str, body: str) -> None:
|
||||
txn_id = uuid.uuid4().hex
|
||||
url = f"{self.homeserver_url}/_matrix/client/v3/rooms/{room_id}/send/m.room.message/{txn_id}"
|
||||
payload = {
|
||||
"msgtype": "m.text",
|
||||
"body": body,
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.put(url, headers=self._headers(), json=payload)
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
def _state_file() -> Path:
|
||||
path = os.environ.get("ELEMENT_STATE_FILE", "").strip()
|
||||
if path:
|
||||
return Path(path)
|
||||
return Path(".element-bot-token")
|
||||
|
||||
|
||||
def _load_cached_access_token() -> str | None:
|
||||
path = _state_file()
|
||||
if not path.exists():
|
||||
return None
|
||||
token = path.read_text(encoding="utf-8").strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def _save_cached_access_token(token: str) -> None:
|
||||
path = _state_file()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(token, encoding="utf-8")
|
||||
|
||||
|
||||
def _bootstrap_access_token(homeserver_url: str) -> str | None:
|
||||
username = os.environ.get("ELEMENT_BOT_USERNAME", "scheduled-bot").strip() or "scheduled-bot"
|
||||
password = os.environ.get("ELEMENT_BOT_PASSWORD", "").strip()
|
||||
auto_register = os.environ.get("ELEMENT_AUTO_REGISTER", "false").strip().lower() in {
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
"on",
|
||||
}
|
||||
|
||||
if auto_register:
|
||||
if not password:
|
||||
password = f"scheduled-bot-{uuid.uuid4().hex}"
|
||||
token = _register_bot(homeserver_url, username, password)
|
||||
if token:
|
||||
_save_cached_access_token(token)
|
||||
return token
|
||||
|
||||
if username and password:
|
||||
token = _login_bot(homeserver_url, username, password)
|
||||
if token:
|
||||
_save_cached_access_token(token)
|
||||
return token
|
||||
return None
|
||||
|
||||
|
||||
def _register_bot(homeserver_url: str, username: str, password: str) -> str | None:
|
||||
url = f"{homeserver_url.rstrip('/')}/_matrix/client/v3/register"
|
||||
payload = {
|
||||
"username": username,
|
||||
"password": password,
|
||||
"auth": {"type": "m.login.dummy"},
|
||||
"initial_device_display_name": "Scheduled Task Bot",
|
||||
}
|
||||
with httpx.Client(timeout=20) as client:
|
||||
response = client.post(url, json=payload)
|
||||
if response.status_code == 401:
|
||||
session = response.json().get("session")
|
||||
if session:
|
||||
payload["auth"]["session"] = session
|
||||
response = client.post(url, json=payload)
|
||||
if response.status_code == 400 and response.json().get("errcode") == "M_USER_IN_USE":
|
||||
password_env = os.environ.get("ELEMENT_BOT_PASSWORD", "").strip()
|
||||
if password_env:
|
||||
return _login_bot(homeserver_url, username, password_env)
|
||||
logger.error(
|
||||
"Element bot username %s already exists and no ELEMENT_BOT_PASSWORD was provided",
|
||||
username,
|
||||
)
|
||||
return None
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
token = data.get("access_token")
|
||||
return token if isinstance(token, str) and token else None
|
||||
|
||||
|
||||
def _login_bot(homeserver_url: str, username: str, password: str) -> str | None:
|
||||
url = f"{homeserver_url.rstrip('/')}/_matrix/client/v3/login"
|
||||
payload = {
|
||||
"type": "m.login.password",
|
||||
"identifier": {"type": "m.id.user", "user": username},
|
||||
"password": password,
|
||||
"initial_device_display_name": "Scheduled Task Bot",
|
||||
}
|
||||
with httpx.Client(timeout=20) as client:
|
||||
response = client.post(url, json=payload)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
token = data.get("access_token")
|
||||
return token if isinstance(token, str) and token else None
|
||||
+453
@@ -0,0 +1,453 @@
|
||||
"""HTML page generation helpers for ``html_page`` scheduled tasks.
|
||||
|
||||
Pure, dependency-light utilities the scheduler uses to turn a GLM5 response
|
||||
into a safe, previewable HTML document:
|
||||
|
||||
- :func:`extract_json_object` — fault-tolerant JSON extraction from a model
|
||||
reply that may be wrapped in prose or ```json fences.
|
||||
- :func:`sanitize_html` — strip script-execution vectors (``<script>``,
|
||||
``<iframe>``, ``on*`` handlers, ``javascript:`` URLs, …) using BeautifulSoup.
|
||||
- :func:`validate_html` — cheap structural checks (doctype/html/head/body,
|
||||
non-empty body, no residual scripts) that gate the optional repair pass.
|
||||
- ``build_*_prompt`` — the GLM5 prompt templates (generation / repair / style
|
||||
extraction).
|
||||
- :func:`screenshot_html` — best-effort Playwright screenshot, a no-op when
|
||||
Playwright is not installed (the offline image ships without a browser).
|
||||
|
||||
Kept free of any ``app.*`` import so it stays inside the harness boundary.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Tags removed wholesale — they either execute code or load remote active
|
||||
# content that the iframe sandbox alone shouldn't be relied on to contain.
|
||||
_DANGEROUS_TAGS = frozenset(
|
||||
{"script", "iframe", "object", "embed", "applet", "frame", "frameset", "base"}
|
||||
)
|
||||
|
||||
# URL schemes that can execute script when navigated/loaded.
|
||||
_DANGEROUS_URL_RE = re.compile(r"^\s*(javascript|vbscript|data:text/html)", re.IGNORECASE)
|
||||
|
||||
# Attributes carrying a URL we must scheme-check.
|
||||
_URL_ATTRS = frozenset({"href", "src", "action", "formaction", "xlink:href", "background", "poster"})
|
||||
|
||||
_LOCAL_DOC_LINK_RE = re.compile(
|
||||
r"^(?![a-z][a-z0-9+.-]*:)(?!//)(?P<path>[^#?]*\.(?:html?|md|markdown))(?P<query>\?[^#]*)?(?P<fragment>#.+)?$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def parse_frontmatter(text: str) -> tuple[dict[str, Any], str]:
|
||||
"""Split a ``---`` YAML frontmatter block from the body of a SKILL.md.
|
||||
|
||||
Returns ``(frontmatter_dict, body)``. When there is no frontmatter the dict
|
||||
is empty and the body is the whole text.
|
||||
"""
|
||||
if not text or not text.lstrip().startswith("---"):
|
||||
return {}, text or ""
|
||||
lines = text.splitlines()
|
||||
# Skip leading blank lines before the opening fence.
|
||||
start = 0
|
||||
while start < len(lines) and not lines[start].strip():
|
||||
start += 1
|
||||
end = None
|
||||
for i in range(start + 1, len(lines)):
|
||||
if lines[i].strip() == "---":
|
||||
end = i
|
||||
break
|
||||
if end is None:
|
||||
return {}, text
|
||||
fm_block = "\n".join(lines[start + 1 : end])
|
||||
body = "\n".join(lines[end + 1 :])
|
||||
try:
|
||||
import yaml
|
||||
|
||||
data = yaml.safe_load(fm_block) or {}
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
except Exception:
|
||||
data = {}
|
||||
return data, body
|
||||
|
||||
|
||||
def extract_json_object(text: str | None) -> dict[str, Any] | None:
|
||||
"""Best-effort parse of a JSON object from a model reply.
|
||||
|
||||
Handles three common shapes: a bare JSON object, a ```json fenced block,
|
||||
and a JSON object embedded in surrounding prose. Returns ``None`` when no
|
||||
balanced object can be recovered.
|
||||
"""
|
||||
if not text or not isinstance(text, str):
|
||||
return None
|
||||
candidate = text.strip()
|
||||
|
||||
# Strip a single ```json ... ``` (or ``` ... ```) fence if present.
|
||||
fence = re.search(r"```(?:json)?\s*(.*?)```", candidate, flags=re.DOTALL | re.IGNORECASE)
|
||||
if fence:
|
||||
candidate = fence.group(1).strip()
|
||||
|
||||
# Fast path: the whole thing is already valid JSON.
|
||||
try:
|
||||
parsed = json.loads(candidate)
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Fallback: scan for the first balanced ``{ ... }`` and parse that.
|
||||
start = candidate.find("{")
|
||||
if start == -1:
|
||||
return None
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape = False
|
||||
for index in range(start, len(candidate)):
|
||||
char = candidate[index]
|
||||
if in_string:
|
||||
if escape:
|
||||
escape = False
|
||||
elif char == "\\":
|
||||
escape = True
|
||||
elif char == '"':
|
||||
in_string = False
|
||||
continue
|
||||
if char == '"':
|
||||
in_string = True
|
||||
elif char == "{":
|
||||
depth += 1
|
||||
elif char == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
blob = candidate[start : index + 1]
|
||||
try:
|
||||
parsed = json.loads(blob)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
return None
|
||||
|
||||
|
||||
def recover_html_document(text: str | None) -> str | None:
|
||||
"""Slice a complete HTML document out of a model reply.
|
||||
|
||||
Used as a fallback when the JSON wrapper around the ``html`` field can't be
|
||||
parsed — the model commonly emits *literal* newlines and *unescaped* quotes
|
||||
(``"zh-CN"``) inside the value, which is invalid JSON, so
|
||||
:func:`extract_json_object` returns ``None``. Without this, the caller would
|
||||
archive the whole ``{"title": ..., "html": "<!doctype html>…"}`` blob as the
|
||||
page. We locate the ``<!doctype html>`` / ``<html …>`` start and the final
|
||||
``</html>`` and return just that span, dropping the surrounding JSON
|
||||
scaffolding. Also accepts a reply that is already bare HTML. Returns
|
||||
``None`` when no HTML document can be found.
|
||||
"""
|
||||
if not text or not isinstance(text, str):
|
||||
return None
|
||||
lowered = text.lower()
|
||||
start = lowered.find("<!doctype html")
|
||||
if start == -1:
|
||||
start = lowered.find("<html")
|
||||
if start == -1:
|
||||
return None
|
||||
end = lowered.rfind("</html>")
|
||||
candidate = text[start:] if end == -1 else text[start : end + len("</html>")]
|
||||
candidate = candidate.strip()
|
||||
# If the html had been a properly-escaped JSON string value (the JSON failed
|
||||
# to parse for some *other* reason), unescape the common sequences so they
|
||||
# don't survive into the rendered page. Only triggers when escapes exist, so
|
||||
# genuinely-literal HTML (the usual broken-JSON case) is left untouched.
|
||||
if "\\n" in candidate or '\\"' in candidate or "\\/" in candidate or "\\t" in candidate:
|
||||
candidate = (
|
||||
candidate.replace('\\"', '"')
|
||||
.replace("\\n", "\n")
|
||||
.replace("\\r", "\r")
|
||||
.replace("\\t", "\t")
|
||||
.replace("\\/", "/")
|
||||
)
|
||||
return candidate or None
|
||||
|
||||
|
||||
def sanitize_html(html: str) -> tuple[str, list[str]]:
|
||||
"""Remove script-execution vectors from ``html``.
|
||||
|
||||
Returns ``(cleaned_html, removed)`` where ``removed`` is a human-readable
|
||||
report of what was stripped (used for logging / repair feedback). The
|
||||
cleaner is defensive but not a full HTML validator — pair it with an
|
||||
``iframe sandbox`` (no ``allow-scripts``) on the preview side.
|
||||
"""
|
||||
if not html or not isinstance(html, str):
|
||||
return "", []
|
||||
try:
|
||||
from bs4 import BeautifulSoup
|
||||
except Exception: # pragma: no cover - bs4 is a declared dependency
|
||||
logger.warning("BeautifulSoup unavailable; returning HTML unsanitized")
|
||||
return html, []
|
||||
|
||||
removed: list[str] = []
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
|
||||
# 1) Drop dangerous tags entirely.
|
||||
for tag in soup.find_all(True):
|
||||
name = (tag.name or "").lower()
|
||||
if name in _DANGEROUS_TAGS:
|
||||
removed.append(f"<{name}>")
|
||||
tag.decompose()
|
||||
continue
|
||||
# External stylesheet / preload links pull remote resources.
|
||||
if name == "link":
|
||||
href = str(tag.get("href") or "")
|
||||
rel = " ".join(tag.get("rel") or []) if isinstance(tag.get("rel"), list) else str(tag.get("rel") or "")
|
||||
if re.match(r"^\s*(https?:)?//", href) and "stylesheet" in rel.lower():
|
||||
removed.append("<link stylesheet>")
|
||||
tag.decompose()
|
||||
continue
|
||||
# meta refresh can redirect to arbitrary URLs.
|
||||
if name == "meta" and str(tag.get("http-equiv") or "").lower() == "refresh":
|
||||
removed.append("<meta refresh>")
|
||||
tag.decompose()
|
||||
continue
|
||||
|
||||
# 2) Strip event handlers and dangerous URL schemes from surviving tags.
|
||||
for tag in soup.find_all(True):
|
||||
for attr in list(tag.attrs.keys()):
|
||||
lowered = attr.lower()
|
||||
if lowered.startswith("on"):
|
||||
removed.append(f"{lowered}=")
|
||||
del tag.attrs[attr]
|
||||
continue
|
||||
if lowered in _URL_ATTRS:
|
||||
value = tag.attrs[attr]
|
||||
value_str = value if isinstance(value, str) else " ".join(value)
|
||||
if _DANGEROUS_URL_RE.match(value_str or ""):
|
||||
removed.append(f"{lowered}={value_str[:24]}")
|
||||
del tag.attrs[attr]
|
||||
|
||||
return str(soup), removed
|
||||
|
||||
|
||||
def constrain_same_page_anchor_links(html: str) -> tuple[str, list[str]]:
|
||||
"""Keep generated HTML document jumps inside the current HTML file."""
|
||||
if not html or not isinstance(html, str):
|
||||
return "", []
|
||||
try:
|
||||
from bs4 import BeautifulSoup
|
||||
except Exception: # pragma: no cover - bs4 is a declared dependency
|
||||
logger.warning("BeautifulSoup unavailable; returning HTML links unconstrained")
|
||||
return html, []
|
||||
|
||||
changed: list[str] = []
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
for tag in soup.find_all("a"):
|
||||
href = tag.get("href")
|
||||
if not isinstance(href, str):
|
||||
continue
|
||||
value = href.strip()
|
||||
if not value or value.startswith("#"):
|
||||
continue
|
||||
match = _LOCAL_DOC_LINK_RE.match(value)
|
||||
if not match:
|
||||
continue
|
||||
fragment = match.group("fragment")
|
||||
if fragment:
|
||||
tag["href"] = fragment
|
||||
changed.append(f"{value}->{fragment}")
|
||||
else:
|
||||
del tag.attrs["href"]
|
||||
changed.append(f"{value}->removed")
|
||||
return str(soup), changed
|
||||
|
||||
|
||||
def validate_html(html: str) -> list[str]:
|
||||
"""Return a list of structural problems with ``html`` (empty == valid).
|
||||
|
||||
A page only counts as a complete document when it has the full skeleton
|
||||
(doctype/html/head/body), a non-empty ``<title>``, visible body content
|
||||
(no white-screen), no residual scripts, and no external stylesheet links.
|
||||
"""
|
||||
errors: list[str] = []
|
||||
if not html or not isinstance(html, str):
|
||||
return ["empty html"]
|
||||
lowered = html.lower()
|
||||
if "<!doctype html" not in lowered:
|
||||
errors.append("缺少 <!doctype html> 声明")
|
||||
if "<html" not in lowered:
|
||||
errors.append("缺少 <html> 根元素")
|
||||
if "<head" not in lowered:
|
||||
errors.append("缺少 <head> 元素")
|
||||
if "<body" not in lowered:
|
||||
errors.append("缺少 <body> 元素")
|
||||
if "<script" in lowered:
|
||||
errors.append("仍包含 <script> 标签(不允许脚本)")
|
||||
|
||||
try:
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
# Title must exist and be non-empty.
|
||||
title_el = soup.find("title")
|
||||
if title_el is None or not title_el.get_text(strip=True):
|
||||
errors.append("缺少非空 <title> 标题")
|
||||
# External stylesheet links pull remote resources — not allowed offline.
|
||||
for link in soup.find_all("link"):
|
||||
href = str(link.get("href") or "")
|
||||
rel = " ".join(link.get("rel") or []) if isinstance(link.get("rel"), list) else str(link.get("rel") or "")
|
||||
if re.match(r"^\s*(https?:)?//", href) and "stylesheet" in rel.lower():
|
||||
errors.append("包含外链样式表(不允许外部 CDN/资源)")
|
||||
break
|
||||
# Body must carry some visible content — guards against white-screen.
|
||||
body = soup.body or soup
|
||||
text = body.get_text(strip=True) if body else ""
|
||||
has_media = bool(body.find(["img", "svg", "canvas", "table", "ul", "ol"])) if body else False
|
||||
if len(text) < 5 and not has_media:
|
||||
errors.append("页面正文为空,可能白屏")
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return errors
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prompt templates
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_GENERATION_TEMPLATE = """你是一个内网页面生成助手。请根据输入数据生成一个完整的 HTML 页面。
|
||||
|
||||
用户页面要求:
|
||||
{page_prompt}
|
||||
{constraint_block}本次数据:
|
||||
{data}
|
||||
|
||||
参考页面风格:
|
||||
{reference_style}
|
||||
|
||||
参考页面布局:
|
||||
{reference_layout}
|
||||
{skill_instructions}
|
||||
要求:
|
||||
1. 只输出 JSON,不要输出 Markdown,不要输出多余解释。
|
||||
2. JSON 字段必须包含 title、html、style_summary、layout_summary。
|
||||
3. html 字段的值必须是合法 JSON 字符串:其中所有换行必须写成 \\n、所有双引号必须转义为 \\",不要在字符串里直接换行或使用未转义的引号。
|
||||
4. html 必须是完整 HTML 文档,包含 <!doctype html>、html、head、body。
|
||||
5. 所有 CSS 写在 <style> 标签内,不要引用外部 CDN 或外链样式表。
|
||||
6. 不要包含 <script>、外链脚本、iframe、表单提交、on* 事件属性。
|
||||
7. 参考页面只用于风格和布局,页面内容必须来自“本次数据”,不要复用参考页旧数据。
|
||||
8. 页面使用中文,排版适合在浏览器中直接预览。
|
||||
9. HTML 内的目录/锚点跳转必须只跳转到当前这个 HTML 文件内部:只使用 href="#section-id",不要使用 href="index.html#section-id"、".md#..."、其它文件路径或任何跨文件锚点;目标区块必须有匹配的 id。
|
||||
"""
|
||||
|
||||
_REPAIR_TEMPLATE = """你是一个 HTML 修复助手。下面的 HTML 存在问题,请修复后重新输出完整页面。
|
||||
|
||||
原始页面要求:
|
||||
{requirements}
|
||||
|
||||
发现的问题:
|
||||
{errors}
|
||||
|
||||
待修复 HTML:
|
||||
{html}
|
||||
|
||||
要求:
|
||||
1. 只输出 JSON,字段包含 fixed_html、changes(修复说明数组)。
|
||||
2. fixed_html 必须是完整 HTML 文档,包含 <!doctype html>、html、head、body。
|
||||
3. 移除所有 <script>、iframe、外链脚本、on* 事件属性、表单提交。
|
||||
4. 保留原有内容与数据,只修复结构与安全问题。
|
||||
5. HTML 内的目录/锚点跳转必须只跳转到当前这个 HTML 文件内部:只使用 href="#section-id",不要链接到 .html/.md 文件作为锚点。
|
||||
"""
|
||||
|
||||
_STYLE_EXTRACT_TEMPLATE = """你是一个页面风格分析助手。请分析下面的 HTML 页面,提取可复用的风格与布局特征。
|
||||
|
||||
HTML 页面:
|
||||
{html}
|
||||
|
||||
要求:
|
||||
1. 只输出 JSON,字段包含 style_summary、layout_summary、content_structure_summary、reuse_prompt。
|
||||
2. style_summary:颜色、字体、间距、圆角、阴影、视觉密度等视觉风格。
|
||||
3. layout_summary:页面分区、卡片、表格、图表、导航等布局结构。
|
||||
4. content_structure_summary:信息组织顺序与层级。
|
||||
5. reuse_prompt:一段可直接拼接到下次生成 prompt 的中文风格说明,不要包含本页的具体数据。
|
||||
"""
|
||||
|
||||
|
||||
def _clip(value: Any, limit: int) -> str:
|
||||
text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, default=str)
|
||||
text = text or ""
|
||||
return text if len(text) <= limit else text[:limit] + "\n…(内容过长已截断)"
|
||||
|
||||
|
||||
def build_generation_prompt(
|
||||
*,
|
||||
page_prompt: str,
|
||||
negative_prompt: str | None,
|
||||
data: Any,
|
||||
reference_style: str | None,
|
||||
reference_layout: str | None,
|
||||
skill_instructions: str | None = None,
|
||||
data_limit: int = 16000,
|
||||
skill_limit: int = 30000,
|
||||
) -> str:
|
||||
skill_block = ""
|
||||
if skill_instructions and skill_instructions.strip():
|
||||
skill_block = "\n可用页面生成技能规范(请严格遵循):\n" + _clip(skill_instructions.strip(), skill_limit) + "\n"
|
||||
# The constraint block is only emitted when the user actually supplied one,
|
||||
# and is framed as a top-priority hard rule that overrides the page
|
||||
# requirements / reference page / data on conflict — otherwise the model
|
||||
# tends to treat "限制条件" as a soft hint and ignore it.
|
||||
constraint_block = ""
|
||||
neg = (negative_prompt or "").strip()
|
||||
if neg:
|
||||
constraint_block = (
|
||||
"\n限制条件(最高优先级的硬性约束,必须逐条严格遵守;"
|
||||
"若与上面的页面要求、参考页面或本次数据发生冲突,一律以这里的限制条件为准):\n"
|
||||
+ neg
|
||||
+ "\n\n"
|
||||
)
|
||||
return _GENERATION_TEMPLATE.format(
|
||||
page_prompt=(page_prompt or "(未提供,使用通用看板风格)").strip(),
|
||||
constraint_block=constraint_block,
|
||||
data=_clip(data, data_limit),
|
||||
reference_style=(reference_style or "无").strip(),
|
||||
reference_layout=(reference_layout or "无").strip(),
|
||||
skill_instructions=skill_block,
|
||||
)
|
||||
|
||||
|
||||
def build_repair_prompt(*, html: str, errors: list[str], requirements: str | None) -> str:
|
||||
return _REPAIR_TEMPLATE.format(
|
||||
requirements=(requirements or "无").strip(),
|
||||
errors="\n".join(f"- {e}" for e in errors) or "- 未知问题",
|
||||
html=_clip(html, 32000),
|
||||
)
|
||||
|
||||
|
||||
def build_style_extract_prompt(*, html: str) -> str:
|
||||
return _STYLE_EXTRACT_TEMPLATE.format(html=_clip(html, 32000))
|
||||
|
||||
|
||||
async def screenshot_html(html: str, output_path) -> str | None:
|
||||
"""Best-effort PNG screenshot of ``html`` for white-screen / console QA.
|
||||
|
||||
Returns the screenshot path on success, or ``None`` when Playwright (or a
|
||||
usable browser) is unavailable — the offline image ships without one, so
|
||||
this must degrade silently rather than fail the run.
|
||||
"""
|
||||
try:
|
||||
from playwright.async_api import async_playwright
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
async with async_playwright() as pw:
|
||||
browser = await pw.chromium.launch()
|
||||
try:
|
||||
page = await browser.new_page()
|
||||
await page.set_content(html, wait_until="networkidle")
|
||||
await page.screenshot(path=str(output_path), full_page=True)
|
||||
finally:
|
||||
await browser.close()
|
||||
return str(output_path)
|
||||
except Exception:
|
||||
logger.debug("Playwright screenshot failed; skipping QA screenshot", exc_info=True)
|
||||
return None
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
"""Process-local scheduled task service registry."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
_service: Any | None = None
|
||||
|
||||
|
||||
def set_scheduled_task_service(service: Any | None) -> None:
|
||||
global _service
|
||||
_service = service
|
||||
|
||||
|
||||
def get_scheduled_task_service() -> Any:
|
||||
if _service is None:
|
||||
raise RuntimeError("Scheduled task service is not initialized.")
|
||||
return _service
|
||||
+2372
File diff suppressed because it is too large.
Load diff
+796
@@ -0,0 +1,796 @@
|
||||
"""HTML 模板「JSON 填充」纯引擎 + 模板注册表。
|
||||
|
||||
定时任务的「模板数据转换器」内置 agent 把用户传入的任意 JSON 智能映射成某个
|
||||
HTML 模板需要的 ``DATA`` 结构后,本模块负责把数据**填充**进模板并产出一份完整、
|
||||
可预览的 HTML 文档。
|
||||
|
||||
设计要点
|
||||
--------
|
||||
* **模板自身即 schema 来源**:每个模板的 HTML 里都内嵌一行 ``const DATA={...};``
|
||||
(台湾滨海防卫展示系统 no.1 还内嵌 ``const MANIFEST={...};``)。我们直接解析这行
|
||||
拿到「参考数据」,既当**目标格式的范例**(喂给大模型),又当**结构校验**的基准
|
||||
(顶层键 + 类型)。注册表因此不需要手写一份庞大的 schema 字面量,改模板即改契约。
|
||||
* **行级安全替换**:模板把每个常量压在**单独一行**(``const DATA=...;`` 以分号结尾、
|
||||
行内无换行),所以用 ``^const VAR=.*;$`` (MULTILINE) 精确命中该行整体替换,绝不
|
||||
误伤模板里别处出现的同名子串。替换值用函数回调写入,避开 ``re.sub`` 把 JSON 里的
|
||||
反斜杠当反向引用的坑。
|
||||
* **harness 层、零 app.* 依赖**:可被调度器(harness)与 Gateway 路由(app)共同 import。
|
||||
|
||||
公开入口:``list_templates`` / ``get_template`` / ``reference_data`` /
|
||||
``schema_skeleton_json`` / ``validate_data`` / ``field_coverage_gaps`` /
|
||||
``shape_mismatches`` / ``fill_template``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
_FENCE_RE = re.compile(r"```(?:json)?\s*(.*?)```", re.DOTALL | re.IGNORECASE)
|
||||
|
||||
|
||||
def _scan_balanced(text: str, open_ch: str, close_ch: str) -> Any | None:
|
||||
"""从 text 里扫第一个**平衡**的 ``open_ch…close_ch`` 块并 ``json.loads``。
|
||||
|
||||
字符串感知(跳过引号内的括号/转义),失败返回 None。供从「含 JSON 的文本」里
|
||||
把 JSON 段抠出来用。
|
||||
"""
|
||||
start = text.find(open_ch)
|
||||
if start == -1:
|
||||
return None
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape = False
|
||||
for i in range(start, len(text)):
|
||||
ch = text[i]
|
||||
if in_string:
|
||||
if escape:
|
||||
escape = False
|
||||
elif ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_string = False
|
||||
continue
|
||||
if ch == '"':
|
||||
in_string = True
|
||||
elif ch == open_ch:
|
||||
depth += 1
|
||||
elif ch == close_ch:
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
blob = text[start : i + 1]
|
||||
try:
|
||||
return json.loads(blob)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def extract_embedded_json(text: str | None) -> Any | None:
|
||||
"""尽力从一段文本里抽出内嵌的 JSON(对象或数组)。
|
||||
|
||||
覆盖三种用户输入:纯 JSON(直接解析)、含 JSON 的文本(抠出第一个平衡的
|
||||
``{…}`` 或 ``[…]``)、纯文本(返回 ``None``)。也识别 ```json fence。
|
||||
"""
|
||||
if not text or not isinstance(text, str):
|
||||
return None
|
||||
s = text.strip()
|
||||
fence = _FENCE_RE.search(s)
|
||||
if fence:
|
||||
inner = fence.group(1).strip()
|
||||
try:
|
||||
return json.loads(inner)
|
||||
except (ValueError, TypeError):
|
||||
s = inner # fence 内不是完整 JSON,继续往下扫
|
||||
try:
|
||||
return json.loads(s)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
# 取最靠前出现的那种括号块(对象优先于数组,谁先出现谁优先)。
|
||||
brace = _scan_balanced(s, "{", "}")
|
||||
bracket = _scan_balanced(s, "[", "]")
|
||||
if brace is not None and bracket is not None:
|
||||
return brace if s.find("{") <= s.find("[") else bracket
|
||||
return brace if brace is not None else bracket
|
||||
|
||||
# 模板资源根目录(随 git 发布,与本模块同级 ``templates/`` 子目录)。
|
||||
_TEMPLATES_ROOT = Path(__file__).parent / "templates"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TemplateSpec:
|
||||
"""一个 HTML 模板的注册信息。
|
||||
|
||||
``file`` 相对 :data:`_TEMPLATES_ROOT`;``data_var``/``manifest_var`` 是模板里
|
||||
待替换的 JS 常量名(``manifest_var`` 为空表示该模板没有 MANIFEST 行)。
|
||||
|
||||
``convertible=False`` 表示该模板暂只「直接展示已有数据」——执行时原样输出模板
|
||||
HTML,不做 JSON 转换/校验/填充(无 ``const DATA=`` 注入行的模板用它,后续接入
|
||||
转换后改回 True)。
|
||||
"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
description: str
|
||||
file: str
|
||||
data_var: str = "DATA"
|
||||
manifest_var: str = ""
|
||||
convertible: bool = True
|
||||
|
||||
|
||||
# 已注册模板。新增 no.2/no.3 时在此追加一条即可——前端下拉、调度器填充全自动生效。
|
||||
TEMPLATES: tuple[TemplateSpec, ...] = (
|
||||
TemplateSpec(
|
||||
id="no1",
|
||||
name="no.1",
|
||||
description="",
|
||||
file="no1/taiwan_littoral_ui_redwhite_v2.html",
|
||||
data_var="DATA",
|
||||
manifest_var="MANIFEST",
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no2",
|
||||
name="no.2",
|
||||
description="",
|
||||
file="no2/taiwan_air_force_v3_2.html",
|
||||
# 暂只展示已有数据,不做 JSON 转换/填充(后续接入转换后再开)。
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no3",
|
||||
name="no.3",
|
||||
description="",
|
||||
file="no3/no3.html",
|
||||
# 无 const DATA= 注入点,暂只展示已有数据(后续接入转换后再开)。
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no4",
|
||||
name="no.4",
|
||||
description="",
|
||||
file="no4/no4.html",
|
||||
# 数据存于 <script id="app-data" type="application/json"> 元素(非 const DATA= 行),
|
||||
# 当前引擎只支持 const VAR= 行注入,故暂注册为只展示;接转换需扩展元素注入。
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no5",
|
||||
name="no.5",
|
||||
description="",
|
||||
file="no5/no5.html",
|
||||
# 数据用 `let DATA = {…}`(let + 空格,非 const DATA= 行),当前引擎不匹配,
|
||||
# 故暂注册为只展示;接转换需扩展行注入正则。
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no6",
|
||||
name="no.6",
|
||||
description="",
|
||||
file="no6/no6.html",
|
||||
# 数据用 `const DATA = {…}`(= 前有空格,当前引擎正则要求 const DATA=),不匹配,
|
||||
# 故暂注册为只展示;接转换需放宽行注入正则。
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no7",
|
||||
name="no.7",
|
||||
description="",
|
||||
file="no7/no7.html",
|
||||
# 数据存于 <script id="PAGE_DATA" type="application/json"> 元素(同 no.4 类元素注入),
|
||||
# 当前引擎只支持 const VAR= 行注入,故暂注册为只展示;接转换需扩展元素注入。
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
# 显示 no.8;id 用 no8b(no8 已被显示名 no.12 的模板占用)。
|
||||
id="no8b",
|
||||
name="no.8",
|
||||
description="",
|
||||
file="no8b/no8b.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
# 显示 no.9;id 用 no9b(no9 已被显示名 no.13 的模板占用)。
|
||||
id="no9b",
|
||||
name="no.9",
|
||||
description="",
|
||||
file="no9b/no9b.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no10",
|
||||
name="no.10",
|
||||
description="",
|
||||
file="no10/no10.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no11",
|
||||
name="no.11",
|
||||
description="",
|
||||
file="no11/no11.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no8",
|
||||
name="no.12",
|
||||
description="",
|
||||
file="no8/no8.html",
|
||||
# 数据存于 <script id="DATA" type="application/json"> 元素(同 no.4/no.7 元素注入),
|
||||
# 当前引擎只支持 const VAR= 行注入,故暂注册为只展示;接转换需扩展元素注入。
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no9",
|
||||
name="no.13",
|
||||
description="",
|
||||
file="no9/no9.html",
|
||||
# 数据用 `const DATA = {…}`(= 前有空格,同 no.6),当前引擎正则要求 const DATA=,不匹配,
|
||||
# 故暂注册为只展示;接转换需放宽行注入正则。
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no14",
|
||||
name="no.14",
|
||||
description="",
|
||||
file="no14/no14.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no15",
|
||||
name="no.15",
|
||||
description="",
|
||||
file="no15/no15.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no16",
|
||||
name="no.16",
|
||||
description="",
|
||||
file="no16/no16.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no17",
|
||||
name="no.17",
|
||||
description="",
|
||||
file="no17/no17.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no18",
|
||||
name="no.18",
|
||||
description="",
|
||||
file="no18/no18.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no19",
|
||||
name="no.19",
|
||||
description="",
|
||||
file="no19/no.19.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no20",
|
||||
name="no.20",
|
||||
description="",
|
||||
file="no20/no.20.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no21",
|
||||
name="no.21",
|
||||
description="",
|
||||
file="no21/no.21.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no22",
|
||||
name="no.22",
|
||||
description="",
|
||||
file="no22/no.22.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no23",
|
||||
name="no.23",
|
||||
description="",
|
||||
file="no23/no.23.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no24",
|
||||
name="no.24",
|
||||
description="",
|
||||
file="no24/no.24.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no25",
|
||||
name="no.25",
|
||||
description="",
|
||||
file="no25/no.25.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no26",
|
||||
name="no.26",
|
||||
description="",
|
||||
file="no26/no.26.html",
|
||||
convertible=False,
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no27",
|
||||
name="no.27",
|
||||
description="",
|
||||
file="no27/no.27.html",
|
||||
convertible=False,
|
||||
),
|
||||
)
|
||||
|
||||
_TEMPLATES_BY_ID: dict[str, TemplateSpec] = {t.id: t for t in TEMPLATES}
|
||||
|
||||
|
||||
class TemplateError(Exception):
|
||||
"""模板缺失 / 解析失败 / 填充失败。"""
|
||||
|
||||
|
||||
def list_templates() -> list[dict[str, Any]]:
|
||||
"""前端下拉用的轻量清单(只含 id/name/description/convertible,不含庞大数据)。"""
|
||||
return [
|
||||
{"id": t.id, "name": t.name, "description": t.description, "convertible": t.convertible}
|
||||
for t in TEMPLATES
|
||||
]
|
||||
|
||||
|
||||
def get_template(template_id: str) -> TemplateSpec | None:
|
||||
return _TEMPLATES_BY_ID.get(template_id)
|
||||
|
||||
|
||||
def is_convertible(template_id: str) -> bool:
|
||||
spec = _TEMPLATES_BY_ID.get(template_id)
|
||||
return bool(spec and spec.convertible)
|
||||
|
||||
|
||||
def _require(template_id: str) -> TemplateSpec:
|
||||
spec = _TEMPLATES_BY_ID.get(template_id)
|
||||
if spec is None:
|
||||
raise TemplateError(f"未知模板 id:{template_id!r}")
|
||||
return spec
|
||||
|
||||
|
||||
def _template_path(spec: TemplateSpec) -> Path:
|
||||
return _TEMPLATES_ROOT / spec.file
|
||||
|
||||
|
||||
def read_template_text(template_id: str) -> str:
|
||||
spec = _require(template_id)
|
||||
path = _template_path(spec)
|
||||
if not path.is_file():
|
||||
raise TemplateError(f"模板文件缺失:{path}")
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _const_line_re(var: str) -> re.Pattern[str]:
|
||||
# 单行 ``const VAR={...};`` —— 默认点号不跨行,故 ``.*`` 恰好吃到该物理行的结尾分号。
|
||||
return re.compile(r"^const " + re.escape(var) + r"=.*;[ \t]*$", re.MULTILINE)
|
||||
|
||||
|
||||
def _extract_const_object(text: str, var: str) -> Any:
|
||||
"""解析模板里 ``const VAR={...};`` 那一行的 JSON 值。"""
|
||||
match = _const_line_re(var).search(text)
|
||||
if match is None:
|
||||
raise TemplateError(f"模板中未找到 const {var}=… 行")
|
||||
line = match.group(0).strip()
|
||||
body = line[len("const ") + len(var) + 1 :] # 去掉 ``const VAR=``
|
||||
body = body.rstrip().rstrip(";").rstrip()
|
||||
try:
|
||||
return json.loads(body)
|
||||
except json.JSONDecodeError as exc: # pragma: no cover - 模板损坏才会触发
|
||||
raise TemplateError(f"解析 const {var} 失败:{exc}") from exc
|
||||
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def reference_data(template_id: str) -> dict[str, Any]:
|
||||
"""模板内嵌的参考 ``DATA`` 对象(目标格式范例 + 校验基准),按模板缓存。"""
|
||||
spec = _require(template_id)
|
||||
text = read_template_text(template_id)
|
||||
obj = _extract_const_object(text, spec.data_var)
|
||||
if not isinstance(obj, dict):
|
||||
raise TemplateError(f"模板 {template_id} 的 {spec.data_var} 不是对象")
|
||||
return obj
|
||||
|
||||
|
||||
def _skeleton(value: Any, *, list_sample: int = 1, depth: int = 0, max_depth: int = 6) -> Any:
|
||||
"""把一份具体数据压成「空占位骨架」:保留全部字段名与类型,值一律抹空。
|
||||
|
||||
模板只是样式外壳,**示例值(模板自带的模拟内容)绝不能进入转换 prompt**——
|
||||
否则大模型会照抄示例内容、或被其领域(如台海防卫)限制住,不肯把用户主题的
|
||||
内容映射进来。叶子按类型给空占位:字符串→\"\"、数字→0、布尔→false、
|
||||
其它→null;数组元素同构,留 1 个抹空样例即可暴露该元素的完整字段集。
|
||||
"""
|
||||
if depth >= max_depth:
|
||||
return None
|
||||
if isinstance(value, dict):
|
||||
return {k: _skeleton(v, list_sample=list_sample, depth=depth + 1, max_depth=max_depth) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
if not value:
|
||||
return []
|
||||
return [_skeleton(v, list_sample=list_sample, depth=depth + 1, max_depth=max_depth) for v in value[:list_sample]]
|
||||
if isinstance(value, bool):
|
||||
return False
|
||||
if isinstance(value, (int, float)):
|
||||
return 0
|
||||
if isinstance(value, str):
|
||||
return ""
|
||||
return None
|
||||
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def schema_skeleton_json(template_id: str) -> str:
|
||||
"""目标格式的空占位骨架(JSON 字符串),注入到大模型的转换 prompt 里。"""
|
||||
skeleton = _skeleton(reference_data(template_id))
|
||||
return json.dumps(skeleton, ensure_ascii=False, indent=1)
|
||||
|
||||
|
||||
def top_level_keys(template_id: str) -> list[str]:
|
||||
return list(reference_data(template_id).keys())
|
||||
|
||||
|
||||
def validate_data(template_id: str, obj: Any) -> list[str]:
|
||||
"""硬校验:转换结果必须是对象,且顶层键齐全、容器类型与模板一致。
|
||||
|
||||
返回错误列表(空 = 通过)。只校验顶层结构——字段级缺失通过
|
||||
:func:`field_coverage_gaps` 作为软反馈回喂大模型,而不在这里硬卡死。
|
||||
"""
|
||||
errors: list[str] = []
|
||||
if not isinstance(obj, dict):
|
||||
return ["转换结果不是 JSON 对象(应为 {…})"]
|
||||
ref = reference_data(template_id)
|
||||
for key, ref_val in ref.items():
|
||||
if key not in obj:
|
||||
errors.append(f"缺少顶层字段「{key}」")
|
||||
continue
|
||||
got = obj[key]
|
||||
if isinstance(ref_val, list) and not isinstance(got, list):
|
||||
errors.append(f"字段「{key}」应为数组")
|
||||
elif isinstance(ref_val, dict) and not isinstance(got, dict):
|
||||
errors.append(f"字段「{key}」应为对象")
|
||||
return errors
|
||||
|
||||
|
||||
def _element_fields(value: Any) -> set[str]:
|
||||
"""取一个数组里所有 dict 元素字段名的并集。"""
|
||||
fields: set[str] = set()
|
||||
if isinstance(value, list):
|
||||
for item in value:
|
||||
if isinstance(item, dict):
|
||||
fields.update(item.keys())
|
||||
return fields
|
||||
|
||||
|
||||
def field_coverage_gaps(template_id: str, obj: Any, *, max_items: int = 40) -> list[str]:
|
||||
"""软反馈:对照参考数据,列出转换结果里缺失的字段(数组元素字段 / 对象子键)。
|
||||
|
||||
用于把「字段没填全」回喂大模型让它补齐,不作为硬性失败。
|
||||
"""
|
||||
gaps: list[str] = []
|
||||
if not isinstance(obj, dict):
|
||||
return gaps
|
||||
ref = reference_data(template_id)
|
||||
for key, ref_val in ref.items():
|
||||
if key not in obj:
|
||||
continue
|
||||
got = obj[key]
|
||||
if isinstance(ref_val, dict) and isinstance(got, dict):
|
||||
for sub in ref_val:
|
||||
if sub not in got:
|
||||
gaps.append(f"{key}.{sub} 缺失")
|
||||
elif isinstance(ref_val, list) and isinstance(got, list):
|
||||
want = _element_fields(ref_val)
|
||||
have = _element_fields(got)
|
||||
for f in sorted(want - have):
|
||||
gaps.append(f"{key}[].{f} 缺失")
|
||||
if len(gaps) >= max_items:
|
||||
return gaps[:max_items] + ["…(更多字段省略)"]
|
||||
return gaps
|
||||
|
||||
|
||||
def _has_content(value: Any) -> bool:
|
||||
"""该值是否含「有效内容」(用于判断子页面 / 字段是否抽到东西)。
|
||||
|
||||
空 / None / 空串 / 全空的列表或字典 视为无内容;数字(含 0)、布尔、非空字符串
|
||||
视为有内容。
|
||||
"""
|
||||
if value is None:
|
||||
return False
|
||||
if isinstance(value, str):
|
||||
return bool(value.strip())
|
||||
if isinstance(value, (list, tuple)):
|
||||
return any(_has_content(v) for v in value)
|
||||
if isinstance(value, dict):
|
||||
return any(_has_content(v) for v in value.values())
|
||||
return True # 数字 / 布尔 / 其它标量
|
||||
|
||||
|
||||
# 元素字段中至少要有这个比例能在模板参考数据的元素字段里找到,否则视为「自造字段」。
|
||||
_LIST_FIELD_OVERLAP_MIN = 0.5
|
||||
# 元素字段至少要覆盖模板参考元素字段的这个比例:低于它意味着大部分展示字段缺失
|
||||
# (卡片大面积空白/undefined),不如整支回退模板原数据。
|
||||
_LIST_FIELD_RECALL_MIN = 0.4
|
||||
|
||||
|
||||
def _list_misaligned(got: Any, ref_val: Any) -> bool:
|
||||
"""非空列表与模板参考列表是否「无法有效渲染」。
|
||||
|
||||
顶层校验挡不住这种情况:转换结果键齐全、类型也对,但列表元素的**字段**不对,
|
||||
填进模板后 JS 读不到字段,页面满屏 ``undefined``。判定(满足其一即错位):
|
||||
|
||||
* 模板元素是对象而转换给了非对象(字符串/数字读不出属性);
|
||||
* 元素字段里能对上模板的比例过低(:data:`_LIST_FIELD_OVERLAP_MIN`,
|
||||
自造字段名占主导);
|
||||
* 元素字段对模板参考字段的**覆盖率**过低(:data:`_LIST_FIELD_RECALL_MIN`,
|
||||
只填了零星几个字段,展示字段大面积缺失)。
|
||||
|
||||
空列表不算错位(交由「无内容回退」处理)。
|
||||
"""
|
||||
if not isinstance(got, list) or not got:
|
||||
return False
|
||||
ref_fields = _element_fields(ref_val)
|
||||
if not ref_fields:
|
||||
return False # 模板元素本身没有对象字段,无从比对
|
||||
ref_dicts = [item for item in ref_val if isinstance(item, dict)]
|
||||
got_dicts = [item for item in got if isinstance(item, dict)]
|
||||
if ref_dicts and not got_dicts:
|
||||
return True # 模板元素是对象,转换给了字符串/数字 → 必然读不到字段
|
||||
if not got_dicts:
|
||||
return False
|
||||
got_fields: set[str] = set()
|
||||
for item in got_dicts:
|
||||
got_fields.update(item.keys())
|
||||
if not got_fields:
|
||||
return False
|
||||
overlap = got_fields & ref_fields
|
||||
if len(overlap) / len(got_fields) < _LIST_FIELD_OVERLAP_MIN:
|
||||
return True # 自造字段名占主导
|
||||
return len(overlap) / len(ref_fields) < _LIST_FIELD_RECALL_MIN # 覆盖率过低
|
||||
|
||||
|
||||
def _mismatch_reason(got: Any, ref_val: Any) -> str:
|
||||
"""错位原因的人话描述(回喂重试用),与 :func:`_list_misaligned` 同判定。"""
|
||||
ref_fields = _element_fields(ref_val)
|
||||
got_fields: set[str] = set()
|
||||
for item in got or []:
|
||||
if isinstance(item, dict):
|
||||
got_fields.update(item.keys())
|
||||
overlap = got_fields & ref_fields
|
||||
if got_fields and len(overlap) / len(got_fields) < _LIST_FIELD_OVERLAP_MIN:
|
||||
return "的元素字段名与模板不一致(疑似自造字段名,必须原样沿用目标结构的字段名)"
|
||||
return "的元素字段覆盖过低(样例元素的字段大部分缺失;缺数据的字段按类型留空补齐,不要省略字段)"
|
||||
|
||||
|
||||
def shape_mismatches(template_id: str, obj: Any, *, max_items: int = 20) -> list[str]:
|
||||
"""硬反馈:列出非空列表分支里「无法有效渲染」的项(供回喂重试)。
|
||||
|
||||
与 :func:`field_coverage_gaps`(软反馈,字段没填全)不同,本函数抓的是
|
||||
**填了也渲染不出来**的情况:列表有内容但元素字段自造(对不上模板)或覆盖
|
||||
过低(展示字段大面积缺失) → 渲染必然大面积 undefined,必须回喂重试。
|
||||
"""
|
||||
out: list[str] = []
|
||||
if not isinstance(obj, dict):
|
||||
return out
|
||||
ref = reference_data(template_id)
|
||||
for key, ref_val in ref.items():
|
||||
got = obj.get(key)
|
||||
if isinstance(ref_val, list) and _list_misaligned(got, ref_val):
|
||||
out.append(f"「{key}」{_mismatch_reason(got, ref_val)}")
|
||||
if len(out) >= max_items:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _ref_element_types(ref_val: list) -> dict[str, Any]:
|
||||
"""参考列表各字段的类型样本(取第一个携带该字段的元素)。"""
|
||||
types: dict[str, Any] = {}
|
||||
for item in ref_val:
|
||||
if isinstance(item, dict):
|
||||
for key, value in item.items():
|
||||
types.setdefault(key, value)
|
||||
return types
|
||||
|
||||
|
||||
def _blank_like(sample: Any) -> Any:
|
||||
"""按参考类型给出「空值」:字符串→空串、列表→空数组、对象→空对象、其它→null。"""
|
||||
if isinstance(sample, str):
|
||||
return ""
|
||||
if isinstance(sample, list):
|
||||
return []
|
||||
if isinstance(sample, dict):
|
||||
return {}
|
||||
return None
|
||||
|
||||
|
||||
def _fill_missing_fields(got: list, ref_val: list) -> list:
|
||||
"""给保留的转换列表逐元素补齐模板元素字段(缺失的按参考类型给空值)。
|
||||
|
||||
模板 JS 常裸读 ``${item.字段}``(不经过空值兜底函数),字段缺失会直接把
|
||||
``undefined`` 打到页面上;补齐成空值后渲染为空白,不再出现字面 undefined。
|
||||
只补缺、不改已有值,多出来的自造键原样保留(JS 不读,无害)。
|
||||
"""
|
||||
types = _ref_element_types(ref_val)
|
||||
if not types:
|
||||
return got
|
||||
out: list[Any] = []
|
||||
for item in got:
|
||||
if isinstance(item, dict):
|
||||
filled = dict(item)
|
||||
for key, sample in types.items():
|
||||
if key not in filled:
|
||||
filled[key] = _blank_like(sample)
|
||||
out.append(filled)
|
||||
else:
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _merge_fill(got: Any, ref: Any) -> Any:
|
||||
"""用 ``got`` 覆盖,但 ``got`` 里「没有有效内容」的部分回退 ``ref``。
|
||||
|
||||
字典逐键递归(空分支回退);列表有内容就整体保留 ``got``(不逐元素合并,避免与
|
||||
原模板元素错配)——**例外**:列表元素无法有效渲染(:func:`_list_misaligned`,
|
||||
自造字段名占主导/覆盖率过低/元素类型不符)时整支回退 ``ref``,否则填进模板
|
||||
JS 读不到字段,页面满屏 undefined。保留的列表会逐元素补齐缺失字段的空值
|
||||
(:func:`_fill_missing_fields`),防止局部缺字段裸读出 undefined。
|
||||
"""
|
||||
if not _has_content(got):
|
||||
return ref
|
||||
if isinstance(ref, dict) and isinstance(got, dict):
|
||||
out = dict(got) # 保留 got 里 ref 没有的额外键
|
||||
for key, ref_val in ref.items():
|
||||
out[key] = _merge_fill(got.get(key), ref_val)
|
||||
return out
|
||||
if isinstance(ref, list) and isinstance(got, list):
|
||||
if _list_misaligned(got, ref):
|
||||
return ref
|
||||
return _fill_missing_fields(got, ref)
|
||||
return got
|
||||
|
||||
|
||||
def merge_with_reference(template_id: str, data: Any) -> dict[str, Any]:
|
||||
"""用转换结果覆盖,但「没抽到有效内容」的子页面 / 字段回退模板原有数据。
|
||||
|
||||
顶层键即子页面:某子页面(及其内部空字段)无有效内容时,用模板自带的原始数据补上,
|
||||
保证页面与子页面不空白。整体为空时等价于返回模板默认数据。
|
||||
"""
|
||||
ref = reference_data(template_id)
|
||||
merged = _merge_fill(data, ref)
|
||||
return merged if isinstance(merged, dict) else dict(ref)
|
||||
|
||||
|
||||
def _dump_const(var: str, obj: Any) -> str:
|
||||
body = json.dumps(obj, ensure_ascii=False)
|
||||
return f"const {var}={body};"
|
||||
|
||||
|
||||
def _escape_html(text: str) -> str:
|
||||
return (
|
||||
text.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace('"', """)
|
||||
)
|
||||
|
||||
|
||||
# 转换结果里约定的两个额外顶层键:页面大标题/副标题(填充时替换页头,不进 DATA)。
|
||||
PAGE_TITLE_KEY = "页面标题"
|
||||
PAGE_SUBTITLE_KEY = "页面副标题"
|
||||
|
||||
|
||||
def pop_page_titles(obj: dict[str, Any]) -> tuple[str | None, str | None]:
|
||||
"""取出并移除转换结果里的「页面标题/页面副标题」额外键。
|
||||
|
||||
模型按转换 prompt 的约定额外输出这两个顶层字符串键;它们不是模板 DATA 的
|
||||
字段(校验本就忽略额外键),填充前摘出来用于替换页头,避免漏进 ``const DATA``。
|
||||
"""
|
||||
def _clean(value: Any) -> str | None:
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return None
|
||||
|
||||
title = _clean(obj.pop(PAGE_TITLE_KEY, None))
|
||||
subtitle = _clean(obj.pop(PAGE_SUBTITLE_KEY, None))
|
||||
return title, subtitle
|
||||
|
||||
|
||||
def fill_template(
|
||||
template_id: str,
|
||||
data_obj: Any,
|
||||
*,
|
||||
manifest_overrides: dict[str, Any] | None = None,
|
||||
update_date: date | None = None,
|
||||
title: str | None = None,
|
||||
subtitle: str | None = None,
|
||||
) -> str:
|
||||
"""把 ``data_obj`` 填进模板的 ``const DATA=…`` 行,产出完整 HTML 文档。
|
||||
|
||||
可选地更新 MANIFEST 的「系统.更新时间」(``update_date``,默认不动) 以及任意
|
||||
``manifest_overrides``(深合并到解析后的 MANIFEST,如改系统名称)。
|
||||
|
||||
``title``/``subtitle`` 来自转换结果里的「页面标题/页面副标题」:模板页头
|
||||
(<title>、第一个 <h1>、其后紧跟的副标题 <p>)是写死的静态 HTML,不随 DATA
|
||||
变化——给出新标题时替换这三处,并把 MANIFEST 的 系统.名称 一并同步;
|
||||
不给则保持模板原文。
|
||||
"""
|
||||
spec = _require(template_id)
|
||||
text = read_template_text(template_id)
|
||||
|
||||
if title:
|
||||
overrides = dict(manifest_overrides or {})
|
||||
system = overrides.get("系统")
|
||||
system = dict(system) if isinstance(system, dict) else {}
|
||||
system["名称"] = title
|
||||
overrides["系统"] = system
|
||||
manifest_overrides = overrides
|
||||
escaped = _escape_html(title)
|
||||
text = re.sub(r"<title>.*?</title>", lambda _m: f"<title>{escaped}</title>", text, count=1, flags=re.DOTALL)
|
||||
text = re.sub(r"<h1>.*?</h1>", lambda _m: f"<h1>{escaped}</h1>", text, count=1, flags=re.DOTALL)
|
||||
if subtitle:
|
||||
escaped_sub = _escape_html(subtitle)
|
||||
text = re.sub(
|
||||
r"(<h1>.*?</h1>\s*<p>).*?(</p>)",
|
||||
lambda m: f"{m.group(1)}{escaped_sub}{m.group(2)}",
|
||||
text,
|
||||
count=1,
|
||||
flags=re.DOTALL,
|
||||
)
|
||||
|
||||
data_re = _const_line_re(spec.data_var)
|
||||
if data_re.search(text) is None:
|
||||
raise TemplateError(f"模板 {template_id} 中未找到 const {spec.data_var}= 行")
|
||||
new_data_line = _dump_const(spec.data_var, data_obj)
|
||||
text = data_re.sub(lambda _m: new_data_line, text, count=1)
|
||||
|
||||
if spec.manifest_var and (manifest_overrides or update_date is not None):
|
||||
manifest_re = _const_line_re(spec.manifest_var)
|
||||
match = manifest_re.search(text)
|
||||
if match is not None:
|
||||
try:
|
||||
manifest = _extract_const_object(text, spec.manifest_var)
|
||||
except TemplateError:
|
||||
manifest = None
|
||||
if isinstance(manifest, dict):
|
||||
if update_date is not None:
|
||||
system = manifest.get("系统")
|
||||
if isinstance(system, dict):
|
||||
system["更新时间"] = update_date.isoformat()
|
||||
if manifest_overrides:
|
||||
_deep_merge(manifest, manifest_overrides)
|
||||
new_manifest_line = _dump_const(spec.manifest_var, manifest)
|
||||
text = manifest_re.sub(lambda _m: new_manifest_line, text, count=1)
|
||||
return text
|
||||
|
||||
|
||||
def _deep_merge(base: dict[str, Any], overrides: dict[str, Any]) -> None:
|
||||
for k, v in overrides.items():
|
||||
if isinstance(v, dict) and isinstance(base.get(k), dict):
|
||||
_deep_merge(base[k], v)
|
||||
else:
|
||||
base[k] = v
|
||||
|
||||
|
||||
# ── require_html 模式选「内置模板」作参考 ─────────────────────────────────────────
|
||||
# 「参考收藏页面」下拉里模板选项的值存成 ``tpl:<id>``,与用户收藏(普通 id)区分。
|
||||
# 选了模板 → 调度器用**真实模板**出页(保留全部子页面),不抽风格摘要(那会丢子页面)。
|
||||
REFERENCE_PREFIX = "tpl:"
|
||||
|
||||
|
||||
def reference_template_id(reference: str | None) -> str | None:
|
||||
"""``tpl:no1`` → ``no1``;非模板参考(普通收藏 id / 空)返回 None。"""
|
||||
if isinstance(reference, str) and reference.startswith(REFERENCE_PREFIX):
|
||||
return reference[len(REFERENCE_PREFIX) :] or None
|
||||
return None
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>台湾滨海防卫知识数据展示系统</title>
|
||||
<style>
|
||||
:root{
|
||||
--red:#c8102e;--red2:#8f1024;--light-red:#fff1f3;--soft-red:#fde7eb;
|
||||
--bg:#f5f5f6;--card:#fff;--text:#262626;--muted:#737373;--line:#e5e5e5;
|
||||
--green:#168a4a;--orange:#c56a00;--shadow:0 8px 24px rgba(74,12,24,.08)
|
||||
}
|
||||
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--bg);color:var(--text);font-family:"PingFang SC","Microsoft YaHei",Arial,sans-serif}
|
||||
button,input,select{font:inherit}.header{position:sticky;top:0;z-index:30;background:#fff;border-bottom:1px solid var(--line);box-shadow:0 3px 12px rgba(0,0,0,.04)}
|
||||
.header-top{height:70px;padding:0 28px;display:flex;align-items:center;gap:24px}.logo{width:42px;height:42px;border-radius:12px;background:linear-gradient(145deg,var(--red),var(--red2));display:grid;place-items:center;color:#fff;font-weight:800}
|
||||
.title{flex:1}.title h1{font-size:19px;margin:0 0 5px}.title p{margin:0;font-size:12px;color:var(--muted)}.header-state{text-align:right;font-size:12px;color:var(--muted)}
|
||||
.tabs{display:flex;padding:0 24px;gap:4px;overflow:auto}.tab{border:0;background:transparent;padding:13px 18px;color:#666;cursor:pointer;border-bottom:3px solid transparent;white-space:nowrap}.tab.active{color:var(--red);font-weight:700;border-bottom-color:var(--red);background:linear-gradient(to top,var(--light-red),transparent)}
|
||||
.main{padding:24px 28px 48px}.hero{background:linear-gradient(135deg,#fff,#fff5f6);border:1px solid #f2d4d9;border-radius:20px;padding:24px;display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:18px;box-shadow:var(--shadow)}
|
||||
.hero h2{margin:0 0 8px;font-size:26px}.hero p{margin:0;color:var(--muted);line-height:1.7}.hero-mark{width:90px;height:90px;border-radius:50%;background:radial-gradient(circle,#fff 0 30%,#fbd5dc 31% 55%,var(--red) 56%);opacity:.9}
|
||||
.btn{border:1px solid #d8d8d8;background:#fff;color:#333;border-radius:9px;padding:8px 13px;cursor:pointer}.btn:hover{border-color:var(--red);color:var(--red)}.btn-red{background:var(--red);border-color:var(--red);color:#fff}.btn-red:hover{background:var(--red2);color:#fff}.btn-soft{background:var(--light-red);color:var(--red);border-color:#f0bec8}
|
||||
.metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:18px}.metric{background:#fff;border:1px solid var(--line);border-radius:16px;padding:17px;box-shadow:var(--shadow);position:relative;overflow:hidden}.metric:after{content:"";position:absolute;right:-20px;top:-30px;width:90px;height:90px;border-radius:50%;background:var(--light-red)}.metric-label{font-size:13px;color:var(--muted)}.metric-value{font-size:30px;font-weight:800;color:var(--red);margin-top:8px}.metric-unit{font-size:12px;margin-left:4px}.metric-note{font-size:12px;color:#888;margin-top:6px}
|
||||
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:16px}.panel{background:#fff;border:1px solid var(--line);border-radius:17px;padding:18px;box-shadow:var(--shadow)}.panel-title{font-weight:800;margin-bottom:14px;display:flex;align-items:center;justify-content:space-between}.panel-title:before{content:"";width:5px;height:18px;background:var(--red);border-radius:5px;margin-right:9px}.panel-title span:first-child{display:flex;align-items:center}
|
||||
.bar-row{display:grid;grid-template-columns:150px 1fr 38px;gap:10px;align-items:center;font-size:12px;margin:10px 0}.bar{height:9px;background:#f1f1f1;border-radius:20px;overflow:hidden}.bar i{display:block;height:100%;background:linear-gradient(90deg,var(--red),#ed6b7e);border-radius:20px}
|
||||
.entry-grid,.card-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.entry-card,.data-card{background:#fff;border:1px solid var(--line);border-radius:16px;padding:17px;box-shadow:var(--shadow);cursor:pointer;transition:.18s}.entry-card:hover,.data-card:hover{transform:translateY(-2px);border-color:#e0a0ab}.entry-card b,.data-card h3{display:block;margin:0 0 8px}.entry-num{font-size:25px;color:var(--red);font-weight:800}.entry-card p,.data-card p{font-size:12px;color:var(--muted);line-height:1.65;margin:8px 0 0}
|
||||
.toolbar{background:#fff;border:1px solid var(--line);border-radius:14px;padding:12px;display:flex;gap:9px;align-items:center;flex-wrap:wrap;margin-bottom:16px;box-shadow:var(--shadow)}.toolbar input,.toolbar select{height:37px;border:1px solid #ddd;border-radius:8px;background:#fff;padding:0 10px;color:#333}.toolbar input{flex:1;min-width:250px}.toolbar-count{margin-left:auto;color:var(--muted);font-size:12px}
|
||||
.chip{display:inline-flex;align-items:center;border-radius:999px;padding:4px 9px;background:#f3f3f3;color:#555;font-size:11px;margin:2px}.chip-red{background:var(--light-red);color:var(--red)}.chip-green{background:#edf9f2;color:var(--green)}.chip-orange{background:#fff6e8;color:var(--orange)}
|
||||
.region-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:15px}.region-card{background:#fff;border:1px solid var(--line);border-radius:18px;padding:18px;box-shadow:var(--shadow);cursor:pointer;position:relative;overflow:hidden}.region-card:before{content:"";position:absolute;left:0;top:0;bottom:0;width:5px;background:var(--red)}.region-card h3{margin:0 0 8px;font-size:18px}.region-card p{font-size:12px;color:var(--muted);line-height:1.7}.region-stats{display:flex;gap:18px;margin-top:13px;border-top:1px solid #f0f0f0;padding-top:12px}.region-stats b{color:var(--red);font-size:18px}
|
||||
.segmented{display:flex;gap:5px;background:#f0f0f0;padding:4px;border-radius:11px;width:max-content;margin-bottom:15px}.seg-btn{border:0;background:transparent;padding:8px 14px;border-radius:8px;color:#666;cursor:pointer}.seg-btn.active{background:#fff;color:var(--red);font-weight:700;box-shadow:0 2px 7px rgba(0,0,0,.08)}
|
||||
.chart-toolbar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px}.chart-view{padding:9px 14px;border:1px solid #e1c3c9;background:#fff7f8;color:#8c2335;border-radius:9px;cursor:pointer}.chart-view.active{background:var(--red);color:#fff;border-color:var(--red)}
|
||||
.org-chart-wrap{overflow:auto;background:#fff;border:1px solid var(--line);border-radius:18px;padding:28px;box-shadow:var(--shadow);min-height:420px}
|
||||
.org-chart{display:flex;justify-content:center;min-width:max-content}.org-chart ul{padding-top:24px;position:relative;display:flex;justify-content:center;margin:0;padding-left:0}.org-chart li{list-style:none;text-align:center;position:relative;padding:24px 8px 0}.org-chart li:before,.org-chart li:after{content:"";position:absolute;top:0;right:50%;border-top:1px solid #c7a8ae;width:50%;height:24px}.org-chart li:after{right:auto;left:50%;border-left:1px solid #c7a8ae}.org-chart li:only-child:after,.org-chart li:only-child:before{display:none}.org-chart li:only-child{padding-top:0}.org-chart li:first-child:before,.org-chart li:last-child:after{border:0}.org-chart li:last-child:before{border-right:1px solid #c7a8ae;border-radius:0 6px 0 0}.org-chart li:first-child:after{border-radius:6px 0 0 0}.org-chart ul ul:before{content:"";position:absolute;top:0;left:50%;border-left:1px solid #c7a8ae;width:0;height:24px}
|
||||
.org-node{width:168px;min-height:80px;background:#fff;border:1px solid #e3c1c7;border-top:4px solid var(--red);border-radius:12px;padding:10px;display:inline-block;box-shadow:0 5px 14px rgba(96,12,28,.08);cursor:pointer}.org-node:hover{background:#fff6f7;border-color:var(--red)}.org-node b{font-size:13px;display:block;line-height:1.45}.org-node small{font-size:10px;color:var(--muted);display:block;margin-top:5px}.org-node .node-kind{font-size:10px;color:var(--red);margin-top:5px}
|
||||
.summary-strip{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin:15px 0}.summary-card{background:#fff;border:1px solid var(--line);border-radius:13px;padding:14px}.summary-card b{display:block;color:var(--red);font-size:21px}.summary-card span{font-size:12px;color:var(--muted)}
|
||||
.data-card{display:flex;flex-direction:column;min-height:205px}.card-top{display:flex;justify-content:space-between;gap:10px}.card-type{font-size:11px;color:var(--red);background:var(--light-red);padding:4px 8px;border-radius:999px;height:max-content}.card-sub{font-size:12px;color:#777;margin-bottom:10px}.card-roles{display:grid;gap:6px;margin-top:8px}.role-line{font-size:12px;background:#fafafa;border-left:3px solid #e7a1ad;padding:7px 9px}.card-footer{margin-top:auto;padding-top:12px;border-top:1px solid #eee;display:flex;justify-content:space-between;color:#888;font-size:11px}
|
||||
.category-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:10px;margin-bottom:16px}.category-card{background:#fff;border:1px solid var(--line);border-radius:13px;padding:13px;cursor:pointer}.category-card:hover{border-color:var(--red)}.category-card b{color:var(--red);font-size:21px;display:block}.category-card span{font-size:11px;color:#666}
|
||||
.timeline{position:relative;padding-left:26px}.timeline:before{content:"";position:absolute;left:7px;top:4px;bottom:4px;width:2px;background:#efc5cc}.time-card{position:relative;background:#fff;border:1px solid var(--line);border-radius:14px;padding:16px;margin-bottom:14px;box-shadow:var(--shadow);cursor:pointer}.time-card:before{content:"";position:absolute;left:-25px;top:19px;width:12px;height:12px;border:3px solid var(--red);background:#fff;border-radius:50%}.time-date{color:var(--red);font-size:12px;font-weight:700;margin-bottom:5px}
|
||||
.pagination{display:flex;justify-content:center;align-items:center;gap:9px;margin-top:18px}.page-no{color:#777;font-size:12px}
|
||||
.overlay{position:fixed;inset:0;background:rgba(36,8,14,.42);z-index:50;display:none}.overlay.show{display:block}.drawer{position:absolute;right:0;top:0;width:min(560px,94vw);height:100%;background:#fff;padding:24px;overflow:auto;box-shadow:-12px 0 35px rgba(0,0,0,.16)}.modal{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:min(840px,92vw);max-height:88vh;overflow:auto;background:#fff;border-radius:18px;padding:24px}.close{float:right}
|
||||
.detail-page{display:none}.detail-page.show{display:block}.detail-hero{background:linear-gradient(135deg,var(--red),var(--red2));color:#fff;border-radius:20px;padding:25px;margin-bottom:16px;box-shadow:var(--shadow)}.detail-hero h2{margin:0 0 10px;font-size:26px}.detail-hero p{margin:0;line-height:1.7;color:#ffe8ed}.detail-tags{margin-top:13px}.detail-tags .chip{background:rgba(255,255,255,.16);color:#fff}
|
||||
.detail-grid{display:grid;grid-template-columns:2fr 1fr;gap:16px}.detail-section{background:#fff;border:1px solid var(--line);border-radius:16px;padding:18px;margin-bottom:16px;box-shadow:var(--shadow)}.detail-section h3{margin:0 0 14px;font-size:16px;display:flex;align-items:center}.detail-section h3:before{content:"";width:4px;height:17px;background:var(--red);border-radius:5px;margin-right:8px}.info-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}.info-item{background:#fafafa;border-radius:10px;padding:11px}.info-item label{display:block;font-size:11px;color:#888;margin-bottom:5px}.info-item div{font-size:13px;line-height:1.55}.text-list{display:grid;gap:9px}.text-item{padding:10px 12px;border-left:4px solid #e5a6b1;background:#fff8f9;border-radius:7px;font-size:13px;line-height:1.6}
|
||||
.mini-card-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}.mini-card{border:1px solid #eee;border-radius:11px;padding:12px;background:#fff}.mini-card b{display:block;margin-bottom:6px}.source-line{padding:9px 0;border-bottom:1px dashed #ddd;font-size:12px}.warning-box{background:#fff7e8;border:1px solid #f1d29e;border-radius:11px;padding:13px;color:#7a4d00;font-size:12px;line-height:1.65}.safe-box{background:#f7f7f7;border:1px solid #ddd;border-radius:11px;padding:13px;color:#555;font-size:12px;line-height:1.65}
|
||||
.query-row{display:grid;grid-template-columns:1fr 120px 1fr 42px;gap:8px;margin-bottom:8px}.query-row select,.query-row input{height:37px;border:1px solid #ddd;border-radius:8px;padding:0 9px}.empty{text-align:center;padding:50px;color:#888}
|
||||
@media(max-width:1150px){.entry-grid,.card-grid,.region-grid{grid-template-columns:repeat(2,1fr)}.category-grid{grid-template-columns:repeat(3,1fr)}.detail-grid{grid-template-columns:1fr}.metrics{grid-template-columns:repeat(2,1fr)}}
|
||||
@media(max-width:720px){.header-top{padding:10px 14px;height:auto}.header-state{display:none}.main{padding:14px}.hero-mark{display:none}.hero h2{font-size:21px}.metrics,.grid2,.entry-grid,.card-grid,.region-grid,.summary-strip,.category-grid,.info-grid,.mini-card-grid{grid-template-columns:1fr}.toolbar input{min-width:100%}.query-row{grid-template-columns:1fr}.org-chart-wrap{padding:15px}.org-node{width:145px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="header">
|
||||
<div class="header-top">
|
||||
<div class="logo">防</div>
|
||||
<div class="title"><h1>台湾滨海防卫知识数据展示系统</h1><p>红白业务版 · 组织架构与单位档案已合并</p></div>
|
||||
<div class="header-state">知识库版本 2.0<br>更新日期 2026-06-23</div>
|
||||
</div>
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
</header>
|
||||
<main class="main">
|
||||
<section id="page"></section>
|
||||
<section id="detailPage" class="detail-page"></section>
|
||||
</main>
|
||||
<div id="drawerOverlay" class="overlay"><aside class="drawer"><button class="btn close" onclick="closeDrawer()">关闭</button><div id="drawer"></div></aside></div>
|
||||
<div id="modalOverlay" class="overlay"><div class="modal"><button class="btn close" onclick="closeModal()">关闭</button><div id="modal"></div></div></div>
|
||||
|
||||
<script>
|
||||
const DATA={"overview": {"核心指标": [{"名称": "综合区域", "数值": 9, "单位": "区", "说明": "覆盖本岛沿岸与主要离岛"}, {"名称": "组织与单位", "数值": 280, "单位": "个", "说明": "已去除组织与单位重复"}, {"名称": "单位深度档案", "数值": 179, "单位": "份", "说明": "已合并到对应组织节点"}, {"名称": "装备条目", "数值": 99, "单位": "项", "说明": "区分规划、采购、测试和列装"}, {"名称": "关键节点", "数值": 141, "单位": "个", "说明": "公共功能与韧性视角"}, {"名称": "演习与项目", "数值": 12, "单位": "项", "说明": "事件时间线与建设项目"}], "组织体系分布": [{"名称": "组织治理体系", "数值": 101}, {"名称": "海巡", "数值": 43}, {"名称": "全民动员", "数值": 29}, {"名称": "国防与联合体系", "数值": 28}, {"名称": "海军", "数值": 21}, {"名称": "陆军", "数值": 18}, {"名称": "空军", "数值": 16}, {"名称": "公共支援", "数值": 16}, {"名称": "海军陆战队", "数值": 8}], "装备类别分布": [{"名称": "无人系统", "数值": 12}, {"名称": "防空", "数值": 11}, {"名称": "海军平台", "数值": 10}, {"名称": "海巡平台", "数值": 9}, {"名称": "航空", "数值": 8}, {"名称": "地面火力", "数值": 7}, {"名称": "装甲", "数值": 5}, {"名称": "雷达与感知", "数值": 5}, {"名称": "反装甲", "数值": 4}, {"名称": "反舰", "数值": 3}, {"名称": "潜舰", "数值": 3}, {"名称": "反水雷", "数值": 3}, {"名称": "舰载防空", "数值": 3}, {"名称": "电子战", "数值": 3}, {"名称": "指挥控制", "数值": 3}, {"名称": "工程保障", "数值": 2}, {"名称": "布雷", "数值": 1}, {"名称": "综合支援", "数值": 1}, {"名称": "反无人机", "数值": 1}, {"名称": "无人水面平台", "数值": 1}, {"名称": "通信", "数值": 1}, {"名称": "机动运输", "数值": 1}, {"名称": "防护", "数值": 1}, {"名称": "医疗保障", "数值": 1}], "节点类别分布": [{"名称": "港口与海运", "数值": 26}, {"名称": "供水", "数值": 22}, {"名称": "能源与燃料", "数值": 18}, {"名称": "机场与航空", "数值": 17}, {"名称": "产业、物流与维修", "数值": 15}, {"名称": "陆路交通", "数值": 13}, {"名称": "医疗与救援", "数值": 11}, {"名称": "通信与数位韧性", "数值": 8}, {"名称": "应变指挥与警报", "数值": 6}, {"名称": "离岛持续保障", "数值": 5}], "业务入口": [{"页面": "regions", "名称": "沿岸区域", "数量": 9, "说明": "九区、县市与海岸分段"}, {"页面": "org_units", "名称": "组织与单位", "数量": 280, "说明": "组织架构图与单位深度档案"}, {"页面": "equipment", "名称": "武器装备", "数量": 99, "说明": "类别、体系、状态和公开作用"}, {"页面": "key_nodes", "名称": "关键节点", "数量": 141, "说明": "公共功能、依赖与替代"}, {"页面": "events_projects", "名称": "演习与项目", "数量": 12, "说明": "事件时间线和建设项目"}], "数据状态": {"知识库版本": "2.0", "页面版本": "2.0", "更新时间": "2026-06-23", "校验状态": "通过"}}, "regions": [{"region_id": "R01", "name": "北部沿岸", "scope": "基隆市、新北市沿岸及台北都会支撑区", "coastal_counties": ["基隆市", "新北市"], "support_areas": ["台北市", "桃园北部"], "coastal_morphology": ["野柳—东北角岬湾岩岸", "基隆港湾与人工港岸", "淡水河口沙岸与河口湿地", "八里—林口台地前缘海岸"], "segment_ids": ["S-R01-01", "S-R01-02", "S-R01-03", "S-R01-04", "S-R01-05"], "source_ids": ["SRC-WRA-TAIPEI-COAST", "SRC-TIPC-PORTS-2026", "SRC-CGA-ORG-2024", "SRC-CAA-AIRPORTS-2024"], "last_verified": "2026-06-23", "safety": "aggregate_only", "编号": "R01", "名称": "北部沿岸", "沿海县市": ["基隆市", "新北市"], "支撑区域": ["台北市", "桃园北部"], "海岸形态": ["野柳—东北角岬湾岩岸", "基隆港湾与人工港岸", "淡水河口沙岸与河口湿地", "八里—林口台地前缘海岸"], "县市子库": [{"county_id": "C-KEELUNG", "name": "基隆市", "region_id": "R01", "coastal_belt": ["基隆港城、外木山及东北角接口"], "dominant_functions": ["港口城市", "国际商港", "都会支撑"], "priority_risks": ["港城交通耦合", "强浪台风", "危险品与港区事故"], "last_verified": "2026-06-23", "safety": "aggregate_only"}, {"county_id": "C-NEWTAIPEI", "name": "新北市", "region_id": "R01", "coastal_belt": ["八里、林口、淡水、三芝、石门、金山、万里、瑞芳、贡寮"], "dominant_functions": ["台北港", "淡水河口", "北海岸观光渔业"], "priority_risks": ["海岸类型差异大", "跨都会交通", "东北角山区通道"], "last_verified": "2026-06-23", "safety": "aggregate_only"}], "海岸分段": [{"segment_id": "S-R01-01", "region_id": "R01", "name": "基隆Line truncated
|
||||
const MANIFEST={"系统": {"名称": "台湾滨海防卫知识数据展示系统", "版本": "2.0", "知识库版本": "2.0", "更新时间": "2026-06-23", "主题": {"模式": "红白", "主色": "#c8102e", "深红": "#8f1024", "浅红": "#fff1f3", "背景": "#f7f7f8", "卡片": "#ffffff", "文字": "#262626"}}, "页面": [{"编号": "overview", "名称": "总览", "数据源": "data/overview.json"}, {"编号": "regions", "名称": "沿岸区域", "数据源": "data/regions.json"}, {"编号": "org_units", "名称": "组织与单位", "数据源": "data/org_units.json", "架构数据": "data/organization_charts.json"}, {"编号": "equipment", "名称": "武器装备", "数据源": "data/equipment.json"}, {"编号": "key_nodes", "名称": "关键节点", "数据源": "data/key_nodes.json"}, {"编号": "events_projects", "名称": "演习与项目", "数据源": "data/events_projects.json"}], "交互规则": {"默认展示": "卡片与图形化面板", "列表限制": "不超过六个核心字段", "快速预览": "右侧抽屉", "复杂档案": "二级详情页", "长数组": "分组卡片或弹框", "查询": "各页面独立关键词、分类筛选和组合条件查询", "禁止展示": ["精确坐标", "实时部署", "兵力库存", "通信拓扑", "行动路线", "脆弱点排序"]}};
|
||||
const QUERY_SCHEMA={"版本": "2.0", "说明": "前端以中文条件构造器生成内部查询对象,不设置独立全库检索页面。", "查询域": {"沿岸区域": {"数据源": "regions", "字段": [{"字段": "名称", "显示名": "区域名称", "操作": ["包含", "等于"]}, {"字段": "沿海县市", "显示名": "沿海县市", "操作": ["包含"]}, {"字段": "海岸形态", "显示名": "海岸形态", "操作": ["包含"]}]}, "组织与单位": {"数据源": "org_units", "字段": [{"字段": "名称", "显示名": "名称", "操作": ["包含", "等于"]}, {"字段": "记录类别", "显示名": "记录类别", "操作": ["等于"]}, {"字段": "体系", "显示名": "体系", "操作": ["等于", "属于"]}, {"字段": "架构层级", "显示名": "架构层级", "操作": ["等于"]}, {"字段": "区域关联", "显示名": "区域关联", "操作": ["包含"]}, {"字段": "当前状态", "显示名": "当前状态", "操作": ["等于"]}]}, "武器装备": {"数据源": "equipment", "字段": [{"字段": "名称", "显示名": "装备名称", "操作": ["包含"]}, {"字段": "类别中文", "显示名": "装备类别", "操作": ["等于"]}, {"字段": "使用体系中文", "显示名": "使用体系", "操作": ["包含"]}, {"字段": "状态中文", "显示名": "公开状态", "操作": ["等于"]}]}, "关键节点": {"数据源": "key_nodes", "字段": [{"字段": "名称", "显示名": "节点名称", "操作": ["包含"]}, {"字段": "类别中文", "显示名": "节点类别", "操作": ["等于"]}, {"字段": "区域中文", "显示名": "所属区域", "操作": ["包含"]}, {"字段": "状态中文", "显示名": "运行状态", "操作": ["等于"]}]}, "演习与项目": {"数据源": "events_projects", "字段": [{"字段": "名称", "显示名": "名称", "操作": ["包含"]}, {"字段": "类型中文", "显示名": "事件类型", "操作": ["等于"]}, {"字段": "类别中文", "显示名": "项目类别", "操作": ["等于"]}, {"字段": "状态中文", "显示名": "状态", "操作": ["等于"]}]}}, "内部查询对象": {"数据域": "页面数据源编号", "关键词": "可选", "条件": [{"字段": "中文字段名", "操作": "包含或等于", "值": "查询值"}], "分页": {"页码": 1, "每页": 18}}};
|
||||
const state={tab:"overview",mode:"chart",chart:"national_defense",q:"",filters:{},conditions:[],page:1,pageSize:18};
|
||||
|
||||
function e(v){return String(v??"").replace(/[&<>"']/g,m=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[m]))}
|
||||
function a(v){return Array.isArray(v)?v:(v===undefined||v===null||v===""?[]:[v])}
|
||||
function text(v){return Array.isArray(v)?v.join(" "):typeof v==="object"&&v?JSON.stringify(v):String(v??"")}
|
||||
function chips(v,red=false,max=8){const x=a(v);return x.slice(0,max).map(y=>`<span class="chip ${red?"chip-red":""}">${e(y)}</span>`).join("")+(x.length>max?`<span class="chip">另${x.length-max}项</span>`:"")}
|
||||
function statusChip(v){const green=/运行|列装|官方|确认|通过/.test(v||"");const orange=/规划|测试|建设|扩建|核验|有限/.test(v||"");return `<span class="chip ${green?"chip-green":orange?"chip-orange":"chip-red"}">${e(v||"未标注")}</span>`}
|
||||
function unique(data,field){const s=new Set();data.forEach(x=>a(x[field]).forEach(v=>v&&s.add(v)));return [...s].sort()}
|
||||
function setTab(tab){state.tab=tab;state.q="";state.filters={};state.conditions=[];state.page=1;location.hash="#/"+tab;render()}
|
||||
function nav(){
|
||||
document.getElementById("tabs").innerHTML=MANIFEST.页面.map(x=>`<button class="tab ${state.tab===x.编号?"active":""}" onclick="setTab('${x.编号}')">${x.名称}</button>`).join("")
|
||||
}
|
||||
function hero(title,desc,actions=""){return `<div class="hero"><div><h2>${title}</h2><p>${desc}</p><div style="margin-top:14px">${actions}</div></div><div class="hero-mark"></div></div>`}
|
||||
function render(){nav();document.getElementById("page").style.display="block";document.getElementById("detailPage").classList.remove("show");const fn=window["render_"+state.tab]||render_overview;fn()}
|
||||
|
||||
function render_overview(){
|
||||
const o=DATA.overview;
|
||||
const metrics=o.核心指标.map(x=>`<div class="metric"><div class="metric-label">${x.名称}</div><div class="metric-value">${x.数值}<span class="metric-unit">${x.单位}</span></div><div class="metric-note">${x.说明}</div></div>`).join("");
|
||||
const max=Math.max(...o.组织体系分布.map(x=>x.数值));
|
||||
const bars=o.组织体系分布.slice(0,10).map(x=>`<div class="bar-row"><span>${e(x.名称)}</span><div class="bar"><i style="width:${x.数值/max*100}%"></i></div><b>${x.数值}</b></div>`).join("");
|
||||
const entries=o.业务入口.map(x=>`<div class="entry-card" onclick="setTab('${x.页面}')"><b>${x.名称}</b><span class="entry-num">${x.数量}</span><p>${x.说明}</p></div>`).join("");
|
||||
document.getElementById("page").innerHTML=hero("知识库业务总览","以区域、组织与单位、装备、公共关键节点、演习和建设项目为主线组织知识数据。")+
|
||||
`<div class="metrics">${metrics}</div><div class="grid2"><div class="panel"><div class="panel-title"><span>组织体系分布</span></div>${bars}</div><div class="panel"><div class="panel-title"><span>业务入口</span></div><div class="entry-grid">${entries}</div></div></div>`;
|
||||
}
|
||||
|
||||
function toolbar(domain,data,filterFields){
|
||||
const selects=filterFields.map(f=>`<select data-filter="${f}"><option value="">${f}:全部</option>${unique(data,f).slice(0,120).map(v=>`<option value="${e(v)}" ${state.filters[f]===String(v)?"selected":""}>${e(v)}</option>`).join("")}</select>`).join("");
|
||||
return `<div class="toolbar"><input id="keyword" value="${e(state.q)}" placeholder="输入关键词查询当前页面">${selects}<button class="btn btn-soft" onclick="openQueryBuilder('${domain}')">组合查询</button><button class="btn" onclick="clearQuery()">清空</button><span class="toolbar-count" id="count"></span></div>`;
|
||||
}
|
||||
function bindToolbar(domain,renderFn){
|
||||
const q=document.getElementById("keyword");if(q)q.oninput=()=>{state.q=q.value;state.page=1;renderFn()};
|
||||
document.querySelectorAll("[data-filter]").forEach(s=>s.onchange=()=>{state.filters[s.dataset.filter]=s.value;state.page=1;renderFn()});
|
||||
}
|
||||
function clearQuery(){state.q="";state.filters={};state.conditions=[];state.page=1;render()}
|
||||
function matches(item,fields){
|
||||
const q=state.q.trim().toLowerCase();
|
||||
if(q&&!fields.some(f=>text(item[f]).toLowerCase().includes(q)))return false;
|
||||
for(const [f,v] of Object.entries(state.filters)){if(v&&!a(item[f]).some(x=>String(x)===String(v)))return false}
|
||||
for(const c of state.conditions){
|
||||
const value=item[c.field],all=a(value);
|
||||
if(c.op==="包含"&&!all.some(x=>String(x).includes(c.value)))return false;
|
||||
if(c.op==="等于"&&!all.some(x=>String(x)===c.value))return false;
|
||||
if(c.op==="属于"&&!all.some(x=>c.value.split(/[、,,]/).map(y=>y.trim()).includes(String(x))))return false;
|
||||
}
|
||||
return true
|
||||
}
|
||||
function paginate(items){const start=(state.page-1)*state.pageSize;return items.slice(start,start+state.pageSize)}
|
||||
function pagination(total,rerender){const pages=Math.max(1,Math.ceil(total/state.pageSize));return `<div class="pagination"><button class="btn" ${state.page<=1?"disabled":""} onclick="state.page--;${rerender}">上一页</button><span class="page-no">第 ${state.page} / ${pages} 页</span><button class="btn" ${state.page>=pages?"disabled":""} onclick="state.page++;${rerender}">下一页</button></div>`}
|
||||
|
||||
function render_regions(){
|
||||
const cards=DATA.regions.map(r=>`<article class="region-card" onclick="openDetail('regions','${r.编号}')"><h3>${r.编号} · ${r.名称}</h3><p>${e(r.档案摘要)}</p><div>${chips(r.海岸形态,true,3)}</div><div class="region-stats"><div><b>${r.县市数量}</b><br><small>县市子库</small></div><div><b>${r.分段数量}</b><br><small>海岸分段</small></div></div></article>`).join("");
|
||||
document.getElementById("page").innerHTML=hero("沿岸区域","采用九个综合研究区,下钻到沿海县市和海岸研究分段。")+`<div class="region-grid">${cards}</div>`;
|
||||
}
|
||||
|
||||
function render_org_units(){
|
||||
const chartActive=state.mode==="chart",cardsActive=state.mode==="cards";
|
||||
document.getElementById("page").innerHTML=hero("组织与单位","组织架构与单位档案使用同一套280个唯一节点。点击架构节点或机构卡片可进入完整档案。")+
|
||||
`<div class="segmented"><button class="seg-btn ${chartActive?"active":""}" onclick="state.mode='chart';render_org_units()">组织架构图</button><button class="seg-btn ${cardsActive?"active":""}" onclick="state.mode='cards';render_org_units()">机构与单位卡片</button></div><div id="orgBody"></div>`;
|
||||
if(chartActive)renderOrgChart();else renderOrgCards(true);
|
||||
}
|
||||
function renderOrgChart(){
|
||||
const views=DATA.organization_charts;
|
||||
const current=views.find(x=>x.id===state.chart)||views[0];
|
||||
const buttons=views.map(x=>`<button class="chart-view ${x.id===current.id?"active":""}" onclick="state.chart='${x.id}';renderOrgChart()">${x.名称}</button>`).join("");
|
||||
const tree=`<div class="org-chart"><ul><li>${chartNode(current.tree)}</li></ul></div>`;
|
||||
const roots=DATA.org_units.filter(x=>!x.行政上级编号).length;
|
||||
document.getElementById("orgBody").innerHTML=`<div class="chart-toolbar">${buttons}</div><div class="panel" style="margin-bottom:14px"><div class="panel-title"><span>${current.名称}</span></div><p style="color:#777;font-size:13px">${current.说明}</p></div><div class="summary-strip"><div class="summary-card"><b>${DATA.org_units.length}</b><span>唯一组织节点</span></div><div class="summary-card"><b>${DATA.org_units.filter(x=>x.记录类别==="单位").length}</b><span>含深度单位档案</span></div><div class="summary-card"><b>${DATA.org_units.filter(x=>x.记录类别==="机构").length}</b><span>制度与组织节点</span></div><div class="summary-card"><b>${roots}</b><span>顶层或独立根节点</span></div></div><div class="org-chart-wrap">${tree}</div>`;
|
||||
}
|
||||
function chartNode(n){
|
||||
if(!n)return "";
|
||||
const children=(n.children||[]).length?`<ul>${n.children.map(c=>`<li>${chartNode(c)}</li>`).join("")}</ul>`:"";
|
||||
return `<div class="org-node" onclick="openDetail('org_units','${n.id}')"><b>${e(n.名称)}</b><small>${e(n.类型)}</small><div class="node-kind">${e(n.记录类别)} · ${e(n.状态)}</div></div>${children}`;
|
||||
}
|
||||
function renderOrgCards(initial=false){
|
||||
const data=DATA.org_units;
|
||||
if(initial){
|
||||
document.getElementById("orgBody").innerHTML=toolbar("组织与单位",data,["记录类别","体系","架构层级","当前状态"])+`<div id="orgCards"></div>`;
|
||||
bindToolbar("组织与单位",()=>renderOrgCards(false));
|
||||
}
|
||||
const filtered=data.filter(x=>matches(x,["名称","档案摘要","体系","架构层级","公开任务","区域关联","装备类别"]));
|
||||
const cards=paginate(filtered).map(x=>`<article class="data-card" onclick="openDetail('org_units','${x.id}')"><div class="card-top"><div><h3>${e(x.名称)}</h3><div class="card-sub">${e(x.体系)} · ${e(x.架构层级)}</div></div><span class="card-type">${e(x.记录类别)}</span></div><p>${e(x.档案摘要)}</p><div class="card-roles">${a(x.公开任务).slice(0,2).map(y=>`<div class="role-line">${e(y)}</div>`).join("")}</div><div class="card-footer"><span>${e(x.行政上级)}</span><span>${e(x.当前状态)}</span></div></article>`).join("");
|
||||
document.getElementById("orgCards").innerHTML=`<div class="card-grid">${cards||'<div class="empty">没有匹配结果</div>'}</div>${pagination(filtered.length,"renderOrgCards(false)")}`;
|
||||
const count=document.getElementById("count");if(count)count.textContent=`共 ${filtered.length} 个节点`;
|
||||
}
|
||||
|
||||
function categorySummary(data,field,onClick){
|
||||
const counts={};data.forEach(x=>{const k=x[field]||"未分类";counts[k]=(counts[k]||0)+1});
|
||||
return `<div class="category-grid">${Object.entries(counts).sort((a,b)=>b[1]-a[1]).slice(0,10).map(([k,v])=>`<div class="category-card" onclick="${onClick}('${e(k)}')"><b>${v}</b><span>${e(k)}</span></div>`).join("")}</div>`
|
||||
}
|
||||
function render_equipment(initial=true){
|
||||
const data=DATA.equipment;
|
||||
document.getElementById("page").innerHTML=hero("武器装备","以装备卡片展示类别、使用体系、公开作用和生命周期状态,不把规划、采购、测试和列装混为一谈。")+
|
||||
categorySummary(data,"类别中文","filterEquipmentCategory")+toolbar("武器装备",data,["类别中文","状态中文","可信度中文"])+`<div id="equipmentCards"></div>`;
|
||||
bindToolbar("武器装备",()=>renderEquipmentCards());
|
||||
renderEquipmentCards();
|
||||
}
|
||||
function filterEquipmentCategory(v){state.filters["类别中文"]=v;state.page=1;render_equipment()}
|
||||
function renderEquipmentCards(){
|
||||
const data=DATA.equipment.filter(x=>matches(x,["名称","别名","类别中文","使用体系中文","公开作用","状态中文"]));
|
||||
const html=paginate(data).map(x=>`<article class="data-card" onclick="openDetail('equipment','${x.id}')"><div class="card-top"><div><h3>${e(x.名称)}</h3><div class="card-sub">${e(x.类别中文)} · ${a(x.使用体系中文).join("、")}</div></div>${statusChip(x.状态中文)}</div><p>${e(x.档案摘要)}</p><div class="card-roles">${a(x.公开作用).slice(0,3).map(y=>`<div class="role-line">${e(y)}</div>`).join("")}</div><div class="card-footer"><span>可信度:${e(x.可信度中文)}</span><span>${e(x.verified_at||"未标注")}</span></div></article>`).join("");
|
||||
document.getElementById("equipmentCards").innerHTML=`<div class="card-grid">${html||'<div class="empty">没有匹配结果</div>'}</div>${pagination(data.length,"renderEquipmentCards()")}`;
|
||||
const c=document.getElementById("count");if(c)c.textContent=`共 ${data.length} 项装备`;
|
||||
}
|
||||
function render_key_nodes(){
|
||||
const data=DATA.key_nodes;
|
||||
document.getElementById("page").innerHTML=hero("关键节点","从公共功能和韧性角度展示港口、机场、交通、能源、通信、供水、医疗和产业节点。")+
|
||||
categorySummary(data,"类别中文","filterNodeCategory")+toolbar("关键节点",data,["类别中文","层级中文","状态中文","可信度中文"])+`<div id="nodeCards"></div>`;
|
||||
bindToolbar("关键节点",()=>renderNodeCards());renderNodeCards();
|
||||
}
|
||||
function filterNodeCategory(v){state.filters["类别中文"]=v;state.page=1;render_key_nodes()}
|
||||
function renderNodeCards(){
|
||||
const data=DATA.key_nodes.filter(x=>matches(x,["名称","类别中文","区域中文","主管运营","公共功能","状态中文"]));
|
||||
const html=paginate(data).map(x=>`<article class="data-card" onclick="openDetail('key_nodes','${x.id}')"><div class="card-top"><div><h3>${e(x.名称)}</h3><div class="card-sub">${e(x.类别中文)} · ${e(x.层级中文)}</div></div>${statusChip(x.状态中文)}</div><p>${e(x.档案摘要)}</p><div>${chips(x.区域中文,true,3)}</div><div class="card-roles">${a(x.公共功能).slice(0,2).map(y=>`<div class="role-line">${e(y)}</div>`).join("")}</div><div class="card-footer"><span>${e(x.主管运营)}</span><span>可信度:${e(x.可信度中文)}</span></div></article>`).join("");
|
||||
document.getElementById("nodeCards").innerHTML=`<div class="card-grid">${html||'<div class="empty">没有匹配结果</div>'}</div>${pagination(data.length,"renderNodeCards()")}`;
|
||||
const c=document.getElementById("count");if(c)c.textContent=`共 ${data.length} 个节点`;
|
||||
}
|
||||
function render_events_projects(){
|
||||
const events=DATA.events.map(x=>`<article class="time-card" onclick="openDetail('events','${x.id}')"><div class="time-date">${e(x.日期显示)}</div><h3 style="margin:0 0 7px">${e(x.名称)}</h3><div>${chips([x.类型中文,...a(x.区域中文)],true,4)}</div><p>${e(x.档案摘要)}</p></article>`).join("");
|
||||
const projects=DATA.projects.map(x=>`<article class="data-card" onclick="openDetail('projects','${x.id}')"><div class="card-top"><div><h3>${e(x.名称)}</h3><div class="card-sub">${e(x.类别中文)}</div></div>${statusChip(x.状态中文)}</div><p>${e(x.档案摘要)}</p><div class="card-footer"><span>建设项目</span><span>${e(x.状态中文)}</span></div></article>`).join("");
|
||||
document.getElementById("page").innerHTML=hero("演习与项目","演习采用时间线,建设项目采用卡片,分别表达日期型事件和生命周期型项目。")+
|
||||
`<div class="grid2"><section class="panel"><div class="panel-title"><span>演习与重要事件</span></div><div class="timeline">${events}</div></section><section class="panel"><div class="panel-title"><span>现代化与建设项目</span></div><div class="card-grid" style="grid-template-columns:1fr">${projects}</div></section></div>`;
|
||||
}
|
||||
|
||||
function findItem(domain,id){
|
||||
if(domain==="regions")return DATA.regions.find(x=>x.编号===id);
|
||||
if(domain==="org_units")return DATA.org_units.find(x=>x.id===id);
|
||||
if(domain==="equipment")return DATA.equipment.find(x=>x.id===id);
|
||||
if(domain==="key_nodes")return DATA.key_nodes.find(x=>x.id===id);
|
||||
if(domain==="events")return DATA.events.find(x=>x.id===id);
|
||||
if(domain==="projects")return DATA.projects.find(x=>x.id===id);
|
||||
}
|
||||
function openDetail(domain,id){
|
||||
const x=findItem(domain,id);if(!x)return;
|
||||
document.getElementById("page").style.display="none";
|
||||
const d=document.getElementById("detailPage");d.classList.add("show");
|
||||
if(domain==="org_units")d.innerHTML=detailOrg(x);
|
||||
else if(domain==="regions")d.innerHTML=detailRegion(x);
|
||||
else if(domain==="equipment")d.innerHTML=detailEquipment(x);
|
||||
else if(domain==="key_nodes")d.innerHTML=detailNode(x);
|
||||
else d.innerHTML=detailEventProject(x,domain);
|
||||
location.hash=`#/detail/${domain}/${encodeURIComponent(id)}`;
|
||||
window.scrollTo({top:0});
|
||||
}
|
||||
function back(){document.getElementById("detailPage").classList.remove("show");document.getElementById("page").style.display="block";location.hash="#/"+state.tab}
|
||||
function info(label,value){return `<div class="info-item"><label>${e(label)}</label><div>${value===undefined||value===null||value===""?'<span style="color:#999">未公开或未标注</span>':value}</div></div>`}
|
||||
function listBlock(values){const v=a(values);return v.length?`<div class="text-list">${v.map(x=>`<div class="text-item">${e(x)}</div>`).join("")}</div>`:`<div class="empty" style="padding:20px">暂无独立条目</div>`}
|
||||
function section(title,body){return `<section class="detail-section"><h3>${title}</h3>${body}</section>`}
|
||||
function detailHeader(title,summary,tags){return `<span class="back-link" onclick="back()" style="color:var(--red);cursor:pointer;display:inline-block;margin-bottom:12px">← 返回上一页</span><div class="detail-hero"><h2>${e(title)}</h2><p>${e(summary)}</p><div class="detail-tags">${chips(tags,false,10)}</div></div>`}
|
||||
|
||||
function detailOrg(x){
|
||||
const core=section("组织与单位概况",`<div class="info-grid">${info("记录类别",e(x.记录类别))}${info("体系",e(x.体系))}${info("架构层级",e(x.架构层级))}${info("组织或单位类型",e(x.单位类型))}${info("当前状态",statusChip(x.当前状态))}${info("可信度",e(x.可信度))}${info("行政上级",e(x.行政上级))}${info("军令或任务上级",e(x.军令或任务上级))}</div>`);
|
||||
const tasks=section("公开职掌与任务",listBlock(x.公开任务));
|
||||
const assoc=section("区域、装备与演训关联",`<div class="info-grid">${info("区域关联",chips(x.区域关联,true,12))}${info("装备类别",chips(x.装备类别,true,12))}${info("演训与事件",chips(x.演训与事件,true,12))}${info("适用范围",e(x.适用范围))}</div>`);
|
||||
const childrenSec=section("直接下级机构或单位",x.下级机构.length?`<div class="mini-card-grid">${x.下级机构.map((n,i)=>`<div class="mini-card" ${x.下级机构编号[i]?`onclick="openDetail('org_units','${x.下级机构编号[i]}')" style="cursor:pointer"`:""}><b>${e(n)}</b><span style="font-size:11px;color:#888">点击查看档案</span></div>`).join("")}</div>`:`<div class="empty" style="padding:20px">未列出直接下级</div>`);
|
||||
const relSec=section("组织关系",x.关系.length?`<div class="mini-card-grid">${x.关系.slice(0,16).map(r=>`<div class="mini-card"><b>${e(r.关系)}</b><div style="font-size:12px;line-height:1.65">${e(r.主体)} → ${e(r.客体)}</div><span style="font-size:11px;color:#888">${e(r.可信度)}</span></div>`).join("")}</div>`:`<div class="empty" style="padding:20px">暂无独立关系条目</div>`);
|
||||
const history=section("历史沿革与说明",`<div class="text-item">${e(x.历史沿革)}</div>${x.说明?`<div class="text-item">${e(x.说明)}</div>`:""}`);
|
||||
const gaps=section("资料缺口",`<div class="warning-box">${a(x.资料缺口).map(y=>`• ${e(y)}`).join("<br>")}</div>`);
|
||||
const sources=section("来源与核实",`<div class="info-grid">${info("核实日期",e(x.核实日期))}${info("来源数量",String(a(x.来源).length))}</div><div style="margin-top:10px">${a(x.来源信息||x.来源).map(s=>`<div class="source-line">${e(s)}</div>`).join("")||'<div class="source-line">尚未列出独立来源编号</div>'}</div>`);
|
||||
const safe=section("安全边界",`<div class="safe-box">${e(x.安全边界)}</div>`);
|
||||
return detailHeader(x.名称,x.档案摘要,[x.记录类别,x.体系,x.当前状态])+`<div class="detail-grid"><div>${core}${tasks}${assoc}${childrenSec}${relSec}</div><aside>${history}${sources}${gaps}${safe}</aside></div>`;
|
||||
}
|
||||
function detailRegion(x){
|
||||
const countyCards=x.县市子库.map(c=>`<div class="mini-card"><b>${e(c.name||c.county_name||c.名称||"县市子库")}</b><div style="font-size:12px;color:#777">${e(c.scope||c.沿岸范围||"沿岸县市档案")}</div></div>`).join("");
|
||||
const segCards=x.海岸分段.map(s=>`<div class="mini-card"><b>${e(s.name||s.名称)}</b><div>${chips([s.coastal_type||s.海岸类型,s.所属区域],true,3)}</div><p style="font-size:11px;color:#777">${e(s.scope||s.空间范围||"")}</p></div>`).join("");
|
||||
return detailHeader(x.名称,x.档案摘要,[x.编号,...a(x.海岸形态)])+
|
||||
`<div class="detail-grid"><div>${section("区域基本信息",`<div class="info-grid">${info("空间范围",e(x.scope))}${info("县市数量",String(x.县市数量))}${info("海岸分段数量",String(x.分段数量))}${info("核实日期",e(x.last_verified||"未标注"))}${info("沿海县市",chips(x.沿海县市,true,15))}${info("支撑区域",chips(x.支撑区域,true,15))}</div>`)}${section("海岸形态",listBlock(x.海岸形态))}${section("海岸研究分段",`<div class="mini-card-grid">${segCards}</div>`)}</div><aside>${section("县市子库",`<div class="mini-card-grid" style="grid-template-columns:1fr">${countyCards}</div>`)}${section("资料来源",`<div>${a(x.来源信息||x.source_ids).map(s=>`<div class="source-line">${e(s)}</div>`).join("")||'<div class="source-line">待进一步补充</div>'}</div>`)}${section("研究边界",`<div class="safe-box">区域分段用于公开空间、治理和韧性研究,不等于军事防区、实际部署边界或行动分区。</div>`)}</aside></div>`;
|
||||
}
|
||||
function detailEquipment(x){
|
||||
return detailHeader(x.名称,x.档案摘要,[x.类别中文,x.状态中文,...a(x.使用体系中文)])+
|
||||
`<div class="detail-grid"><div>${section("装备概况",`<div class="info-grid">${info("装备类别",e(x.类别中文))}${info("使用体系",chips(x.使用体系中文,true,10))}${info("公开状态",statusChip(x.状态中文))}${info("可信度",e(x.可信度中文))}${info("别名",chips(x.aliases,true,10))}${info("核实日期",e(x.verified_at||"未标注"))}</div>`)}${section("公开作用",listBlock(x.公开作用))}${section("生命周期解释",`<div class="text-list"><div class="text-item">规划、预算、签约、交付、接装、训练、测评和形成能力属于不同阶段。</div><div class="text-item">本条目的当前状态为:${e(x.状态中文)}。</div><div class="text-item">装备价值需与感知、指挥、平台、保障和训练共同评估。</div></div>`)}</div><aside>${section("来源",a(x.来源信息||x.sources).map(s=>`<div class="source-line">${e(s)}</div>`).join("")||'<div class="source-line">待补</div>')}${section("备注",`<div class="text-item">${e(x.notes||"无额外公开说明。")}</div>`)}${section("资料边界",`<div class="safe-box">不记录或推断库存、精确部署、妥善率、射界、航线、战法和单位实际配赋。</div>`)}</aside></div>`;
|
||||
}
|
||||
function detailNode(x){
|
||||
return detailHeader(x.名称,x.档案摘要,[x.类别中文,x.层级中文,x.状态中文])+
|
||||
`<div class="detail-grid"><div>${section("节点概况",`<div class="info-grid">${info("节点类别",e(x.类别中文))}${info("节点层级",e(x.层级中文))}${info("所属区域",chips(x.区域中文,true,10))}${info("运行状态",statusChip(x.状态中文))}${info("主管或运营主体",e(x.主管运营))}${info("可信度",e(x.可信度中文))}</div>`)}${section("公共功能",listBlock(x.公共功能))}${section("上游依赖",listBlock(x.依赖类别))}${section("替代与备援",listBlock(x.替代备援))}</div><aside>${section("来源",a(x.来源信息||x.sources).map(s=>`<div class="source-line">${e(s)}</div>`).join("")||'<div class="source-line">待补</div>')}${section("资料说明",`<div class="text-item">${e(x.note||"无额外公开说明。")}</div>`)}${section("研究边界",`<div class="safe-box">节点用于公共功能、治理和韧性研究,不展示精确坐标、内部拓扑、实时容量、库存、脆弱点或攻击价值。</div>`)}</aside></div>`;
|
||||
}
|
||||
function detailEventProject(x,domain){
|
||||
const isEvent=domain==="events";
|
||||
return detailHeader(x.名称,x.档案摘要,[isEvent?x.类型中文:x.类别中文,x.状态中文])+
|
||||
`<div class="detail-grid"><div>${section(isEvent?"事件信息":"项目信息",`<div class="info-grid">${info(isEvent?"事件类型":"项目类别",e(isEvent?x.类型中文:x.类别中文))}${info("状态",statusChip(x.状态中文))}${info("日期",e(x.日期显示||"不适用"))}${info("区域",chips(x.区域中文,true,12))}</div>`)}${section(isEvent?"主题与验证重点":"项目评估链条",isEvent?listBlock(x.topics):`<div class="text-list"><div class="text-item">规划与需求确认</div><div class="text-item">预算与采购</div><div class="text-item">生产、交付与接装</div><div class="text-item">训练、测评、保障与形成能力</div></div>`)}</div><aside>${section("来源",`<div class="source-line">${e(a(x.来源信息).join(";")||x.source||"待补")}</div>`)}${section("分析限制",`<div class="safe-box">${isEvent?"单次演习不能直接证明永久编制、完整战备或真实作战效果。":"项目存在不等于已经交付、接装或形成能力。"}</div>`)}</aside></div>`;
|
||||
}
|
||||
|
||||
function openQueryBuilder(domainName){
|
||||
const conf=QUERY_SCHEMA.查询域[domainName];if(!conf)return;
|
||||
const opts=conf.字段.map(x=>`<option value="${e(x.字段)}">${e(x.显示名)}</option>`).join("");
|
||||
const rows=(state.conditions.length?state.conditions:[{field:conf.字段[0].字段,op:"包含",value:""}]).map((c,i)=>queryRow(opts,c,i)).join("");
|
||||
openModal(`<h2 style="margin-top:0">组合条件查询</h2><p style="color:#777;font-size:13px">使用中文字段构造条件,查询只作用于当前业务页面。</p><div id="queryRows">${rows}</div><button class="btn" onclick="addQueryRow('${domainName}')">增加条件</button> <button class="btn btn-red" onclick="applyQuery('${domainName}')">应用查询</button>`);
|
||||
}
|
||||
function queryRow(opts,c,i){return `<div class="query-row" data-query-row><select class="q-field">${opts.replace(`value="${c.field}"`,`value="${c.field}" selected`)}</select><select class="q-op"><option ${c.op==="包含"?"selected":""}>包含</option><option ${c.op==="等于"?"selected":""}>等于</option><option ${c.op==="属于"?"selected":""}>属于</option></select><input class="q-value" value="${e(c.value)}" placeholder="输入查询值"><button class="btn" onclick="this.parentElement.remove()">×</button></div>`}
|
||||
function addQueryRow(domainName){const conf=QUERY_SCHEMA.查询域[domainName];const opts=conf.字段.map(x=>`<option value="${e(x.字段)}">${e(x.显示名)}</option>`).join("");document.getElementById("queryRows").insertAdjacentHTML("beforeend",queryRow(opts,{field:conf.字段[0].字段,op:"包含",value:""},99))}
|
||||
function applyQuery(){state.conditions=[...document.querySelectorAll("[data-query-row]")].map(r=>({field:r.querySelector(".q-field").value,op:r.querySelector(".q-op").value,value:r.querySelector(".q-value").value})).filter(x=>x.value);state.page=1;closeModal();render()}
|
||||
function openModal(html){document.getElementById("modal").innerHTML=html;document.getElementById("modalOverlay").classList.add("show")}
|
||||
function closeModal(){document.getElementById("modalOverlay").classList.remove("show")}
|
||||
function closeDrawer(){document.getElementById("drawerOverlay").classList.remove("show")}
|
||||
document.getElementById("modalOverlay").onclick=x=>{if(x.target.id==="modalOverlay")closeModal()};
|
||||
document.getElementById("drawerOverlay").onclick=x=>{if(x.target.id==="drawerOverlay")closeDrawer()};
|
||||
const hash=location.hash.match(/^#\/([^/]+)/);if(hash&&MANIFEST.页面.some(x=>x.编号===hash[1]))state.tab=hash[1];render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>台方向“解放军无法战胜”叙事专题数据库</title><style>
|
||||
:root{
|
||||
--bg:#fbf3ef;--paper:#fffdfb;--paper2:#fff7f2;--ink:#271312;--muted:#7b6760;
|
||||
--red:#b92e27;--red2:#8e211c;--red3:#d35142;--line:#ecd6cc;--soft:#f6e6df;
|
||||
--shadow:0 14px 35px rgba(78,30,18,.12);--radius:22px;
|
||||
}
|
||||
*{box-sizing:border-box}html,body{margin:0;padding:0}body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",Arial,sans-serif;background:linear-gradient(180deg,#fff 0,#fbf1ec 240px,#fffaf7 100%);color:var(--ink);}
|
||||
.hero{background:linear-gradient(135deg,var(--red2),var(--red3));color:#fff;padding:30px 40px 34px;box-shadow:0 8px 30px rgba(104,23,17,.22)}
|
||||
.hero h1{margin:0 0 14px;font-size:34px;line-height:1.22;letter-spacing:.5px}.hero p{margin:0;max-width:1280px;font-size:18px;line-height:1.75;opacity:.96}.meta-row{display:flex;gap:12px;flex-wrap:wrap;margin-top:18px}.meta-pill{border:1px solid rgba(255,255,255,.42);background:rgba(255,255,255,.12);padding:8px 14px;border-radius:999px;font-weight:700}
|
||||
main{max-width:1520px;margin:0 auto;padding:22px 24px 50px}.tabs-wrap{position:sticky;top:0;z-index:20;background:rgba(251,243,239,.94);border-bottom:1px solid var(--line);backdrop-filter:blur(10px);margin:0 -24px 20px;padding:14px 24px 12px;overflow:auto}.tabs{display:flex;gap:10px;min-width:max-content}.tab-btn{appearance:none;border:1px solid var(--line);background:white;color:var(--red2);border-radius:999px;padding:11px 16px;font-weight:900;cursor:pointer;box-shadow:0 6px 14px rgba(102,38,26,.06);white-space:nowrap}.tab-btn small{color:inherit;opacity:.72;margin-left:5px}.tab-btn.active{background:var(--red2);color:#fff;border-color:var(--red2)}
|
||||
.toolbar{display:grid;grid-template-columns:1fr 220px 210px 170px;gap:14px;align-items:center;background:rgba(255,255,255,.88);border:1px solid var(--line);border-radius:20px;padding:14px;margin-bottom:22px;box-shadow:var(--shadow)}.searchbox{height:54px;border:1px solid var(--line);border-radius:16px;background:white;display:flex;align-items:center;overflow:hidden}.searchbox span{width:78px;text-align:center;color:var(--red);font-weight:900;font-size:22px;letter-spacing:4px}.searchbox input{border:0;outline:0;flex:1;font-size:17px;padding:0 18px;background:transparent;color:var(--ink)}select,.btn{height:54px;border:1px solid var(--line);border-radius:16px;background:white;padding:0 16px;font-size:16px;color:var(--ink)}.btn{font-weight:900;cursor:pointer}.btn.primary{background:var(--red);color:#fff;border-color:var(--red)}
|
||||
.section-intro,.panel{background:rgba(255,255,255,.9);border:1px solid var(--line);border-radius:var(--radius);padding:22px;margin-bottom:20px;box-shadow:var(--shadow)}.intro-head{display:flex;gap:22px;justify-content:space-between}.intro-head h2{margin:0 0 8px;color:var(--red2);font-size:26px}.intro-head p{margin:0 0 8px;color:var(--muted);line-height:1.7}.stats{display:flex;gap:10px;min-width:270px}.stat{flex:1;background:var(--paper2);border:1px solid var(--line);border-radius:16px;padding:12px;text-align:center}.stat b{display:block;font-size:26px;color:var(--red)}.stat span{font-size:13px;color:var(--muted)}.profile-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-top:18px}.profile-card{background:#fff;border:1px solid var(--line);border-radius:16px;padding:16px}.profile-card b{display:block;color:var(--red2);margin-bottom:8px}.profile-card p,.profile-card li{color:var(--muted);line-height:1.65;margin:0}.profile-card ul{margin:0;padding-left:18px}.chipbar{display:flex;gap:8px;flex-wrap:wrap;margin:0 0 18px}.chip{border:1px solid var(--line);background:white;border-radius:999px;padding:7px 12px;cursor:pointer;color:var(--red2);font-weight:800}.chip.active{background:var(--red2);color:white;border-color:var(--red2)}.result-note,.footer-note{background:#fff8f4;border:1px solid var(--line);border-radius:16px;padding:12px 16px;color:var(--muted);line-height:1.7;margin-bottom:18px}.footer-note{margin-top:20px}
|
||||
.card-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.record-card,.chain-card{background:#fff;border:1px solid var(--line);border-radius:22px;padding:18px;box-shadow:0 10px 25px rgba(78,30,18,.09);display:flex;flex-direction:column;gap:12px}.record-card h3,.chain-card h3{margin:0;color:var(--red2);font-size:21px}.record-card p,.chain-card p{margin:0;color:var(--muted);line-height:1.7}.badge{display:inline-block;background:#f8e4dc;color:var(--red2);border:1px solid var(--line);border-radius:999px;padding:5px 10px;font-weight:900;font-size:13px}.field-list{display:grid;gap:8px}.mini-kv{border-left:4px solid var(--red3);background:#fff8f4;border-radius:10px;padding:9px 10px}.mini-kv b{display:block;color:var(--red2);margin-bottom:4px}.mini-kv span{color:var(--muted);line-height:1.55}.tags{display:flex;gap:7px;flex-wrap:wrap}.tag,.source-pill{font-size:12px;border-radius:999px;padding:5px 9px;background:#f5eee9;color:#61423b;border:1px solid var(--line)}.source-pill{background:#fff2e8;color:#9a3a2f}.card-actions{margin-top:auto;display:flex;justify-content:flex-end}.open-btn{border:0;background:var(--red);color:white;border-radius:12px;padding:10px 14px;font-weight:900;cursor:pointer}.empty{padding:40px;text-align:center;background:#fff;border:1px dashed var(--line);border-radius:20px;color:var(--muted)}
|
||||
.timeline{position:relative;margin-left:16px}.timeline:before{content:"";position:absolute;left:14px;top:0;bottom:0;width:3px;background:var(--line)}.timeline-item{position:relative;margin:0 0 16px 42px}.timeline-item:before{content:"";position:absolute;left:-34px;top:26px;width:15px;height:15px;border-radius:50%;background:var(--red);box-shadow:0 0 0 6px #f9e7df}.chain-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:18px}.chain-steps{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.step{background:#fff5ef;border:1px solid var(--line);border-radius:12px;padding:9px 10px;color:var(--red2);font-weight:800}.arrow{color:var(--red);font-weight:900}.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:18px;background:#fff}table{width:100%;border-collapse:collapse;min-width:900px}th,td{padding:13px 14px;border-bottom:1px solid var(--line);vertical-align:top;text-align:left;line-height:1.55}th{background:#fff1eb;color:var(--red2);position:sticky;top:0;z-index:1}tr:hover td{background:#fffaf7}.cell-title{font-weight:900;color:var(--red2)}
|
||||
.model-grid,.source-grid,.detail-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.model-card,.source-card,.kv{background:#fff;border:1px solid var(--line);border-radius:16px;padding:15px}.model-card b,.source-card b,.kv b{display:block;color:var(--red2);margin-bottom:7px}.model-card li,.source-card p,.source-card span,.kv span{color:var(--muted);line-height:1.65}.source-card a,.source-line a{color:var(--red);font-weight:900;text-decoration:none}.modal-backdrop{display:none;position:fixed;inset:0;background:rgba(30,15,13,.52);z-index:99;align-items:center;justify-content:center;padding:24px}.modal{width:min(1120px,96vw);max-height:90vh;overflow:hidden;background:var(--paper);border-radius:26px;box-shadow:0 20px 70px rgba(0,0,0,.32);border:1px solid var(--line);display:flex;flex-direction:column}.modal-head{background:linear-gradient(135deg,var(--red2),var(--red3));color:#fff;padding:22px 26px;display:flex;justify-content:space-between;gap:18px}.modal-head h2{margin:0 0 8px;font-size:24px}.modal-head p{margin:0;line-height:1.65;opacity:.95}.close{width:42px;height:42px;border-radius:50%;border:1px solid rgba(255,255,255,.4);background:rgba(255,255,255,.16);color:#fff;font-size:28px;cursor:pointer}.modal-body{overflow:auto;padding:22px}.detail-grid{grid-template-columns:repeat(2,1fr);margin:16px 0}.detail-section{background:#fff;border:1px solid var(--line);border-radius:18px;padding:18px;margin:14px 0}.detail-section h3{margin:0 0 10px;color:var(--red2)}.detail-section p,.detail-section li{line-height:1.75;color:var(--muted)}.source-list{display:grid;gap:10px}.source-line{background:#fff8f4;border:1px solid var(--line);border-radius:14px;padding:13px}.source-line p{margin:4px 0;color:var(--muted)}
|
||||
@media(max-width:1180px){.toolbar{grid-template-columns:1fr 1fr}.card-grid,.profile-grid,.model-grid,.source-grid{grid-template-columns:repeat(2,1fr)}}@media(max-width:760px){.hero{padding:24px 18px}.hero h1{font-size:24px}main{padding:14px}.tabs-wrap{margin:0 -14px 14px;padding:12px 14px}.toolbar,.card-grid,.profile-grid,.chain-grid,.model-grid,.source-grid,.detail-grid{grid-template-columns:1fr}.intro-head{flex-direction:column}.stats{min-width:0}.modal-backdrop{padding:8px}}
|
||||
</style></head><body>
|
||||
<header class="hero"><h1>台方向“解放军无法战胜”叙事专题数据库</h1><p>围绕“台湾难以抗衡 / 抵抗代价过高 / 外援不确定”的安全叙事,展示事件、口径、党派转译、平台链路、受众画像、青年兵役与疑美叙事。</p><div class="meta-row"><span class="meta-pill">版本:纯中文展示版 v5.0</span><span class="meta-pill">横向 Tab 导航</span><span class="meta-pill">无可见 JSON 区块</span><span class="meta-pill">本地单文件可运行</span></div></header>
|
||||
<main><div class="tabs-wrap"><nav class="tabs" id="tabs"><button class="tab-btn active" data-tab="overview">专题总览 <small>(4)</small></button><button class="tab-btn " data-tab="core_narratives">核心叙事库 <small>(12)</small></button><button class="tab-btn " data-tab="narrative_chains">叙事链条拆解 <small>(6)</small></button><button class="tab-btn " data-tab="timeline">事件时间线 <small>(12)</small></button><button class="tab-btn " data-tab="official_positions">官方口径对照 <small>(9)</small></button><button class="tab-btn " data-tab="party_translation">台湾党派转译 <small>(8)</small></button><button class="tab-btn " data-tab="platform_chains">平台传播链路 <small>(9)</small></button><button class="tab-btn " data-tab="audience_profiles">受众群体画像 <small>(10)</small></button><button class="tab-btn " data-tab="youth_conscription">青年与兵役专题 <small>(9)</small></button><button class="tab-btn " data-tab="us_skepticism">疑美叙事专题 <small>(7)</small></button></nav></div><section class="toolbar"><label class="searchbox"><span>搜索</span><input id="searchInput" placeholder="输入关键词:军演、兵役、疑美、Dcard、封锁、青年……"></label><select id="tagSelect"><option value="">全部标签</option></select><select id="viewSelect"><option value="rich">丰富卡片</option><option value="table">表格视图</option></select><button class="btn primary" id="exportBtn">导出当前表格</button></section><section id="content"><section class="section-intro"><div class="intro-head"><div><h2>专题总览</h2><p>定义研究对象、时间范围、边界、资料来源和系统结构。</p><p class="result-note">本页将底层数据转为中文卡片、时间线、链条图、表格和详情面板,不显示 JSON 原文。</p></div><div class="stats"><div class="stat"><b>4</b><span>条目</span></div><div class="stat"><b>8</b><span>标签</span></div><div class="stat"><b>3</b><span>来源引用</span></div></div></div><div class="profile-grid"><div class="profile-card"><b>研究重点</b><p>给出专题边界、研究对象、数据层构成、平台环境基线与安全边界。</p></div><div class="profile-card"><b>展示方式</b><p>总览卡片、统计面板、叙事—心理—行为模型、来源索引。</p></div><div class="profile-card"><b>适合回答</b><ul><li>这个专题研究什么?</li><li>数据有哪些层次?</li><li>哪些内容可以直接入库?</li><li>有哪些伦理边界?</li></ul></div><div class="profile-card"><b>核心字段</b><ul><li>研究对象</li><li>时间范围</li><li>研究边界</li><li>主要社群平台</li><li>数据结构</li></ul></div></div></section><div class="result-note">当前显示 <b>4</b> / 4 条记录。点击“查看完整详情”可打开中文详情面板。</div><div class="card-grid"><article class="record-card"><div><span class="badge">OV001 · 专题总览</span></div><h3>专题定义</h3><p>研究台湾方向围绕“解放军无法战胜 / 台湾难以抗衡 / 抵抗代价过高”的安全叙事体系。</p><div class="field-list"><div class="mini-kv"><b>研究对象</b><span>台湾舆论场中的安全叙事、党派转译、平台传播、受众心理与社会反应</span></div><div class="mini-kv"><b>时间范围</b><span>1995—1996;2022—2026为重点</span></div><div class="mini-kv"><b>研究边界</b><span>公开资料研究,不做隐蔽影响、定向操控、恐吓传播或虚假信息设计</span></div></div><div class="tags"><span class="tag">研究对象</span><span class="tag">范围</span></div><div class="card-actions"><button class="open-btn primary" data-open="OV001">查看完整详情</button></div></article><article class="record-card"><div><span class="badge">OV002 · 专题总览</span></div><h3>数据层说明</h3><p>本库包括10个栏目、12类核心叙事、6条叙事链、12个事件/战术动作条目、9类平台链路和10类受众画像。</p><div class="field-list"><div class="mini-kv"><b>栏目数量</b><span>10</span></div><div class="mini-kv"><b>核心叙事</b><span>12</span></div><div class="mini-kv"><b>叙事链</b><span>6</span></div><div class="mini-kv"><b>事件条目</b><span>12</span></div></div><div class="tags"><span class="tag">数据结构</span><span class="tag">知识库</span></div><div class="card-actions"><button class="open-btn primary" data-open="OV002">查看完整详情</button></div></article><article class="record-card"><div><span class="badge">OV003 · 专题总览</span></div><h3>安全与伦理边界</h3><p>本系统定位为研究型工具,输出为公开舆情研究、风险沟通和信息韧性分析。</p><div class="field-list"><div class="mini-kv"><b>允许方向</b><span>公开舆情研究、平台机制分析、风险沟通、政策研究</span></div><div class="mini-kv"><b>禁止方向</b><span>隐蔽投放、心理操控、恐吓传播、谣言制造、群体污名化、军事攻击Line truncated
|
||||
<div class="modal-backdrop" id="modalBackdrop"><div class="modal"><div class="modal-head"><div><h2 id="modalTitle"></h2><p id="modalSummary"></p></div><button class="close" id="closeBtn">×</button></div><div class="modal-body" id="modalBody"></div></div></div>
|
||||
<script type="application/json" id="app-data">{"metadata":{"title":"台方向“解放军无法战胜”叙事专题数据库","subtitle":"围绕“台湾难以抗衡 / 抵抗代价过高 / 外援不确定”的安全叙事,展示事件、口径、党派转译、平台链路、受众画像、青年兵役与疑美叙事。","version":"1.0.0","language":"zh-CN","created_at":"2026-06-25T11:56:25","data_date":"2026-06-25","scope":"公开资料研究、叙事结构分析、平台链路与受众心理研究","ethics_boundary":"仅用于透明、非操纵、非煽动的研究型分析;不用于隐蔽影响、恐吓传播、群体污名化或虚假信息设计。","display_version":"Rich UI v3.1","ui_note":"横向Tab、中文卡片、字段网格、时间线、链条图、详情面板、来源说明。"},"stats":{"tab_count":10,"record_count":86,"source_count":16,"last_updated":"2026-06-25","current_timezone":"Asia/Tokyo","data_status":{"framework":"complete","event_cards":"initial_completed","official_raw_quotes":"needs_more_original_text","platform_samples":"schema_ready_needs_collection","poll_data":"partial","front_end":"single_page_offline"}},"tabs":[{"id":"overview","name":"专题总览","description":"定义研究对象、时间范围、边界、资料来源和系统结构。","records":[{"id":"OV001","title":"专题定义","summary":"研究台湾方向围绕“解放军无法战胜 / 台湾难以抗衡 / 抵抗代价过高”的安全叙事体系。","category":"专题总览","tags":["研究对象","范围"],"level":"研究条目","fields":{"研究对象":"台湾舆论场中的安全叙事、党派转译、平台传播、受众心理与社会反应","时间范围":"1995—1996;2022—2026为重点","研究边界":"公开资料研究,不做隐蔽影响、定向操控、恐吓传播或虚假信息设计"},"detail_sections":[{"title":"核心问题","bullets":["该叙事如何由军演、军售、领导人讲话等事件激活?","它如何被台湾内部政党、媒体、政论节目和社群平台转译?","它如何与兵役焦虑、疑美论、棋子论、乌克兰化和避战论结合?","哪些受众更易将其转化为政治态度、家庭风险或个人规划问题?"]},{"title":"入库原则","bullets":["事实、观点、推测分开记录。","官方来源、民调、智库、媒体、社群样本分级标注。","平台语料只做公开研究与机制分析,不制作操控性传播内容。"]}],"source_refs":[],"display_type":"overview","中文展示摘要":"专题定义:研究台湾方向围绕“解放军无法战胜 / 台湾难以抗衡 / 抵抗代价过高”的安全叙事体系。"},{"id":"OV002","title":"数据层说明","summary":"本库包括10个栏目、12类核心叙事、6条叙事链、12个事件/战术动作条目、9类平台链路和10类受众画像。","category":"专题总览","tags":["数据结构","知识库"],"level":"研究条目","fields":{"栏目数量":10,"核心叙事":12,"叙事链":6,"事件条目":12,"平台类型":9,"受众类型":10},"detail_sections":[{"title":"可前端展示功能","bullets":["Tab切换","全库检索","栏目内筛选","详情弹框","来源查看","结构化详情查看","导出当前栏目表格"]}],"source_refs":[],"display_type":"overview","中文展示摘要":"数据层说明:本库包括10个栏目、12类核心叙事、6条叙事链、12个事件/战术动作条目、9类平台链路和10类受众画像。"},{"id":"OV003","title":"安全与伦理边界","summary":"本系统定位为研究型工具,输出为公开舆情研究、风险沟通和信息韧性分析。","category":"专题总览","tags":["安全边界","研究用途"],"level":"研究条目","fields":{"允许方向":"公开舆情研究、平台机制分析、风险沟通、政策研究","禁止方向":"隐蔽投放、心理操控、恐吓传播、谣言制造、群体污名化、军事攻击细节"},"detail_sections":[{"title":"研究注意事项","bullets":["不得把单一平台声量直接等同于台湾社会整体民意。","不得把青年对兵役不满直接等同于没有防卫意志。","不得把政党表态当成群体共识。","涉及社群样本时应保留来源、时间和上下文。"]}],"source_refs":[],"display_type":"overview","中文展示摘要":"安全与伦理边界:本系统定位为研究型工具,输出为公开舆情研究、风险沟通和信息韧性分析。"},{"id":"OV004","title":"数字与平台环境基线","summary":"台湾互联网和社群普及率很高,YouTube、Facebook、Instagram、Dcard、Threads、PTT 等平台承担不同传播功能。","category":"专题总览","tags":["平台环境","基线数据"],"level":"研究条目","fields":{"2025社群用户身份":"约1840万,占总人口约79.4%","2025年底互联网用户":"约2230万,普及率约96.7%","主要社群平台":"YouTube、Facebook、Instagram、Dcard、Threads、PTT、LINE"},"detail_sections":[{"title":"平台环境解释","bullets":["高互Line truncated
|
||||
<script>
|
||||
'use strict';
|
||||
const DATA = JSON.parse(document.getElementById('app-data').textContent);
|
||||
const $ = s => document.querySelector(s);
|
||||
const arr = x => Array.isArray(x) ? x : (x ? [x] : []);
|
||||
const state = { tab: DATA.tabs?.[0]?.id || '', q: '', tag: '', view: 'rich' };
|
||||
function esc(v) { return String(v ?? '').replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m])); }
|
||||
function textOf(v) { if (v === null || v === undefined) return ''; if (Array.isArray(v)) return v.map(textOf).join('、'); if (typeof v === 'object') return Object.entries(v).map(([k,val]) => k + ':' + textOf(val)).join(';'); return String(v); }
|
||||
function allText(obj) { return textOf(obj).toLowerCase(); }
|
||||
function getTab() { return DATA.tabs.find(t => t.id === state.tab) || DATA.tabs[0]; }
|
||||
function getSource(id) { return (DATA.sources || []).find(s => s.id === id); }
|
||||
function tagHtml(tags) { return arr(tags).map(t => `<span class="tag">${esc(t)}</span>`).join(''); }
|
||||
function sourceHtml(ids) { return arr(ids).map(id => `<span class="source-pill">来源 ${esc(id)}</span>`).join(''); }
|
||||
function list(items) { return arr(items).map(x => `<li>${esc(x)}</li>`).join(''); }
|
||||
function sourceDetail(ids) { const sources = arr(ids).map(getSource).filter(Boolean); if (!sources.length) return ''; return `<section class="detail-section"><h3>来源说明</h3><div class="source-list">${sources.map(s => `<div class="source-line"><b>${esc(s.id)} · ${esc(s.title)}</b><p>${esc(s.publisher)}|${esc(s.date)}|可信度:${esc(s.reliability)}</p><p>${esc(s.note || '')}</p><p><a href="${esc(s.url)}" target="_blank" rel="noopener">打开来源</a></p></div>`).join('')}</div></section>`; }
|
||||
function renderIntro(tab) { const p = tab.profile || {}; return `<section class="section-intro"><div class="intro-head"><div><h2>${esc(tab.name)}</h2><p>${esc(tab.description || tab.richness_note || '')}</p><p class="result-note">本页将底层数据转为中文卡片、时间线、链条图、表格和详情面板,不显示 JSON 原文。</p></div><div class="stats"><div class="stat"><b>${tab.records.length}</b><span>条目</span></div><div class="stat"><b>${tab.tag_count || 0}</b><span>标签</span></div><div class="stat"><b>${tab.source_ref_count || 0}</b><span>来源引用</span></div></div></div><div class="profile-grid"><div class="profile-card"><b>研究重点</b><p>${esc(p['研究重点'] || '本栏目提供可结构化入库的数据条目。')}</p></div><div class="profile-card"><b>展示方式</b><p>${esc(p['展示方式'] || '中文字段、详情面板、来源说明。')}</p></div><div class="profile-card"><b>适合回答</b><ul>${list(p['适合回答'] || [])}</ul></div><div class="profile-card"><b>核心字段</b><ul>${list(p['核心字段'] || [])}</ul></div></div></section>`; }
|
||||
function fieldRows(r, max=4) { const entries = Object.entries(r.fields || {}).slice(0, max); return entries.length ? entries.map(([k,v]) => `<div class="mini-kv"><b>${esc(k)}</b><span>${esc(textOf(v))}</span></div>`).join('') : '<div class="mini-kv"><b>说明</b><span>该条目暂无额外字段,完整信息见详情面板。</span></div>'; }
|
||||
function cardHtml(r) { return `<article class="record-card"><div><span class="badge">${esc(r.id)} · ${esc(r.category || r.level || '条目')}</span></div><h3>${esc(r.title)}</h3><p>${esc(r.summary || '')}</p><div class="field-list">${fieldRows(r,4)}</div><div class="tags">${tagHtml(r.tags)}${sourceHtml(r.source_refs)}</div><div class="card-actions"><button class="open-btn primary" data-open="${esc(r.id)}">查看完整详情</button></div></article>`; }
|
||||
function renderCards(records) { return records.length ? `<div class="card-grid">${records.map(cardHtml).join('')}</div>` : '<div class="empty">没有匹配的记录。请调整搜索词或标签。</div>'; }
|
||||
function renderTimeline(records) { return records.length ? `<div class="timeline">${records.map(r => `<div class="timeline-item">${cardHtml(r)}</div>`).join('')}</div>` : '<div class="empty">没有匹配的时间线记录。</div>'; }
|
||||
function renderChains(records) { if (!records.length) return '<div class="empty">没有匹配的叙事链条。</div>'; return `<div class="chain-grid">${records.map(r => { const chain = (r.fields && r.fields['叙事链条']) ? String(r.fields['叙事链条']).split('→').map(s => s.trim()).filter(Boolean) : []; return `<article class="chain-card"><span class="badge">${esc(r.id)}</span><h3>${esc(r.title)}</h3><p>${esc(r.summary || '')}</p><div class="chain-steps">${chain.map((s,i) => `<span class="step">${esc(s)}</span>${i < chain.length - 1 ? '<span class="arrow">→</span>' : ''}`).join('')}</div><div class="field-list">${fieldRows(r,4)}</div><div class="tags">${tagHtml(r.tags)}${sourceHtml(r.source_refs)}</div><div class="card-actions"><button class="open-btn primary" data-open="${esc(r.id)}">查看完整详情</button></div></article>`; }).join('')}</div>`; }
|
||||
function renderTable(records) { if (!records.length) return '<div class="empty">没有匹配记录。</div>'; return `<div class="table-wrap"><table><thead><tr><th>ID</th><th>标题</th><th>摘要</th><th>主要字段</th><th>标签/来源</th><th>操作</th></tr></thead><tbody>${records.map(r => `<tr><td><span class="badge">${esc(r.id)}</span></td><td class="cell-title">${esc(r.title)}</td><td>${esc(r.summary || '')}</td><td>${Object.entries(r.fields || {}).slice(0,6).map(([k,v]) => `<b>${esc(k)}:</b>${esc(textOf(v))}`).join('<br>')}</td><td>${tagHtml(r.tags)}<br>${sourceHtml(r.source_refs)}</td><td><button class="open-btn primary" data-open="${esc(r.id)}">详情</button></td></tr>`).join('')}</tbody></table></div>`; }
|
||||
function renderModels() { if (state.tab !== 'overview') return ''; const m = DATA.models || {}; return `<section class="panel"><h3>叙事 → 心理 → 行为模型</h3><div class="model-grid"><div class="model-card"><b>叙事到心理</b><ul>${arr(m.narrative_to_psychology).map(x => `<li>${esc(x.narrative)} → ${esc(x.psychology)}</li>`).join('')}</ul></div><div class="model-card"><b>心理到行为</b><ul>${arr(m.psychology_to_behavior).map(x => `<li>${esc(x.psychology)} → ${esc(x.behavior)}</li>`).join('')}</ul></div><div class="model-card"><b>可观测行为指标</b><ul>${arr(m.observable_behavior_indicators).map(x => `<li>${esc(x)}</li>`).join('')}</ul></div></div></section>`; }
|
||||
function renderSourcesPanel(tab) { const ids = [...new Set(tab.records.flatMap(r => arr(r.source_refs)))]; const sources = (ids.length ? ids.map(getSource).filter(Boolean) : (DATA.sources || []).slice(0,8)); if (!sources.length) return ''; return `<section class="panel"><h3>来源索引</h3><div class="source-grid">${sources.map(s => `<div class="source-card"><b>${esc(s.id)} · ${esc(s.title)}</b><span>${esc(s.publisher)}|${esc(s.date)}|可信度:${esc(s.reliability)}</span><p>${esc(s.note || '')}</p><p><a href="${esc(s.url)}" target="_blank" rel="noopener">打开来源</a></p></div>`).join('')}</div></section>`; }
|
||||
function filterRecords(tab) { return tab.records.filter(r => (!state.q || allText(r).includes(state.q)) && (!state.tag || arr(r.tags).includes(state.tag))); }
|
||||
function buildTagOptions(tab) { const tags = [...new Set(tab.records.flatMap(r => arr(r.tags)))].sort(); $('#tagSelect').innerHTML = '<option value="">全部标签</option>' + tags.map(t => `<option value="${esc(t)}">${esc(t)}</option>`).join(''); }
|
||||
function renderChips(tab) { const tags = [...new Set(tab.records.flatMap(r => arr(r.tags)))].slice(0, 24); $('#chips').innerHTML = `<button class="chip ${state.tag === '' ? 'active' : ''}" data-tag="">全部</button>` + tags.map(t => `<button class="chip ${state.tag === t ? 'active' : ''}" data-tag="${esc(t)}">${esc(t)}</button>`).join(''); }
|
||||
function renderRecordsOnly() { const tab = getTab(); const records = filterRecords(tab); let body = ''; if (state.view === 'table') body = renderTable(records); else if (tab.id === 'timeline') body = renderTimeline(records); else if (tab.id === 'narrative_chains') body = renderChains(records); else body = renderCards(records); $('#recordsHost').innerHTML = `<div class="result-note">当前显示 <b>${records.length}</b> / ${tab.records.length} 条记录。点击“查看完整详情”可打开中文详情面板。</div>` + body + renderModels() + renderSourcesPanel(tab) + `<div class="footer-note">后续可继续补充:${esc(arr(DATA.schema_note?.recommended_next_collection).slice(0,7).join(';'))}</div>`; }
|
||||
function render() { const tab = getTab(); document.querySelectorAll('.tab-btn').forEach(b => b.classList.toggle('active', b.dataset.tab === state.tab)); buildTagOptions(tab); $('#tagSelect').value = state.tag; $('#content').innerHTML = renderIntro(tab) + '<div class="chipbar" id="chips"></div><div id="recordsHost"></div>'; renderChips(tab); renderRecordsOnly(); }
|
||||
function findRecord(id) { for (const t of DATA.tabs) for (const r of t.records) if (r.id === id) return r; }
|
||||
function sectionHtml(sec) { let h = `<section class="detail-section"><h3>${esc(sec.title || '详情')}</h3>`; if (sec.text) h += `<p>${esc(sec.text)}</p>`; if (sec.bullets) h += `<ul>${arr(sec.bullets).map(b => `<li>${esc(b)}</li>`).join('')}</ul>`; if (sec.table) { const rows = arr(sec.table); const keys = [...new Set(rows.flatMap(o => Object.keys(o)))]; h += `<div class="table-wrap"><table><thead><tr>${keys.map(k => `<th>${esc(k)}</th>`).join('')}</tr></thead><tbody>${rows.map(row => `<tr>${keys.map(k => `<td>${esc(textOf(row[k]))}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`; } return h + '</section>'; }
|
||||
function openModal(id) { const r = findRecord(id); if (!r) return; $('#modalTitle').textContent = `${r.id} · ${r.title}`; $('#modalSummary').textContent = r.summary || ''; const fields = Object.entries(r.fields || {}).map(([k,v]) => `<div class="kv"><b>${esc(k)}</b><span>${esc(textOf(v))}</span></div>`).join(''); const sections = arr(r.detail_sections).map(sectionHtml).join(''); $('#modalBody').innerHTML = `<div class="tags">${tagHtml(r.tags)}${sourceHtml(r.source_refs)}</div><div class="detail-grid">${fields || '<div class="kv"><b>说明</b><span>该条目暂无额外字段,主要内容已在摘要和下方说明中展示。</span></div>'}</div>${sections || '<section class="detail-section"><h3>说明</h3><p>该条目暂无二级详情,已展示全部可读字段。</p></section>'}${sourceDetail(r.source_refs)}`; $('#modalBackdrop').style.display = 'flex'; }
|
||||
function closeModal() { $('#modalBackdrop').style.display = 'none'; }
|
||||
function csvEscape(v) { return '"' + textOf(v).replace(/"/g, '""') + '"'; }
|
||||
function exportCurrentTabCsv() { const tab = getTab(); const rows = filterRecords(tab); const baseCols = ['id','title','summary','category','tags','source_refs']; const dyn = [...new Set(rows.flatMap(r => Object.keys(r.fields || {})))]; const header = baseCols.concat(dyn); const lines = [header.map(csvEscape).join(',')]; rows.forEach(r => { lines.push(header.map(c => csvEscape(c in r ? (Array.isArray(r[c]) ? r[c].join('、') : r[c]) : (r.fields || {})[c])).join(',')); }); const blob = new Blob(['' + lines.join('\n')], {type:'text/csv;charset=utf-8'}); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = tab.id + '_records.csv'; a.click(); URL.revokeObjectURL(a.href); }
|
||||
function init() { $('#tabs').innerHTML = DATA.tabs.map(t => `<button class="tab-btn" data-tab="${esc(t.id)}">${esc(t.name)} <small>(${t.records.length})</small></button>`).join(''); $('#tabs').addEventListener('click', e => { const btn = e.target.closest('.tab-btn'); if (!btn) return; state.tab = btn.dataset.tab; state.tag = ''; state.q = $('#searchInput').value.trim().toLowerCase(); render(); window.scrollTo({top:0,behavior:'smooth'}); }); $('#searchInput').addEventListener('input', e => { state.q = e.target.value.trim().toLowerCase(); renderRecordsOnly(); }); $('#tagSelect').addEventListener('change', e => { state.tag = e.target.value; renderChips(getTab()); renderRecordsOnly(); }); $('#viewSelect').addEventListener('change', e => { state.view = e.target.value; renderRecordsOnly(); }); $('#content').addEventListener('click', e => { const btn = e.target.closest('[data-open]'); if (btn) openModal(btn.dataset.open); const chip = e.target.closest('[data-tag]'); if (chip) { state.tag = chip.dataset.tag; $('#tagSelect').value = state.tag; renderChips(getTab()); renderRecordsOnly(); } }); $('#exportBtn').addEventListener('click', exportCurrentTabCsv); $('#closeBtn').addEventListener('click', closeModal); $('#modalBackdrop').addEventListener('click', e => { if (e.target.id === 'modalBackdrop') closeModal(); }); window.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); }); render(); }
|
||||
try { init(); } catch (err) { console.error(err); $('#content').innerHTML = `<div class="empty">页面加载出错:${esc(err.message)}。请使用新版 v5 文件或更换 Chrome / Edge 打开。</div>`; }
|
||||
</script></body></html>
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>驻印太美国军事群体专题数据库</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg0:#5b0d14;
|
||||
--bg1:#7f1620;
|
||||
--bg2:#2b080b;
|
||||
--card:#ffffff;
|
||||
--ink:#241015;
|
||||
--muted:#6f5960;
|
||||
--line:#ead9dc;
|
||||
--soft:#fff7f8;
|
||||
--accent:#b6202d;
|
||||
--accent2:#f2d7dc;
|
||||
--ok:#1f7a4d;
|
||||
--warn:#a96b00;
|
||||
--danger:#b6202d;
|
||||
--shadow:0 18px 45px rgba(27,5,9,.18);
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;font-family:"Microsoft YaHei", "PingFang SC", Arial, sans-serif;background:radial-gradient(circle at 20% 0%, #9e2430 0, var(--bg1) 22%, var(--bg0) 50%, var(--bg2) 100%);color:var(--ink);}
|
||||
.hero{max-width:1320px;margin:0 auto;padding:34px 24px 18px;color:#fff;}
|
||||
.hero-top{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;}
|
||||
.title-block h1{font-size:34px;margin:0 0 10px;letter-spacing:.5px}
|
||||
.title-block p{margin:0;max-width:900px;line-height:1.75;color:#ffe9ed;font-size:14px}
|
||||
.version{border:1px solid rgba(255,255,255,.35);padding:10px 14px;border-radius:999px;background:rgba(255,255,255,.1);white-space:nowrap;font-weight:700}
|
||||
.shell{max-width:1320px;margin:0 auto 40px;padding:0 24px 28px;}
|
||||
.panel{background:rgba(255,255,255,.96);border:1px solid rgba(255,255,255,.45);border-radius:26px;box-shadow:var(--shadow);overflow:hidden;}
|
||||
.tabs{display:flex;gap:8px;overflow-x:auto;padding:14px 14px 0;background:linear-gradient(180deg,#fff,#fff8f9);border-bottom:1px solid var(--line);}
|
||||
.tab-btn{border:1px solid var(--line);background:#fff;color:var(--muted);padding:10px 16px;border-radius:999px;font-weight:700;cursor:pointer;white-space:nowrap;transition:.18s;}
|
||||
.tab-btn:hover{transform:translateY(-1px);border-color:#d9aab1;color:var(--accent)}
|
||||
.tab-btn.active{background:var(--accent);border-color:var(--accent);color:#fff;box-shadow:0 8px 18px rgba(182,32,45,.22)}
|
||||
.content{padding:22px;}
|
||||
.tab-section{display:none}
|
||||
.tab-section.active{display:block}
|
||||
.section-head{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;margin-bottom:16px;}
|
||||
.section-head h2{margin:0;font-size:24px;color:#2b0c10}
|
||||
.section-head p{margin:6px 0 0;color:var(--muted);line-height:1.65}
|
||||
.toolbar{display:flex;gap:10px;flex-wrap:wrap;margin:14px 0 18px;}
|
||||
.input,.select{height:42px;border:1px solid var(--line);border-radius:14px;padding:0 12px;background:#fff;outline:none;color:var(--ink);}
|
||||
.input{min-width:260px;flex:1}
|
||||
.select{min-width:160px}
|
||||
.stats-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:20px;}
|
||||
.stat{background:linear-gradient(180deg,#fff,#fff6f7);border:1px solid var(--line);border-radius:20px;padding:16px;}
|
||||
.stat .value{font-size:26px;font-weight:900;color:var(--accent);margin-bottom:6px}
|
||||
.stat .label{font-weight:800;margin-bottom:8px}
|
||||
.stat .note{font-size:12px;color:var(--muted);line-height:1.5}
|
||||
.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;}
|
||||
.card{background:#fff;border:1px solid var(--line);border-radius:22px;padding:16px;box-shadow:0 10px 26px rgba(58,16,23,.07);position:relative;overflow:hidden;}
|
||||
.card::before{content:"";position:absolute;top:0;left:0;right:0;height:4px;background:linear-gradient(90deg,var(--accent),#e8a1ab)}
|
||||
.card h3{margin:4px 0 6px;font-size:19px;color:#2b0c10}
|
||||
.sub{font-size:13px;color:var(--muted);line-height:1.55;margin-bottom:12px}
|
||||
.meta-row{display:grid;grid-template-columns:90px 1fr;gap:8px;font-size:13px;margin:8px 0;line-height:1.5}
|
||||
.meta-row b{color:#5a1b22}
|
||||
.tags{display:flex;gap:6px;flex-wrap:wrap;margin-top:12px}
|
||||
.tag{font-size:12px;padding:5px 8px;border-radius:999px;background:var(--soft);border:1px solid var(--accent2);color:#7b2430;font-weight:700}
|
||||
.risk{position:absolute;right:14px;top:13px;font-size:12px;padding:5px 9px;border-radius:999px;color:#fff;background:var(--warn);font-weight:800}
|
||||
.risk.high{background:var(--danger)}
|
||||
.risk.medium{background:var(--warn)}
|
||||
.risk.low{background:var(--ok)}
|
||||
.btn{border:0;background:var(--accent);color:#fff;border-radius:12px;padding:10px 12px;font-weight:800;cursor:pointer;margin-top:12px;}
|
||||
.btn.secondary{background:#fff;color:var(--accent);border:1px solid var(--accent2)}
|
||||
.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:18px;background:#fff;}
|
||||
table{border-collapse:collapse;width:100%;min-width:980px}
|
||||
th,td{border-bottom:1px solid var(--line);padding:12px 12px;text-align:left;vertical-align:top;line-height:1.55;font-size:13px}
|
||||
th{background:#fff3f5;color:#5b1118;position:sticky;top:0;z-index:1}
|
||||
tr:hover td{background:#fffafa}
|
||||
.timeline{position:relative;margin:8px 0 0;padding-left:24px}
|
||||
.timeline::before{content:"";position:absolute;left:8px;top:0;bottom:0;width:2px;background:#e7b5bd}
|
||||
.event{position:relative;margin:0 0 14px;padding:14px 14px 14px 18px;background:#fff;border:1px solid var(--line);border-radius:18px;}
|
||||
.event::before{content:"";position:absolute;left:-22px;top:20px;width:12px;height:12px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 4px #f7dce1}
|
||||
.event .year{font-weight:900;color:var(--accent);font-size:14px}
|
||||
.event h3{margin:4px 0 8px}
|
||||
.columns{display:grid;grid-template-columns:1fr 1fr;gap:16px}
|
||||
.list-card{border:1px solid var(--line);border-radius:18px;padding:14px;background:#fff}
|
||||
.list-card h3{margin:0 0 10px;color:#391016}
|
||||
.list-card ul{margin:0;padding-left:18px;line-height:1.8;color:#443238}
|
||||
.schema-box{background:#fff;border:1px solid var(--line);border-radius:18px;padding:14px;margin-bottom:12px}
|
||||
.schema-title{font-weight:900;color:#5b1118;margin-bottom:10px}
|
||||
.field-list{display:flex;flex-wrap:wrap;gap:8px}
|
||||
.field{padding:7px 9px;border:1px solid var(--accent2);background:#fff7f8;border-radius:10px;font-size:12px;font-weight:700;color:#6d222b}
|
||||
.note-box{background:#fff7f8;border:1px solid var(--accent2);border-radius:18px;padding:14px;color:#5d4047;line-height:1.7;margin:14px 0}
|
||||
.modal-backdrop{display:none;position:fixed;inset:0;background:rgba(25,0,5,.55);z-index:20;padding:28px;overflow:auto}
|
||||
.modal{max-width:980px;margin:20px auto;background:#fff;border-radius:24px;box-shadow:0 25px 70px rgba(0,0,0,.35);overflow:hidden}
|
||||
.modal-head{padding:18px 22px;background:linear-gradient(90deg,#7f1620,#b6202d);color:#fff;display:flex;justify-content:space-between;gap:14px;align-items:center}
|
||||
.modal-head h2{margin:0;font-size:22px}
|
||||
.close{background:rgba(255,255,255,.16);color:#fff;border:1px solid rgba(255,255,255,.35);border-radius:12px;padding:8px 10px;cursor:pointer;font-weight:900}
|
||||
.modal-body{padding:20px}
|
||||
.detail-grid{display:grid;grid-template-columns:160px 1fr;gap:10px;border:1px solid var(--line);border-radius:18px;overflow:hidden}
|
||||
.detail-k{background:#fff6f7;color:#6d222b;font-weight:900;padding:11px;border-bottom:1px solid var(--line)}
|
||||
.detail-v{padding:11px;border-bottom:1px solid var(--line);line-height:1.65}
|
||||
.footer{padding:16px 22px;background:#fff8f9;border-top:1px solid var(--line);color:var(--muted);font-size:12px;line-height:1.6}
|
||||
.empty{text-align:center;padding:28px;color:var(--muted);background:#fff;border:1px dashed var(--line);border-radius:18px}
|
||||
@media(max-width:1000px){.stats-grid{grid-template-columns:repeat(2,1fr)}.grid{grid-template-columns:repeat(2,1fr)}.columns{grid-template-columns:1fr}}
|
||||
@media(max-width:680px){.hero-top{flex-direction:column}.stats-grid,.grid{grid-template-columns:1fr}.content{padding:14px}.detail-grid{grid-template-columns:1fr}.detail-k{border-bottom:0;padding-bottom:0}.input{min-width:100%}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="hero">
|
||||
<div class="hero-top">
|
||||
<div class="title-block">
|
||||
<h1>驻印太美国军事群体专题库</h1>
|
||||
<p>围绕日本、韩国、关岛等地区的美国军事群体、基地网络、地方舆情、SOFA争议、环境健康、NEO撤离与信息安全风险进行结构化展示。</p>
|
||||
</div>
|
||||
<div class="version">V1.2</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="shell">
|
||||
<section class="panel">
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
<div class="content" id="content"></div>
|
||||
<div class="footer">资料边界:本页面仅展示公开资料研究数据,避免包含非公开部署细节、敏感坐标、警备路线、具体集合点或可操作化攻击信息。建议在正式发布前继续核验年度人员、预算、地方投诉与民调数据。</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div class="modal-backdrop" id="modalBackdrop" onclick="if(event.target.id==='modalBackdrop') closeModal()">
|
||||
<div class="modal">
|
||||
<div class="modal-head"><h2 id="modalTitle">详情</h2><button class="close" onclick="closeModal()">关闭</button></div>
|
||||
<div class="modal-body" id="modalBody"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const DB = {"metadata": {"title": "驻印太美国军事群体专题数据库", "version": "V1.2", "language": "zh-CN", "generated_at": "2026-06-25", "scope": "公开资料研究型专题,覆盖驻日本、韩国、关岛等印太地区美国军事群体、基地社区、地方舆情、法律制度、环境健康、NEO与信息安全风险。", "safety_note": "本数据库只用于公开资料研究与专题展示,不包含非公开部署细节、敏感坐标、警备路线、具体集合点或可操作化攻击信息。", "primary_modules": ["基地档案", "地方舆情与民调", "历史事件", "人群画像", "SOFA与预算", "环境健康", "NEO与信息安全", "涉华涉台立场"]}, "overview_metrics": [{"label": "印太司令部全区军事人员", "value": "约36万", "note": "skill速查口径,需按DMDC或DoD最新口径周期更新"}, {"label": "驻日美军", "value": "约53,500", "note": "日本全境现役规模概数"}, {"label": "驻韩美军", "value": "约23,600—28,500", "note": "不同统计口径包括实际现役与政策上限口径"}, {"label": "关岛美军", "value": "约7,000+", "note": "不含全部家属、文职和承包商扩展口径"}, {"label": "驻日美军家属", "value": "约35,000", "note": "USFJ公开口径"}, {"label": "日本当地雇员", "value": "约25,000", "note": "驻日基地经济与同盟分担重要变量"}, {"label": "DoDEA太平洋学校", "value": "46所", "note": "服务太平洋美军与合格DoD文职子女"}, {"label": "核心矛盾", "value": "威慑 / 负担 / 法律 / 环境", "note": "专题分析四条主线"}], "tabs": [{"id": "overview", "name": "总览"}, {"id": "bases", "name": "基地档案"}, {"id": "opinion", "name": "地方舆情"}, {"id": "events", "name": "事件时间线"}, {"id": "groups", "name": "人群画像"}, {"id": "legal_budget", "name": "SOFA与预算"}, {"id": "environment", "name": "环境健康"}, {"id": "neo_opsec", "name": "NEO与信息安全"}, {"id": "geopolitics", "name": "涉华涉台"}, {"id": "schemas", "name": "数据字段"}], "bases": [{"id": "JP-YOKOTA-001", "name_cn": "横田空军基地", "name_en": "Yokota Air Base", "country_area": "日本", "region": "日本本土", "location": "东京都多摩地区,东京西北方向", "service": "空军/太空军/联合指挥", "command": "USFJ、第五空军、374th Airlift Wing", "core_position": "驻日美军司令部所在地;印太方向空运、后勤、联络和危机协调枢纽", "units": ["374th Airlift Wing", "第五空军相关机构", "USFJ总部", "多个任务伙伴"], "missions": ["战区空运", "人员与物资输送", "危机支援", "日美联合协调", "首都圈军事联络"], "population": "374th Airlift Wing支撑约11,500人的基地人口;USFJ整体包含约60,000名军人、35,000名家属、7,000名DoD文职/承包商与约25,000名日本雇员。", "community": "首都圈型基地,家属、文职、日方雇员、任务伙伴较多,具有总部—后勤—家庭社区复合属性。", "facilities": ["空运设施", "指挥办公设施", "住房", "学校", "家庭支援", "医疗与生活服务"], "controversies": ["噪音", "空域管制", "首都圈军事存在", "基地开放与周边秩序"], "opinion_tags": ["首都圈基地", "指挥中枢", "空运枢纽", "噪音", "空域"], "visual_hint": "作为驻日美军总部节点展示,并与横须贺、嘉手纳、岩国形成指挥—海军—空军—陆战队网络。", "risk_level": "中", "source_note": "USFJ与Yokota官方公开资料"}, {"id": "JP-YOKOSUKA-002", "name_cn": "横须贺海军基地", "name_en": "Commander Fleet Activities Yokosuka", "country_area": "日本", "region": "日本本土", "location": "神奈川县横须贺市", "service": "海军", "command": "Commander, Navy Region Japan;第七舰队支撑体系", "core_position": "第七舰队前沿部署核心母港之一,支撑航母打击群及前沿部署海军力量。", "units": ["第七舰队相关前沿部署单位", "舰艇维修与后勤单位", "港口保障单位"], "missions": ["舰艇母港", "舰队后勤", "维修", "家庭支援", "港口保障", "同盟联络"], "population": "港口城市型基地,军人、家属、文职、承包商与当地商业区互动频繁。", "community": "基地与横须贺城市经济、旅游、港口身份高度绑定,同时舰艇可见性强。", "facilities": ["港口", "舰艇支援设施", "家庭服务", "宗教服务", "住房", "生活配套", "紧急管理设施"], "controversies": ["核动力舰艇停靠", "港口安全", "夜间秩序", "地方商业依赖", "军人外出行为"], "opinion_tags": ["第七舰队", "航母母港", "港口城市", "地方商业", "核动力舰艇"], "visual_hint": "适合做港口—舰艇—城市经济三层图,不展示具体舰艇行动细节。", "risk_level": "中高", "source_note": "CFA Yokosuka官方公开资料与日媒公开报道"}, {"id": "JP-KADENA-003", "name_cn": "嘉手纳空军基Line truncated
|
||||
const state = { active:'overview' };
|
||||
const $ = sel => document.querySelector(sel);
|
||||
const content = $('#content');
|
||||
|
||||
function esc(v){
|
||||
if(v === null || v === undefined) return '';
|
||||
return String(v).replace(/[&<>"']/g, s=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[s]));
|
||||
}
|
||||
function arr(v){ return Array.isArray(v) ? v : (v ? [v] : []); }
|
||||
function tags(list){ return arr(list).map(t=>`<span class="tag">${esc(t)}</span>`).join(''); }
|
||||
function riskClass(r){ if(!r) return 'medium'; if(r.includes('高')) return 'high'; if(r.includes('低')) return 'low'; return 'medium'; }
|
||||
function includesText(obj, q){ return JSON.stringify(obj).toLowerCase().includes(q.toLowerCase()); }
|
||||
function filterByRegion(list, region){ return !region || region==='全部' ? list : list.filter(x => (x.region||x.country_area||'').includes(region) || (x.area||'').includes(region)); }
|
||||
|
||||
function initTabs(){
|
||||
$('#tabs').innerHTML = DB.tabs.map(t=>`<button class="tab-btn ${t.id===state.active?'active':''}" onclick="switchTab('${t.id}')">${esc(t.name)}</button>`).join('');
|
||||
}
|
||||
function switchTab(id){ state.active=id; initTabs(); render(); window.scrollTo({top:0,behavior:'smooth'}); }
|
||||
|
||||
function head(title, desc){ return `<div class="section-head"><div><h2>${esc(title)}</h2><p>${esc(desc)}</p></div></div>`; }
|
||||
|
||||
function renderOverview(){
|
||||
const stats = DB.overview_metrics.map(m=>`<div class="stat"><div class="value">${esc(m.value)}</div><div class="label">${esc(m.label)}</div><div class="note">${esc(m.note)}</div></div>`).join('');
|
||||
const baseCount = DB.bases.length, opinionCount = DB.local_opinion.length, eventCount = DB.events.length, groupCount = DB.groups.length;
|
||||
return `${head('专题总览','以“前沿威慑—基地社会—同盟成本—地方冲突—家庭压力—信息安全—台海/朝鲜半岛风险”为主线。')}
|
||||
<div class="stats-grid">${stats}</div>
|
||||
<div class="columns">
|
||||
<div class="list-card"><h3>数据库构成</h3><ul>
|
||||
<li>基地档案:${baseCount} 条</li><li>地方舆情/民调:${opinionCount} 条</li><li>历史事件:${eventCount} 条</li><li>人群画像:${groupCount} 类</li>
|
||||
<li>SOFA制度:${DB.legal_sofa.length} 条</li><li>预算条目:${DB.budget.length} 条</li><li>环境健康:${DB.environment.length} 条</li>
|
||||
</ul></div>
|
||||
<div class="list-card"><h3>专题主线</h3><ul>
|
||||
<li>基地网络:日本本土、冲绳、韩国、关岛三层结构。</li>
|
||||
<li>地方舆情:冲绳反基地、韩国全国/地方分裂、关岛原住民与住房压力。</li>
|
||||
<li>制度争议:SOFA、刑事管辖、环境进入权、承包商身份。</li>
|
||||
<li>风险维度:NEO家庭压力、OPSEC、台海和朝鲜半岛危机暴露。</li>
|
||||
</ul></div>
|
||||
</div>
|
||||
<div class="note-box"><b>使用建议:</b>先用“基地档案”建立核心对象,再用“事件时间线”和“地方舆情”解释社会反应,最后用“SOFA与预算”“环境健康”“NEO与信息安全”补足专题深度。</div>`;
|
||||
}
|
||||
|
||||
function baseCard(b){
|
||||
return `<article class="card"><span class="risk ${riskClass(b.risk_level)}">风险${esc(b.risk_level||'中')}</span><h3>${esc(b.name_cn)}</h3><div class="sub">${esc(b.name_en)} · ${esc(b.country_area)} / ${esc(b.region)}</div>
|
||||
<div class="meta-row"><b>军种</b><span>${esc(b.service)}</span></div>
|
||||
<div class="meta-row"><b>上级</b><span>${esc(b.command)}</span></div>
|
||||
<div class="meta-row"><b>定位</b><span>${esc(b.core_position)}</span></div>
|
||||
<div class="tags">${tags(b.opinion_tags)}</div><button class="btn" onclick="openBase('${b.id}')">查看详情</button></article>`;
|
||||
}
|
||||
function renderBases(){
|
||||
const regions = ['全部', ...new Set(DB.bases.map(b=>b.region))];
|
||||
return `${head('基地详细档案','按地区、军种和关键词检索基地,点击卡片可查看完整画像。')}
|
||||
<div class="toolbar"><input class="input" id="baseSearch" placeholder="搜索:基地名、军种、争议、任务、标签..." oninput="updateBases()"><select class="select" id="baseRegion" onchange="updateBases()">${regions.map(r=>`<option>${esc(r)}</option>`).join('')}</select></div><div class="grid" id="baseGrid"></div>`;
|
||||
}
|
||||
function updateBases(){
|
||||
const q = ($('#baseSearch')?.value || '').trim(); const region = $('#baseRegion')?.value || '全部';
|
||||
let list = filterByRegion(DB.bases, region); if(q) list = list.filter(b=>includesText(b,q));
|
||||
$('#baseGrid').innerHTML = list.length ? list.map(baseCard).join('') : '<div class="empty">没有找到匹配基地。</div>';
|
||||
}
|
||||
function openBase(id){
|
||||
const b = DB.bases.find(x=>x.id===id); if(!b) return;
|
||||
const rows = [
|
||||
['基地ID', b.id], ['中文名', b.name_cn], ['英文名', b.name_en], ['国家/地区', b.country_area], ['区域', b.region], ['所在地', b.location], ['所属军种', b.service], ['上级体系', b.command], ['核心定位', b.core_position], ['主要单位', arr(b.units).join('、')], ['主要任务', arr(b.missions).join('、')], ['人员/社区', b.population], ['社区特征', b.community], ['主要设施', arr(b.facilities).join('、')], ['争议点', arr(b.controversies).join('、')], ['舆情标签', arr(b.opinion_tags).join('、')], ['可视化建议', b.visual_hint], ['风险等级', b.risk_level], ['资料来源说明', b.source_note]
|
||||
];
|
||||
openModal(b.name_cn, detailRows(rows));
|
||||
}
|
||||
|
||||
function renderOpinion(){
|
||||
const regions = ['全部', ...new Set(DB.local_opinion.map(o=>o.region))];
|
||||
return `${head('地方舆情与民调数据库','重点呈现冲绳、韩国、关岛三个典型场景:地方负担、全国/地方分裂、原住民与住房压力。')}
|
||||
<div class="toolbar"><input class="input" id="opSearch" placeholder="搜索:边野古、THAAD、关岛、住房、SOFA..." oninput="updateOpinion()"><select class="select" id="opRegion" onchange="updateOpinion()">${regions.map(r=>`<option>${esc(r)}</option>`).join('')}</select></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>时间</th><th>地区</th><th>议题</th><th>核心数据</th><th>支持/反对</th><th>深层矛盾</th><th>标签</th></tr></thead><tbody id="opRows"></tbody></table></div>`;
|
||||
}
|
||||
function updateOpinion(){
|
||||
const q = ($('#opSearch')?.value || '').trim(); const region = $('#opRegion')?.value || '全部';
|
||||
let list = filterByRegion(DB.local_opinion, region); if(q) list = list.filter(o=>includesText(o,q));
|
||||
$('#opRows').innerHTML = list.map(o=>`<tr><td>${esc(o.date)}</td><td>${esc(o.area)}</td><td><b>${esc(o.issue)}</b><br><span class="sub">${esc(o.source_type)} / 可信度:${esc(o.confidence)}</span></td><td>${esc(o.core_data)}</td><td>支持:${esc(o.support)}<br>反对:${esc(o.oppose)}<br>中立:${esc(o.neutral)}</td><td>${esc(o.deep_conflict)}</td><td>${tags(o.tags)}</td></tr>`).join('') || '<tr><td colspan="7">没有匹配结果。</td></tr>';
|
||||
}
|
||||
|
||||
function renderEvents(){
|
||||
return `${head('历史事件时间线','将个案事件与SOFA、地方自治、环境健康、基地扩张和大国博弈连接。')}
|
||||
<div class="toolbar"><input class="input" id="eventSearch" placeholder="搜索:冲绳、SOFA、THAAD、PFAS、关岛..." oninput="updateEvents()"></div>
|
||||
<div class="timeline" id="eventTimeline"></div>`;
|
||||
}
|
||||
function updateEvents(){
|
||||
const q = ($('#eventSearch')?.value || '').trim(); let list = DB.events; if(q) list = list.filter(e=>includesText(e,q));
|
||||
$('#eventTimeline').innerHTML = list.map(e=>`<div class="event"><div class="year">${esc(e.date)} · ${esc(e.region)} · ${esc(e.type)}</div><h3>${esc(e.title)}</h3><p>${esc(e.summary)}</p><p><b>影响:</b>${esc(e.impact)}</p><p><b>深层矛盾:</b>${esc(e.deep_conflict)}</p><div class="tags">${tags(e.tags)}</div></div>`).join('') || '<div class="empty">没有匹配事件。</div>';
|
||||
}
|
||||
|
||||
function renderGroups(){
|
||||
return `${head('人群画像','把“美军群体”拆成军人、家属、文职、承包商、当地雇员和混合国籍家庭。')}
|
||||
<div class="toolbar"><input class="input" id="groupSearch" placeholder="搜索:配偶、子女、承包商、NEO、就业..." oninput="updateGroups()"></div><div class="grid" id="groupGrid"></div>`;
|
||||
}
|
||||
function updateGroups(){
|
||||
const q = ($('#groupSearch')?.value || '').trim(); let list = DB.groups; if(q) list = list.filter(g=>includesText(g,q));
|
||||
$('#groupGrid').innerHTML = list.map(g=>`<article class="card"><h3>${esc(g.name)}</h3><div class="sub">${esc(g.category)} · ${esc(g.display)}</div><p>${esc(g.profile)}</p><div class="meta-row"><b>主要需求</b><span>${esc(arr(g.needs).join('、'))}</span></div><div class="meta-row"><b>核心压力</b><span>${esc(arr(g.pressures).join('、'))}</span></div><div class="tags">${tags(g.risks)}</div></article>`).join('') || '<div class="empty">没有匹配画像。</div>';
|
||||
}
|
||||
|
||||
function renderLegalBudget(){
|
||||
return `${head('SOFA与预算','把法律身份、刑事管辖、环境进入权、同盟分担和基地建设放在同一制度框架下观察。')}
|
||||
<h3>SOFA制度要点</h3><div class="table-wrap"><table><thead><tr><th>议题</th><th>日本方向</th><th>韩国方向</th><th>专题解释</th></tr></thead><tbody>${DB.legal_sofa.map(x=>`<tr><td><b>${esc(x.topic)}</b></td><td>${esc(x.japan)}</td><td>${esc(x.korea)}</td><td>${esc(x.meaning)}</td></tr>`).join('')}</tbody></table></div>
|
||||
<h3 style="margin-top:20px">预算与同盟分担</h3><div class="table-wrap"><table><thead><tr><th>地区</th><th>时期</th><th>项目</th><th>金额/口径</th><th>说明</th><th>标签</th></tr></thead><tbody>${DB.budget.map(x=>`<tr><td>${esc(x.area)}</td><td>${esc(x.period)}</td><td><b>${esc(x.item)}</b></td><td>${esc(x.amount)}</td><td>${esc(x.explain)}</td><td>${tags(x.tags)}</td></tr>`).join('')}</tbody></table></div>`;
|
||||
}
|
||||
|
||||
function renderEnvironment(){
|
||||
return `${head('环境与公共健康','重点覆盖PFAS、噪音、土地占用、海洋生态等与基地社会关系最密切的议题。')}
|
||||
<div class="grid">${DB.environment.map(e=>`<article class="card"><h3>${esc(e.type)}</h3><div class="sub">涉及地点:${esc(arr(e.locations).join('、'))}</div><p><b>已知问题:</b>${esc(e.known_issue)}</p><p><b>社会影响:</b>${esc(e.social_impact)}</p><div class="meta-row"><b>字段</b><span>${esc(arr(e.fields).join('、'))}</span></div><div class="tags">${tags(e.tags)}</div></article>`).join('')}</div>`;
|
||||
}
|
||||
|
||||
function renderNeoOpsec(){
|
||||
return `${head('NEO与信息安全','以家庭风险、撤离资格、信息安全治理为主题,不展示具体路线、集合点或可操作细节。')}
|
||||
<div class="columns"><div><h3>NEO风险场景</h3>${DB.neo.map(n=>`<div class="list-card" style="margin-bottom:12px"><h3>${esc(n.region)}</h3><p><b>触发:</b>${esc(n.risk_trigger)}</p><p><b>对象:</b>${esc(n.objects)}</p><p><b>压力:</b>${esc(n.pressure)}</p><div class="tags">${tags(n.tags)}</div></div>`).join('')}</div>
|
||||
<div><h3>OPSEC风险类型</h3>${DB.opsec.map(o=>`<div class="list-card" style="margin-bottom:12px"><h3>${esc(o.risk_type)}</h3><p><b>案例:</b>${esc(o.case)}</p><p><b>对象:</b>${esc(o.objects)}</p><p><b>机制:</b>${esc(o.mechanism)}</p><p><b>展示口径:</b>${esc(o.display)}</p><div class="tags">${tags(o.tags)}</div></div>`).join('')}</div></div>`;
|
||||
}
|
||||
|
||||
function renderGeopolitics(){
|
||||
return `${head('涉华涉台与地缘风险','从第一岛链、台湾问题、朝鲜半岛、关岛角色与中国叙事五个角度呈现。')}
|
||||
<div class="grid">${DB.geopolitics.map(g=>`<article class="card"><h3>${esc(g.issue)}</h3><p><b>美国官方口径:</b>${esc(g.official_line)}</p><p><b>基地/群体关联:</b>${esc(g.base_link)}</p><p><b>社会争议:</b>${esc(g.social_conflict)}</p><div class="tags">${tags(g.tags)}</div></article>`).join('')}</div>`;
|
||||
}
|
||||
|
||||
function renderSchemas(){
|
||||
const boxes = Object.entries(DB.schemas).map(([k, fields])=>`<div class="schema-box"><div class="schema-title">${esc(k)}</div><div class="field-list">${fields.map(f=>`<span class="field">${esc(f)}</span>`).join('')}</div></div>`).join('');
|
||||
const gaps = DB.data_gaps.map(g=>`<tr><td><b>${esc(g.gap)}</b></td><td>${esc(g.priority)}</td><td>${esc(g.explain)}</td></tr>`).join('');
|
||||
return `${head('数据字段与后续缺口','用于后续扩展JSON、接入外部数据源和长期更新。')}${boxes}<h3>当前数据缺口</h3><div class="table-wrap"><table><thead><tr><th>缺口</th><th>优先级</th><th>说明</th></tr></thead><tbody>${gaps}</tbody></table></div>`;
|
||||
}
|
||||
|
||||
function detailRows(rows){
|
||||
return `<div class="detail-grid">${rows.map(([k,v])=>`<div class="detail-k">${esc(k)}</div><div class="detail-v">${esc(v)}</div>`).join('')}</div>`;
|
||||
}
|
||||
function openModal(title, body){ $('#modalTitle').textContent = title; $('#modalBody').innerHTML = body; $('#modalBackdrop').style.display='block'; document.body.style.overflow='hidden'; }
|
||||
function closeModal(){ $('#modalBackdrop').style.display='none'; document.body.style.overflow=''; }
|
||||
|
||||
function render(){
|
||||
let html = '';
|
||||
if(state.active==='overview') html = renderOverview();
|
||||
if(state.active==='bases') html = renderBases();
|
||||
if(state.active==='opinion') html = renderOpinion();
|
||||
if(state.active==='events') html = renderEvents();
|
||||
if(state.active==='groups') html = renderGroups();
|
||||
if(state.active==='legal_budget') html = renderLegalBudget();
|
||||
if(state.active==='environment') html = renderEnvironment();
|
||||
if(state.active==='neo_opsec') html = renderNeoOpsec();
|
||||
if(state.active==='geopolitics') html = renderGeopolitics();
|
||||
if(state.active==='schemas') html = renderSchemas();
|
||||
content.innerHTML = `<section class="tab-section active">${html}</section>`;
|
||||
if(state.active==='bases') updateBases();
|
||||
if(state.active==='opinion') updateOpinion();
|
||||
if(state.active==='events') updateEvents();
|
||||
if(state.active==='groups') updateGroups();
|
||||
}
|
||||
initTabs(); render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>美国涉华涉台政策权力网络专题平台</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg1:#7a0d18; --bg2:#3d0710; --card:#fffaf7; --card2:#fff4ec; --ink:#241314; --muted:#6f5452;
|
||||
--line:#e8cfc9; --accent:#b21f2d; --accent2:#d88a5b; --deep:#520812; --good:#1f7a5b; --warn:#bd6b00; --danger:#a41422;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin:0; font-family: "Microsoft YaHei", "PingFang SC", system-ui, -apple-system, Segoe UI, sans-serif; color:var(--ink); background: radial-gradient(circle at 20% 0%, #a12b38 0, var(--bg1) 30%, var(--bg2) 100%); }
|
||||
header { padding: 34px 42px 22px; color:#fff; position:relative; overflow:hidden; }
|
||||
header:after { content:""; position:absolute; right:-130px; top:-120px; width:360px; height:360px; border:1px solid rgba(255,255,255,.16); border-radius:50%; }
|
||||
h1 { margin:0; font-size:32px; letter-spacing:.04em; }
|
||||
.subtitle { margin-top:10px; max-width:1120px; opacity:.88; line-height:1.7; font-size:14px; }
|
||||
.topbar { display:flex; gap:12px; margin-top:20px; align-items:center; flex-wrap:wrap; }
|
||||
.search { flex:1; min-width:280px; background:rgba(255,255,255,.14); border:1px solid rgba(255,255,255,.38); color:#fff; border-radius:999px; padding:12px 18px; outline:none; }
|
||||
.search::placeholder { color:rgba(255,255,255,.72); }
|
||||
.btn { border:none; background:#fff; color:var(--deep); border-radius:999px; padding:10px 16px; cursor:pointer; font-weight:700; box-shadow:0 10px 24px rgba(0,0,0,.12); }
|
||||
.container { padding:0 28px 42px; }
|
||||
.shell { background:rgba(255,255,255,.92); border:1px solid rgba(255,255,255,.55); border-radius:28px; min-height:680px; box-shadow:0 28px 70px rgba(0,0,0,.25); overflow:hidden; }
|
||||
.tabs { display:flex; gap:8px; overflow:auto; padding:14px 18px; background:#fff8f4; border-bottom:1px solid var(--line); position:sticky; top:0; z-index:5; }
|
||||
.tab { white-space:nowrap; padding:10px 15px; border:1px solid var(--line); background:white; color:var(--muted); border-radius:999px; cursor:pointer; font-weight:700; }
|
||||
.tab.active { background:var(--accent); color:#fff; border-color:var(--accent); }
|
||||
.panel { display:none; padding:24px; }
|
||||
.panel.active { display:block; }
|
||||
.grid { display:grid; grid-template-columns: repeat(auto-fill, minmax(280px,1fr)); gap:16px; }
|
||||
.card { background:var(--card); border:1px solid var(--line); border-radius:20px; padding:18px; box-shadow:0 10px 20px rgba(80,20,20,.06); cursor:pointer; transition:.18s; }
|
||||
.card:hover { transform:translateY(-2px); box-shadow:0 16px 30px rgba(80,20,20,.12); }
|
||||
.card h3 { margin:0 0 8px; font-size:18px; color:var(--deep); }
|
||||
.meta { color:var(--muted); font-size:13px; line-height:1.6; }
|
||||
.tags { display:flex; flex-wrap:wrap; gap:6px; margin:10px 0; }
|
||||
.tag { border:1px solid #e0b8ad; color:#7a1a24; background:#fff; border-radius:999px; padding:4px 9px; font-size:12px; }
|
||||
.kpis { display:grid; grid-template-columns:repeat(auto-fit, minmax(180px,1fr)); gap:14px; margin-bottom:18px; }
|
||||
.kpi { background:linear-gradient(135deg,#fff,#fff0e7); border:1px solid var(--line); border-radius:18px; padding:18px; }
|
||||
.kpi .num { font-size:32px; font-weight:800; color:var(--accent); }
|
||||
.kpi .label { color:var(--muted); margin-top:4px; }
|
||||
.section-title { display:flex; align-items:center; justify-content:space-between; gap:14px; margin:0 0 14px; }
|
||||
.section-title h2 { margin:0; font-size:22px; color:var(--deep); }
|
||||
.filters { display:flex; gap:8px; flex-wrap:wrap; margin:12px 0 18px; }
|
||||
.filter { padding:8px 12px; border-radius:999px; border:1px solid var(--line); background:#fff; cursor:pointer; color:var(--muted); }
|
||||
.filter.active { background:var(--deep); color:#fff; }
|
||||
.table-wrap { overflow:auto; border:1px solid var(--line); border-radius:18px; background:#fff; }
|
||||
table { border-collapse:collapse; width:100%; min-width:900px; }
|
||||
th,td { padding:12px 13px; border-bottom:1px solid #f1ded9; text-align:left; vertical-align:top; font-size:13px; line-height:1.55; }
|
||||
th { background:#fff0e9; color:#5a1520; position:sticky; top:0; z-index:1; }
|
||||
tr:hover td { background:#fffaf7; }
|
||||
.chain { display:grid; gap:10px; }
|
||||
.step { display:flex; gap:12px; align-items:flex-start; background:#fff; border:1px solid var(--line); border-radius:16px; padding:12px; }
|
||||
.step .dot { width:26px; height:26px; border-radius:50%; background:var(--accent); color:#fff; display:grid; place-items:center; flex:0 0 auto; font-size:12px; font-weight:800; }
|
||||
.risk { display:grid; grid-template-columns:repeat(auto-fit, minmax(230px,1fr)); gap:12px; }
|
||||
.riskbox { border:1px solid var(--line); border-radius:16px; padding:14px; background:#fff; }
|
||||
.riskbox strong { color:var(--deep); }
|
||||
.badge { padding:3px 8px; border-radius:999px; font-size:12px; background:#fff0e9; color:#7a1a24; }
|
||||
.graphbar { display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-bottom:12px; }
|
||||
.graph { background:#fff; border:1px solid var(--line); border-radius:20px; height:660px; overflow:hidden; position:relative; }
|
||||
svg { width:100%; height:100%; }
|
||||
.node-label { font-size:12px; fill:#3d0710; font-weight:700; pointer-events:none; }
|
||||
.edge { stroke:#a4786d; stroke-opacity:.35; }
|
||||
.edge.strong { stroke:#a41422; stroke-opacity:.75; }
|
||||
.node { cursor:pointer; }
|
||||
.legend { display:flex; gap:8px; flex-wrap:wrap; margin-top:10px; color:var(--muted); font-size:13px; }
|
||||
.legend span { background:#fff; border:1px solid var(--line); border-radius:999px; padding:5px 9px; }
|
||||
.modal { position:fixed; inset:0; background:rgba(0,0,0,.44); display:none; align-items:center; justify-content:center; z-index:20; padding:20px; }
|
||||
.modal.show { display:flex; }
|
||||
.modal-card { width:min(860px, 94vw); max-height:86vh; overflow:auto; background:#fff; border-radius:24px; padding:24px; box-shadow:0 30px 100px rgba(0,0,0,.4); }
|
||||
.modal-head { display:flex; justify-content:space-between; gap:14px; align-items:flex-start; border-bottom:1px solid var(--line); padding-bottom:12px; margin-bottom:14px; }
|
||||
.close { border:none; border-radius:50%; width:36px; height:36px; background:#fff0e9; color:var(--deep); cursor:pointer; font-size:20px; }
|
||||
.detail-grid { display:grid; grid-template-columns:180px 1fr; gap:8px 14px; font-size:14px; line-height:1.7; }
|
||||
.detail-grid b { color:#6f242c; }
|
||||
.small { font-size:12px; color:var(--muted); }
|
||||
.source-link { color:var(--accent); text-decoration:none; }
|
||||
.empty { padding:24px; color:var(--muted); text-align:center; }
|
||||
@media (max-width:760px) { header { padding:24px 18px; } .container { padding:0 12px 28px; } .panel { padding:16px; } .detail-grid { grid-template-columns:1fr; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>美国涉华涉台政策权力网络专题平台</h1>
|
||||
<div class="subtitle">基于公开资料与 Skill 框架整理的结构化研究平台:覆盖白宫、行政部门、国会委员会、利益集团、智库媒体、摩擦事件、风险指标与关系图谱。研究边界:公开资料、结构性分析、风险预警;不包含私人信息或定向影响操作。</div>
|
||||
<div class="topbar"><input id="globalSearch" class="search" placeholder="搜索节点、人物、委员会、政策工具、事件、风险指标……"><button class="btn" onclick="downloadJSON()">下载当前 JSON</button><button class="btn" onclick="resetSearch()">重置搜索</button></div>
|
||||
</header>
|
||||
<div class="container">
|
||||
<div class="shell">
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
<section id="overview" class="panel active"></section>
|
||||
<section id="nodes" class="panel"></section>
|
||||
<section id="tools" class="panel"></section>
|
||||
<section id="congress" class="panel"></section>
|
||||
<section id="graph" class="panel"></section>
|
||||
<section id="chains" class="panel"></section>
|
||||
<section id="interest" class="panel"></section>
|
||||
<section id="thinktank" class="panel"></section>
|
||||
<section id="events" class="panel"></section>
|
||||
<section id="risks" class="panel"></section>
|
||||
<section id="sources" class="panel"></section>
|
||||
</div>
|
||||
</div>
|
||||
<div id="modal" class="modal"><div class="modal-card"><div class="modal-head"><div><h2 id="modalTitle" style="margin:0;color:var(--deep)"></h2><div id="modalSub" class="meta"></div></div><button class="close" onclick="closeModal()">×</button></div><div id="modalBody"></div></div></div>
|
||||
<script>
|
||||
const DATA = {"metadata": {"标题": "美国涉华涉台政策权力网络专题数据库", "英文标题": "US-China Policy Power Network Dataset", "版本": "v1.0", "生成日期": "2026-06-25", "时间口径": "截至2026年6月25日的公开资料与本专题已补充数据。", "研究边界": "仅使用公开资料进行结构性政策研究、风险预警和认知防护分析;不包含私人信息、定向影响操作或作战敏感细节。", "证据等级说明": {"A": "官方网页、国会官网、政府文件直接证明", "B": "权威媒体、主流智库、权威数据库支持", "C": "基于公开结构的合理推断,需后续核验"}}, "dashboard": {"栏目": ["总览仪表盘", "白宫与NSC", "行政工具系统", "国会网络", "利益集团", "智库媒体", "摩擦事件", "影响链条", "风险预警", "关系图谱", "来源审查"], "统计": {"节点数量": 79, "边数量": 101, "政策工具数量": 10, "事件数量": 6, "风险指标数量": 8, "影响链条数量": 5}, "五层结构": ["第一层:总统 / 白宫 / NSC", "第二层:行政部门工具系统", "第三层:国会监督与立法系统", "第四层:利益攸关群体", "第五层:舆论与认知场"], "核心判断": "白宫定调,NSC协调,行政部门掌握工具,国会负责立法和施压,利益集团提供资源、数据和游说,智库媒体塑造议题,民意决定政策成本。"}, "nodes": [{"id": "P001", "名称": "Donald J. Trump / 白宫", "英文名称": "Donald J. Trump / The White House", "节点类型": "人物/机构", "所属层级": "第一层:总统 / 白宫 / NSC", "政策领域": ["总体战略", "关税", "台湾", "峰会外交"], "权力来源": "总统正式决策权;行政令、峰会、关税与危机反应定调。", "政策工具": ["行政令", "峰会声明", "关税安排", "军售节奏"], "核心诉求": ["政策交易空间", "国内政治成本控制", "美国优先议程"], "涉华立场": "竞争性、交易型、工具化强。", "涉台立场": "维持美台关系工具性与危机控制并行。", "近期动作": ["白宫发布内阁与政策事实清单。"], "风险信号": ["总统直接点名台湾或关税;中美峰会取消;军售节奏异常。"], "证据等级": "A", "来源": ["S001"]}, {"id": "A001", "名称": "Marco Rubio", "英文名称": "Marco Rubio", "节点类型": "人物", "所属层级": "第二层:行政部门工具系统", "政策领域": ["外交", "台湾", "人权", "盟友协调"], "权力来源": "国务卿,掌握外交声明、国务院政策口径与盟友协调。", "政策工具": ["外交声明", "签证限制", "盟友联合声明", "台湾交往指南"], "核心诉求": ["强化美国外交优势", "价值观议题与安全议题联动"], "涉华立场": "强硬竞争与价值观议题结合。", "涉台立场": "支持台湾国际空间与非官方关系强化。", "近期动作": ["白宫列名其为国务卿。"], "风险信号": ["国务院升级台湾表述;联合盟友点名中国行动。"], "证据等级": "A", "来源": ["S001"]}, {"id": "A002", "名称": "Pete Hegseth", "英文名称": "Pete Hegseth", "节点类型": "人物", "所属层级": "第二层:行政部门工具系统", "政策领域": ["军事安全", "台海", "印太", "军售"], "权力来源": "白宫页面列为Secretary of War;负责军事工具、国防预算与威慑态势。", "政策工具": ["军售", "印太部署", "国防预算", "军事演训"], "核心诉求": ["提升战备", "威慑对手", "强化军工与前沿部署"], "涉华立场": "以军事威慑和战备为主。", "涉台立场": "支持强化台海威慑与区域协同。", "近期动作": ["白宫页面列其为Secretary of War。"], "风险信号": ["印太军力前推;NDAA台湾条款加码;军售加速。"], "证据等级": "A", "来源": ["S001"]}, {"id": "A003", "名称": "Scott Bessent", "英文名称": "Scott Bessent", "节点类型": "人物", "所属层级": "第二层:行政部门工具系统", "政策领域": ["金融", "制裁", "投资审查"], "权力来源": "财政部长,影响OFAC、CFIUS、对外投资限制和金融风险边界。", "政策工具": ["OFAC制裁", "CFIUS", "对外投资安全规则", "金融沟通"], "核心诉求": ["金融稳定", "资本安全", "敏感技术投资边界"], "涉华立场": "通过金融和资本工具塑造竞争边界。", "涉台立场": "可通过制裁或投资限制影响涉台军工与技术网络。", "近期动作": ["白宫列名其为财政部长。"], "风险信号": ["制裁大型机构;CFIUS扩张;对外投资规则加码。"], "证据等级": "A", "来源": ["S001", "S007"]}, {"id": "A004", "名称": "Howard Lutnick", "英文名称": "Howard Lutnick", "节点类型": "人物", "所属层级": "第二层:行政部门工具系统", "政策领域": ["出口管制", "半导体", "产业安全"], "权力来源": "商务部长,影响BIS、实体清单、许可证和产Line truncated
|
||||
const tabs = [
|
||||
["overview","总览仪表盘"],["nodes","权力节点"],["tools","行政工具"],["congress","国会网络"],["graph","关系图谱"],["chains","影响链条"],["interest","利益集团"],["thinktank","智库媒体"],["events","摩擦事件"],["risks","风险预警"],["sources","来源审查"]
|
||||
];
|
||||
let query = "";
|
||||
let graphFilter = "全部";
|
||||
const $ = id => document.getElementById(id);
|
||||
function esc(s) { return String(s ?? '').replace(/[&<>"]/g, m => ({'&':'&','<':'<','>':'>','"':'"'}[m])); }
|
||||
function arr(v) { return Array.isArray(v) ? v : (v ? [v] : []); }
|
||||
function tags(list) { return `<div class="tags">${arr(list).map(x=>`<span class="tag">${esc(x)}</span>`).join('')}</div>`; }
|
||||
function match(obj) { if(!query) return true; return JSON.stringify(obj).toLowerCase().includes(query.toLowerCase()); }
|
||||
function short(text, n=140) { text = String(text||''); return text.length>n ? text.slice(0,n)+'……' : text; }
|
||||
function initTabs() {
|
||||
$('tabs').innerHTML = tabs.map((t,i)=>`<button class="tab ${i==0?'active':''}" onclick="showTab('${t[0]}', this)">${t[1]}</button>`).join('');
|
||||
}
|
||||
function showTab(id, btn) { document.querySelectorAll('.panel').forEach(p=>p.classList.remove('active')); $(id).classList.add('active'); document.querySelectorAll('.tab').forEach(b=>b.classList.remove('active')); btn.classList.add('active'); if(id==='graph') renderGraph(); }
|
||||
function card(obj, title, sub, body, click=true) { return `<div class="card" ${click?`onclick='openDetail(${JSON.stringify(obj).replace(/'/g,"'")})'`:''}><h3>${esc(title)}</h3><div class="meta">${esc(sub||'')}</div>${body||''}</div>`; }
|
||||
function openDetail(obj) {
|
||||
$('modalTitle').textContent = obj.名称 || obj.工具名称 || obj.事件名称 || obj.指标名称 || obj.名称 || obj.edge_id || obj.id || '详情';
|
||||
$('modalSub').textContent = obj.英文名称 || obj.节点类型 || obj.类型 || obj.政策性质 || obj.时间 || '';
|
||||
let rows = Object.entries(obj).filter(([k])=>!['可视化样式'].includes(k)).map(([k,v])=>`<b>${esc(k)}</b><div>${Array.isArray(v)? v.map(esc).join('、') : typeof v === 'object' && v ? `<pre>${esc(JSON.stringify(v,null,2))}</pre>` : esc(v)}</div>`).join('');
|
||||
$('modalBody').innerHTML = `<div class="detail-grid">${rows}</div>`;
|
||||
$('modal').classList.add('show');
|
||||
}
|
||||
function closeModal() { $('modal').classList.remove('show'); }
|
||||
function resetSearch() { query=''; $('globalSearch').value=''; renderAll(); }
|
||||
$('globalSearch').addEventListener('input', e=>{ query=e.target.value.trim(); renderAll(); });
|
||||
function renderOverview() {
|
||||
const s=DATA.dashboard.统计;
|
||||
$('overview').innerHTML = `<div class="section-title"><h2>总览仪表盘</h2><span class="badge">${esc(DATA.metadata.版本)} · ${esc(DATA.metadata.生成日期)}</span></div>
|
||||
<div class="kpis">${Object.entries(s).map(([k,v])=>`<div class="kpi"><div class="num">${v}</div><div class="label">${k}</div></div>`).join('')}</div>
|
||||
<div class="grid">
|
||||
${card(DATA.dashboard, '五层权力结构', DATA.dashboard.核心判断, tags(DATA.dashboard.五层结构), false)}
|
||||
${card(DATA.metadata, '研究边界', DATA.metadata.时间口径, `<p class="meta">${esc(DATA.metadata.研究边界)}</p>`, false)}
|
||||
${card(DATA.metadata.证据等级说明, '证据等级', 'A/B/C 分级用于页面筛选和来源审查', `<div class="detail-grid"><b>A</b><div>${DATA.metadata.证据等级说明.A}</div><b>B</b><div>${DATA.metadata.证据等级说明.B}</div><b>C</b><div>${DATA.metadata.证据等级说明.C}</div></div>`, false)}
|
||||
</div>`;
|
||||
}
|
||||
const layers = ["全部","第一层:总统 / 白宫 / NSC","第二层:行政部门工具系统","第三层:国会监督与立法系统","第四层:利益攸关群体","第五层:舆论与认知场"];
|
||||
let nodeLayer='全部';
|
||||
function renderNodes() {
|
||||
const filtered = DATA.nodes.filter(x=>match(x) && (nodeLayer==='全部'||x.所属层级===nodeLayer));
|
||||
$('nodes').innerHTML = `<div class="section-title"><h2>权力节点库</h2><span class="badge">${filtered.length} / ${DATA.nodes.length}</span></div>
|
||||
<div class="filters">${layers.map(l=>`<button class="filter ${nodeLayer===l?'active':''}" onclick="nodeLayer='${l}';renderNodes()">${l.replace(':',':<br>')}</button>`).join('')}</div>
|
||||
<div class="grid">${filtered.map(x=>card(x,x.名称,x.所属层级,`${tags(x.政策领域)}<p class="meta">${esc(short(x.权力来源 || x.核心诉求?.[0]))}</p>`)).join('') || '<div class="empty">没有匹配结果</div>'}</div>`;
|
||||
}
|
||||
function renderTools() {
|
||||
const rows = DATA.policy_tools.filter(match).map(x=>`<tr onclick='openDetail(${JSON.stringify(x).replace(/'/g,"'")})'><td>${esc(x.工具名称)}</td><td>${esc(x.主责机构)}</td><td>${esc(x.政策性质)}</td><td>${arr(x.政策领域).map(esc).join('、')}</td><td>${esc(x.功能说明)}</td><td>${esc(x.建议字段)}</td></tr>`).join('');
|
||||
$('tools').innerHTML = `<div class="section-title"><h2>行政政策工具系统</h2><span class="badge">${DATA.policy_tools.filter(match).length} 项</span></div><div class="table-wrap"><table><thead><tr><th>工具名称</th><th>主责机构</th><th>政策性质</th><th>政策领域</th><th>功能说明</th><th>建议字段</th></tr></thead><tbody>${rows}</tbody></table></div>`;
|
||||
}
|
||||
function renderCongress() {
|
||||
const congress = DATA.nodes.filter(x=>match(x) && (x.所属层级||'').includes('国会'));
|
||||
const legs = DATA.legislation.filter(match);
|
||||
$('congress').innerHTML = `<div class="section-title"><h2>国会委员会、人物与法案库</h2><span class="badge">${congress.length} 个节点 · ${legs.length} 项法案/议题</span></div>
|
||||
<div class="grid">${congress.map(x=>card(x,x.名称,x.权力来源,tags(x.政策领域))).join('')}</div>
|
||||
<h2 style="margin-top:24px;color:var(--deep)">法案与立法议题</h2><div class="table-wrap"><table><thead><tr><th>名称</th><th>状态</th><th>牵引节点</th><th>意义</th><th>证据</th></tr></thead><tbody>${legs.map(x=>`<tr onclick='openDetail(${JSON.stringify(x).replace(/'/g,"'")})'><td>${esc(x.名称)}</td><td>${esc(x.状态)}</td><td>${arr(x.牵引节点).map(esc).join('、')}</td><td>${esc(x.涉华涉台意义)}</td><td>${esc(x.证据等级)}</td></tr>`).join('')}</tbody></table></div>`;
|
||||
}
|
||||
function renderInterest() {
|
||||
const list = DATA.nodes.filter(x=>match(x) && x.所属层级==='第四层:利益攸关群体');
|
||||
$('interest').innerHTML = `<div class="section-title"><h2>利益集团画像</h2><span class="badge">${list.length} 个节点</span></div><div class="grid">${list.map(x=>card(x,x.名称,x.节点类型,`${tags(x.政策领域)}<p class="meta">${esc(short(x.核心诉求?.[0],180))}</p>`)).join('')}</div>`;
|
||||
}
|
||||
function renderThinktank() {
|
||||
const list = DATA.nodes.filter(x=>match(x) && x.所属层级==='第五层:舆论与认知场');
|
||||
$('thinktank').innerHTML = `<div class="section-title"><h2>智库媒体与叙事生态</h2><span class="badge">${list.length} 个节点</span></div><div class="grid">${list.map(x=>card(x,x.名称,x.英文名称,`${tags(x.政策领域)}<p class="meta">${esc(short(x.核心诉求?.[0],180))}</p>`)).join('')}</div>`;
|
||||
}
|
||||
function renderEvents() {
|
||||
const list=DATA.friction_events.filter(match);
|
||||
$('events').innerHTML=`<div class="section-title"><h2>摩擦事件库</h2><span class="badge">${list.length} 件</span></div><div class="grid">${list.map(x=>card(x,x.事件名称,`${x.时间} · ${x.类型} · 风险:${x.风险等级}`,`${tags(x.涉及主体)}<p class="meta"><b>美国动作:</b>${esc(short(x.美国动作))}</p><p class="meta"><b>中方可能反应:</b>${esc(short(x.中方可能反应))}</p>`)).join('')}</div>`;
|
||||
}
|
||||
function renderRisks() {
|
||||
const list=DATA.risk_indicators.filter(match);
|
||||
$('risks').innerHTML=`<div class="section-title"><h2>风险预警指标体系</h2><span class="badge">${list.length} 个指标</span></div><div class="grid">${list.map(x=>`<div class="card" onclick='openDetail(${JSON.stringify(x).replace(/'/g,"'")})'><h3>${esc(x.指标名称)}</h3>${tags(x.关联领域)}<div class="risk"><div class="riskbox"><strong>低</strong><br>${esc(x.低风险)}</div><div class="riskbox"><strong>中</strong><br>${esc(x.中风险)}</div><div class="riskbox"><strong>高</strong><br>${esc(x.高风险)}</div><div class="riskbox"><strong>极高</strong><br>${esc(x.极高风险)}</div></div></div>`).join('')}</div>`;
|
||||
}
|
||||
function renderChains() {
|
||||
const list=DATA.influence_chains.filter(match);
|
||||
$('chains').innerHTML=`<div class="section-title"><h2>关键影响链条</h2><span class="badge">${list.length} 条</span></div><div class="grid">${list.map(c=>`<div class="card" onclick='openDetail(${JSON.stringify(c).replace(/'/g,"'")})'><h3>${esc(c.名称)}</h3><span class="badge">风险:${esc(c.风险)}</span><div class="chain" style="margin-top:12px">${c.路径.map((s,i)=>`<div class="step"><div class="dot">${i+1}</div><div>${esc(s)}</div></div>`).join('')}</div></div>`).join('')}</div>`;
|
||||
}
|
||||
function renderSources() {
|
||||
const list=DATA.sources.filter(match);
|
||||
$('sources').innerHTML=`<div class="section-title"><h2>来源审查</h2><span class="badge">${list.length} 个来源</span></div><div class="table-wrap"><table><thead><tr><th>ID</th><th>名称</th><th>类型</th><th>等级</th><th>说明</th><th>链接</th></tr></thead><tbody>${list.map(s=>`<tr><td>${s.id}</td><td>${esc(s.名称)}</td><td>${esc(s.类型)}</td><td>${esc(s.证据等级)}</td><td>${esc(s.说明)}</td><td><a class="source-link" href="${esc(s.url)}" target="_blank">打开来源</a></td></tr>`).join('')}</tbody></table></div>`;
|
||||
}
|
||||
function renderGraph() {
|
||||
const fields=["全部",...Array.from(new Set(DATA.edges.flatMap(e=>e.政策领域||[]))).slice(0,18)];
|
||||
const edges=DATA.edges.filter(e=>match(e) && (graphFilter==='全部'||(e.政策领域||[]).includes(graphFilter))).slice(0,120);
|
||||
const ids=new Set(edges.flatMap(e=>[e.source,e.target]));
|
||||
const nodes=DATA.nodes.filter(n=>ids.has(n.id) || ids.has(n.名称)).slice(0,80);
|
||||
const fallbackIds=[...ids].filter(id=>!nodes.some(n=>n.id===id||n.名称===id)).map(id=>({id,名称:id,所属层级:'外部概念',节点类型:'概念',政策领域:[]}));
|
||||
const all=[...nodes,...fallbackIds];
|
||||
const layersOrder=["第一层:总统 / 白宫 / NSC","第二层:行政部门工具系统","第三层:国会监督与立法系统","第四层:利益攸关群体","第五层:舆论与认知场","外部概念"];
|
||||
const width=1200, height=640, margin=70;
|
||||
const pos={};
|
||||
layersOrder.forEach((ly,li)=>{ const group=all.filter(n=>(n.所属层级||'外部概念')===ly); group.forEach((node,i)=>{ pos[node.id]=pos[node.名称]={x: margin + li*(width-2*margin)/(layersOrder.length-1), y: 55 + (i+1)*(height-110)/(group.length+1)}; }); });
|
||||
const color=(ly)=>({"第一层:总统 / 白宫 / NSC":"#a41422","第二层:行政部门工具系统":"#d45a35","第三层:国会监督与立法系统":"#7a1f77","第四层:利益攸关群体":"#276f55","第五层:舆论与认知场":"#2f68a8","外部概念":"#999"}[ly]||'#777');
|
||||
const lineSvg=edges.map(ed=>{ const a=pos[ed.source], b=pos[ed.target]; if(!a||!b) return ''; return `<line class="edge ${ed.强度>=5?'strong':''}" x1="${a.x}" y1="${a.y}" x2="${b.x}" y2="${b.y}" stroke-width="${Math.max(1,ed.强度/1.3)}"><title>${esc(ed.关系类型)}</title></line>`; }).join('');
|
||||
const nodeSvg=all.map(nd=>{ const p=pos[nd.id]||pos[nd.名称]; if(!p) return ''; const r = nd.节点类型==='人物'?12: nd.节点类型==='委员会'?15: 13; return `<g class="node" onclick='openDetail(${JSON.stringify(nd).replace(/'/g,"'")})'><circle cx="${p.x}" cy="${p.y}" r="${r}" fill="${color(nd.所属层级||'外部概念')}" stroke="#fff" stroke-width="2"><title>${esc(nd.名称)}</title></circle><text class="node-label" x="${p.x+16}" y="${p.y+4}">${esc(nd.名称).slice(0,18)}</text></g>`; }).join('');
|
||||
$('graph').innerHTML=`<div class="section-title"><h2>关系图谱</h2><span class="badge">${edges.length} 条边 · ${all.length} 个节点</span></div><div class="graphbar">${fields.map(f=>`<button class="filter ${graphFilter===f?'active':''}" onclick="graphFilter='${f}';renderGraph()">${esc(f)}</button>`).join('')}</div><div class="graph"><svg viewBox="0 0 ${width} ${height}">${lineSvg}${nodeSvg}</svg></div><div class="legend"><span>红:白宫</span><span>橙:行政部门/工具</span><span>紫:国会</span><span>绿:利益集团</span><span>蓝:智库媒体</span><span>线越粗关系越强</span></div>`;
|
||||
}
|
||||
function renderAll() { renderOverview(); renderNodes(); renderTools(); renderCongress(); renderGraph(); renderChains(); renderInterest(); renderThinktank(); renderEvents(); renderRisks(); renderSources(); }
|
||||
function downloadJSON() { const blob=new Blob([JSON.stringify(DATA,null,2)],{type:'application/json'}); const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='us_china_policy_power_network_data.json'; a.click(); URL.revokeObjectURL(a.href); }
|
||||
initTabs(); renderAll();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>美国左翼/进步群体涉华涉台专题研究平台(增强版)</title>
|
||||
<style>
|
||||
:root{
|
||||
--bg:#781d22;--bg2:#4d1014;--card:#fffaf5;--card2:#fff3eb;--soft:#f8e8de;--line:rgba(95,27,31,.22);
|
||||
--text:#261313;--muted:#755e5e;--accent:#b33a3f;--accent2:#8e2f34;--gold:#b98b54;--ok:#236e56;--warn:#a05a16;
|
||||
--shadow:0 18px 55px rgba(45,10,12,.22);--radius:22px;--radius2:14px;
|
||||
}
|
||||
*{box-sizing:border-box} body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",Arial,sans-serif;background:radial-gradient(circle at 20% 0%,#9b3035 0,#781d22 36%,#4d1014 100%);color:var(--text)}
|
||||
a{color:var(--accent2);text-decoration:none} a:hover{text-decoration:underline}.wrap{max-width:1500px;margin:0 auto;padding:28px 22px 48px}.hero{background:linear-gradient(135deg,rgba(255,250,245,.96),rgba(247,232,222,.92));border:1px solid rgba(255,255,255,.52);border-radius:30px;box-shadow:var(--shadow);padding:28px;position:relative;overflow:hidden}.hero:after{content:"";position:absolute;right:-80px;top:-80px;width:300px;height:300px;border-radius:50%;background:rgba(179,58,63,.12)}.eyebrow{font-size:13px;color:var(--accent2);font-weight:800;letter-spacing:.12em;text-transform:uppercase}.hero h1{margin:10px 0 8px;font-size:34px;line-height:1.2;color:#2b1113}.subtitle{color:var(--muted);font-size:16px;max-width:940px;line-height:1.75}.pillbar{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}.pill,.tag{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;border-radius:999px;background:#fff;border:1px solid var(--line);font-size:12px;color:#553333}.pill.strong{background:#792026;color:#fff;border-color:#792026}.toolbar{margin:18px 0;background:rgba(255,250,245,.94);border:1px solid rgba(255,255,255,.45);border-radius:22px;box-shadow:0 10px 32px rgba(39,7,9,.14);padding:14px;display:grid;grid-template-columns:minmax(260px,1.6fr) repeat(4,minmax(130px,.7fr)) auto;gap:10px;align-items:center}.toolbar input,.toolbar select,.toolbar button{height:42px;border-radius:14px;border:1px solid var(--line);background:#fff;color:var(--text);padding:0 12px;font-size:14px}.toolbar button{background:var(--accent);color:#fff;border-color:var(--accent);font-weight:700;cursor:pointer}.tabs{display:flex;gap:8px;overflow-x:auto;padding:4px 0 12px}.tab{border:1px solid rgba(255,255,255,.45);background:rgba(255,250,245,.88);color:#5b2a2d;border-radius:999px;padding:10px 16px;white-space:nowrap;font-weight:800;cursor:pointer}.tab.active{background:#fff;color:#781d22;box-shadow:0 8px 22px rgba(55,8,10,.2)}.panel{background:rgba(255,250,245,.96);border:1px solid rgba(255,255,255,.52);border-radius:28px;box-shadow:var(--shadow);padding:22px;min-height:560px}.panel-head{display:flex;justify-content:space-between;gap:16px;align-items:flex-end;margin-bottom:18px}.panel-title{font-size:25px;font-weight:900;margin:0;color:#2d1214}.panel-desc{color:var(--muted);line-height:1.65;margin:8px 0 0}.count-badge{background:#5a1519;color:#fff;border-radius:999px;padding:7px 12px;font-size:13px;font-weight:800}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}.grid.two{grid-template-columns:repeat(2,minmax(0,1fr))}.card{background:#fff;border:1px solid var(--line);border-radius:20px;padding:16px;box-shadow:0 7px 18px rgba(51,16,15,.07);cursor:pointer;transition:.15s}.card:hover{transform:translateY(-2px);box-shadow:0 14px 32px rgba(51,16,15,.14);border-color:rgba(179,58,63,.45)}.card h3{margin:0 0 8px;font-size:18px;color:#2a1012;line-height:1.35}.card .meta{color:var(--muted);font-size:13px;line-height:1.6;margin-bottom:10px}.summary{font-size:14px;line-height:1.72;color:#3b2222;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}.kv{display:grid;grid-template-columns:150px 1fr;gap:8px;border-top:1px dashed var(--line);padding-top:10px;margin-top:10px;font-size:14px}.kv b{color:#5b2225}.list{display:flex;flex-wrap:wrap;gap:7px;margin-top:8px}.chip{display:inline-flex;padding:5px 9px;border-radius:999px;background:var(--soft);border:1px solid var(--line);font-size:12px;color:#653234}.chip.red{background:#ffe3de;color:#8b2327}.chip.green{background:#e9f5ef;color:#236e56}.chip.gold{background:#fff0d9;color:#8d5816}.stat-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:12px;margin-bottom:18px}.stat{background:#fff;border:1px solid var(--line);border-radius:20px;padding:16px}.stat .num{font-size:28px;font-weight:950;color:#8c2429}.stat .lab{color:var(--muted);font-size:13px;margin-top:4px}.section-grid{display:grid;grid-template-columns:1.2fr .8fr;gap:16px}.info-box{background:#fff;border:1px solid var(--line);border-radius:20px;padding:18px;margin-bottom:14px}.info-box h3{margin:0 0 12px;color:#3a1517}.info-box p,.info-box li{line-height:1.75;color:#442626}.timeline{position:relative;padding-left:22px}.timeline:before{content:"";position:absolute;left:8px;top:4px;bottom:4px;width:2px;background:#e2c6bd}.titem{position:relative;background:#fff;border:1px solid var(--line);border-radius:18px;padding:14px 16px;margin-bottom:12px;cursor:pointer}.titem:before{content:"";position:absolute;left:-20px;top:20px;width:12px;height:12px;border-radius:50%;background:var(--accent);border:3px solid #fff;box-shadow:0 0 0 1px var(--accent)}.tdate{font-weight:900;color:#8c2429;font-size:13px}.matrix{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.matrix-card{background:#fff;border:1px solid var(--line);border-radius:20px;padding:16px;cursor:pointer}.split{display:grid;grid-template-columns:1fr 1fr;gap:16px}.table-wrap{overflow:auto;background:#fff;border:1px solid var(Line truncated
|
||||
@media(max-width:1100px){.toolbar{grid-template-columns:1fr 1fr}.grid,.grid.two,.matrix,.split,.section-grid,.stat-grid{grid-template-columns:1fr 1fr}.doc-layout{grid-template-columns:1fr}.doc-nav{position:relative;max-height:none}.field{grid-template-columns:1fr}.subcards{grid-template-columns:1fr}}
|
||||
@media(max-width:720px){.wrap{padding:14px 10px}.hero h1{font-size:25px}.toolbar,.grid,.grid.two,.matrix,.split,.section-grid,.stat-grid{grid-template-columns:1fr}.modal{padding:8px}.modal-head{padding:16px}.modal-body{padding:16px}.panel{padding:14px}.tabs{gap:6px}.tab{padding:9px 12px;font-size:13px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header class="hero">
|
||||
<div class="eyebrow">Research Dashboard · Enhanced Display</div>
|
||||
<h1 id="pageTitle">美国左翼/进步群体涉华涉台专题研究平台(增强版)</h1>
|
||||
<div class="subtitle" id="pageSubtitle"></div>
|
||||
<div class="pillbar" id="boundaryPills"></div>
|
||||
</header>
|
||||
<section class="toolbar">
|
||||
<input id="q" placeholder="搜索组织、事件、叙事、关系、来源……" />
|
||||
<select id="factionFilter"><option value="">全部阵营</option></select>
|
||||
<select id="relevanceFilter"><option value="">全部相关度</option></select>
|
||||
<select id="confidenceFilter"><option value="">全部可信度</option></select>
|
||||
<select id="yearFilter"><option value="">全部年份</option></select>
|
||||
<button id="resetBtn">重置</button>
|
||||
</section>
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
<main class="panel" id="panel"></main>
|
||||
<div class="footer-note">本页面仅用于公开资料研究与来源核验,不包含普通成员隐私、个人弱点、线下行动操作指南或定向操纵建议。</div>
|
||||
</div>
|
||||
<div class="modal" id="modal" onclick="if(event.target.id==='modal') closeModal()">
|
||||
<div class="modal-card">
|
||||
<div class="modal-head">
|
||||
<div><div class="modal-title" id="modalTitle"></div><div class="modal-sub" id="modalSub"></div></div>
|
||||
<button class="close" onclick="closeModal()">×</button>
|
||||
</div>
|
||||
<div class="modal-body" id="modalBody"></div>
|
||||
</div>
|
||||
</div>
|
||||
<script id="data-json" type="application/json">{"meta": {"title": "美国左翼/进步群体涉华涉台专题研究平台(增强版)", "subtitle": "公开资料研究 · 组织深描 · 事件时间线 · 叙事语料 · 关系图谱 · 争议与来源", "version": "v2-enhanced-display", "updated_at": "2026-06-25T18:20:00+09:00", "language": "zh-CN", "scope_note": "本数据包基于公开网页、组织自述、媒体报道和政策/倡议文本,服务学术研究和公开资料分析。组织立场不等于普通成员个人立场;间接相关组织不得被强行解释为涉台组织。", "safety_boundary": {"allowed_scope": ["公开资料研究", "组织层级生态分析", "非定向叙事风险评估", "来源可信度审查", "公共沟通误读预警"], "excluded": ["个人脆弱点", "住址/行程/家庭/普通成员账号", "线下行动操作指南", "规避执法或平台审核", "欺骗性影响行动", "冒充身份或假草根动员"], "terminology_rule": "将“脆弱点”统一改写为“内部矛盾、传播风险、误读点、韧性需求”。"}, "data_note": "展示层 JSON 由 v2 原始数据转换而成,供单文件 HTML 离线检索、筛选、弹框展示使用。", "enhancement_note": "增强版将弹框从原始 JSON 改为分区式详情页,并增加 Markdown 原始研究摘编、组织深描、事件研究价值、争议处理和来源可信度说明。"}, "tabs": [{"id": "overview", "label": "专题总览", "dataset": "dashboard", "layout": "dashboard"}, {"id": "factions", "label": "阵营分类", "dataset": "factions", "layout": "cards", "modal": "factions"}, {"id": "organizations", "label": "组织画像", "dataset": "organizations", "layout": "cards", "modal": "organizations"}, {"id": "events", "label": "事件时间线", "dataset": "events", "layout": "timeline", "modal": "events"}, {"id": "narratives", "label": "叙事矩阵", "dataset": "narratives", "layout": "matrix", "modal": "narratives"}, {"id": "corpus", "label": "叙事语料", "dataset": "corpus", "layout": "cards", "modal": "corpus"}, {"id": "relationships", "label": "关系图谱", "dataset": "relationships", "layout": "network", "modal": "relationships"}, {"id": "platforms", "label": "平台传播", "dataset": "platforms", "layout": "cards", "modal": "platforms"}, {"id": "public_opinion", "label": "民意基础", "dataset": "public_opinion", "layout": "evidence", "modal": "public_opinion"}, {"id": "finance_resources", "label": "资源能力", "dataset": "finance_resources", "layout": "cards", "modal": "finance_resources"}, {"id": "disputes_sources", "label": "争议与来源", "dataset": "disputes", "layout": "split", "modal": "disputes"}, {"id": "research_doc", "label": "研究文档摘编", "dataset": "research_sections", "layout": "document", "modal": null}], "global_filters": [{"id": "faction", "label": "阵营", "type": "multi_select", "options": ["亚裔/华裔反新冷战派", "人权与台湾主体性左翼/反威权左翼", "制度内民主社会主义派", "反战反帝国主义派", "无政府主义、Antifa与黑块式网络", "校园亲巴勒斯坦与反殖民左翼", "气候正义与环境直接行动派", "种族正义与废除主义派", "选举进步派与民主党左翼外围", "革命社会主义/共产主义组织派"]}, {"id": "organization_type", "label": "组织类型", "type": "select", "options": ["abolitionist organization", "anti-Zionist Jewish advocacy organization", "anti-new-cold-war advocacy network", "antiwar NGO / global peace network", "antiwar coalition", "antiwar feminist grassroots organization", "candidate recruitment / progressive PAC-style organization", "communist party", "diasporic Chinese left media/education collective", "global climate movement organization", "left movement space / education venue", "membership organization / democratic socialist", "nonviolent direct action climate movement", "online racial justice advocacy organization", "peace organization / veterans network", "progressive advocacy / petition platform", "progressive electoral party / ballot line organization", "racial justice coalition", "revolutionary socialist party / party media network", "student Palestine solidarity network", "student/youth network", "youth climate movement"]}, {"id": "relevance", "label": "涉华涉台相关度", "type": "select", "options": ["中等:通过反新冷战、反军工、台湾主体性内部讨论进入", "中高:反战动员中出现No war with China和亚太基地议题", "中高:有台湾与南海军事对抗、冲绳基地等文章", "中高:设有China Working Group并提到佩洛西访台抗议", "中:不一定频繁涉台,但在中国/关税/新冷战议题上有公开文章", "中:曾有请愿要求佩洛西重新考虑访台风险", "中:通过中国社会主义、反帝论坛和左翼教育议题关联", "低到中:以校园政治为通道,涉台多为间接", "低到中:通过国会进步派候选人和外交预Line truncated
|
||||
<script>
|
||||
const DATA = JSON.parse(document.getElementById('data-json').textContent);
|
||||
const D = DATA.datasets;
|
||||
const sourceIndex = Object.fromEntries((D.sources||[]).map(s=>[s.id,s]));
|
||||
const orgIndex = Object.fromEntries((D.organizations||[]).map(o=>[o.id,o]));
|
||||
const state = {tab:'overview', q:'', faction:'', relevance:'', confidence:'', year:''};
|
||||
const tabDesc = {
|
||||
overview:'总览数据规模、核心发现、研究边界、补充摘要和仍需补充的数据缺口。',
|
||||
factions:'展示美国左翼/进步派生态的阵营分类、社会基础、组织能力和涉华涉台立场。',
|
||||
organizations:'展示组织画像、公开结构、涉华涉台活动、组织深描、争议入口和资料来源。',
|
||||
events:'按时间线展示涉华涉台及关联事件,突出触发因素、组织反应、研究价值和争议。',
|
||||
narratives:'展示叙事框架、道德入口、接受与反弹结构、证据要求和安全边界。',
|
||||
corpus:'展示公开声明、文章、活动页和短摘录语料,用于支撑叙事分析。',
|
||||
relationships:'展示组织—组织、组织—议题之间的关系边、证据基础和简易网络图。',
|
||||
platforms:'展示社交平台、组织官网和独立媒体的传播适配、内容形式和研究指标。',
|
||||
public_opinion:'展示民意、社会基础和受众背景,用来解释叙事为什么有进入空间或反弹风险。',
|
||||
finance_resources:'展示公开财务与资源能力信息,同时明确禁止用途。',
|
||||
disputes_sources:'展示争议、反驳、研究处理方式和来源可信度注册表。',
|
||||
research_doc:'尽量保留 v2 Markdown 的原始研究知识,以文档摘编形式完整展示。'
|
||||
};
|
||||
const titleFields = {
|
||||
factions:'阵营名称', organizations:'显示标题', events:'事件标题', narratives:'叙事名称', corpus:'中文摘要', relationships:'关系类型', platforms:'平台名称', public_opinion:'主题', finance_resources:'组织名称', disputes:'争议标题', sources:'标题'
|
||||
};
|
||||
function esc(x){return String(x??'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}
|
||||
function arr(v){ if(!v) return []; if(Array.isArray(v)) return v.filter(x=>x!==''&&x!=null); return [v]; }
|
||||
function isEmpty(v){return v==null || v==='' || (Array.isArray(v)&&v.length===0);}
|
||||
function textOf(v){ if(Array.isArray(v)) return v.map(textOf).join(' '); if(v&&typeof v==='object') return Object.values(v).map(textOf).join(' '); return String(v??''); }
|
||||
function orgName(id){ return orgIndex[id]?.['组织名称'] || orgIndex[id]?.['显示标题'] || id; }
|
||||
function tagList(items, cls=''){ const a=arr(items); if(!a.length) return ''; return `<div class="list">${a.map(x=>`<span class="chip ${cls}">${esc(formatToken(x))}</span>`).join('')}</div>`; }
|
||||
function formatToken(x){ if(orgIndex[x]) return orgName(x); return String(x??''); }
|
||||
function fieldValue(v, key=''){
|
||||
if(isEmpty(v)) return '<span style="color:#967979">暂无记录</span>';
|
||||
if(Array.isArray(v)){
|
||||
if(key.includes('来源')) return v.map(sourceCard).join('') || '<span style="color:#967979">暂无来源</span>';
|
||||
return '<ul>'+v.map(x=>`<li>${esc(formatToken(x))}</li>`).join('')+'</ul>';
|
||||
}
|
||||
const s=String(v);
|
||||
if(/^https?:\/\//.test(s)) return `<a href="${esc(s)}" target="_blank" rel="noopener">${esc(s)}</a>`;
|
||||
return `<p>${esc(s).replace(/\n/g,'<br>')}</p>`;
|
||||
}
|
||||
function sourceCard(idOrObj){
|
||||
const sid = typeof idOrObj==='string'?idOrObj:(idOrObj?.id||idOrObj?.source_id||'');
|
||||
const s = sourceIndex[sid];
|
||||
if(!s) return `<div class="source-card"><div class="source-title">${esc(sid || textOf(idOrObj))}</div><div class="source-meta">未在来源表中展开,建议后续补齐。</div></div>`;
|
||||
const link = s['链接'] ? `<a href="${esc(s['链接'])}" target="_blank" rel="noopener">打开来源</a>` : '无链接';
|
||||
return `<div class="source-card"><div class="source-title">${esc(s['标题']||s.id)}</div><div class="source-meta">${esc(s['来源类型']||'')} · 可信度:${esc(s['可信度']||'')} · ${link}</div>${s['说明']?`<div class="source-meta">${esc(s['说明'])}</div>`:''}</div>`;
|
||||
}
|
||||
function init(){
|
||||
document.getElementById('pageTitle').textContent = DATA.meta.title;
|
||||
document.getElementById('pageSubtitle').textContent = DATA.meta.subtitle + '。' + (DATA.meta.enhancement_note||'');
|
||||
const b = D.safety_boundary || {};
|
||||
document.getElementById('boundaryPills').innerHTML = ['公开资料研究','分区式详情页','完整文档摘编','可检索数据'].map((x,i)=>`<span class="pill ${i===0?'strong':''}">${x}</span>`).join('') + (b.allowed_scope? b.allowed_scope.slice(0,4).map(x=>`<span class="pill">${esc(x)}</span>`).join(''):'');
|
||||
document.getElementById('tabs').innerHTML = DATA.tabs.map(t=>`<button class="tab ${t.id===state.tab?'active':''}" onclick="switchTab('${t.id}')">${esc(t.label)}</button>`).join('');
|
||||
populateFilters(); bind(); render();
|
||||
}
|
||||
function bind(){
|
||||
document.getElementById('q').addEventListener('input',e=>{state.q=e.target.value.trim(); render();});
|
||||
['factionFilter','relevanceFilter','confidenceFilter','yearFilter'].forEach(id=>document.getElementById(id).addEventListener('change',e=>{state[id.replace('Filter','')]=e.target.value; render();}));
|
||||
document.getElementById('resetBtn').onclick=()=>{state.q='';state.faction='';state.relevance='';state.confidence='';state.year='';document.querySelectorAll('.toolbar input,.toolbar select').forEach(el=>el.value='');render();};
|
||||
}
|
||||
function populateFilters(){
|
||||
const factions=[...new Set((D.organizations||[]).flatMap(o=>arr(o['所属阵营'])).filter(Boolean))].sort();
|
||||
const relevance=[...new Set((D.organizations||[]).map(o=>o['涉华涉台相关度']).filter(Boolean))].sort();
|
||||
const conf=[...new Set(Object.values(D).flatMap(ds=>Array.isArray(ds)?ds.map(x=>x['来源可信度']||x['可信度']||x['补充来源可信度']).filter(Boolean):[]))].sort();
|
||||
const years=[...new Set((D.events||[]).concat(D.corpus||[]).map(x=>x['年份']).filter(Boolean))].sort().reverse();
|
||||
fillSelect('factionFilter',factions); fillSelect('relevanceFilter',relevance); fillSelect('confidenceFilter',conf); fillSelect('yearFilter',years);
|
||||
}
|
||||
function fillSelect(id, vals){ const el=document.getElementById(id); const first=el.options[0].outerHTML; el.innerHTML=first+vals.map(v=>`<option value="${esc(v)}">${esc(v)}</option>`).join('');}
|
||||
function switchTab(id){state.tab=id;document.querySelectorAll('.tab').forEach(b=>b.classList.toggle('active',b.textContent===DATA.tabs.find(t=>t.id===id).label));render();}
|
||||
function datasetForTab(){ const t=DATA.tabs.find(x=>x.id===state.tab); return t?.dataset; }
|
||||
function filtered(items){
|
||||
return items.filter(item=>{
|
||||
const txt=textOf(item).toLowerCase();
|
||||
if(state.q && !txt.includes(state.q.toLowerCase())) return false;
|
||||
if(state.faction && !arr(item['所属阵营']).includes(state.faction) && !arr(item['易接受阵营']).includes(state.faction) && !arr(item['易反弹阵营']).includes(state.faction)) return false;
|
||||
if(state.relevance && item['涉华涉台相关度']!==state.relevance) return false;
|
||||
if(state.confidence && ![item['来源可信度'],item['可信度'],item['补充来源可信度']].includes(state.confidence)) return false;
|
||||
if(state.year && item['年份']!==state.year) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
function panelHead(label, desc, count){return `<div class="panel-head"><div><h2 class="panel-title">${esc(label)}</h2><p class="panel-desc">${esc(desc||'')}</p></div>${count!=null?`<div class="count-badge">${count} 条</div>`:''}</div>`;}
|
||||
function render(){
|
||||
document.getElementById('tabs').innerHTML = DATA.tabs.map(t=>`<button class="tab ${t.id===state.tab?'active':''}" onclick="switchTab('${t.id}')">${esc(t.label)}</button>`).join('');
|
||||
const t=DATA.tabs.find(x=>x.id===state.tab); const panel=document.getElementById('panel');
|
||||
if(state.tab==='overview'){ panel.innerHTML=renderOverview(); return; }
|
||||
if(state.tab==='research_doc'){ panel.innerHTML=renderDocument(); return; }
|
||||
if(state.tab==='disputes_sources'){ panel.innerHTML=renderSplit(t); return; }
|
||||
const data=filtered(D[t.dataset]||[]);
|
||||
let body='';
|
||||
if(t.layout==='timeline') body=renderTimeline(data,t.modal);
|
||||
else if(t.layout==='matrix') body=renderMatrix(data,t.modal);
|
||||
else if(t.layout==='network') body=renderNetwork(data,t.modal);
|
||||
else body=renderCards(data,t.dataset,t.modal);
|
||||
panel.innerHTML=panelHead(t.label,tabDesc[t.id],data.length)+body;
|
||||
}
|
||||
function renderOverview(){
|
||||
const counts=DATA.dashboard.counts||{}; const summary=DATA.dashboard.completion_summary||{}; const safety=DATA.dashboard.safety_boundary||{};
|
||||
const stats=[['阵营',counts.factions],['组织',counts.organizations],['事件',counts.events],['叙事框架',counts.narratives],['语料',counts.corpus],['关系边',counts.relationships],['来源',counts.sources],['研究文档节',counts.research_sections]];
|
||||
return panelHead('专题总览',tabDesc.overview,null)+`
|
||||
<div class="stat-grid">${stats.map(([k,v])=>`<div class="stat"><div class="num">${esc(v??0)}</div><div class="lab">${esc(k)}</div></div>`).join('')}</div>
|
||||
<div class="section-grid">
|
||||
<div>
|
||||
<div class="info-box"><h3>核心发现</h3><ul>${(DATA.dashboard.core_findings||[]).map(x=>`<li>${esc(x)}</li>`).join('')}</ul></div>
|
||||
<div class="info-box"><h3>v2 补充摘要</h3><div class="grid two">${Object.entries(summary).map(([k,v])=>`<div class="card" style="cursor:default"><h3>${esc(k)}</h3><div class="summary">新增/补充 ${esc(v)} 条</div></div>`).join('')}</div></div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="info-box"><h3>研究边界</h3><p><b>允许范围:</b></p>${tagList(safety.allowed_scope,'green')}<p><b>排除内容:</b></p>${tagList(safety.excluded,'red')}<p>${esc(safety.terminology_rule||'')}</p></div>
|
||||
<div class="info-box"><h3>后续数据缺口</h3><ul>${(DATA.dashboard.remaining_gaps_v2||[]).map(x=>`<li>${esc(x)}</li>`).join('')}</ul></div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
function cardTitle(item, ds){return item[titleFields[ds]] || item['标题'] || item['id'];}
|
||||
function cardSummary(item, ds){
|
||||
const keys={factions:['涉华涉台立场','组织能力'], organizations:['公开自我描述','涉华涉台活动','组织能力判断'], events:['触发因素','组织反应','研究价值','结果'], narratives:['核心主张','风险说明'], corpus:['中文摘要','原文短摘'], platforms:['适配场景','涉华涉台用途'], public_opinion:['最新观察','研究相关性'], finance_resources:['已知公开信息','研究用途'], disputes:['研究处理方式','主张A','主张B'], sources:['说明']};
|
||||
return (keys[ds]||[]).map(k=>item[k]).filter(Boolean).join(' ');
|
||||
}
|
||||
function renderCards(items, ds, modal){
|
||||
if(!items.length) return '<div class="empty">没有匹配结果</div>';
|
||||
return `<div class="grid">${items.map(item=>`<article class="card" onclick='openModal("${modal||ds}",${JSON.stringify(item.id)})'><h3>${esc(cardTitle(item,ds))}</h3><div class="meta">${esc(item['组织类型']||item['阵营类型']||item['事件类型']||item['平台名称']||item['来源类型']||'')}</div><div class="summary">${esc(cardSummary(item,ds))}</div>${renderCardChips(item)}</article>`).join('')}</div>`;
|
||||
}
|
||||
function renderCardChips(item){
|
||||
const chips=[]; ['所属阵营','涉华涉台相关度','来源可信度','可信度','争议等级','年份'].forEach(k=>{if(item[k]) chips.push(...arr(item[k]).slice(0,3));});
|
||||
if(item['议题焦点']) chips.push(...arr(item['议题焦点']).slice(0,3));
|
||||
if(item['叙事标签']) chips.push(...arr(item['叙事标签']).slice(0,3));
|
||||
return tagList(chips.slice(0,8));
|
||||
}
|
||||
function renderTimeline(items, modal){
|
||||
if(!items.length) return '<div class="empty">没有匹配事件</div>';
|
||||
return `<div class="timeline">${items.map(item=>`<div class="titem" onclick='openModal("${modal}",${JSON.stringify(item.id)})'><div class="tdate">${esc(item['日期']||'未注明日期')}</div><h3>${esc(item['事件标题'])}</h3><div class="summary">${esc(cardSummary(item,'events'))}</div>${tagList([item['事件类型'],...(arr(item['叙事标签']).slice(0,4)), item['来源可信度']].filter(Boolean))}</div>`).join('')}</div>`;
|
||||
}
|
||||
function renderMatrix(items, modal){
|
||||
if(!items.length) return '<div class="empty">没有匹配叙事</div>';
|
||||
return `<div class="matrix">${items.map(item=>`<div class="matrix-card" onclick='openModal("${modal}",${JSON.stringify(item.id)})'><h3>${esc(item['叙事名称'])}</h3><div class="summary">${esc(item['核心主张'])}</div><div class="kv"><b>道德入口</b><div>${tagList(item['道德入口'])}</div><b>争议等级</b><div>${esc(item['争议等级']||'')}</div></div></div>`).join('')}</div>`;
|
||||
}
|
||||
function renderNetwork(items, modal){
|
||||
const top=items.slice(0,50); const nodes=[]; const seen=new Set(); top.forEach(e=>{[e['源节点'],e['目标节点']].forEach(n=>{if(n&&!seen.has(n)){seen.add(n);nodes.push(n)}})});
|
||||
const N=Math.min(nodes.length,24); const cx=520,cy=160,R=125; const pos={}; nodes.slice(0,N).forEach((n,i)=>{pos[n]=[cx+R*Math.cos(2*Math.PI*i/N),cy+R*Math.sin(2*Math.PI*i/N)]});
|
||||
const svg=`<div class="network"><svg viewBox="0 0 1040 320">${top.map(e=>pos[e['源节点']]&&pos[e['目标节点']]?`<line class="edge" x1="${pos[e['源节点']][0]}" y1="${pos[e['源节点']][1]}" x2="${pos[e['目标节点']][0]}" y2="${pos[e['目标节点']][1]}"/>`:'' ).join('')}${nodes.slice(0,N).map(n=>`<g><circle class="node" cx="${pos[n][0]}" cy="${pos[n][1]}" r="24"/><text class="nodeText" text-anchor="middle" x="${pos[n][0]}" y="${pos[n][1]+4}">${esc(orgName(n)).slice(0,14)}</text></g>`).join('')}</svg></div>`;
|
||||
const table=`<div class="table-wrap"><table><thead><tr><th>源节点</th><th>目标节点</th><th>关系类型</th><th>议题语境</th><th>强度</th><th>可信度</th></tr></thead><tbody>${items.map(item=>`<tr onclick='openModal("${modal}",${JSON.stringify(item.id)})'><td>${esc(item['源节点名称'])}</td><td>${esc(item['目标节点名称'])}</td><td>${esc(item['关系类型'])}</td><td>${esc(item['议题语境'])}</td><td>${esc(item['强度']||'')}</td><td>${esc(item['来源可信度']||'')}</td></tr>`).join('')}</tbody></table></div>`;
|
||||
return svg+table;
|
||||
}
|
||||
function renderSplit(t){
|
||||
const disputes=filtered(D.disputes||[]); const sources=filtered(D.sources||[]);
|
||||
return panelHead('争议与来源',tabDesc.disputes_sources,disputes.length+sources.length)+`<div class="split"><div><h3>争议与反驳记录</h3>${renderCards(disputes,'disputes','disputes')}</div><div><h3>来源注册表</h3><div class="table-wrap"><table><thead><tr><th>标题</th><th>类型</th><th>可信度</th><th>说明</th></tr></thead><tbody>${sources.map(s=>`<tr onclick='openModal("sources",${JSON.stringify(s.id)})'><td>${esc(s['标题'])}</td><td>${esc(s['来源类型'])}</td><td>${esc(s['可信度'])}</td><td>${esc(s['说明']||'')}</td></tr>`).join('')}</tbody></table></div></div></div>`;
|
||||
}
|
||||
function renderDocument(){
|
||||
const sections=D.research_sections||[];
|
||||
return panelHead('研究文档摘编',tabDesc.research_doc,sections.length)+`<div class="doc-layout"><div class="doc-nav">${sections.map(s=>`<button onclick="document.getElementById('${s.id}').scrollIntoView({behavior:'smooth',block:'start'})">${esc(s.title)}</button>`).join('')}</div><div class="doc-body">${sections.map(s=>`<section class="md-section" id="${s.id}"><h2>${esc(s.title)}</h2>${mdToHtml(s.markdown)}</section>`).join('')}</div></div>`;
|
||||
}
|
||||
function mdToHtml(md){
|
||||
const lines=(md||'').split(/\n/); let out='', i=0;
|
||||
while(i<lines.length){
|
||||
const line=lines[i];
|
||||
if(!line.trim()){i++; continue;}
|
||||
if(line.startsWith('|')){
|
||||
let rows=[]; while(i<lines.length && lines[i].startsWith('|')){rows.push(lines[i]); i++;}
|
||||
const clean=rows.filter(r=>!/^[|\s:\-]+$/.test(r));
|
||||
if(clean.length){ out+='<div class="md-table"><table>'+clean.map((r,idx)=>'<tr>'+r.split('|').slice(1,-1).map(c=>idx===0?`<th>${esc(c.trim())}</th>`:`<td>${esc(c.trim())}</td>`).join('')+'</tr>').join('')+'</table></div>'; }
|
||||
continue;
|
||||
}
|
||||
if(/^###\s+/.test(line)){out+=`<h3>${esc(line.replace(/^###\s+/,''))}</h3>`;i++;continue;}
|
||||
if(/^[-*]\s+/.test(line)){let items=[]; while(i<lines.length && /^[-*]\s+/.test(lines[i])){items.push(lines[i].replace(/^[-*]\s+/,''));i++;} out+='<ul>'+items.map(x=>`<li>${esc(x)}</li>`).join('')+'</ul>'; continue;}
|
||||
out+=`<p>${esc(line)}</p>`; i++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function openModal(ds, id){
|
||||
let item=(D[ds]||[]).find(x=>x.id===id);
|
||||
if(!item && ds==='sources') item=(D.sources||[]).find(x=>x.id===id);
|
||||
if(!item) return;
|
||||
const title=cardTitle(item,ds)||id; document.getElementById('modalTitle').textContent=title;
|
||||
document.getElementById('modalSub').innerHTML=modalSubtitle(item,ds);
|
||||
document.getElementById('modalBody').innerHTML=renderDetail(item,ds)+renderRelated(item,ds);
|
||||
document.getElementById('modal').classList.add('show');
|
||||
}
|
||||
function modalSubtitle(item,ds){
|
||||
const vals=[item['组织类型'],item['阵营类型'],item['事件类型'],item['平台名称'],item['来源类型'],item['日期'],item['来源可信度']||item['可信度']].filter(Boolean);
|
||||
return vals.map(esc).join(' · ');
|
||||
}
|
||||
function renderDetail(item,ds){
|
||||
const schema=DATA.rich_modal_schemas[ds]||[{title:'详情字段',fields:Object.keys(item).filter(k=>k!=='搜索文本')}];
|
||||
let used=new Set();
|
||||
let html=schema.map(sec=>{
|
||||
const fields=sec.fields.filter(k=>!isEmpty(item[k])); fields.forEach(k=>used.add(k));
|
||||
if(!fields.length) return '';
|
||||
return `<section class="detail-section"><h3>${esc(sec.title)}</h3>${fields.map(k=>`<div class="field"><div class="field-label">${esc(k)}</div><div class="field-value">${fieldValue(item[k],k)}</div></div>`).join('')}</section>`;
|
||||
}).join('');
|
||||
const rest=Object.keys(item).filter(k=>!used.has(k)&&!['id','搜索文本','显示标题'].includes(k)&&!isEmpty(item[k]));
|
||||
if(rest.length){ html+=`<section class="detail-section"><h3>其他补充字段</h3>${rest.map(k=>`<div class="field"><div class="field-label">${esc(k)}</div><div class="field-value">${fieldValue(item[k],k)}</div></div>`).join('')}</section>`; }
|
||||
return html;
|
||||
}
|
||||
function renderRelated(item,ds){
|
||||
let blocks=[];
|
||||
if(ds==='organizations'){
|
||||
const oid=item.id;
|
||||
const ev=(D.events||[]).filter(e=>arr(e['涉及组织']).includes(oid)).slice(0,6);
|
||||
const rel=(D.relationships||[]).filter(r=>r['源节点']===oid||r['目标节点']===oid).slice(0,8);
|
||||
const corp=(D.corpus||[]).filter(c=>c['来源组织']===oid).slice(0,6);
|
||||
blocks.push(relatedCards('关联事件',ev,'events','事件标题',['日期','研究价值','触发因素']));
|
||||
blocks.push(relatedCards('关系边',rel,'relationships','关系类型',['源节点名称','目标节点名称','议题语境']));
|
||||
blocks.push(relatedCards('相关语料',corp,'corpus','中文摘要',['日期','平台','反弹风险']));
|
||||
}
|
||||
if(ds==='events'){
|
||||
const tags=arr(item['叙事标签']).concat(arr(item['议题框架']));
|
||||
const ns=(D.narratives||[]).filter(n=>tags.some(t=>textOf(n).includes(t))).slice(0,6);
|
||||
blocks.push(relatedCards('相关叙事框架',ns,'narratives','叙事名称',['核心主张','风险说明']));
|
||||
}
|
||||
if(ds==='narratives'){
|
||||
const name=item['叙事名称'];
|
||||
const corp=(D.corpus||[]).filter(c=>arr(c['叙事标签']).some(t=>name.includes(t)||t.includes(name)||item['核心主张']?.includes(t))).slice(0,8);
|
||||
blocks.push(relatedCards('支撑语料样本',corp,'corpus','中文摘要',['来源组织名称','日期','反弹风险']));
|
||||
}
|
||||
return blocks.filter(Boolean).join('');
|
||||
}
|
||||
function relatedCards(title,items,ds,titleKey,fields){
|
||||
if(!items.length) return '';
|
||||
return `<section class="detail-section related-block"><h3>${esc(title)}</h3><div class="subcards">${items.map(it=>`<div class="subcard" onclick='openModal("${ds}",${JSON.stringify(it.id)})'><h4>${esc(it[titleKey]||it.id)}</h4><p>${esc(fields.map(f=>it[f]).filter(Boolean).join(' · ')).slice(0,220)}</p></div>`).join('')}</div></section>`;
|
||||
}
|
||||
function closeModal(){document.getElementById('modal').classList.remove('show');}
|
||||
document.addEventListener('keydown',e=>{if(e.key==='Escape')closeModal()});
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>美方新右翼与极右翼群体研究专题库 v3</title>
|
||||
<style>
|
||||
:root{
|
||||
--bg:#f4f5f7; --card:#fff; --ink:#1f2933; --muted:#657282; --line:#e1e4e8;
|
||||
--red:#7a1f1f; --red2:#9f2b2b; --softred:#fff4f4; --accent:#b84632;
|
||||
--green:#2e7d32; --yellow:#b7791f; --orange:#c05621; --high:#c62828; --severe:#5f0f0f;
|
||||
--shadow:0 14px 36px rgba(31,41,51,.12);
|
||||
}
|
||||
*{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--ink);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",Arial,sans-serif;line-height:1.6}
|
||||
.header{background:linear-gradient(135deg,#6b1717,#9c2f2f 64%,#c25a42);color:#fff;padding:32px 28px 26px;border-bottom:6px solid rgba(255,255,255,.18)}
|
||||
.header-inner{max-width:1440px;margin:auto}.header h1{margin:0 0 8px;font-size:30px;letter-spacing:.5px}.header p{margin:0;color:rgba(255,255,255,.88);font-size:15px;max-width:1100px}.top-pills{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}
|
||||
.app{max-width:1440px;margin:0 auto;padding:20px 24px 38px}.toolbar{background:#fff;border:1px solid var(--line);border-radius:18px;padding:14px;box-shadow:0 8px 22px rgba(31,41,51,.06);position:sticky;top:0;z-index:20}
|
||||
.search-row{display:grid;grid-template-columns:minmax(280px,1fr) 170px 190px 140px 96px;gap:10px}.input,.select{width:100%;border:1px solid #d7dce2;border-radius:12px;padding:11px 12px;background:#fff;color:var(--ink);outline:none}.input:focus,.select:focus{border-color:#a93a31;box-shadow:0 0 0 3px rgba(169,58,49,.12)}
|
||||
.btn{border:0;border-radius:12px;padding:10px 14px;background:var(--red);color:#fff;cursor:pointer;font-weight:700}.btn.secondary{background:#f1f3f5;color:#334155;border:1px solid #dbe1e8}.btn:hover{filter:brightness(.96)}
|
||||
.tabs{display:flex;gap:8px;overflow-x:auto;padding:14px 0 4px}.tab{white-space:nowrap;border:1px solid #e1d0d0;background:#fff;color:#5f1d1d;border-radius:999px;padding:9px 13px;cursor:pointer;font-weight:700}.tab.active{background:var(--red);color:#fff;border-color:var(--red)}
|
||||
.notice{border-radius:16px;padding:14px 16px;margin:14px 0;border:1px solid #ead7d7;background:#fffafa}.notice b{color:var(--red)}.notice.safe{background:#fbfff7;border-color:#d9eac8}.notice.warn{background:#fffaf0;border-color:#f0dfb8}.notice.danger{background:#fff4f4;border-color:#eac2c2}
|
||||
.section-title{display:flex;align-items:flex-end;justify-content:space-between;gap:12px;margin:22px 0 12px}.section-title h2{font-size:20px;margin:0;color:#5c1717}.section-title small{color:var(--muted)}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px}.grid.two{grid-template-columns:repeat(auto-fit,minmax(400px,1fr))}.grid.three{grid-template-columns:repeat(auto-fit,minmax(260px,1fr))}.overview-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin-bottom:14px}.stat,.card{background:var(--card);border:1px solid var(--line);border-radius:18px;padding:16px;box-shadow:0 8px 22px rgba(31,41,51,.05);position:relative}.stat .label{color:var(--muted);font-size:13px}.stat .value{font-size:24px;font-weight:900;color:#7a1f1f;margin:6px 0}.stat .desc,.sub,.mini{color:var(--muted);font-size:13px}.card h3{margin:0 0 6px;font-size:18px;color:#253041}.card .kv{color:#4b5563;font-size:14px;margin:10px 0}.card-actions{display:flex;justify-content:space-between;align-items:center;margin-top:12px;gap:10px}.linkbtn{border:1px solid #d8caca;background:#fff;color:#7a1f1f;border-radius:10px;padding:7px 10px;cursor:pointer;font-weight:800}.linkbtn:hover{background:#fff4f4}
|
||||
.tags{display:flex;flex-wrap:wrap;gap:7px}.pill{display:inline-flex;align-items:center;gap:5px;border-radius:999px;padding:4px 9px;background:#f1f3f5;color:#344054;font-size:12px;max-width:100%;word-break:break-word}.pill.red{background:#fff1f1;color:#7a1f1f}.pill.orange{background:#fff7ed;color:#9a3412}.pill.blue{background:#eef6ff;color:#075985}.pill.light{background:rgba(255,255,255,.16);color:#fff;border:1px solid rgba(255,255,255,.26)}
|
||||
.risk{position:absolute;top:14px;right:14px;color:#fff;border-radius:999px;padding:4px 10px;font-size:12px;font-weight:900}.risk.low{background:var(--green)}.risk.mid{background:var(--yellow)}.risk.midhi{background:var(--orange)}.risk.high{background:var(--high)}.risk.severe{background:var(--severe)}
|
||||
.chain{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.step{border:1px solid #eadede;background:#fffafa;border-radius:12px;padding:7px 9px;font-size:13px}.arrow{color:#a33;font-weight:900}
|
||||
.table-wrap{background:#fff;border:1px solid var(--line);border-radius:16px;overflow:auto;margin:10px 0}table{width:100%;border-collapse:collapse;font-size:14px}th{background:#faf3f3;color:#6b1717;text-align:left;position:sticky;top:0;z-index:1}th,td{padding:10px 12px;border-bottom:1px solid #edf0f3;vertical-align:top}td ul{margin:0;padding-left:18px}.timeline{border-left:3px solid #b84632;margin-left:12px}.timeline-item{margin:0 0 16px 18px;position:relative}.timeline-item:before{content:"";width:12px;height:12px;background:#b84632;border-radius:50%;position:absolute;left:-26px;top:22px;box-shadow:0 0 0 5px #f7dada}
|
||||
.search-results{display:none;background:#fff;border:1px solid var(--line);border-radius:16px;margin-top:12px;max-height:330px;overflow:auto}.result-row{display:flex;justify-content:space-between;gap:12px;align-items:center;border-top:1px solid #eef0f2;padding:10px 12px}.result-row:first-child{border-top:0}.result-title{font-weight:900}.result-source{font-size:12px;color:var(--muted)}.empty{background:#fff;border:1px dashed #d2d8e0;border-radius:16px;padding:22px;text-align:center;color:var(--muted)}
|
||||
.modal-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.45);display:none;align-items:center;justify-content:center;z-index:100;padding:18px}.modal{width:min(1180px,96vw);max-height:92vh;background:#fff;border-radius:22px;box-shadow:var(--shadow);display:flex;flex-direction:column;overflow:hidden}.modal-head{padding:18px 20px;background:linear-gradient(135deg,#711818,#a5362f);color:#fff;display:flex;justify-content:space-between;gap:12px;align-items:flex-start}.modal-head h2{margin:0;font-size:22px}.modal-sub{font-size:13px;color:rgba(255,255,255,.82);margin-top:4px}.modal-close{border:1px solid rgba(255,255,255,.35);background:rgba(255,255,255,.14);color:#fff;border-radius:10px;padding:8px 10px;cursor:pointer;font-weight:800;white-space:nowrap}.modal-tabs{display:flex;gap:8px;overflow-x:auto;padding:12px 16px;border-bottom:1px solid var(--line);background:#fff7f7}.modal-tab{border:1px solid #e2cfcf;background:#fff;color:#6b1717;border-radius:999px;padding:8px 12px;cursor:pointer;white-space:nowrap;font-weight:800}.modal-tab.active{background:#7a1f1f;color:#fff;border-color:#7a1f1f}.modal-body{padding:18px;overflow:auto}.detail-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:14px}.detail-section{border:1px solid #e5e7eb;border-radius:16px;background:#fff;padding:14px}.detail-section h4{margin:0 0 8px;color:#6b1717}.detail-section p{margin:0;white-space:pre-line}.field-list{margin:0;padding-left:18px}.object-card{border:1px solid #e7eaf0;background:#fbfcfe;border-radius:14px;padding:10px;margin:8px 0}.object-card h5{margin:0 0 6px;color:#354052}.modal-grid-large{display:grid;grid-template-columns:1.2fr .8fr;gap:14px}.json-note{font-size:12px;color:rgba(255,255,255,.86);margin-top:6px}
|
||||
@media(max-width:900px){.search-row{grid-template-columns:1fr}.grid.two,.grid.three,.modal-grid-large{grid-template-columns:1fr}.header h1{font-size:24px}.app{padding:14px}.modal{width:100vw;height:100vh;max-height:100vh;border-radius:0}.modal-backdrop{padding:0}.modal-head{flex-direction:column}.risk{position:static;display:inline-block;margin-bottom:8px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="header"><div class="header-inner"><h1 id="pageTitle"></h1><p id="pageSubtitle"></p><div class="top-pills" id="metaPills"></div></div></header>
|
||||
<main class="app">
|
||||
<section class="toolbar">
|
||||
<div class="search-row">
|
||||
<input class="input" id="globalSearch" placeholder="全局搜索:组织、人物、平台、事件、叙事、涉华涉台议题……" />
|
||||
<select class="select" id="riskFilter"><option value="">全部风险等级</option></select>
|
||||
<select class="select" id="typeFilter"><option value="">全部类型/节点</option></select>
|
||||
<select class="select" id="sourceFilter"><option value="">全部来源</option></select>
|
||||
<button class="btn secondary" id="resetBtn">重置</button>
|
||||
</div>
|
||||
<div id="searchResults" class="search-results"></div>
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
</section>
|
||||
<div class="notice" id="tabDesc"></div>
|
||||
<section id="content"></section>
|
||||
</main>
|
||||
<div class="modal-backdrop" id="modalBackdrop">
|
||||
<div class="modal" role="dialog" aria-modal="true">
|
||||
<div class="modal-head">
|
||||
<div><h2 id="modalTitle"></h2><div class="modal-sub" id="modalSubtitle"></div><div class="json-note">详情页为结构化展示;原始 JSON 仅可通过按钮复制。</div></div>
|
||||
<div style="display:flex;gap:8px;align-items:center"><button class="modal-close" id="copyJsonBtn">复制本条JSON</button><button class="modal-close" id="closeModal">关闭</button></div>
|
||||
</div>
|
||||
<div class="modal-tabs" id="modalTabs"></div>
|
||||
<div class="modal-body" id="modalBody"></div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const DATA = {"meta": {"title": "美方新右翼与极右翼群体研究专题库", "subtitle": "公开资料研究|组织谱系|叙事结构|平台生态|地方嵌入|涉华涉台议题", "version": "v3.0-full-structured-no-blank", "language": "zh-CN", "lastUpdated": "2026-06-25", "researchScope": ["美国新右翼政策网络", "极右翼街头组织", "反政府民兵", "白人民族主义组织", "阴谋论运动", "地方文化战生态", "涉华涉台右翼叙事"], "researchBoundary": "本专题库仅用于公开资料研究、政策分析、舆情观察和风险防护,不用于渗透、动员、骚扰、目标定位、动员招募、规避平台治理或暴力指导。", "methodNote": "所有条目均以公开资料研究为定位;风险等级是研究性提示,不等同于法律定性。新右翼、传统保守主义、宗教保守主义、共和党支持者与暴力极端主义必须严格区分。", "dataDesignNote": "v3 修复详情页空白问题:弹框改为按字段动态分组,只有存在内容的二级页才显示;同时增加“全部字段”结构化页,避免知识删减或字段遗漏。", "allowedUses": ["公开资料研究", "非操控性风险监测", "舆情趋势分析", "反极端主义预防", "政策建议", "公共沟通建议", "族群安全风险提示", "来源可信度审查"], "prohibitedUses": ["渗透、诱导、策反或操控任何群体", "制造、放大或投放欺骗性信息", "对特定个人进行画像、骚扰、跟踪、威胁或 doxxing", "规避平台治理、执法监测或安全机制", "提供暴力、破坏、骚乱组织、逃避执法或现场对抗的操作性指导", "针对族裔、宗教、政治立场、国籍、性别或性取向群体进行仇恨动员"], "coreResearchChain": ["概念区分", "历史演化", "主要群体与组织谱系", "人员结构与社会基础", "叙事结构与受众心理", "社交媒体与平台生态", "生态网络与影响通道", "涉华涉台议题嵌入路径", "风险行为链条", "地方社会与经济利益", "资源、法律与治理反应"], "interpretationPrinciple": "保守主义立场、共和党支持、反移民政策主张、反中共言论、支持台湾或反对美国介入台湾,本身均不等于极端主义;只有出现去人化、暴力正当化、具体目标指向、威胁或行动化迹象,才进入高风险研判。"}, "dictionaries": {"riskLevels": {"低": "普通政治表达、政策争议或低风险研究对象", "中": "存在议题极化、阴谋论倾向或平台扩散风险", "中-高": "存在群体泛化、目标个人化、地方冲突或跨平台扩散风险", "高": "存在反政府动员、仇恨叙事、线下行动化或暴力正当化风险", "严重": "存在现实暴力、模仿袭击、攻击者崇拜或明确威胁风险"}, "riskColors": {"低": "green", "中": "yellow", "中-高": "orange", "高": "red", "严重": "darkred"}, "sourceLevels": {"A": "法院、政府、国会、执法机构等官方公开文件", "B": "主流媒体或可靠地方媒体", "C": "研究机构、智库、倡议组织", "D": "学术论文、预印本、数据集", "E": "公开社交媒体样本,仅作为舆情线索", "F": "匿名论坛、截图、二手转述,只能作为待核查线索"}, "organizationTypes": ["新右翼政策网络", "极右翼街头组织", "反政府民兵", "白人民族主义组织", "阴谋论运动", "主权公民运动", "宗教民族主义网络", "男性至上主义生态", "反移民组织", "去中心化训练网络"], "platformTypes": ["主流社交平台", "替代社交平台", "匿名论坛", "长视频平台", "播客生态", "众筹平台", "地方社群平台", "邮件/通讯平台", "独立网站"], "researchModules": {"concepts_typology": "概念与谱系:区分新右翼、极右翼和暴力极端主义", "history_evolution": "历史演化:从白人至上、民兵、Tea Party、Alt-Right 到 MAGA 与新右翼制度化", "groups_organizations": "群体与组织:组织资料卡、行动形态与风险边界", "personnel_social_base": "人员与社会基础:受众分层、人员生态与地方嵌入", "narratives_psychology": "叙事与心理:解释世界、塑造敌人、吸引受众的叙事结构", "social_media_ecology": "社交媒体生态:引流、沉淀、强化、迁移和线下转化", "influence_networks": "生态网络与影响通道:思想、媒体、平台、地方、资金如何形成影响", "china_taiwan_issues": "涉华涉台议题:TikTok、芯片、疫情、留学生、芬太尼、台湾和台海", "local_society_economics": "地方社会与经济利益:学校、教会、县级政治、注意力经济与法律基金"}, "riskBehaviorSignals": ["明确敌人 + 末日紧迫感", "去人化语言 + 行动号召", "目标地点 + 时间窗口", "个人 grievance + 武器文化 + 社群鼓励", "过去袭击者崇拜 + 模仿语言", "执法/法院不合法叙事 + 被捕者殉道化"], "sourLine truncated
|
||||
let activeTab = 'dashboard';
|
||||
let currentModalItem = null; let currentModalKey = null; let currentModalGroup = null;
|
||||
const KEY_TO_TITLE = Object.fromEntries(DATA.tabs.map(t=>[t.dataKey,t.name]));
|
||||
const SEARCH_KEYS = (DATA.queryConfig && DATA.queryConfig.searchKeys) || DATA.tabs.map(t=>t.dataKey).filter(k=>Array.isArray(DATA[k]));
|
||||
const riskClass = r => ({'低':'low','中':'mid','中-高':'midhi','高':'high','严重':'severe'}[r] || '');
|
||||
function esc(s){ return String(s ?? '').replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m])); }
|
||||
function arr(v){ return Array.isArray(v) ? v : (v === undefined || v === null || v === '' ? [] : [v]); }
|
||||
function isEmpty(v){ return v === undefined || v === null || v === '' || (Array.isArray(v)&&v.length===0) || (typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).length===0); }
|
||||
function titleOf(item){ return item['名称'] || item['事件'] || item['议题'] || item['平台'] || item['场景'] || item['受众类型'] || item['阶段'] || item['概念'] || item['类型'] || item.label || item.id || '条目'; }
|
||||
function subOf(item){ return item['中文名称'] || item['英文'] || item['事件类型'] || item['议题类型'] || item['平台类型'] || item['节点类型'] || item['时间'] || item['基本定位'] || item.description || ''; }
|
||||
function riskBadge(r){ return r ? `<span class="risk ${riskClass(r)}">${esc(r)}</span>` : ''; }
|
||||
function tags(list, cls=''){ return arr(list).slice(0,18).map(x=>`<span class="pill ${cls}">${esc(typeof x==='object' ? objectSummary(x) : x)}</span>`).join(''); }
|
||||
function objectSummary(o){ return Object.entries(o).map(([k,v])=>`${k}:${Array.isArray(v)?v.join('、'):v}`).join(';'); }
|
||||
function init(){
|
||||
document.getElementById('pageTitle').textContent = DATA.meta.title || '专题库';
|
||||
document.getElementById('pageSubtitle').textContent = (DATA.meta.subtitle||'') + '。' + (DATA.meta.interpretationPrinciple||'');
|
||||
document.getElementById('metaPills').innerHTML = [`版本:${DATA.meta.version}`,`更新:${DATA.meta.lastUpdated}`,'11个研究栏目','结构化详情页','无空白二级页'].map(x=>`<span class="pill light">${esc(x)}</span>`).join('');
|
||||
renderFilters(); renderTabs(); bindEvents(); render();
|
||||
}
|
||||
function renderFilters(){
|
||||
const rf=document.getElementById('riskFilter'); Object.keys(DATA.dictionaries.riskLevels||{}).forEach(r=>rf.insertAdjacentHTML('beforeend',`<option>${esc(r)}</option>`));
|
||||
const sf=document.getElementById('sourceFilter'); Object.keys(DATA.dictionaries.sourceLevels||{}).forEach(s=>sf.insertAdjacentHTML('beforeend',`<option>${esc(s)}</option>`));
|
||||
updateTypeFilter();
|
||||
}
|
||||
function updateTypeFilter(){
|
||||
const sel=document.getElementById('typeFilter'); const old=sel.value; sel.innerHTML='<option value="">全部类型/节点</option>';
|
||||
const tab=DATA.tabs.find(t=>t.id===activeTab); const d=DATA[tab.dataKey]; const set=new Set();
|
||||
if(Array.isArray(d)) d.forEach(it=>['类型','节点类型','平台类型','事件类型','议题类型','受众类型','场景','概念'].forEach(k=>{if(it[k]) set.add(it[k]);}));
|
||||
[...set].sort().forEach(v=>sel.insertAdjacentHTML('beforeend',`<option>${esc(v)}</option>`));
|
||||
if([...set].includes(old)) sel.value=old;
|
||||
}
|
||||
function renderTabs(){ document.getElementById('tabs').innerHTML = DATA.tabs.map(t=>`<button class="tab ${t.id===activeTab?'active':''}" data-tab="${t.id}">${esc(t.name)}</button>`).join(''); }
|
||||
function bindEvents(){
|
||||
document.getElementById('tabs').addEventListener('click', e=>{if(e.target.dataset.tab){activeTab=e.target.dataset.tab; renderTabs(); updateTypeFilter(); render();}});
|
||||
['globalSearch','riskFilter','typeFilter','sourceFilter'].forEach(id=>document.getElementById(id).addEventListener('input',()=>{ renderSearch(); render(); }));
|
||||
document.getElementById('resetBtn').onclick=()=>{['globalSearch','riskFilter','typeFilter','sourceFilter'].forEach(id=>document.getElementById(id).value=''); document.getElementById('searchResults').style.display='none'; render();};
|
||||
document.getElementById('closeModal').onclick=closeModal;
|
||||
document.getElementById('modalBackdrop').addEventListener('click', e=>{if(e.target.id==='modalBackdrop') closeModal();});
|
||||
document.getElementById('copyJsonBtn').onclick=()=>{ if(currentModalItem) navigator.clipboard.writeText(JSON.stringify(currentModalItem,null,2)); };
|
||||
document.getElementById('modalTabs').addEventListener('click', e=>{ if(e.target.dataset.group){currentModalGroup=e.target.dataset.group; renderModalBody();} });
|
||||
}
|
||||
function itemText(it){ return JSON.stringify(it).toLowerCase(); }
|
||||
function filterData(items){
|
||||
if(!Array.isArray(items)) return items;
|
||||
const q=document.getElementById('globalSearch').value.trim().toLowerCase(); const risk=document.getElementById('riskFilter').value; const type=document.getElementById('typeFilter').value; const source=document.getElementById('sourceFilter').value;
|
||||
return items.filter(it=>{
|
||||
if(q && !itemText(it).includes(q)) return false;
|
||||
if(risk && it['风险等级']!==risk) return false;
|
||||
if(source && !arr(it['来源等级']).includes(source)) return false;
|
||||
if(type){ const vals=['类型','节点类型','平台类型','事件类型','议题类型','受众类型','场景','概念'].map(k=>it[k]).filter(Boolean); if(!vals.includes(type)) return false; }
|
||||
return true;
|
||||
});
|
||||
}
|
||||
function render(){
|
||||
const tab=DATA.tabs.find(t=>t.id===activeTab); document.getElementById('tabDesc').innerHTML = `<b>${esc(tab.name)}</b>:${esc(tab.description||'')}`;
|
||||
const raw=DATA[tab.dataKey]; const filtered=filterData(raw);
|
||||
if(tab.dataKey==='dashboard') return renderDashboard(raw);
|
||||
if(tab.layout==='timeline' || tab.layout==='timelineTable') return renderTimeline(filtered, tab.dataKey);
|
||||
if(tab.layout==='tableCard') return renderTableCards(filtered, tab.dataKey);
|
||||
return renderCards(filtered, tab.dataKey, tab.layout);
|
||||
}
|
||||
function renderDashboard(d){
|
||||
const html = [];
|
||||
html.push(`<div class="overview-grid">${d.summaryCards.map(c=>`<div class="stat"><div class="label">${esc(c.label)}</div><div class="value">${esc(c.value)}${c.unit?`<span style="font-size:14px">${esc(c.unit)}</span>`:''}</div><div class="desc">${esc(c.description||'')}</div></div>`).join('')}</div>`);
|
||||
html.push(`<div class="notice safe"><b>研究边界:</b>${esc(DATA.meta.researchBoundary)}<br><b>判读原则:</b>${esc(DATA.meta.interpretationPrinciple)}</div>`);
|
||||
html.push(`<div class="grid two"><div class="card"><h3>热点议题</h3><div class="tags">${tags(d.hotIssues,'red')}</div></div><div class="card"><h3>重点风险关注</h3>${listBlock(d.riskFocus)}</div></div>`);
|
||||
html.push(section('核心研究问题','来自原 Skill 的研究框架'));
|
||||
html.push(`<div class="grid three">${d.coreQuestions.map(q=>`<div class="card"><h3>${esc(q.title)}</h3><p class="sub">${esc(q.content)}</p></div>`).join('')}</div>`);
|
||||
html.push(section('风险行为链条模型','结构化展示,不提供操作性行动方案'));
|
||||
html.push(`<div class="grid">${d.riskBehaviorModels.map(m=>`<div class="card"><h3>${esc(m.name)}</h3><div class="chain">${m.steps.map((s,i)=>`${i?'<span class="arrow">→</span>':''}<span class="step">${esc(s)}</span>`).join('')}</div></div>`).join('')}</div>`);
|
||||
html.push(section('八类核心叙事模块','叙事-受众-风险点'));
|
||||
html.push(simpleTable(d.narrativeModules,['叙事','核心内容','主要受众','风险点']));
|
||||
html.push(section('六层生态网络','思想、媒体、平台、地方、街头、资源'));
|
||||
html.push(simpleTable(d.ecosystemLayers,['层级','功能','典型节点']));
|
||||
html.push(section('来源材料地图','对应原 Skill references/source_materials_map.md'));
|
||||
html.push(renderObjectCards(d.sourceMaterialsMap,'来源类型'));
|
||||
html.push(section('公开资料研究检查清单','对应原 Skill references/open_source_research_checklist.md'));
|
||||
html.push(`<div class="grid three">${Object.entries(d.openSourceResearchChecklist||{}).map(([k,v])=>`<div class="card"><h3>${esc(k)}</h3>${listBlock(v)}</div>`).join('')}</div>`);
|
||||
html.push(section('标准报告模板','对应原 Skill 的标准输出结构与模板'));
|
||||
html.push(renderObjectCards(d.standardTemplates,'模板'));
|
||||
html.push(section('未来趋势判断框架','对应原 Skill 的未来十年趋势判断框架'));
|
||||
html.push(`<div class="card">${listBlock(d.futureTrendFramework)}</div>`);
|
||||
html.push(`<div class="grid two" style="margin-top:14px"><div class="card"><h3>最小可用研判公式</h3><p class="sub" style="font-weight:900;color:#7a1f1f">${esc(d.minimumAssessmentFormula)}</p>${listBlock(d.formulaInterpretation)}</div><div class="card"><h3>事件触发覆盖范围</h3><div class="tags">${tags(d.triggerEventCoverage,'orange')}</div></div></div>`);
|
||||
document.getElementById('content').innerHTML = html.join('');
|
||||
}
|
||||
function section(h,small=''){return `<div class="section-title"><h2>${esc(h)}</h2><small>${esc(small)}</small></div>`;}
|
||||
function renderCards(items,key,layout){
|
||||
const content=document.getElementById('content'); if(!items.length){content.innerHTML='<div class="empty">没有匹配的数据。请调整搜索或筛选条件。</div>';return;}
|
||||
content.innerHTML = `<div class="grid">${items.map(it=>cardHTML(it,key)).join('')}</div>`; bindOpenButtons();
|
||||
}
|
||||
function pickTags(it){ return it['核心叙事'] || it['核心特征'] || it['主要议题'] || it['关联议题'] || it['易触发议题'] || it['典型内容'] || it['主要形式'] || it['外溢风险'] || it['代表现象'] || []; }
|
||||
function cardHTML(it,key){
|
||||
const title=titleOf(it), sub=subOf(it), risk=it['风险等级'];
|
||||
const line1 = it['基本定位'] || it['公开身份'] || it['功能定位'] || it['研究意义'] || it['事件概况'] || it['研究价值'] || it['风险关注']?.[0] || '';
|
||||
return `<article class="card">${riskBadge(risk)}<h3>${esc(title)}</h3><div class="sub">${esc(sub)}</div><div class="kv">${esc(String(line1)).slice(0,220)}</div><div class="tags">${tags(pickTags(it))}</div><div class="card-actions"><button class="linkbtn open-detail" data-id="${esc(it.id||title)}" data-key="${key}">查看结构化详情</button>${it['来源等级']?`<span class="mini">来源:${arr(it['来源等级']).join('/')}</span>`:''}</div></article>`;
|
||||
}
|
||||
function renderTimeline(items,key){
|
||||
if(!items.length){document.getElementById('content').innerHTML='<div class="empty">没有匹配的数据。</div>';return;}
|
||||
const rows=items.map(it=>`<div class="timeline-item"><div class="card">${riskBadge(it['风险等级'])}<h3>${esc(titleOf(it))}</h3><div class="sub">${esc(it['时间']||'')} ${it['地点']?'|'+esc(it['地点']):''}</div><div class="kv">${esc(it['研究意义']||it['事件类型']||it['事件概况']||'')}</div><div class="tags">${tags(it['主要特征']||it['核心叙事']||it['代表现象'])}</div><button class="linkbtn open-detail" data-id="${esc(it.id||titleOf(it))}" data-key="${key}">查看详情</button></div></div>`).join('');
|
||||
document.getElementById('content').innerHTML=`<div class="timeline">${rows}</div>`; bindOpenButtons();
|
||||
}
|
||||
function renderTableCards(items,key){
|
||||
if(!items.length){document.getElementById('content').innerHTML='<div class="empty">没有匹配的数据。</div>';return;}
|
||||
document.getElementById('content').innerHTML = `<div class="table-wrap"><table><thead><tr><th>类型</th><th>对应生态</th><th>主要形式</th><th>相关议题</th><th>风险</th><th>操作</th></tr></thead><tbody>${items.map(it=>`<tr><td><b>${esc(it['类型'])}</b></td><td>${renderSimple(it['对应生态'])}</td><td>${renderSimple(it['主要形式'])}</td><td>${renderSimple(it['相关议题'])}</td><td>${it['风险等级']?`<span class="pill red">${esc(it['风险等级'])}</span>`:''}</td><td><button class="linkbtn open-detail" data-id="${esc(it.id||it['类型'])}" data-key="${key}">详情</button></td></tr>`).join('')}</tbody></table></div>`; bindOpenButtons();
|
||||
}
|
||||
function renderSimple(v){ return arr(v).map(x=>esc(typeof x==='object'?objectSummary(x):x)).join('、'); }
|
||||
function simpleTable(rows, cols){ return `<div class="table-wrap"><table><thead><tr>${cols.map(c=>`<th>${esc(c)}</th>`).join('')}</tr></thead><tbody>${(rows||[]).map(r=>`<tr>${cols.map(c=>`<td>${renderValue(r[c])}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`; }
|
||||
function renderObjectCards(rows,titleKey){ return `<div class="grid">${(rows||[]).map((r,i)=>`<div class="card"><h3>${esc(r[titleKey] || titleOf(r) || ('条目 '+(i+1)))}</h3>${Object.entries(r).filter(([k])=>k!==titleKey).map(([k,v])=>`<div style="margin-top:9px"><b style="color:#6b1717">${esc(k)}:</b>${renderValue(v)}</div>`).join('')}</div>`).join('')}</div>`; }
|
||||
function listBlock(list){ return `<ul>${arr(list).map(x=>`<li>${esc(typeof x==='object'?objectSummary(x):x)}</li>`).join('')}</ul>`; }
|
||||
function bindOpenButtons(){ document.querySelectorAll('.open-detail').forEach(btn=>btn.onclick=()=>openDetail(btn.dataset.key, btn.dataset.id)); }
|
||||
function openDetail(key,id){
|
||||
const arrData=DATA[key]||[]; currentModalItem=arrData.find(x=>(x.id||titleOf(x))===id) || arrData.find(x=>titleOf(x)===id); currentModalKey=key;
|
||||
if(!currentModalItem) return; const groups=availableGroups(currentModalItem); currentModalGroup=groups[0]?.id || 'all';
|
||||
document.getElementById('modalTitle').textContent=titleOf(currentModalItem); document.getElementById('modalSubtitle').textContent=(KEY_TO_TITLE[key]||key) + (subOf(currentModalItem)?'|'+subOf(currentModalItem):'');
|
||||
renderModalTabs(); renderModalBody(); document.getElementById('modalBackdrop').style.display='flex';
|
||||
}
|
||||
function closeModal(){ document.getElementById('modalBackdrop').style.display='none'; }
|
||||
function groupDefs(){ return (DATA.detailConfig && DATA.detailConfig.groups) || []; }
|
||||
function groupFields(item, group){
|
||||
const keys = group.keys === '*' ? Object.keys(item) : group.keys;
|
||||
return keys.filter(k=>!isEmpty(item[k]));
|
||||
}
|
||||
function assignedKeys(){
|
||||
const s=new Set(); groupDefs().forEach(g=>{ if(g.keys !== '*') g.keys.forEach(k=>s.add(k)); }); return s;
|
||||
}
|
||||
function availableGroups(item){
|
||||
const defs=groupDefs();
|
||||
const groups=[];
|
||||
defs.forEach(g=>{
|
||||
if(g.keys==='*') return;
|
||||
if(groupFields(item,g).length) groups.push(g);
|
||||
});
|
||||
// Always include all fields as a structured page, never blank, but not JSON raw.
|
||||
groups.push(defs.find(g=>g.id==='all') || {id:'all',name:'全部字段',keys:'*'});
|
||||
return groups;
|
||||
}
|
||||
function renderModalTabs(){
|
||||
const groups=availableGroups(currentModalItem);
|
||||
if(!groups.find(g=>g.id===currentModalGroup)) currentModalGroup=groups[0].id;
|
||||
document.getElementById('modalTabs').innerHTML=groups.map(g=>`<button class="modal-tab ${g.id===currentModalGroup?'active':''}" data-group="${esc(g.id)}">${esc(g.name)}</button>`).join('');
|
||||
}
|
||||
function renderModalBody(){
|
||||
renderModalTabs(); const group=availableGroups(currentModalItem).find(g=>g.id===currentModalGroup); let html='';
|
||||
if(currentModalGroup==='boundary') html += `<div class="notice danger"><b>安全提醒:</b>${esc(DATA.meta.researchBoundary)}</div>`;
|
||||
if(currentModalGroup==='all') {
|
||||
const entries=Object.entries(currentModalItem).filter(([k,v])=>!isEmpty(v));
|
||||
html += `<div class="notice warn"><b>全部字段结构化展示:</b>这一页不是 JSON 原文,而是将该条目的所有非空字段按字段卡片呈现,避免详情内容遗漏。</div>`;
|
||||
html += `<div class="detail-grid">${entries.map(([k,v])=>fieldHTML(k,v)).join('')}</div>`;
|
||||
} else {
|
||||
const fields=groupFields(currentModalItem, group);
|
||||
if(!fields.length) html += '<div class="empty">该分类没有可展示字段,已自动隐藏;请查看“全部字段”。</div>';
|
||||
else html += `<div class="detail-grid">${fields.map(k=>fieldHTML(k,currentModalItem[k])).join('')}</div>`;
|
||||
}
|
||||
document.getElementById('modalBody').innerHTML=html;
|
||||
}
|
||||
function fieldHTML(k,v){ return `<section class="detail-section"><h4>${esc(k)}</h4><div class="field">${renderValue(v)}</div></section>`; }
|
||||
function renderValue(v){
|
||||
if(isEmpty(v)) return '<span class="mini">暂无数据</span>';
|
||||
if(Array.isArray(v)){
|
||||
if(v.every(x=>typeof x !== 'object')){
|
||||
if(v.length<=12 && v.every(x=>String(x).length<60)) return `<div class="tags">${tags(v)}</div>`;
|
||||
return `<ul class="field-list">${v.map(x=>`<li>${esc(x)}</li>`).join('')}</ul>`;
|
||||
}
|
||||
return v.map((obj,i)=>`<div class="object-card"><h5>条目 ${i+1}</h5>${objectTable(obj)}</div>`).join('');
|
||||
}
|
||||
if(typeof v === 'object') return objectTable(v);
|
||||
const str=String(v);
|
||||
if(str.length>180) return `<p>${esc(str)}</p>`;
|
||||
return `<p>${esc(str)}</p>`;
|
||||
}
|
||||
function objectTable(obj){ return `<div class="table-wrap"><table><tbody>${Object.entries(obj).filter(([k,v])=>!isEmpty(v)).map(([k,v])=>`<tr><th>${esc(k)}</th><td>${renderValue(v)}</td></tr>`).join('')}</tbody></table></div>`; }
|
||||
function renderSearch(){
|
||||
const q=document.getElementById('globalSearch').value.trim().toLowerCase(); const box=document.getElementById('searchResults');
|
||||
if(!q){box.style.display='none';return;}
|
||||
const res=[]; SEARCH_KEYS.forEach(k=>(DATA[k]||[]).forEach(it=>{ if(itemText(it).includes(q)) res.push({key:k,item:it}); }));
|
||||
box.style.display='block'; box.innerHTML = `<div style="padding:10px 12px"><b>全局搜索结果:${res.length} 条</b></div>` + (res.length?res.slice(0,50).map(r=>`<div class="result-row"><div><div class="result-title">${esc(titleOf(r.item))}</div><div class="result-source">来源栏目:${esc(KEY_TO_TITLE[r.key]||r.key)} ${r.item['风险等级']?'|风险:'+esc(r.item['风险等级']):''}</div></div><button class="linkbtn" onclick="openDetail('${r.key}','${esc(r.item.id||titleOf(r.item))}')">查看</button></div>`).join(''):'<div class="empty">无匹配结果</div>');
|
||||
}
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+10758
File diff suppressed because it is too large.
Load diff
+220
@@ -0,0 +1,220 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>台海经济民生叙事监测专题平台</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg:#7f1d1d;
|
||||
--bg2:#991b1b;
|
||||
--panel:#fff7ed;
|
||||
--card:#ffffff;
|
||||
--text:#1f2937;
|
||||
--muted:#6b7280;
|
||||
--line:#e5e7eb;
|
||||
--primary:#b91c1c;
|
||||
--primary2:#ef4444;
|
||||
--amber:#f59e0b;
|
||||
--green:#16a34a;
|
||||
--blue:#2563eb;
|
||||
--shadow: 0 18px 45px rgba(30, 41, 59, .18);
|
||||
--radius: 22px;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Microsoft YaHei',Arial,sans-serif;background:linear-gradient(135deg,var(--bg),#b91c1c 45%,#f97316);color:var(--text);}
|
||||
a{color:var(--primary);text-decoration:none}
|
||||
a:hover{text-decoration:underline}
|
||||
.shell{max-width:1440px;margin:0 auto;padding:28px 24px 60px;}
|
||||
.hero{background:linear-gradient(135deg,rgba(255,255,255,.94),rgba(255,247,237,.88));border:1px solid rgba(255,255,255,.8);border-radius:32px;padding:28px;box-shadow:var(--shadow);position:relative;overflow:hidden}
|
||||
.hero:after{content:'';position:absolute;right:-80px;top:-120px;width:300px;height:300px;border:42px solid rgba(185,28,28,.08);border-radius:50%;}
|
||||
.hero h1{margin:0;font-size:34px;letter-spacing:.5px;color:#7f1d1d}
|
||||
.hero p{max-width:980px;line-height:1.75;color:#4b5563;font-size:15px;margin:14px 0 0}
|
||||
.hero-meta{display:flex;flex-wrap:wrap;gap:10px;margin-top:18px}
|
||||
.badge{display:inline-flex;align-items:center;gap:6px;border-radius:999px;padding:7px 12px;font-size:12px;background:#fff;border:1px solid #fecaca;color:#7f1d1d;font-weight:700}
|
||||
.toolbar{margin:18px 0;background:rgba(255,255,255,.92);border:1px solid rgba(255,255,255,.8);border-radius:22px;padding:14px;display:grid;grid-template-columns:1fr 180px 180px 180px;gap:12px;box-shadow:0 8px 24px rgba(0,0,0,.08)}
|
||||
.toolbar input,.toolbar select{width:100%;border:1px solid #e5e7eb;border-radius:14px;padding:12px 14px;font-size:14px;background:#fff;color:var(--text);outline:none}
|
||||
.tabs{position:sticky;top:0;z-index:10;margin:16px 0 18px;background:rgba(255,255,255,.9);backdrop-filter:blur(14px);border:1px solid rgba(255,255,255,.8);border-radius:24px;padding:8px;display:flex;gap:8px;overflow-x:auto;box-shadow:0 10px 24px rgba(0,0,0,.12)}
|
||||
.tab-btn{border:0;background:transparent;white-space:nowrap;padding:11px 15px;border-radius:18px;color:#6b7280;font-weight:800;cursor:pointer}
|
||||
.tab-btn.active{background:linear-gradient(135deg,#b91c1c,#ef4444);color:white;box-shadow:0 8px 18px rgba(185,28,28,.25)}
|
||||
.main{background:rgba(255,255,255,.93);border:1px solid rgba(255,255,255,.8);border-radius:30px;padding:24px;box-shadow:var(--shadow);min-height:580px}
|
||||
.section-head{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;margin-bottom:18px;border-bottom:1px solid var(--line);padding-bottom:14px}
|
||||
.section-head h2{margin:0;color:#7f1d1d;font-size:24px}
|
||||
.section-head p{margin:6px 0 0;color:var(--muted);line-height:1.65}
|
||||
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}
|
||||
.grid3{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
|
||||
.grid2{display:grid;grid-template-columns:repeat(2,1fr);gap:16px}
|
||||
.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:18px;box-shadow:0 8px 20px rgba(31,41,55,.06);position:relative;overflow:hidden}
|
||||
.card h3{margin:0 0 10px;color:#111827;font-size:17px}
|
||||
.card p{margin:8px 0;color:#4b5563;line-height:1.68;font-size:14px}
|
||||
.kpi .value{font-size:28px;font-weight:900;color:#991b1b;margin-top:8px}
|
||||
.kpi .sub{font-size:13px;color:#6b7280;margin-top:6px}
|
||||
.tag-row{display:flex;flex-wrap:wrap;gap:6px;margin-top:12px}
|
||||
.tag{display:inline-flex;border-radius:999px;background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;padding:4px 8px;font-size:12px;font-weight:700}
|
||||
.tag.high,.risk-high{background:#fee2e2;border-color:#fecaca;color:#991b1b}
|
||||
.tag.medium,.risk-medium{background:#fef3c7;border-color:#fde68a;color:#92400e}
|
||||
.tag.low,.risk-low{background:#dcfce7;border-color:#bbf7d0;color:#166534}
|
||||
.temp-wrap{display:grid;grid-template-columns: 1fr 1fr;gap:16px;margin-bottom:18px}
|
||||
.temp-card{background:linear-gradient(135deg,#fff,#fff7ed);border:1px solid #fed7aa;border-radius:24px;padding:18px}
|
||||
.bars{display:flex;gap:8px;margin-top:12px;align-items:end;height:74px}
|
||||
.bar{flex:1;background:linear-gradient(180deg,#ef4444,#991b1b);border-radius:10px 10px 4px 4px;min-height:8px;position:relative}
|
||||
.bar span{position:absolute;bottom:100%;left:50%;transform:translateX(-50%);font-size:12px;font-weight:900;color:#7f1d1d;margin-bottom:4px}
|
||||
.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:18px;background:#fff}
|
||||
table{border-collapse:collapse;width:100%;font-size:14px;min-width:780px}
|
||||
th,td{border-bottom:1px solid var(--line);padding:12px 14px;text-align:left;vertical-align:top;line-height:1.55}
|
||||
th{background:#fff7ed;color:#7f1d1d;font-weight:900;position:sticky;top:0}
|
||||
tr:hover td{background:#fffafa}
|
||||
.timeline{position:relative;margin-left:8px}
|
||||
.timeline:before{content:'';position:absolute;left:18px;top:4px;bottom:4px;width:3px;background:#fecaca;border-radius:99px}
|
||||
.tl-item{position:relative;margin:0 0 14px 0;padding-left:54px}
|
||||
.tl-dot{position:absolute;left:8px;top:18px;width:23px;height:23px;background:#fff;border:5px solid #b91c1c;border-radius:50%;box-shadow:0 0 0 5px #fee2e2}
|
||||
.tl-card{cursor:pointer;transition:.2s}
|
||||
.tl-card:hover{transform:translateY(-2px);box-shadow:0 12px 28px rgba(185,28,28,.16)}
|
||||
.tl-date{font-weight:900;color:#991b1b;font-size:13px;margin-bottom:6px}
|
||||
.pill{display:inline-block;padding:5px 9px;border-radius:999px;background:#f3f4f6;color:#4b5563;font-size:12px;font-weight:800;margin-right:6px;margin-top:6px}
|
||||
.source-list{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}
|
||||
.source-item{border:1px solid var(--line);border-radius:16px;padding:14px;background:#fff}
|
||||
.source-item strong{color:#7f1d1d}
|
||||
.muted{color:var(--muted)}
|
||||
.empty{padding:40px;border:1px dashed #fecaca;border-radius:20px;text-align:center;color:#9ca3af;background:#fffafa}
|
||||
.modal-backdrop{position:fixed;inset:0;background:rgba(17,24,39,.55);display:none;align-items:center;justify-content:center;z-index:50;padding:20px}
|
||||
.modal{max-width:900px;width:100%;max-height:86vh;overflow:auto;background:#fff;border-radius:28px;box-shadow:0 32px 80px rgba(0,0,0,.35);padding:24px;border:1px solid #fee2e2}
|
||||
.modal h2{color:#7f1d1d;margin:0 0 10px}
|
||||
.modal-close{float:right;border:0;background:#fee2e2;color:#991b1b;border-radius:12px;padding:8px 12px;font-weight:900;cursor:pointer}
|
||||
.footer{margin-top:18px;color:#fff7ed;text-align:center;font-size:13px;line-height:1.7}
|
||||
@media (max-width:1100px){.grid{grid-template-columns:repeat(2,1fr)}.grid3{grid-template-columns:repeat(2,1fr)}.toolbar{grid-template-columns:1fr 1fr}.source-list{grid-template-columns:1fr}}
|
||||
@media (max-width:720px){.shell{padding:16px 12px 42px}.hero h1{font-size:25px}.main{padding:16px}.grid,.grid2,.grid3,.temp-wrap{grid-template-columns:1fr}.toolbar{grid-template-columns:1fr}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<header class="hero">
|
||||
<h1>台海经济民生叙事监测专题平台</h1>
|
||||
<p>围绕“军事介入台海经济民生必下降”这一叙事,建立公开资料研究型数据库。页面用于拆解事件、预算、军售、半导体、航运、贸易、受众和平台传播之间的关系,同时展示竞争叙事与反弹逻辑。</p>
|
||||
<div class="hero-meta">
|
||||
<span class="badge">版本 1.0</span>
|
||||
<span class="badge">生成日期:2026-06-25</span>
|
||||
<span class="badge">公开资料研究</span>
|
||||
<span class="badge">非操纵性传播方案</span>
|
||||
</div>
|
||||
</header>
|
||||
<div class="toolbar">
|
||||
<input id="searchBox" placeholder="搜索事件、叙事、受众、关键词……" />
|
||||
<select id="categoryFilter"><option value="all">全部类别</option></select>
|
||||
<select id="riskFilter"><option value="all">全部风险</option><option value="high">高风险</option><option value="medium">中风险</option><option value="low">低风险</option></select>
|
||||
<select id="regionFilter"><option value="all">全部地区</option></select>
|
||||
</div>
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
<main class="main" id="content"></main>
|
||||
<div class="footer">边界说明:本页面仅用于公开资料研究、政策风险监测与舆论观察;不提供虚假信息、隐蔽影响、假账号或定向操纵建议。</div>
|
||||
</div>
|
||||
<div class="modal-backdrop" id="modalBackdrop"><div class="modal" id="modal"></div></div>
|
||||
<script id="dataset" type="application/json">{"metadata": {"title": "台海经济民生叙事监测专题数据库", "version": "1.0", "generated_at": "2026-06-25", "language": "zh-CN", "scope": "公开资料研究、舆论观察、风险评估、政策过程分析。", "safety_boundary": "不包含虚假信息制造、假账号操作、定向骚扰、隐蔽影响或操纵性传播方案。", "core_question": "美国对台军售、印太军事部署与台海战备如何被叙事化为经济民生风险,以及该叙事如何与威慑避战、供应链韧性等反叙事竞争。"}, "tabs": [{"id": "overview", "name": "总览仪表盘", "description": "展示当前叙事温度、核心 KPI、重大事件和风险等级。"}, {"id": "events", "name": "关键事件时间线", "description": "汇总军售、军演、预算、半导体、贸易和航运事件。"}, {"id": "budget", "name": "防务预算与民生成本", "description": "分析国防预算、特别预算、财政压力和民生争议。"}, {"id": "arms", "name": "美国军售与军工链", "description": "展示军售项目、金额、后勤、供应商核查和交付争议。"}, {"id": "semi", "name": "半导体与硅盾变化", "description": "展示台积电、ICT 出口、半导体外移和供应链韧性。"}, {"id": "maritime", "name": "海峡航运与贸易通道", "description": "展示封锁、检疫、海警、保险和海峡贸易风险。"}, {"id": "trade", "name": "美台贸易与美国成本", "description": "分析美台贸易逆差、关税、产业回流和纳税人成本叙事。"}, {"id": "tw_audience", "name": "台湾内部受众", "description": "分析 DPP、KMT、中间选民、青年、工商业界和疑美群体。"}, {"id": "us_audience", "name": "美国国内受众", "description": "分析鹰派、MAGA 成本派、财政保守派和科技安全派。"}, {"id": "allies", "name": "亚太盟友与产业界", "description": "分析日本、韩国、菲律宾、澳大利亚、航运业和投资者。"}, {"id": "platforms", "name": "平台传播与关键词", "description": "展示平台观察矩阵和中英文关键词库。"}, {"id": "frames", "name": "叙事框架与反叙事", "description": "展示核心叙事框架、脆弱点和反叙事。"}], "sources": [{"id": "SRC-TW-MND", "name": "台湾国防部 National Defense Budgeting", "type": "官方", "url": "https://www.mnd.gov.tw/en/publication/129", "credibility": "A", "notes": "2026 防务预算、NATO 口径、GDP 占比、国防部预算增幅。"}, {"id": "SRC-TSMC", "name": "TSMC 官方新闻稿:扩大美国投资", "type": "企业官方", "url": "https://pr.tsmc.com/english/news/3210", "credibility": "A", "notes": "台积电美国投资增至 1650 亿美元、三座晶圆厂、两座先进封装设施、研发中心。"}, {"id": "SRC-USTR", "name": "美国贸易代表办公室:Taiwan", "type": "官方", "url": "https://ustr.gov/countries-regions/china/taiwan", "credibility": "A", "notes": "2025 年美台货物贸易额、美国对台出口、进口、逆差。"}, {"id": "SRC-TW-MOF-2025", "name": "台湾财政部 / Taiwan Today:2025 外贸创新高", "type": "官方/官方媒体", "url": "https://www.taiwantoday.tw/print/Economics/Top-News/280295/Taiwan-reports-record-high-foreign-trade-in-2025", "credibility": "A-", "notes": "2025 年台湾出口、进口、贸易顺差数据。"}, {"id": "SRC-CSIS-STRAIT", "name": "CSIS:Taiwan Strait trade disruption analysis", "type": "智库", "url": "https://www.csis.org/analysis/disruptions-trade-taiwan-strait-would-severely-impact-chinas-economy", "credibility": "A-", "notes": "台湾海峡贸易规模、区域经济体依赖估算。"}, {"id": "SRC-CHICAGO-2025", "name": "Chicago Council:Americans Grow More Supportive of Aiding Taiwan", "type": "民调/研究机构", "url": "https://globalaffairs.org/research/public-opinion-survey/americans-grow-more-supportive-aiding-taiwan-china-crisis", "credibility": "A-", "notes": "美国公众在台湾危机中的援助、制裁、军援、海军打破封锁、派兵支持率。"}, {"id": "SRC-BROOKINGS-2026", "name": "Brookings:How partisan is Taiwan's security debate?", "type": "智库/民调分析", "url": "https://www.brookings.edu/articles/how-partisan-is-taiwans-security-debate/", "credibility": "A-", "notes": "台湾特别防务预算支持率及党派差异。"}, {"id": "SRC-DSCA-TECO", "name": "DSCA:TECRO major arms sales archive", "type": "美国官方", "url": "https://www.dsca.mil/Press-Media/Major-Arms-Sales/Tag/295270/taipei-economic-and-cultural-representative-office-in-the-united-states-tecro", "credibility": "A", "notes": "2025 年 12 月及 2025 年 11 月对台军售通知。"}, {"id": "SRC-USTBC-2025-ARMS", "name": "USTBC:Eight arms sales to Taiwan valued at over US$11.1bn", "type": "行业组织/汇总", "url": "https://www.us-taiwan.org/resources/ustbc-comments-on-eight-arms-sales-to-taiwan-valued-at-over-us-11-1-billion/", "credibility": "A-", "Line truncated
|
||||
<script>
|
||||
const DATA = JSON.parse(document.getElementById('dataset').textContent);
|
||||
let activeTab = 'overview';
|
||||
const $ = sel => document.querySelector(sel);
|
||||
const content = $('#content');
|
||||
function sourceLinks(ids=[]){
|
||||
return ids.map(id=>DATA.sources.find(s=>s.id===id)).filter(Boolean)
|
||||
.map(s=>`<a href="${s.url}" target="_blank">${s.name}</a>`).join(';') || '<span class="muted">未标注来源</span>';
|
||||
}
|
||||
function riskClass(r){ return r==='high'||r==='高'?'high':r==='medium'||r==='中'?'medium':'low'; }
|
||||
function esc(v){return String(v??'').replace(/[&<>"]/g, m=>({'&':'&','<':'<','>':'>','"':'"'}[m]));}
|
||||
function matchFilter(obj){
|
||||
const q = $('#searchBox').value.trim().toLowerCase();
|
||||
const cat = $('#categoryFilter').value;
|
||||
const risk = $('#riskFilter').value;
|
||||
const region = $('#regionFilter').value;
|
||||
const text = JSON.stringify(obj).toLowerCase();
|
||||
if(q && !text.includes(q)) return false;
|
||||
if(cat !== 'all' && (obj.category||obj.type) !== cat) return false;
|
||||
if(risk !== 'all' && riskClass(obj.risk_level||obj.risk) !== risk) return false;
|
||||
if(region !== 'all' && (obj.region||'') !== region) return false;
|
||||
return true;
|
||||
}
|
||||
function initFilters(){
|
||||
const cats = [...new Set([...DATA.events.map(e=>e.category), ...DATA.indicators.map(i=>i.category)])].filter(Boolean);
|
||||
$('#categoryFilter').innerHTML = '<option value="all">全部类别</option>' + cats.map(c=>`<option value="${esc(c)}">${esc(c)}</option>`).join('');
|
||||
const regions = [...new Set([...DATA.events.map(e=>e.region), ...DATA.audiences.map(a=>a.region)])].filter(Boolean);
|
||||
$('#regionFilter').innerHTML = '<option value="all">全部地区</option>' + regions.map(r=>`<option value="${esc(r)}">${esc(r)}</option>`).join('');
|
||||
}
|
||||
function initTabs(){
|
||||
$('#tabs').innerHTML = DATA.tabs.map(t=>`<button class="tab-btn ${t.id===activeTab?'active':''}" data-tab="${t.id}">${t.name}</button>`).join('');
|
||||
document.querySelectorAll('.tab-btn').forEach(btn=>btn.onclick=()=>{activeTab=btn.dataset.tab; render(); initTabs();});
|
||||
}
|
||||
function head(title, desc){ return `<div class="section-head"><div><h2>${title}</h2><p>${desc||''}</p></div></div>`; }
|
||||
function kpiCard(k){ return `<div class="card kpi"><h3>${k.name}</h3><div class="value">${k.value}</div><div class="sub">${k.sub_value||''}</div><p>${k.interpretation||''}</p><div class="tag-row"><span class="tag ${riskClass(k.risk_level)}">${k.risk_level}风险</span><span class="tag">${k.category}</span></div><p class="muted">来源:${sourceLinks(k.source_ids)}</p></div>`; }
|
||||
function card(title, body, tags=[], sources=[]){ return `<div class="card"><h3>${title}</h3><p>${body}</p><div class="tag-row">${tags.map(t=>`<span class="tag">${esc(t)}</span>`).join('')}</div>${sources.length?`<p class="muted">来源:${sourceLinks(sources)}</p>`:''}</div>`; }
|
||||
function renderOverview(){
|
||||
const temp = DATA.scoring_rules.current_temperature_sample;
|
||||
content.innerHTML = head('总览仪表盘', DATA.tabs.find(t=>t.id==='overview').description) +
|
||||
`<div class="temp-wrap"><div class="temp-card"><h3>叙事温度样本</h3><p>${temp.explanation}</p><div class="bars">${
|
||||
[['原叙事',temp.original_narrative_heat],['竞争',temp.competing_narrative_heat],['反弹',temp.backlash_intensity],['政策',temp.policy_impact_likelihood]].map(([n,v])=>`<div class="bar" style="height:${v*14}px"><span>${v}</span></div>`).join('')
|
||||
}</div><div class="tag-row">${temp.key_drivers.map(x=>`<span class="tag">${x}</span>`).join('')}</div></div><div class="temp-card"><h3>专题解释边界</h3><p>${DATA.metadata.safety_boundary}</p><p>核心问题:${DATA.metadata.core_question}</p></div></div>`+
|
||||
`<div class="grid">${DATA.dashboard_kpis.map(kpiCard).join('')}</div>`+
|
||||
`<div style="margin-top:18px">${head('数据缺口与后续采集', '这些字段已在页面预留,但需要后续日度或周度采样。')}<div class="grid3">${DATA.data_gaps.map(g=>card(g.item, g.reason, [g.status])).join('')}</div></div>`;
|
||||
}
|
||||
function openEvent(e){
|
||||
$('#modal').innerHTML = `<button class="modal-close" onclick="closeModal()">关闭</button><h2>${e.title}</h2><p><strong>时间:</strong>${e.date} <strong>类别:</strong>${e.category} <strong>风险:</strong>${e.risk_level}</p><p>${e.event_summary}</p><h3>经济传导</h3><p>${(e.economic_link||[]).join('、')}</p><h3>叙事影响</h3><p>${e.narrative_effect}</p><h3>涉及行为体</h3><p>${(e.involved_actors||[]).join('、')}</p><h3>受影响受众</h3><p>${(e.affected_audiences||[]).join('、')}</p><div class="tag-row">${(e.tags||[]).map(t=>`<span class="tag">${t}</span>`).join('')}</div><p class="muted">来源:${sourceLinks(e.source_ids)}</p>`;
|
||||
$('#modalBackdrop').style.display='flex';
|
||||
}
|
||||
function closeModal(){$('#modalBackdrop').style.display='none'}
|
||||
window.closeModal = closeModal;
|
||||
$('#modalBackdrop').onclick = e => { if(e.target.id==='modalBackdrop') closeModal(); };
|
||||
function renderEvents(){
|
||||
const arr = DATA.events.filter(matchFilter).sort((a,b)=>a.date.localeCompare(b.date));
|
||||
content.innerHTML = head('关键事件时间线', DATA.tabs.find(t=>t.id==='events').description) + (arr.length?`<div class="timeline">${arr.map(e=>`<div class="tl-item"><div class="tl-dot"></div><div class="card tl-card" onclick='openEvent(${JSON.stringify(e).replace(/'/g,"'")})'><div class="tl-date">${e.date}</div><h3>${e.title}</h3><p>${e.event_summary}</p><span class="pill">${e.category}</span><span class="pill">${e.region}</span><span class="pill">${e.risk_level}</span></div></div>`).join('')}</div>`:'<div class="empty">没有匹配事件</div>');
|
||||
}
|
||||
function renderBudget(){
|
||||
content.innerHTML = head('防务预算与民生成本', DATA.tabs.find(t=>t.id==='budget').description) + `<div class="grid">${DATA.budget.cards.map(c=>`<div class="card kpi"><h3>${c.label}</h3><div class="value">${c.value}</div><p>${c.note}</p><span class="tag ${riskClass(c.risk)}">${c.risk}风险</span></div>`).join('')}</div><div style="margin-top:18px" class="grid2">${DATA.budget.debate_points.map(d=>card(d.title,d.content,d.tags)).join('')}</div><p class="muted">来源:${sourceLinks(DATA.budget.source_ids)}</p>`;
|
||||
}
|
||||
function renderArms(){
|
||||
const rows = DATA.arms_sales.map(a=>`<tr><td><strong>${a.project}</strong><br><span class="muted">${a.id}</span></td><td>${a.amount_usd}</td><td>${a.type}</td><td>${a.narrative}</td><td>${sourceLinks(a.source_ids)}</td></tr>`).join('');
|
||||
content.innerHTML = head('美国军售与军工链', DATA.tabs.find(t=>t.id==='arms').description) + `<div class="table-wrap"><table><thead><tr><th>项目</th><th>估值</th><th>类型</th><th>叙事关联</th><th>来源</th></tr></thead><tbody>${rows}</tbody></table></div>`;
|
||||
}
|
||||
function renderSemi(){
|
||||
content.innerHTML = head('半导体与“硅盾”变化', DATA.tabs.find(t=>t.id==='semi').description) + `<div class="grid">${DATA.semiconductor.tsmc_investment.map(x=>`<div class="card kpi"><h3>${x.label}</h3><div class="value">${x.value}</div></div>`).join('')}</div><div style="margin-top:18px" class="table-wrap"><table><thead><tr><th>出口类别</th><th>金额</th><th>同比</th><th>叙事意义</th></tr></thead><tbody>${DATA.semiconductor.export_structure.map(x=>`<tr><td>${x.category}</td><td>${x.amount}</td><td>${x.yoy}</td><td>${x.meaning}</td></tr>`).join('')}</tbody></table></div><div style="margin-top:18px" class="grid2">${DATA.semiconductor.frames.map(f=>card(f.title,f.content)).join('')}</div><p class="muted">来源:${sourceLinks(DATA.semiconductor.source_ids)}</p>`;
|
||||
}
|
||||
function renderMaritime(){
|
||||
content.innerHTML = head('台湾海峡航运与贸易通道', DATA.tabs.find(t=>t.id==='maritime').description) + `<div class="grid">${DATA.maritime.metrics.map(m=>`<div class="card kpi"><h3>${m.label}</h3><div class="value">${m.value}</div><p>${m.note}</p></div>`).join('')}</div><div style="margin-top:18px" class="grid2">${DATA.maritime.risk_types.map(r=>card(r.type,r.transmission)).join('')}</div><p class="muted">来源:${sourceLinks(DATA.maritime.source_ids)}</p>`;
|
||||
}
|
||||
function renderTrade(){
|
||||
content.innerHTML = head('美台贸易与美国成本叙事', DATA.tabs.find(t=>t.id==='trade').description) + `<div class="grid">${DATA.trade.us_taiwan.map(x=>`<div class="card kpi"><h3>${x.label}</h3><div class="value">${x.value}</div><p>${x.note||''}</p></div>`).join('')}</div><div style="margin-top:18px" class="grid2">${DATA.trade.frames.map(f=>card(f.title,f.content)).join('')}</div><p class="muted">来源:${sourceLinks(DATA.trade.source_ids)}</p>`;
|
||||
}
|
||||
function audienceCard(a){
|
||||
return `<div class="card"><h3>${a.audience_group}</h3><p><strong>反应:</strong>${a.current_reaction} <strong>类别:</strong>${a.category}</p><p><strong>关注点:</strong>${a.concerns.join('、')}</p><p><strong>可能行为:</strong>${a.likely_behavior.join('、')}</p><p><strong>竞争叙事:</strong>${a.competing_narratives.join('、')}</p><div class="tag-row"><span class="tag">${a.region}</span><span class="tag">置信度:${a.confidence}</span></div><p class="muted">${a.caveat}</p></div>`;
|
||||
}
|
||||
function renderAudience(regionSet, title, desc){
|
||||
const arr = DATA.audiences.filter(a=>regionSet.includes(a.region)).filter(matchFilter);
|
||||
content.innerHTML = head(title, desc) + (arr.length?`<div class="grid3">${arr.map(audienceCard).join('')}</div>`:'<div class="empty">没有匹配受众</div>');
|
||||
}
|
||||
function renderPlatforms(){
|
||||
const platCards = DATA.platform_observations.map(p=>`<div class="card"><h3>${p.platform}</h3><p>${p.narrative_variant}</p><p><strong>受众反应:</strong>${p.audience_reaction}</p><div class="tag-row">${p.example_keywords.map(k=>`<span class="tag">${k}</span>`).join('')}<span class="tag ${p.backlash_level==='high'?'high':p.backlash_level==='medium'?'medium':'low'}">反弹:${p.backlash_level}</span></div><p class="muted">${p.caveat}</p></div>`).join('');
|
||||
const kw = Object.entries(DATA.keywords).map(([lang,groups])=>`<div class="card"><h3>${lang}</h3>${groups.map(g=>`<p><strong>${g.category}:</strong>${g.terms.map(t=>`<span class="pill">${t}</span>`).join('')}</p>`).join('')}</div>`).join('');
|
||||
content.innerHTML = head('平台传播与关键词监测', DATA.tabs.find(t=>t.id==='platforms').description) + `<div class="grid2">${platCards}</div><div style="margin-top:18px" class="grid2">${kw}</div>`;
|
||||
}
|
||||
function renderFrames(){
|
||||
const arr = DATA.narrative_frames.filter(matchFilter);
|
||||
content.innerHTML = head('叙事框架与反叙事库', DATA.tabs.find(t=>t.id==='frames').description) + `<div class="grid2">${arr.map(f=>`<div class="card"><h3>${f.frame_name}</h3><p><strong>核心主张:</strong>${f.core_claim}</p><p><strong>支撑证据:</strong>${f.supporting_evidence.join(';')}</p><p><strong>脆弱点:</strong>${f.vulnerability}</p><p><strong>反叙事:</strong>${f.counter_frame}</p><div class="tag-row">${f.typical_trigger.map(t=>`<span class="tag">${t}</span>`).join('')}<span class="tag ${riskClass(f.risk_level)}">${f.risk_level}</span></div><p class="muted">来源:${sourceLinks(f.source_ids)}</p></div>`).join('')}</div><div style="margin-top:18px">${head('来源库', '核心事实来源与可信度。')}<div class="source-list">${DATA.sources.map(s=>`<div class="source-item"><strong>${s.name}</strong><p>${s.notes}</p><p><span class="pill">${s.type}</span><span class="pill">可信度 ${s.credibility}</span></p><a href="${s.url}" target="_blank">打开来源</a></div>`).join('')}</div></div>`;
|
||||
}
|
||||
function render(){
|
||||
const t = DATA.tabs.find(x=>x.id===activeTab);
|
||||
if(activeTab==='overview') return renderOverview();
|
||||
if(activeTab==='events') return renderEvents();
|
||||
if(activeTab==='budget') return renderBudget();
|
||||
if(activeTab==='arms') return renderArms();
|
||||
if(activeTab==='semi') return renderSemi();
|
||||
if(activeTab==='maritime') return renderMaritime();
|
||||
if(activeTab==='trade') return renderTrade();
|
||||
if(activeTab==='tw_audience') return renderAudience(['Taiwan'], '台湾内部受众反应', t.description);
|
||||
if(activeTab==='us_audience') return renderAudience(['United States'], '美国国内受众反应', t.description);
|
||||
if(activeTab==='allies') return renderAudience(['Japan','South Korea','Philippines','Australia','Global'], '亚太盟友与产业界反应', t.description);
|
||||
if(activeTab==='platforms') return renderPlatforms();
|
||||
if(activeTab==='frames') return renderFrames();
|
||||
}
|
||||
['searchBox','categoryFilter','riskFilter','regionFilter'].forEach(id=>document.getElementById(id).addEventListener('input', render));
|
||||
initFilters(); initTabs(); render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+1764
File diff suppressed because it is too large.
Load diff
+322
@@ -0,0 +1,322 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>台湾飞行部队知识数据展示平台 v3</title><style>
|
||||
:root{
|
||||
--red:#b4232d;--red2:#d94a54;--red3:#fff1f2;--red4:#7e1620;
|
||||
--bg:#f4f6f8;--white:#fff;--text:#1e2329;--muted:#667085;
|
||||
--line:#e5e7eb;--soft:#f8fafc;--green:#14804a;--amber:#b4690e;
|
||||
--shadow:0 12px 36px rgba(31,41,55,.09);
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
html,body{margin:0;min-height:100%;font-family:"Microsoft YaHei","PingFang SC","Noto Sans CJK SC",Arial,sans-serif;color:var(--text);background:var(--bg)}
|
||||
button,input,select{font:inherit}
|
||||
button{cursor:pointer}
|
||||
a{color:var(--red);text-decoration:none}
|
||||
.hidden{display:none!important}
|
||||
.app{min-height:100vh;display:flex;flex-direction:column}
|
||||
.header{height:76px;background:linear-gradient(120deg,var(--red4),var(--red));color:#fff;display:flex;align-items:center;justify-content:space-between;padding:0 28px;box-shadow:0 5px 18px rgba(126,22,32,.22);position:sticky;top:0;z-index:50}
|
||||
.brand{display:flex;align-items:center;gap:14px}
|
||||
.brand-mark{width:45px;height:45px;border:2px solid rgba(255,255,255,.72);border-radius:13px;display:grid;place-items:center;font-weight:800;font-size:21px;background:rgba(255,255,255,.1)}
|
||||
.brand h1{font-size:21px;margin:0 0 4px;letter-spacing:.5px}
|
||||
.brand p{font-size:12px;margin:0;color:rgba(255,255,255,.78)}
|
||||
.header-actions{display:flex;align-items:center;gap:10px}
|
||||
.search{position:relative}
|
||||
.search input{width:330px;border:1px solid rgba(255,255,255,.25);background:rgba(255,255,255,.13);color:#fff;border-radius:10px;padding:11px 42px 11px 14px;outline:none}
|
||||
.search input::placeholder{color:rgba(255,255,255,.72)}
|
||||
.search .icon{position:absolute;right:13px;top:10px;font-size:18px}
|
||||
.search-pop{position:absolute;right:0;top:48px;width:460px;max-height:460px;overflow:auto;background:#fff;color:var(--text);border:1px solid var(--line);border-radius:12px;box-shadow:var(--shadow);padding:7px;z-index:120}
|
||||
.search-item{display:flex;gap:10px;padding:11px;border-radius:9px;border-bottom:1px dashed #eee}
|
||||
.search-item:hover{background:var(--red3)}
|
||||
.search-kind{min-width:58px;color:var(--red);font-size:12px;font-weight:700}
|
||||
.search-item strong{display:block;font-size:14px;margin-bottom:4px}
|
||||
.search-item small{color:var(--muted);line-height:1.45}
|
||||
.btn{border:0;border-radius:9px;padding:10px 15px;font-weight:700;transition:.18s}
|
||||
.btn.primary{background:var(--red);color:#fff}
|
||||
.btn.primary:hover{background:var(--red4)}
|
||||
.btn.white{background:#fff;color:var(--red)}
|
||||
.btn.ghost{background:rgba(255,255,255,.12);color:#fff;border:1px solid rgba(255,255,255,.25)}
|
||||
.btn.light{background:var(--red3);color:var(--red)}
|
||||
.btn.line{background:#fff;color:var(--red);border:1px solid #efb7bc}
|
||||
.btn.sm{padding:7px 11px;font-size:12px}
|
||||
.tabs{height:56px;background:#fff;display:flex;align-items:end;gap:2px;padding:0 24px;border-bottom:1px solid var(--line);position:sticky;top:76px;z-index:40;overflow-x:auto}
|
||||
.tab{border:0;background:transparent;color:#4b5563;font-weight:700;padding:17px 18px 14px;white-space:nowrap;border-bottom:3px solid transparent}
|
||||
.tab:hover{color:var(--red)}
|
||||
.tab.active{color:var(--red);border-bottom-color:var(--red)}
|
||||
.main{width:min(1540px,100%);margin:auto;padding:24px 28px 54px;flex:1}
|
||||
.page{display:none}
|
||||
.page.active{display:block}
|
||||
.page-head{display:flex;justify-content:space-between;gap:18px;align-items:flex-start;margin-bottom:20px}
|
||||
.page-head h2{margin:0 0 7px;font-size:25px}
|
||||
.page-head p{margin:0;color:var(--muted);line-height:1.65}
|
||||
.page-actions{display:flex;gap:9px;flex-wrap:wrap}
|
||||
.stats{display:grid;grid-template-columns:repeat(6,1fr);gap:14px}
|
||||
.stat{background:#fff;border:1px solid var(--line);border-top:4px solid var(--red);border-radius:13px;padding:17px;box-shadow:0 5px 17px rgba(31,41,55,.04)}
|
||||
.stat .label{color:var(--muted);font-size:13px}
|
||||
.stat .num{font-size:29px;font-weight:850;margin:9px 0 3px}
|
||||
.stat .hint{font-size:12px;color:#98a2b3}
|
||||
.grid{display:grid;gap:15px}
|
||||
.grid.cols2{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.grid.cols3{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||
.grid.cols4{grid-template-columns:repeat(4,minmax(0,1fr))}
|
||||
.panel{background:#fff;border:1px solid var(--line);border-radius:14px;box-shadow:0 6px 22px rgba(31,41,55,.045);padding:18px}
|
||||
.panel-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:15px}
|
||||
.panel h3,.panel h4{margin:0}
|
||||
.panel-head p{margin:4px 0 0;color:var(--muted);font-size:12px}
|
||||
.section-title{display:flex;justify-content:space-between;align-items:end;margin:25px 0 13px}
|
||||
.section-title h3{font-size:18px;margin:0}
|
||||
.section-title span{color:var(--muted);font-size:12px}
|
||||
.entry{background:#fff;border:1px solid var(--line);border-radius:14px;padding:19px;min-height:150px;position:relative;overflow:hidden;box-shadow:0 5px 18px rgba(31,41,55,.045)}
|
||||
.entry:before{content:"";position:absolute;right:-25px;top:-35px;width:110px;height:110px;border-radius:50%;background:var(--red3)}
|
||||
.entry .letter{position:relative;width:39px;height:39px;border-radius:10px;background:var(--red);color:#fff;display:grid;place-items:center;font-weight:800;margin-bottom:16px}
|
||||
.entry strong{font-size:16px}
|
||||
.entry p{color:var(--muted);line-height:1.65;font-size:13px}
|
||||
.entry:hover{transform:translateY(-2px);box-shadow:var(--shadow);border-color:#efb7bc}
|
||||
.notice{background:linear-gradient(120deg,#fff8f8,#fff);border:1px solid #f2c6ca;border-left:4px solid var(--red);border-radius:10px;padding:14px;line-height:1.7;color:#5e3034}
|
||||
.badge,.chip{display:inline-flex;align-items:center;border-radius:999px;padding:5px 9px;font-size:12px;font-weight:700;margin:2px 4px 2px 0}
|
||||
.badge.red,.chip.red{background:var(--red3);color:var(--red)}
|
||||
.badge.green{background:#e9f8ef;color:var(--green)}
|
||||
.badge.amber{background:#fff5e6;color:var(--amber)}
|
||||
.badge.gray{background:#f1f3f5;color:#667085}
|
||||
.bar-row{display:grid;grid-template-columns:90px 1fr 35px;align-items:center;gap:10px;margin:14px 0;font-size:13px}
|
||||
.bar-track{height:9px;border-radius:8px;background:#f0f1f3;overflow:hidden}
|
||||
.bar-fill{height:100%;background:linear-gradient(90deg,var(--red),var(--red2));border-radius:8px}
|
||||
.unit-card{background:#fff;border:1px solid var(--line);border-radius:14px;padding:17px;display:flex;flex-direction:column;min-height:245px;box-shadow:0 5px 18px rgba(31,41,55,.04)}
|
||||
.unit-card:hover{border-color:#e8a2a8;box-shadow:var(--shadow);transform:translateY(-2px)}
|
||||
.unit-card .top{display:flex;justify-content:space-between;gap:12px}
|
||||
.unit-card h4{font-size:16px;margin:0 0 5px}
|
||||
.unit-card .sub{color:var(--muted);font-size:12px}
|
||||
.unit-card p{color:#555f6d;line-height:1.65;font-size:13px;flex:1}
|
||||
.unit-card .foot{display:flex;justify-content:space-between;align-items:center;margin-top:13px}
|
||||
.filters{display:grid;grid-template-columns:1.4fr repeat(4,1fr) auto;gap:10px;background:#fff;border:1px solid var(--line);border-radius:13px;padding:13px;margin-bottom:15px}
|
||||
.input,.select{width:100%;border:1px solid #d8dde4;border-radius:9px;padding:10px 11px;background:#fff;outline:none}
|
||||
.input:focus,.select:focus{border-color:var(--red);box-shadow:0 0 0 3px rgba(180,35,45,.08)}
|
||||
.view-switch{display:flex;gap:5px;background:#f5f6f8;padding:4px;border-radius:9px}
|
||||
.view-switch button{border:0;background:transparent;padding:7px 10px;border-radius:7px;color:#667085}
|
||||
.view-switch button.active{background:#fff;color:var(--red);box-shadow:0 2px 8px rgba(0,0,0,.07)}
|
||||
.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:12px;background:#fff}
|
||||
table{width:100%;border-collapse:collapse;min-width:900px}
|
||||
th{position:sticky;top:0;background:#fff5f5;color:#6e1e24;text-align:left;font-size:13px;padding:12px;border-bottom:1px solid #f1c8cc;z-index:2}
|
||||
td{font-size:13px;padding:12px;border-bottom:1px solid #edf0f2;vertical-align:top;line-height:1.55}
|
||||
tr:hover td{background:#fffafa}
|
||||
.pagination{display:flex;justify-content:center;align-items:center;gap:8px;margin-top:16px}
|
||||
.org-layout{display:grid;grid-template-columns:230px minmax(0,1fr) 305px;gap:15px}
|
||||
.side-nav,.side-info{background:#fff;border:1px solid var(--line);border-radius:13px;padding:14px;height:max-content;position:sticky;top:151px}
|
||||
.side-nav button{width:100%;border:0;background:#fff;text-align:left;padding:11px;border-radius:8px;color:#475467;font-weight:700}
|
||||
.side-nav button.active,.side-nav button:hover{background:var(--red3);color:var(--red)}
|
||||
.org-canvas{background:#fff;border:1px solid var(--line);border-radius:14px;overflow:auto;min-height:610px;padding:22px}
|
||||
.org-toolbar{display:flex;justify-content:space-between;gap:10px;align-items:center;margin-bottom:18px}
|
||||
.zoom{display:flex;gap:5px}
|
||||
.tree{--scale:1;transform:scale(var(--scale));transform-origin:top center;min-width:980px;padding:10px 35px 50px}
|
||||
.tree ul{padding-top:24px;position:relative;display:flex;justify-content:center}
|
||||
.tree li{list-style:none;text-align:center;position:relative;padding:24px 7px 0}
|
||||
.tree li:before,.tree li:after{content:"";position:absolute;top:0;width:50%;height:24px;border-top:1px solid #d8a5a9}
|
||||
.tree li:before{right:50%;border-right:1px solid #d8a5a9}
|
||||
.tree li:after{left:50%;border-left:1px solid #d8a5a9}
|
||||
.tree li:only-child:before,.tree li:only-child:after{display:none}
|
||||
.tree li:first-child:before,.tree li:last-child:after{border:0}
|
||||
.tree li:last-child:before{border-radius:0 7px 0 0}
|
||||
.tree li:first-child:after{border-radius:7px 0 0 0}
|
||||
.tree ul ul:before{content:"";position:absolute;top:0;left:50%;height:24px;border-left:1px solid #d8a5a9}
|
||||
.org-node{width:155px;min-height:62px;padding:10px 8px;border:1px solid #e4aab0;background:#fff;border-radius:10px;display:inline-flex;flex-direction:column;justify-content:center;box-shadow:0 4px 12px rgba(31,41,55,.055)}
|
||||
.org-node.root{background:var(--red);color:#fff;border-color:var(--red)}
|
||||
.org-node.branch{background:#fff2f3;color:var(--red4);font-weight:800}
|
||||
.org-node:hover{box-shadow:0 9px 23px rgba(180,35,45,.15);transform:translateY(-2px)}
|
||||
.org-node small{font-size:10px;margin-top:5px;color:#8b8f99}
|
||||
.org-node.root small{color:rgba(255,255,255,.75)}
|
||||
.kv{display:grid;grid-template-columns:86px 1fr;gap:9px;padding:10px 0;border-bottom:1px dashed #e7e8eb;font-size:13px}
|
||||
.kv .k{color:var(--muted)}
|
||||
.kv .v{font-weight:650;line-height:1.55}
|
||||
.equipment-layout{display:grid;grid-template-columns:220px minmax(0,1fr);gap:15px}
|
||||
.category-list button{width:100%;display:flex;justify-content:space-between;border:0;background:#fff;padding:11px;border-radius:8px;margin:3px 0;color:#475467}
|
||||
.category-list button.active,.category-list button:hover{background:var(--red3);color:var(--red);font-weight:700}
|
||||
.equip-card{background:#fff;border:1px solid var(--line);border-radius:13px;padding:16px;min-height:190px;display:flex;flex-direction:column}
|
||||
.equip-card h4{margin:0 0 5px}
|
||||
.equip-card p{font-size:13px;color:var(--muted);line-height:1.6;flex:1}
|
||||
.flow{display:flex;align-items:stretch;gap:9px;overflow:auto;padding:5px 0 15px}
|
||||
.flow-step{min-width:150px;background:#fff;border:1px solid #efb9be;border-radius:12px;padding:14px;position:relative}
|
||||
.flow-step:not(:last-child):after{content:"›";position:absolute;right:-10px;top:40%;font-size:25px;color:var(--red)}
|
||||
.flow-step .no{width:26px;height:26px;border-radius:50%;background:var(--red);color:#fff;display:grid;place-items:center;font-size:12px;font-weight:800}
|
||||
.flow-step h4{margin:10px 0 5px}
|
||||
.flow-step p{font-size:12px;color:var(--muted);line-height:1.55}
|
||||
.lane{display:grid;grid-template-columns:140px 1fr;gap:12px;align-items:start;margin-bottom:12px}
|
||||
.lane-title{background:var(--red);color:#fff;border-radius:10px;padding:14px;font-weight:800}
|
||||
.lane-items{display:flex;gap:9px;flex-wrap:wrap}
|
||||
.lane-item{background:#fff;border:1px solid var(--line);border-radius:10px;padding:12px;min-width:150px;flex:1}
|
||||
.industry-stack{display:grid;gap:12px}
|
||||
.industry-layer{background:#fff;border:1px solid var(--line);border-left:5px solid var(--red);border-radius:12px;padding:15px;display:grid;grid-template-columns:190px 1fr;gap:14px}
|
||||
.risk-card{background:#fff;border:1px solid var(--line);border-radius:12px;padding:15px}
|
||||
.risk-card h4{margin:0 0 8px;color:var(--red4)}
|
||||
.timeline{position:relative;padding-left:27px}
|
||||
.timeline:before{content:"";position:absolute;left:8px;top:7px;bottom:5px;width:2px;background:#e6b3b8}
|
||||
.event{position:relative;background:#fff;border:1px solid var(--line);border-radius:11px;padding:14px;margin-bottom:12px}
|
||||
.event:before{content:"";position:absolute;left:-25px;top:17px;width:12px;height:12px;border-radius:50%;background:var(--red);border:3px solid #ffd8dc}
|
||||
.event .date{font-size:12px;color:var(--red);font-weight:800}
|
||||
.event h4{margin:5px 0}
|
||||
.event p{margin:0;color:var(--muted);font-size:13px;line-height:1.6}
|
||||
.source-layout{display:grid;grid-template-columns:1.15fr .85fr;gap:15px}
|
||||
.source-card{border:1px solid var(--line);background:#fff;border-radius:11px;padding:14px;margin-bottom:10px}
|
||||
.source-card:hover{border-color:#e5a4aa;background:#fffafa}
|
||||
.source-card h4{margin:0 0 7px}
|
||||
.source-card p{margin:0;color:var(--muted);font-size:13px;line-height:1.55}
|
||||
.empty{padding:40px;text-align:center;color:var(--muted)}
|
||||
.modal,.drawer,.detail,.query-panel{position:fixed;inset:0}.detail{z-index:200}.drawer{z-index:320}.modal{z-index:420}.query-panel{z-index:500}
|
||||
.backdrop{position:absolute;inset:0;background:rgba(20,24,31,.52);backdrop-filter:blur(2px)}
|
||||
.modal-card{position:relative;width:min(820px,calc(100% - 34px));max-height:86vh;overflow:auto;margin:7vh auto;background:#fff;border-radius:16px;box-shadow:0 24px 80px rgba(0,0,0,.24);padding:26px}
|
||||
.close{position:absolute;right:15px;top:14px;border:0;width:34px;height:34px;border-radius:9px;background:#f2f4f7;font-size:21px;color:#667085}
|
||||
.drawer-card{position:absolute;right:0;top:0;height:100%;width:min(650px,92vw);background:#fff;box-shadow:-12px 0 45px rgba(0,0,0,.2);overflow:auto;padding:68px 25px 30px}
|
||||
.drawer-head{position:absolute;right:0;top:0;width:min(650px,92vw);height:58px;background:#fff;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 20px;z-index:3}
|
||||
.detail{background:#f4f6f8;overflow:auto}
|
||||
.detail-top{height:72px;background:var(--red4);color:#fff;display:flex;align-items:center;justify-content:space-between;padding:0 25px;position:sticky;top:0;z-index:3}
|
||||
.detail-body{width:min(1320px,100%);margin:auto;padding:24px}
|
||||
.detail-hero{background:linear-gradient(120deg,var(--red),#d84955);color:#fff;border-radius:16px;padding:25px;display:grid;grid-template-columns:1fr 330px;gap:20px;box-shadow:var(--shadow)}
|
||||
.detail-hero h2{font-size:27px;margin:0 0 9px}
|
||||
.detail-hero p{line-height:1.7;color:rgba(255,255,255,.86)}
|
||||
.detail-summary{background:rgba(255,255,255,.13);border:1px solid rgba(255,255,255,.2);border-radius:12px;padding:13px}
|
||||
.detail-nav{display:flex;gap:4px;background:#fff;border:1px solid var(--line);border-radius:12px;padding:6px;margin:15px 0;position:sticky;top:84px;z-index:2;overflow:auto}
|
||||
.detail-nav button{border:0;background:transparent;padding:10px 14px;border-radius:8px;font-weight:700;color:#667085;white-space:nowrap}
|
||||
.detail-nav button.active{background:var(--red3);color:var(--red)}
|
||||
.detail-section{scroll-margin-top:150px;margin-bottom:15px}
|
||||
.detail-section h3{border-left:4px solid var(--red);padding-left:10px}
|
||||
.rich{line-height:1.82;color:#475467}
|
||||
.query-card{position:relative;width:min(1180px,calc(100% - 30px));height:88vh;margin:6vh auto;background:#fff;border-radius:16px;box-shadow:0 24px 80px rgba(0,0,0,.24);display:grid;grid-template-columns:310px 1fr;overflow:hidden}
|
||||
.query-form{background:#fff8f8;border-right:1px solid #f2c9cd;padding:25px}
|
||||
.query-result{padding:25px;overflow:auto}
|
||||
.query-row{border:1px solid var(--line);border-radius:10px;padding:12px;margin-bottom:9px}
|
||||
.query-row:hover{border-color:#e4a3aa;background:#fffafa}
|
||||
.json{white-space:pre-wrap;word-break:break-word;background:#1f242b;color:#f5f7fa;padding:16px;border-radius:10px;font:12px/1.65 Consolas,monospace}
|
||||
.footer{background:#fff;border-top:1px solid var(--line);color:#777f8b;padding:16px 28px;display:flex;justify-content:space-between;font-size:12px}
|
||||
.mt{margin-top:15px}.mb{margin-bottom:15px}
|
||||
@media(max-width:1180px){.stats{grid-template-columns:repeat(3,1fr)}.org-layout{grid-template-columns:200px 1fr}.side-info{display:none}.grid.cols4{grid-template-columns:repeat(2,1fr)}}
|
||||
@media(max-width:820px){.header{height:auto;padding:13px 16px;align-items:flex-start}.brand p{display:none}.header-actions{display:none}.tabs{top:69px;padding-left:8px}.main{padding:17px 12px 45px}.stats{grid-template-columns:repeat(2,1fr)}.grid.cols2,.grid.cols3,.grid.cols4{grid-template-columns:1fr}.filters{grid-template-columns:1fr 1fr}.org-layout,.equipment-layout,.source-layout{grid-template-columns:1fr}.side-nav{position:static}.org-canvas{min-height:500px}.detail-hero{grid-template-columns:1fr}.query-card{grid-template-columns:1fr;height:94vh;margin:3vh auto}.query-form{border-right:0;border-bottom:1px solid #f2c9cd}.footer{display:block;line-height:1.8}}
|
||||
|
||||
.knowledge-layout{display:grid;grid-template-columns:230px minmax(0,1fr);gap:16px}
|
||||
.knowledge-side{background:#fff;border:1px solid var(--line);border-radius:14px;padding:14px;height:max-content;position:sticky;top:151px}
|
||||
.knowledge-side button{width:100%;border:0;background:#fff;text-align:left;padding:10px 11px;border-radius:8px;color:#475467;display:flex;justify-content:space-between;gap:8px}
|
||||
.knowledge-side button:hover,.knowledge-side button.active{background:var(--red3);color:var(--red);font-weight:750}
|
||||
.knowledge-card{background:#fff;border:1px solid var(--line);border-radius:14px;padding:18px;display:flex;flex-direction:column;min-height:220px;box-shadow:0 5px 18px rgba(31,41,55,.04)}
|
||||
.knowledge-card:hover{border-color:#e5a3a9;box-shadow:var(--shadow);transform:translateY(-2px)}
|
||||
.knowledge-card h4{margin:0 0 8px;font-size:16px}.knowledge-card p{color:var(--muted);line-height:1.7;font-size:13px;flex:1}
|
||||
.knowledge-meta{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0}.knowledge-path{font:11px Consolas,monospace;color:#8b929d;word-break:break-all;margin-top:8px}
|
||||
.reader-layout{display:grid;grid-template-columns:245px minmax(0,1fr);gap:17px;align-items:start}
|
||||
.reader-toc{background:#fff;border:1px solid var(--line);border-radius:13px;padding:13px;position:sticky;top:95px;max-height:calc(100vh - 120px);overflow:auto}
|
||||
.reader-toc h4{margin:4px 8px 10px}.reader-toc button{width:100%;border:0;background:#fff;text-align:left;padding:9px 10px;border-radius:7px;color:#596273;font-size:13px;line-height:1.45}
|
||||
.reader-toc button:hover,.reader-toc button.active{background:var(--red3);color:var(--red);font-weight:750}
|
||||
.reader-main{min-width:0}.md-section{background:#fff;border:1px solid var(--line);border-radius:14px;padding:22px 25px;margin-bottom:15px;scroll-margin-top:95px;box-shadow:0 4px 16px rgba(31,41,55,.035)}
|
||||
.md-section>h2{margin:0 -25px 19px;padding:0 25px 14px;border-bottom:1px solid #eee;font-size:20px;color:#6f1820}
|
||||
.md-body{font-size:14px;line-height:1.92;color:#394150}.md-body h1,.md-body h2{color:#741923}.md-body h3{margin-top:25px;color:#8f2029;font-size:17px}.md-body h4{color:#333b46}
|
||||
.md-body p{margin:10px 0}.md-body ul,.md-body ol{padding-left:25px}.md-body li{margin:5px 0}.md-body blockquote{margin:14px 0;padding:12px 15px;border-left:4px solid var(--red);background:#fff6f7;color:#5c3437;border-radius:0 8px 8px 0}
|
||||
.md-body table{min-width:0;width:100%;display:table;margin:15px 0;border:1px solid var(--line);border-radius:9px;overflow:hidden}.md-body th{position:static;background:#fff1f2;color:#701920}.md-body td,.md-body th{border:1px solid #eceff2;padding:9px 11px}
|
||||
.md-body pre{background:#20252c;color:#f5f6f7;border-radius:10px;padding:15px;overflow:auto;line-height:1.65}.md-body code{background:#f1f2f4;border-radius:5px;padding:2px 5px;font-family:Consolas,monospace;color:#8d2630}.md-body pre code{background:transparent;color:inherit;padding:0}
|
||||
.md-body hr{border:0;border-top:1px solid #eceef1;margin:22px 0}.md-body strong{color:#252a31}.inline-ref,.inline-doc{border:0;border-radius:5px;background:#fff0f1;color:var(--red);padding:2px 6px;font:inherit;cursor:pointer}.inline-doc{font-family:Consolas,monospace;word-break:break-all}
|
||||
.record-hero{background:linear-gradient(120deg,#fff5f6,#fff);border:1px solid #efc5c9;border-left:5px solid var(--red);border-radius:13px;padding:18px;margin:12px 0 17px}.record-hero h2{margin:0 0 8px}.record-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:13px}.record-group{background:#fff;border:1px solid var(--line);border-radius:12px;padding:15px}.record-group h3{margin:0 0 12px;color:#751b23}.record-field{display:grid;grid-template-columns:125px 1fr;gap:10px;padding:10px 0;border-bottom:1px dashed #e7e9ed;font-size:13px;line-height:1.65}.record-field:last-child{border-bottom:0}.record-field .label{color:#737b88}.record-field .value{font-weight:600;word-break:break-word}
|
||||
.related-docs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.related-doc{border:1px solid #ecd1d4;background:#fffafa;border-radius:10px;padding:12px;cursor:pointer}.related-doc:hover{border-color:var(--red)}.related-doc strong{display:block;margin-bottom:6px;color:#741b23}.related-doc p{margin:0;color:#69717e;font-size:12px;line-height:1.55}
|
||||
.field-list{display:grid;gap:9px}.field-item{border:1px solid var(--line);border-radius:10px;padding:11px;background:#fff}.field-item strong{display:block;color:#7a1e26;margin-bottom:5px}.human-table{width:100%;min-width:0}.human-table th{position:static;width:170px}.technical-details{margin-top:15px;border:1px solid #e1e4e8;border-radius:10px;background:#fafbfc;padding:10px 13px}.technical-details summary{cursor:pointer;color:#666f7c;font-weight:700}.technical-details table{margin-top:10px}
|
||||
.knowledge-preview{background:#fff;border:1px solid var(--line);border-radius:13px;padding:16px;margin-top:14px}.knowledge-preview h3{margin-top:0}.knowledge-preview .md-body{max-height:470px;overflow:auto;padding-right:6px}
|
||||
.source-ref-btn{display:inline-flex;align-items:center;gap:5px;border:1px solid #e6aeb3;border-radius:7px;background:#fff4f5;color:var(--red);padding:3px 8px;margin:1px 3px;font:inherit;font-size:12px;font-weight:700;vertical-align:middle}.source-ref-btn:hover{background:var(--red);color:#fff}.source-ref-btn:before{content:"源";display:grid;place-items:center;width:18px;height:18px;border-radius:5px;background:rgba(180,35,45,.12);font-size:10px}.source-ref-btn:hover:before{background:rgba(255,255,255,.2)}
|
||||
.missing-source{border-style:dashed;color:#9a6700;background:#fff8e6}.missing-source:before{content:"待";background:#fff0c2}
|
||||
.org-ref-btn{display:inline-flex;align-items:center;border:1px solid #d7dce2;border-radius:7px;background:#f7f8fa;color:#344054;padding:3px 8px;margin:1px 3px;font:inherit;font-size:12px;font-weight:700}.org-ref-btn:hover{border-color:var(--red);color:var(--red);background:#fff5f6}
|
||||
.unit-ref-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px;margin-top:5px}.unit-ref-card{border:1px solid #ead0d3;border-radius:10px;background:#fffafa;padding:10px 11px;text-align:left;color:#303640;min-width:0}.unit-ref-card:hover{border-color:var(--red);box-shadow:0 5px 15px rgba(180,35,45,.1)}.unit-ref-card strong{display:block;color:#771b24;margin-bottom:4px;white-space:normal}.unit-ref-card small{display:block;color:#747c89;line-height:1.45;white-space:normal}.unit-ref-card.static{cursor:default}.unit-ref-card.static:hover{box-shadow:none;border-color:#ead0d3}
|
||||
.object-value-list{display:grid;gap:7px}.object-value-item{border:1px solid #e2e5e9;border-radius:8px;background:#fafbfc;padding:8px 10px}.object-value-item strong{display:block;color:#771b24;margin-bottom:3px}.object-value-item span{display:block;color:#69717e;font-size:12px;line-height:1.5}
|
||||
@media(max-width:760px){.unit-ref-grid{grid-template-columns:1fr}}
|
||||
@media(max-width:900px){.knowledge-layout,.reader-layout{grid-template-columns:1fr}.knowledge-side,.reader-toc{position:static;max-height:none}.record-grid,.related-docs{grid-template-columns:1fr}.md-section{padding:17px}.md-section>h2{margin-left:-17px;margin-right:-17px;padding-left:17px;padding-right:17px}}
|
||||
|
||||
.offline-source-panel{border:1px solid #efc1c5;background:#fffafa;border-radius:13px;padding:16px;margin:14px 0}
|
||||
.offline-source-panel h3{margin:0 0 10px;color:var(--red4)}
|
||||
.offline-status{display:inline-flex;align-items:center;gap:6px;border-radius:999px;padding:5px 10px;background:#f2f4f7;color:#475467;font-size:12px;font-weight:700}
|
||||
.offline-status.available{background:#e9f8ef;color:#14804a}.offline-status.context{background:#fff3e8;color:#a55a08}
|
||||
.citation-context{border:1px solid var(--line);border-left:4px solid var(--red);background:#fff;border-radius:10px;padding:13px;margin:10px 0;cursor:pointer}
|
||||
.citation-context:hover{border-color:#dfa0a6;background:#fff8f8}.citation-context h4{margin:0 0 5px}.citation-context p{margin:0;color:#667085;line-height:1.7;font-size:13px}
|
||||
.offline-link-disabled{color:#667085;border-bottom:1px dotted #98a2b3;cursor:default}.offline-reference-note{font-size:12px;color:#667085;margin-top:6px}
|
||||
.structured-mention{display:grid;grid-template-columns:92px 1fr;gap:10px;border:1px solid var(--line);border-radius:10px;padding:12px;margin:9px 0;background:#fff}
|
||||
.structured-mention .dataset{color:var(--red);font-weight:800;font-size:12px}.structured-mention strong{display:block;margin-bottom:4px}.structured-mention p{margin:0;color:#667085;font-size:13px;line-height:1.55}
|
||||
</style></head><body>
|
||||
<div class="app">
|
||||
<header class="header"><div class="brand"><div class="brand-mark">航</div><div><h1>台湾飞行部队知识数据展示平台</h1><p>结构化数据检索 + Markdown全文 + 可点击来源与单位关系</p></div></div><div class="header-actions"><div class="search"><input id="globalSearch" placeholder="查询单位、装备、专题正文或来源"><span class="icon">⌕</span><div id="searchPop" class="search-pop hidden"></div></div><button class="btn white" data-action="open-query">交互查询</button><button class="btn ghost" data-action="reset">重置</button></div></header>
|
||||
<nav class="tabs" id="tabs"><button class="tab active" data-tab="overview">总览</button><button class="tab" data-tab="organization">组织机构</button><button class="tab" data-tab="units">单位与兵力</button><button class="tab" data-tab="equipment">装备体系</button><button class="tab" data-tab="training">训练与保障</button><button class="tab" data-tab="industry">工业链与外部依赖</button><button class="tab" data-tab="safety">飞安与风险治理</button><button class="tab" data-tab="timeline">时间线与来源</button><button class="tab" data-tab="knowledge">知识专题库</button></nav>
|
||||
<main class="main"><section id="page-overview" class="page active"></section><section id="page-organization" class="page"></section><section id="page-units" class="page"></section><section id="page-equipment" class="page"></section><section id="page-training" class="page"></section><section id="page-industry" class="page"></section><section id="page-safety" class="page"></section><section id="page-timeline" class="page"></section><section id="page-knowledge" class="page"></section></main>
|
||||
<footer class="footer"><span>单文件离线原型 v3.1 · Markdown全文与来源链接修复版</span><span>公开资料边界:不展示实时战备、人员员额、可飞数量、弹药库存和内部设施</span></footer></div>
|
||||
<div id="modal" class="modal hidden"><div class="backdrop" data-action="close-modal"></div><div class="modal-card"><button class="close" data-action="close-modal">×</button><div id="modalBody"></div></div></div>
|
||||
<div id="drawer" class="drawer hidden"><div class="backdrop" data-action="close-drawer"></div><div class="drawer-head"><strong id="drawerTitle">详情</strong><button class="close" style="position:static" data-action="close-drawer">×</button></div><div class="drawer-card" id="drawerBody"></div></div>
|
||||
<div id="detail" class="detail hidden"></div>
|
||||
<div id="queryPanel" class="query-panel hidden"><div class="backdrop" data-action="close-query"></div><div class="query-card"><button class="close" data-action="close-query">×</button><div class="query-form" id="queryForm"></div><div class="query-result" id="queryResult"></div></div></div>
|
||||
<script>const DATA={"meta":{"title":"台湾飞行部队知识数据展示平台","version":"原型版 3.2(离线来源内容版)","updated":"2026-06-23","notice":"基于公开资料构建;单位级人员、飞机可用数量及实时战备状态未公开时均不作推断。","offline":true},"units":[{"profile_id":"UFP-001","organization_id":"ORG-AF-SONGSHAN","name":"空军松山基地指挥部","path":"entities/units/air_force/songshan_base_command.md","type":"unit_profile","priority":"P1","topic_group":"unit_force_profiles","service":"air_force","organization_type":"base_command","parent_id":"ORG-AF-HQ","status":"CURRENT_CONFIRMED","confidence":"A","public_location":"台北松山地区(公开基地层级)","summary":"松山基地指挥部是空军特种运输、行政航空和首都地区基地运行的公开组织节点,内部同时包含飞行、修护补给和基地勤务功能。","mission_roles":["特种/行政运输","专机与公务航空保障","基地运行与军民航协调"],"platforms":["B-737-800","Fokker 50","Beech 1900等公开特种运输平台"],"force_structure":"基地指挥部级;公开内部要素包括特种运输队、修护补给队和基地勤务队。飞行单位规模和机组数量未公开。","personnel_domains":["特种运输飞行员与机组","专机任务与服务人员","机务与航电人员","航管/基地勤务/消防人员"],"training_profile":"执行机型换装、专机程序、仪表飞行、复杂空域和应急训练;具体课目与资格数量未公开。","support_profile":"修护补给队承担机务与补给,基地勤务队承担场站运行;涉及军民共用机场协调。","quantity_reference":"官方沿革明确2000年B-737-800成军;其他平台在官网公开列示。当前各型机确切数量和可用率不公开。","history":"由松山站、供应分队、机场勤务中队和基地大队等单位演变,1966年扩编为松山基地指挥部。","source_ids":["AF-SONGSHAN","AF-SPECIAL-AIRCRAFT"],"relations":["ORG-AF-SONGSHAN-SPECIAL-TRANSPORT","ORG-AF-SONGSHAN-MAINT","ORG-AF-SONGSHAN-BASE-SERVICE"],"force_level":"基地指挥部级","readiness_statement":"公开资料可确认单位、平台或任务存在,但不公开实时战备等级、可飞数量和当日人员状态。","notes":"","registry_status":"CURRENT_CONFIRMED","registry_confidence":"A","last_verified":"2026-06-23","unit_personnel_strength":"NOT_PUBLIC","unit_aircraft_strength":"NOT_PUBLIC_OR_NOT_STABLE","commander_field":"不写入静态档案;需查询单位官网最新公开信息","do_not_infer":["实时可飞数量或妥善率","人员实际员额、值班名单或资格分布","弹药库存和挂载数量","飞行频率、值班节奏和临时部署","基地内部设施、机堡位置和警卫布置"]},{"profile_id":"UFP-002","organization_id":"ORG-AF-SONGSHAN-SPECIAL-TRANSPORT","name":"空军松山基地指挥部特种运输队","path":"entities/units/air_force/songshan_special_transport_unit.md","type":"unit_profile","priority":"P2","topic_group":"unit_force_profiles","service":"air_force","organization_type":"special_transport_unit","parent_id":"ORG-AF-SONGSHAN","status":"CURRENT_PROBABLE","confidence":"B","public_location":"台北松山地区(公开基地层级)","summary":"特种运输队是松山基地指挥部内承担专机与行政运输的飞行要素,其档案重点是任务机组、平台构成和特殊服务程序,而不是推断高层行程。","mission_roles":["行政运输","专机运输","紧急或公务航空支援"],"platforms":["B-737-800","Fokker 50","Beech 1900等"],"force_structure":"队级飞行单位;上级为松山基地指挥部。现行完整内部机组编制和飞机分配未公开。","personnel_domains":["固定翼飞行员","任务机组与客舱服务","任务规划","机务与航电专业"],"training_profile":"机型换装、仪表飞行、机场程序、紧急程序和任务服务标准化。","support_profile":"依托所属联队的修护补给、基地勤务、航管气象和武器保障;单位级确切班组与员额未公开。","quantity_reference":"单位级飞机编配数、可飞数和飞行员员额未公开;仅确认机型/任务归属,不从联队总量反推。","history":"其前身与松山基地历次专机/运输编组有关,现行正式名称依据公开组织资料为较高可信。","source_ids":["AF-SONGSHAN","AF-SPECIAL-AIRCRAFT"],"relations":["ORG-AF-SONGSHAN"],"force_level":"special_transport_unit","readiness_statement":"公开资料可确认单位、平台或任务存在,但不公开实时战备等级、可飞数量和当日人员状态。","notes":"","registry_status":"CURRENT_PROBABLE","registry_confidence":"B","last_verified":"2026-06-23","unit_personnel_strength":"NOT_PUBLIC","unit_aircraft_strength":"NOT_PUBLIC_OR_NOT_STABLE","commander_field":"不写入静态档案;需查询单位官网最新公开信息","do_not_infer":["实时可飞数量或妥善率","人员实际Line truncated
|
||||
(()=>{
|
||||
'use strict';
|
||||
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
||||
const esc=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));
|
||||
const arr=v=>Array.isArray(v)?v:(v?String(v).split(/;|;|、/).map(x=>x.trim()).filter(Boolean):[]);
|
||||
const uniq=a=>[...new Set(a.filter(Boolean))];
|
||||
const clip=(v,n=110)=>String(v||'').length>n?String(v).slice(0,n)+'…':String(v||'');
|
||||
const labels={service:{air_force:'空军',army:'陆军',navy:'海军',civil:'民政航空',other:'其他'},status:{CURRENT_CONFIRMED:'现行确认',CURRENT_PROBABLE:'现行较高可信',CURRENT_CONFIRMED_OR_TRANSITIONING:'现行/转型中',FIELD_CONFIRMED:'现役确认',FUNCTION_CONFIRMED:'功能确认',FUNCTION_INFERRED:'功能推定',PROCUREMENT_TRANSITIONING:'采购转型中',PROCUREMENT_CONFIRMED:'采购确认',PROCUREMENT_PACKAGE_CONFIRMED:'采购包确认',CURRENT_ROLE_CONFIRMED:'岗位确认',CURRENT_USE_CONFIRMED:'使用确认',TRAINING_FUNCTION_CONFIRMED:'训练功能确认',TRAINING_PIPELINE_INFERRED:'训练链推定',ORGANIZATION_UNRESOLVED:'组织待核',CURRENT_CONFIRMED_FUNCTION:'现行功能确认',HISTORICAL_BASELINE:'历史基线',NOT_PUBLIC:'未公开',NOT_PUBLIC_OR_NOT_STABLE:'未公开或非稳定口径',OPEN_SOURCE_LIMITED:'公开资料有限',PARTIALLY_COMPLETE:'部分完整',COMPLETED:'已完成',ANALYTICAL_ASSESSMENT:'分析评估',HIGH_EXTERNAL_DEPENDENCY:'外部依赖较高',OEM_AUTHORIZED_FMS_CONTROLLED:'原厂授权/军售管制',FMS_CONTROLLED:'军售管制',DOMESTIC_INTEGRATOR:'国内系统整合',DOMESTIC_DESIGN_AND_INTEGRATION:'国内设计与整合',JOINT_DEVELOPMENT_EXTERNAL_COMPONENTS:'合作研制/含外部部件',JOINT_OR_FOREIGN_CORE_DEPENDENCY:'合作或外部核心依赖',MIXED_UNRESOLVED:'混合/待核'},category:{FA:'飞行事故',SI:'严重征候',NI:'近失事件',GS:'地面安全',AN:'航管与导航',MQ:'维修质量',US:'无人航空安全',HR:'危险源报告',SAR:'搜救事件'}};
|
||||
const FIELD_LABELS={profile_id:'档案编号',organization_id:'组织编号',name:'名称',name_zh:'名称',path:'知识文件路径',type:'类型',priority:'优先级',topic_group:'主题分组',service:'军种/系统',organization_type:'组织类型',parent_id:'上级组织编号',status:'状态',confidence:'可信度',public_location:'公开驻地',summary:'摘要',mission_roles:'主要任务',platforms:'平台与系统',force_structure:'兵力结构',personnel_domains:'人员专业',training_profile:'训练与资格',support_profile:'维修保障',quantity_reference:'数量口径',history:'沿革',source_ids:'来源编号',relations:'关联组织',force_level:'单位层级',readiness_statement:'战备信息边界',notes:'备注',registry_status:'登记状态',registry_confidence:'登记可信度',last_verified:'最后核验',unit_personnel_strength:'人员数量',unit_aircraft_strength:'飞机数量',commander_field:'主官字段',do_not_infer:'禁止推断',organization:'单位/机构',category:'类别',evidence:'公开证据',training_stage:'训练阶段',instructor_requirement:'教员要求',configuration_status:'构型状态',delivery_status:'交付/使用状态',platform_or_role:'平台或任务',platform_family:'平台族',level:'维修层级',task_family:'任务类别',responsible_entity:'责任单位',key_outputs:'主要输出',quality_gate:'质量关口',technical_dependency:'技术依赖',node_type:'节点类型',capabilities:'能力范围',maturity:'成熟度',foreign_interface:'国外接口',platform_or_system:'平台或系统',dimension:'依赖维度',domestic_capability:'国内能力',foreign_dependency:'外部依赖',mitigation:'缓解/自主化措施',unresolved:'待核问题',risk:'风险描述',examples:'表现或示例',controls:'控制措施',hfacs_level:'HFACS层级',stage:'治理阶段',owner:'责任主体',inputs:'输入',outputs:'输出',date:'日期',platform:'平台',severity:'严重度',outcome:'结果',grounding:'停飞/限制',return_to_flight:'复飞状态',cause_status:'原因状态',title:'标题',usage:'主要用途',url:'网址',verified:'核验日期'};
|
||||
const state={tab:'overview',unitView:'cards',unitPage:1,unitSize:12,unitFilters:{q:'',service:'全部',level:'全部',location:'全部',status:'全部'},equipCat:'全部',orgService:'air_force',orgZoom:1,sourceQ:'',knowledgeCategory:'全部',knowledgeQ:'',knowledgePage:1,knowledgeSize:15};
|
||||
const sourceMap=Object.fromEntries(DATA.sources.map(x=>[x.source_id,x]));const sourceLocalMap=SOURCE_LOCAL||{};
|
||||
const orgMap=Object.fromEntries(DATA.organizations.map(x=>[x.organization_id,x]));
|
||||
const unitMap=Object.fromEntries(DATA.units.map(x=>[x.organization_id,x]));
|
||||
const knowledgeMap=Object.fromEntries(KNOWLEDGE.map(x=>[x.path,x]));
|
||||
const status=v=>labels.status[v]||v||'待核'; const service=v=>labels.service[v]||v||'其他';
|
||||
const badge=(v,kind='status')=>{const t=kind==='confidence'?`可信度 ${v||'待核'}`:status(v);let c=/确认|完成|现役/.test(t)?'green':(/待核|未公开|推定|有限/.test(t)?'amber':'red');return `<span class="badge ${c}">${esc(t)}</span>`};
|
||||
const chips=(xs,limit=8)=>arr(xs).slice(0,limit).map(x=>`<span class="chip red">${esc(x)}</span>`).join('');
|
||||
const kv=(k,v)=>`<div class="kv"><span class="k">${esc(k)}</span><span class="v">${v}</span></div>`;
|
||||
const sourcePrefixes=new Set(Object.keys(sourceMap).map(id=>String(id).split('-')[0]));
|
||||
const sourceButton=id=>sourceMap[id]?`<button type="button" class="source-ref-btn" data-action="open-source" data-id="${esc(id)}" title="查看来源详情">${esc(id)}</button>`:`<button type="button" class="source-ref-btn missing-source" data-action="missing-source" data-id="${esc(id)}" title="来源索引中暂未匹配">${esc(id)} · 待补来源</button>`;
|
||||
const unitRefInfo=item=>{if(item===null||item===undefined)return null;let id='',name='',meta='';if(typeof item==='object'){id=item.organization_id||item.org_id||item.id||'';name=item.name||item.name_zh||item.organization_name||'';meta=item.relationship||item.relation||item.status||''}else{const raw=String(item).trim();id=(unitMap[raw]||orgMap[raw])?raw:'';name=unitMap[raw]?.name||orgMap[raw]?.name_zh||raw}if(id){name=name||unitMap[id]?.name||orgMap[id]?.name_zh||id;meta=meta||unitMap[id]?.force_level||orgMap[id]?.organization_type||'关联单位'}return{name:name||'未命名单位',id,meta}};
|
||||
const renderUnitRefs=value=>{const items=arr(value).map(unitRefInfo).filter(Boolean);if(!items.length)return '待核';return `<div class="unit-ref-grid">${items.map(x=>{const action=x.id?(unitMap[x.id]?'open-unit':'open-org'):'';return action?`<button type="button" class="unit-ref-card" data-action="${action}" data-id="${esc(x.id)}"><strong>${esc(x.name)}</strong><small>${esc(x.meta||x.id)}</small></button>`:`<div class="unit-ref-card static"><strong>${esc(x.name)}</strong><small>${esc(x.meta||'公开关联单位')}</small></div>`}).join('')}</div>`};
|
||||
const objectLabel=o=>o?.name||o?.name_zh||o?.title||o?.organization||o?.platform_or_system||o?.platform_or_role||o?.organization_id||o?.id||'结构化对象';
|
||||
const objectSummary=o=>Object.entries(o||{}).filter(([k,v])=>!['name','name_zh','title','organization','platform_or_system','platform_or_role'].includes(k)&&v!==null&&v!==''&&typeof v!=='object').slice(0,3).map(([k,v])=>`${FIELD_LABELS[k]||k}:${String(v)}`).join(';');
|
||||
const humanValue=(k,v)=>{if(v===null||v===undefined||v==='')return '未提供/待核';if(k==='source_ids')return arr(v).map(id=>sourceButton(String(id))).join(' ');if(['related_units','units_public','relations'].includes(k))return renderUnitRefs(v);if(Array.isArray(v)){if(!v.length)return '无';if(v.some(x=>x&&typeof x==='object'))return `<div class="object-value-list">${v.map(x=>typeof x==='object'?`<div class="object-value-item"><strong>${esc(objectLabel(x))}</strong><span>${esc(objectSummary(x)||'结构化关联对象')}</span></div>`:`<span class="chip red">${esc(x)}</span>`).join('')}</div>`;return chips(v,30)}if(typeof v==='object')return `<div class="object-value-list">${Object.entries(v).map(([a,b])=>`<div class="object-value-item"><strong>${esc(FIELD_LABELS[a]||a)}</strong><span>${esc(typeof b==='object'?JSON.stringify(b):String(b))}</span></div>`).join('')}</div>`;if(k==='service')return esc(service(v));if(/status/.test(k))return badge(v);if(k==='confidence')return badge(v,'confidence');return esc(String(v));};
|
||||
const looksLikeSourceId=id=>/^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/.test(id)&&sourcePrefixes.has(id.split('-')[0]);
|
||||
function enrichKnowledgeHtml(raw){const box=document.createElement('div');box.innerHTML=raw||'';
|
||||
box.querySelectorAll('[data-source-id]').forEach(n=>{const id=n.getAttribute('data-source-id');n.outerHTML=sourceButton(id)});
|
||||
box.querySelectorAll('[data-knowledge-path]').forEach(n=>{const p=n.getAttribute('data-knowledge-path'),label=n.textContent.trim()||knowledgeMap[p]?.title||p;n.outerHTML=knowledgeMap[p]?`<button type="button" class="org-ref-btn" data-action="open-knowledge" data-path="${esc(p)}">${esc(label)}</button>`:`<span class="offline-link-disabled">${esc(label)}</span>`});
|
||||
box.querySelectorAll('a').forEach(a=>{const label=a.textContent.trim()||'外部资料';a.outerHTML=`<span class="offline-link-disabled" title="离线部署未收录该外部页面内容">${esc(label)}</span>`});
|
||||
box.querySelectorAll('code').forEach(code=>{const id=code.textContent.trim();if(sourceMap[id]||looksLikeSourceId(id)){code.outerHTML=sourceButton(id)}else if(unitMap[id]){code.outerHTML=`<button type="button" class="org-ref-btn" data-action="open-unit" data-id="${esc(id)}">${esc(unitMap[id].name||id)}</button>`}else if(orgMap[id]){code.outerHTML=`<button type="button" class="org-ref-btn" data-action="open-org" data-id="${esc(id)}">${esc(orgMap[id].name_zh||id)}</button>`}});
|
||||
const walker=document.createTreeWalker(box,NodeFilter.SHOW_TEXT);const nodes=[];while(walker.nextNode())nodes.push(walker.currentNode);nodes.forEach(node=>{if(node.parentElement?.closest('button,script,style,code'))return;const text=node.nodeValue||'';const re=/\[([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)\]/g;if(!re.test(text))return;re.lastIndex=0;const frag=document.createDocumentFragment();let last=0,m;while((m=re.exec(text))){frag.append(document.createTextNode(text.slice(last,m.index)));const id=m[1];if(sourceMap[id]||looksLikeSourceId(id)){const wrap=document.createElement('span');wrap.innerHTML=sourceButton(id);frag.append(wrap.firstElementChild)}else{frag.append(document.createTextNode(m[0]))}last=re.lastIndex}frag.append(document.createTextNode(text.slice(last)));node.replaceWith(frag)});return box.innerHTML}
|
||||
function setTab(tab){state.tab=tab;$$('.tab').forEach(x=>x.classList.toggle('active',x.dataset.tab===tab));$$('.page').forEach(x=>x.classList.toggle('active',x.id===`page-${tab}`));window.scrollTo(0,0)}
|
||||
function openModal(html){$('#modalBody').innerHTML=html;$('#modal').classList.remove('hidden');document.body.style.overflow='hidden'} function closeModal(){$('#modal').classList.add('hidden');document.body.style.overflow=''}
|
||||
function openDrawer(title,html){$('#drawerTitle').textContent=title;$('#drawerBody').innerHTML=html;$('#drawer').classList.remove('hidden');document.body.style.overflow='hidden'} function closeDrawer(){$('#drawer').classList.add('hidden');document.body.style.overflow=''}
|
||||
function closeDetail(){$('#detail').classList.add('hidden');$('#detail').innerHTML='';document.body.style.overflow=''} function closeQuery(){$('#queryPanel').classList.add('hidden');document.body.style.overflow=''}
|
||||
function relatedDocs(paths){const ds=uniq(paths).map(p=>knowledgeMap[p]).filter(Boolean);return ds.length?`<div class="related-docs">${ds.map(d=>`<div class="related-doc" data-action="open-knowledge" data-path="${esc(d.path)}"><strong>${esc(d.title)}</strong><p>${esc(clip(d.summary,100))}</p></div>`).join('')}</div>`:'<p class="rich">暂无匹配的知识正文。</p>'}
|
||||
function technicalFields(x){return `<details class="technical-details"><summary>查看全部结构化字段(中文字段名)</summary><table class="human-table"><tbody>${Object.entries(x).map(([k,v])=>`<tr><th>${esc(FIELD_LABELS[k]||k)}</th><td>${humanValue(k,v)}</td></tr>`).join('')}</tbody></table></details>`}
|
||||
function infoGroup(title,fields,x){return `<section class="record-group"><h3>${esc(title)}</h3>${fields.filter(k=>k in x).map(k=>`<div class="record-field"><span class="label">${esc(FIELD_LABELS[k]||k)}</span><span class="value">${humanValue(k,x[k])}</span></div>`).join('')}</section>`}
|
||||
const RELATED={simulator:['capabilities/training/simulators_training_devices_and_digital_training.md','capabilities/training/flight_training_pipeline_and_qualification_generation.md'],maintenance:['capabilities/maintenance/maintenance_levels_airworthiness_quality_and_configuration.md','capabilities/logistics/aviation_materials_suppliers_and_lifecycle_supply_chain.md'],industry:['capabilities/industry/domestic_aviation_industry_and_defense_ecosystem.md','capabilities/industry/external_technology_dependencies_and_autonomy_boundaries.md'],dependency:['capabilities/industry/external_technology_dependencies_and_autonomy_boundaries.md'],risk:['safety/frameworks/human_factors_crm_hfacs_fatigue_and_safety_culture.md','safety/frameworks/environment_atc_base_ground_and_uas_safety.md'],process:['safety/governance/investigation_evidence_grounding_inspection_and_return_to_flight.md','safety/governance/aviation_safety_governance_organizations_and_institutions.md'],training:['capabilities/training/flight_training_pipeline_and_qualification_generation.md'],safety:['safety/events/public_major_aviation_safety_events_timeline.md','safety/governance/investigation_evidence_grounding_inspection_and_return_to_flight.md']};
|
||||
function recordTitle(type,x){return x.name||x.name_zh||x.title||x.organization||x.platform_or_system||x.platform_or_role||x.platform_family||x.domain||x.stage||x.summary||'专题详情'}
|
||||
function openRecord(type,x){let groups=[];if(type==='simulator')groups=[['基本信息',['platform_or_role','category','organization','delivery_status','confidence']],['训练应用',['training_stage','evidence','instructor_requirement']],['构型与保障',['configuration_status','source_ids']]];else if(type==='maintenance')groups=[['维修对象',['platform_family','level','task_family','service','status']],['责任与输出',['responsible_entity','key_outputs','quality_gate']],['技术支撑',['technical_dependency','confidence','source_ids']]];else if(type==='industry')groups=[['产业节点',['organization','node_type','maturity','status','confidence']],['能力范围',['capabilities','platforms']],['外部接口',['foreign_interface','source_ids']]];else if(type==='dependency')groups=[['平台与维度',['platform_or_system','dimension','level']],['国内能力',['domestic_capability','mitigation']],['外部依赖与待核',['foreign_dependency','evidence','unresolved','source_ids']]];else if(type==='risk')groups=[['风险识别',['domain','risk','hfacs_level']],['表现与控制',['examples','controls']]];else if(type==='process')groups=[['治理阶段',['stage','owner','status']],['输入与输出',['inputs','outputs']],['证据依据',['evidence']]];else if(type==='training')groups=[['训练阶段',['stage_name','career_track','stage_order','service','status']],['责任与输入',['responsible_entity','input','academic']],['模拟与实飞',['simulator','flight','output']],['证据',['confidence','source_ids']]];else if(type==='safety')groups=[['事件概览',['date','service','platform','category','severity','summary','outcome']],['处置与恢复',['grounding','return_to_flight']],['调查状态',['cause_status','confidence','source_ids']]];else groups=[['详细字段',Object.keys(x)]];
|
||||
const paths=RELATED[type]||[];openModal(`<div class="record-hero"><h2>${esc(recordTitle(type,x))}</h2><p>以下内容已按业务语义重新分组,原始JSON不再作为默认展示。</p></div><div class="record-grid">${groups.map(g=>infoGroup(g[0],g[1],x)).join('')}</div><section class="detail-section"><h3>关联知识正文</h3>${relatedDocs(paths)}</section>${technicalFields(x)}`)}
|
||||
function renderKnowledgeDetail(doc,unit){if(!doc)return;const heroExtra=unit?`<div class="detail-summary">${kv('单位层级',esc(unit.force_level))}${kv('公开驻地',esc(unit.public_location))}${kv('状态',badge(unit.registry_status||unit.status))}${kv('可信度',badge(unit.registry_confidence||unit.confidence,'confidence'))}</div>`:`<div class="detail-summary">${kv('专题分类',esc(doc.category))}${kv('档案类型',esc(doc.type))}${kv('当前阶段',esc(doc.stage))}${kv('正文规模',`${doc.word_count} 字符`)}</div>`;$('#detail').innerHTML=`<div class="detail-top"><div><strong>${unit?'单位与兵力档案':'知识专题正文'}</strong><span style="opacity:.72;margin-left:12px">Markdown全文呈现</span></div><button class="btn white" data-action="close-detail">返回</button></div><div class="detail-body"><section class="detail-hero"><div><h2>${esc(doc.title)}</h2><p>${esc(doc.summary||doc.when||'知识库专题正文')}</p><div><span class="badge red">${esc(doc.category)}</span><span class="badge red">${esc(doc.type)}</span>${doc.confidence?badge(doc.confidence,'confidence'):''}</div></div>${heroExtra}</section><div class="reader-layout mt"><aside class="reader-toc"><h4>本页目录</h4>${doc.sections.map((s,i)=>`<button class="${i===0?'active':''}" data-action="reader-scroll" data-target="${s.id}">${esc(s.title)}</button>`).join('')}</aside><article class="reader-main">${doc.sections.map(s=>`<section id="${s.id}" class="md-section"><h2>${esc(s.title)}</h2><div class="md-body">${enrichKnowledgeHtml(s.html)}</div></section>`).join('')}</article></div></div>`;$('#detail').classList.remove('hidden');document.body.style.overflow='hidden'}
|
||||
function openKnowledge(path){renderKnowledgeDetail(knowledgeMap[path])} function openUnit(id){const u=unitMap[id];if(!u)return;const d=knowledgeMap[u.path];if(d)renderKnowledgeDetail(d,u);else openRecord('unit',u)}
|
||||
function unitCard(u){return `<article class="unit-card" data-action="open-unit" data-id="${esc(u.organization_id)}"><div class="top"><div><h4>${esc(u.name)}</h4><div class="sub">${esc(service(u.service))} · ${esc(u.force_level||u.organization_type)}</div></div>${badge(u.registry_status||u.status)}</div><div class="mt">${chips(u.platforms,4)}</div><p>${esc(clip(u.summary,145))}</p><div class="foot"><span>${esc(u.public_location||'驻地待核')}</span><button class="btn light sm">阅读完整档案</button></div></article>`}
|
||||
function renderOverview(){const stats=[['单位档案',DATA.units.length,'41篇单位Markdown'],['组织实体',DATA.organizations.length,'组织与支援关系'],['装备平台',DATA.equipment.length,'平台与状态'],['知识专题',KNOWLEDGE.length,'非重复Markdown全文'],['飞安事件',DATA.safetyEvents.length,'公开事件基线'],['官方来源',DATA.sources.length,'一手资料索引']];const entry=[['组织机构','organization','组织架构图','按军种展开联队、旅、大队和队级飞行单位'],['单位兵力','units','完整单位档案','直接阅读对应Markdown全部章节'],['装备体系','equipment','装备专题','结构化装备信息关联知识正文'],['训练保障','training','能力生成','模拟器和维修弹框改为业务详情页'],['工业依赖','industry','产业专题','国内能力、供应商和外部依赖'],['飞安治理','safety','风险闭环','事故、人因、调查与复飞正文'],['知识专题','knowledge','Markdown全文','按分类浏览全部96篇非重复知识文件']];$('#page-overview').innerHTML=`<div class="page-head"><div><h2>全库态势总览</h2><p>结构化JSON用于检索、筛选和关联;Markdown正文作为详情页面的主要内容源,最大限度保留知识深度。</p></div><div class="page-actions"><button class="btn line" data-action="open-query">交互查询</button><button class="btn primary" data-action="goto-tab" data-tab="knowledge">进入知识专题库</button></div></div><div class="stats">${stats.map(s=>`<div class="stat"><div class="label">${s[0]}</div><div class="num">${s[1]}</div><div class="hint">${s[2]}</div></div>`).join('')}</div><div class="section-title"><h3>专题入口</h3><span>详情默认采用中文业务结构与Markdown全文</span></div><div class="grid cols3">${entry.map(e=>`<article class="entry" data-action="goto-tab" data-tab="${e[1]}"><div class="letter">${e[0][0]}</div><strong>${e[0]}</strong><p>${e[3]}</p><span class="badge red">${e[2]}</span></article>`).join('')}</div><div class="grid cols2 mt"><div class="panel"><h3>本版核心变化</h3>${['取消默认原始JSON弹框','单位详情加载完整Markdown','增加96篇知识专题浏览','搜索覆盖Markdown全文','专题详情采用字段分组、流程、关系和来源卡片'].map(x=>`<div class="source-card">${x}</div>`).join('')}</div><div class="panel"><h3>数据边界与口径</h3><div class="notice">${esc(DATA.meta.notice)}</div>${kv('Markdown正文','保留章节、表格、列表、引用、代码块和关联分析')}${kv('结构化数据','用于交互查询和跨实体关联,不替代知识正文')}${kv('数量口径','区分历史接收、项目总量、单位分配与实时可用')}</div></div><div class="section-title"><h3>重点单位</h3><span>进入二级页面阅读单位Markdown全文</span></div><div class="grid cols3">${DATA.units.filter(x=>x.priority==='P1').slice(0,9).map(unitCard).join('')}</div>`}
|
||||
function orgImportant(o){return unitMap[o.organization_id]||['service_headquarters','functional_command','tactical_fighter_wing','tactical_composite_wing','composite_wing','aviation_brigade','aviation_group','training_command','base_command','rescue_squadron'].includes(o.organization_type)}
|
||||
function orgTreeData(svc){const active=DATA.organizations.filter(o=>o.service===svc&&!String(o.status).includes('HISTORICAL')&&!String(o.status).includes('DEPRECATED')&&orgImportant(o));const ids=new Set(active.map(x=>x.organization_id)),roots=active.filter(x=>!x.parent_public||!ids.has(x.parent_public)),children={};active.forEach(x=>(children[x.parent_public]??=[]).push(x));return{roots,children}}
|
||||
function nodeHtml(o,children,depth=0){const kids=(children[o.organization_id]||[]).sort((a,b)=>a.name_zh.localeCompare(b.name_zh,'zh-CN')),cls=depth===0?'root':depth===1?'branch':'';return `<li><button class="org-node ${cls}" data-action="open-org" data-id="${esc(o.organization_id)}"><span>${esc(o.name_zh)}</span><small>${esc(status(o.status))}</small></button>${kids.length?`<ul>${kids.map(k=>nodeHtml(k,children,depth+1)).join('')}</ul>`:''}</li>`}
|
||||
function renderOrganization(){const groups=[['air_force','空军体系'],['army','陆军航空'],['navy','海军航空'],['civil','民政航空支援']],{roots,children}=orgTreeData(state.orgService);$('#page-organization').innerHTML=`<div class="page-head"><div><h2>组织机构图</h2><p>点击节点查看中文组织详情;已有单位Markdown的节点可继续进入全文档案。</p></div></div><div class="org-layout"><aside class="side-nav"><h3 style="margin:5px 8px 12px">组织分类</h3>${groups.map(g=>`<button class="${state.orgService===g[0]?'active':''}" data-action="org-service" data-service="${g[0]}">${g[1]}</button>`).join('')}<div class="notice mt">完整119个组织实体仍可通过交互查询检索。</div></aside><div class="org-canvas"><div class="org-toolbar"><div><strong>${groups.find(x=>x[0]===state.orgService)?.[1]||'组织体系'}</strong><div style="font-size:12px;color:#667085;margin-top:4px">点击组织节点进行下钻</div></div><div class="zoom"><button class="btn light sm" data-action="zoom-out">缩小</button><button class="btn light sm" data-action="zoom-reset">复原</button><button class="btn light sm" data-action="zoom-in">放大</button></div></div><div class="tree" style="--scale:${state.orgZoom}"><ul>${roots.map(r=>nodeHtml(r,children)).join('')||'<div class="empty">暂无主干节点</div>'}</ul></div></div><aside class="side-info"><h3>组织图说明</h3>${kv('红色节点','军种或主干根节点')}${kv('浅红节点','联队、旅、大队等主要分支')}${kv('白色节点','队级飞行单位或专业组织')}<div class="notice mt">组织存在不等于完整兵力公开。</div></aside></div>`}
|
||||
function openOrg(id){const o=orgMap[id];if(!o)return;const u=unitMap[id],parent=orgMap[o.parent_public],childs=DATA.organizations.filter(x=>x.parent_public===id&&!String(x.status).includes('HISTORICAL')).slice(0,18);const orgDocPaths=['entities/organizations/air_force_headquarters_and_four_commands.md','entities/organizations/air_force_wings_1_to_7.md','entities/organizations/army_aviation_special_forces_system.md','entities/organizations/naval_antisubmarine_aviation_system.md'].filter(p=>knowledgeMap[p]);openModal(`<div class="record-hero"><h2>${esc(o.name_zh)}</h2><p>${esc(o.notes||'公开组织实体与关系档案')}</p></div><div class="record-grid">${infoGroup('组织身份',['organization_type','service','status','confidence','last_verified'],o)}<section class="record-group"><h3>隶属与关联</h3>${kv('公开上级',esc(parent?.name_zh||'待核/不适用'))}${kv('下级单位数',String(childs.length))}${childs.map(x=>`<div class="field-item" data-action="open-org" data-id="${esc(x.organization_id)}"><strong>${esc(x.name_zh)}</strong><span>${esc(status(x.status))}</span></div>`).join('')}</section></div>${u?`<button class="btn primary mt" data-action="open-unit" data-id="${esc(id)}">阅读完整单位Markdown档案</button>`:''}<section class="detail-section"><h3>关联组织专题</h3>${relatedDocs(orgDocPaths)}</section>${technicalFields(o)}`)}
|
||||
function filteredUnits(){return DATA.units.filter(u=>{const f=state.unitFilters;return(!f.q||JSON.stringify(u).toLowerCase().includes(f.q.toLowerCase()))&&(f.service==='全部'||service(u.service)===f.service)&&(f.level==='全部'||String(u.force_level).includes(f.level))&&(f.location==='全部'||String(u.public_location).includes(f.location))&&(f.status==='全部'||status(u.registry_status||u.status)===f.status)})}
|
||||
function renderUnits(){const all=filteredUnits(),pages=Math.max(1,Math.ceil(all.length/state.unitSize));state.unitPage=Math.min(state.unitPage,pages);const show=all.slice((state.unitPage-1)*state.unitSize,state.unitPage*state.unitSize),services=['全部',...uniq(DATA.units.map(x=>service(x.service)))],levels=['全部',...uniq(DATA.units.map(x=>x.force_level).filter(Boolean)).slice(0,12)],locs=['全部',...uniq(DATA.units.map(x=>String(x.public_location||'').split('(')[0]).filter(Boolean)).slice(0,15)],sts=['全部',...uniq(DATA.units.map(x=>status(x.registry_status||x.status)))];$('#page-units').innerHTML=`<div class="page-head"><div><h2>单位与兵力档案</h2><p>41个单位均连接对应Markdown全文,卡片摘要不再代替详细知识。</p></div><div class="view-switch"><button class="${state.unitView==='cards'?'active':''}" data-action="unit-view" data-view="cards">卡片</button><button class="${state.unitView==='table'?'active':''}" data-action="unit-view" data-view="table">矩阵</button></div></div><div class="filters"><input class="input" id="uQ" value="${esc(state.unitFilters.q)}" placeholder="查询单位、任务、装备或驻地"><select class="select" id="uService">${services.map(x=>`<option ${state.unitFilters.service===x?'selected':''}>${esc(x)}</option>`).join('')}</select><select class="select" id="uLevel">${levels.map(x=>`<option ${state.unitFilters.level===x?'selected':''}>${esc(x)}</option>`).join('')}</select><select class="select" id="uLoc">${locs.map(x=>`<option ${state.unitFilters.location===x?'selected':''}>${esc(x)}</option>`).join('')}</select><select class="select" id="uStatus">${sts.map(x=>`<option ${state.unitFilters.status===x?'selected':''}>${esc(x)}</option>`).join('')}</select><button class="btn light" data-action="clear-units">清空</button></div>${state.unitView==='cards'?`<div class="grid cols3">${show.map(unitCard).join('')||'<div class="empty">没有匹配单位</div>'}</div>`:`<div class="table-wrap"><table><thead><tr><th>单位名称</th><th>军种</th><th>层级</th><th>驻地</th><th>平台</th><th>任务</th><th>状态</th><th>完整档案</th></tr></thead><tbody>${show.map(u=>`<tr><td><strong>${esc(u.name)}</strong></td><td>${esc(service(u.service))}</td><td>${esc(u.force_level)}</td><td>${esc(u.public_location)}</td><td>${chips(u.platforms,4)}</td><td>${esc(arr(u.mission_roles).slice(0,3).join('、'))}</td><td>${badge(u.registry_status||u.status)}</td><td><button class="btn primary sm" data-action="open-unit" data-id="${esc(u.organization_id)}">阅读全文</button></td></tr>`).join('')}</tbody></table></div>`}<div class="pagination"><button class="btn line sm" data-action="unit-page" data-page="${state.unitPage-1}" ${state.unitPage<=1?'disabled':''}>上一页</button><span>第 ${state.unitPage} / ${pages} 页,共 ${all.length} 个单位</span><button class="btn line sm" data-action="unit-page" data-page="${state.unitPage+1}" ${state.unitPage>=pages?'disabled':''}>下一页</button></div>`;['uQ','uService','uLevel','uLoc','uStatus'].forEach(id=>$('#'+id).addEventListener(id==='uQ'?'input':'change',e=>{const k={uQ:'q',uService:'service',uLevel:'level',uLoc:'location',uStatus:'status'}[id];state.unitFilters[k]=e.target.value;state.unitPage=1;renderUnits()}))}
|
||||
function equipName(x){return x.display_name||x.name_zh||x.platform_name||x.platform_id} function equipCat(x){const n=equipName(x),c=x.category||'';if(/F-16|Mirage|F-CK|战斗/.test(n+c))return'战斗机';if(/T-34|AJT|AT-3|TH-67|教练/.test(n+c))return'教练机';if(/E-2|预警/.test(n+c))return'预警机';if(/C-130|运输|B-737|Fokker|Beech/.test(n+c))return'运输与专机';if(/P-3|反潜巡逻/.test(n+c))return'反潜巡逻机';if(/AH-|UH-|OH-|CH-|S-70|EC225|500MD|直升/.test(n+c))return'直升机';if(/无人|MQ-|腾云|剑翔|锐鸢|Altius|Switchblade/.test(n+c))return'无人航空器';return'其他平台'}
|
||||
function equipDocs(x){const cat=equipCat(x),m={'无人航空器':['entities/equipment/unmanned_aviation_forces.md','entities/equipment/unmanned_equipment_maturity_and_program_status.md'],'直升机':['entities/equipment/aircraft_platform_lineage.md','entities/equipment/army_navy_aviation_weapons_and_mission_systems.md'],'战斗机':['entities/equipment/aircraft_platform_lineage.md','entities/equipment/air_force_airborne_weapons_munitions_and_pods.md'],'教练机':['entities/equipment/aircraft_platform_lineage.md','capabilities/training/flight_training_pipeline_and_qualification_generation.md'],'预警机':['entities/equipment/special_rescue_vip_and_electronic_warfare_aircraft.md','capabilities/missions/mission_system_and_joint_relations.md'],'运输与专机':['entities/equipment/special_rescue_vip_and_electronic_warfare_aircraft.md'],'反潜巡逻机':['entities/equipment/special_rescue_vip_and_electronic_warfare_aircraft.md','entities/equipment/army_navy_aviation_weapons_and_mission_systems.md']};return m[cat]||['entities/equipment/aircraft_platform_lineage.md']}
|
||||
function renderEquipment(){const cats=['全部',...uniq(DATA.equipment.map(equipCat))],list=DATA.equipment.filter(x=>state.equipCat==='全部'||equipCat(x)===state.equipCat);$('#page-equipment').innerHTML=`<div class="page-head"><div><h2>装备体系</h2><p>装备详情采用业务字段、武器关系、来源卡和关联Markdown专题,不再展示裸JSON。</p></div></div><div class="equipment-layout"><aside class="side-nav category-list"><h3 style="margin:5px 8px 12px">装备分类</h3>${cats.map(c=>`<button class="${state.equipCat===c?'active':''}" data-action="equip-cat" data-cat="${esc(c)}"><span>${esc(c)}</span><span>${c==='全部'?DATA.equipment.length:DATA.equipment.filter(x=>equipCat(x)===c).length}</span></button>`).join('')}</aside><div><div class="grid cols3">${list.map(x=>`<article class="equip-card" data-action="open-equip" data-id="${esc(x.platform_id)}"><div class="top"><h4>${esc(equipName(x))}</h4>${badge(x.status)}</div><div>${chips([equipCat(x),service(x.service)],4)}</div><p>公开配属:${esc(arr(x.units_public).join('、')||'待核')}。点击查看任务关系、武器系统、来源和专题正文。</p><div class="foot"><span>${esc(x.last_verified||'')}</span><button class="btn light sm">丰富详情</button></div></article>`).join('')}</div></div></div>`}
|
||||
function openEquip(id){const x=DATA.equipment.find(e=>e.platform_id===id);if(!x)return;const rel=DATA.platformWeapon.filter(r=>String(r.platform).includes(equipName(x))||String(r.platform).includes(x.name_zh||'')),unitValue=(x.related_units&&x.related_units.length?x.related_units:x.units_public),srcs=arr(x.source_ids).map(id=>sourceMap[id]).filter(Boolean);openModal(`<div class="record-hero"><h2>${esc(equipName(x))}</h2><p>平台、任务、配属、武器关系、来源和关联知识正文综合展示。</p><div>${badge(x.status)} ${badge(x.confidence,'confidence')} <span class="badge red">${esc(equipCat(x))}</span></div></div><div class="record-grid"><section class="record-group"><h3>平台身份</h3>${kv('所属体系',esc(service(x.service)))}<div class="record-field"><span class="label">公开单位</span><span class="value">${renderUnitRefs(unitValue)}</span></div>${kv('最后核验',esc(x.last_verified||'待核'))}</section><section class="record-group"><h3>数量与状态边界</h3><p class="rich">军售批准、采购、交付、接装和稳定形成能力属于不同状态;不从全军采购总量推算单位编配或实时可用数量。</p></section></div><section class="detail-section"><h3>武器与任务系统关系</h3>${rel.length?`<div class="table-wrap"><table><thead><tr><th>武器或系统</th><th>用途</th><th>状态</th><th>可信度</th></tr></thead><tbody>${rel.map(r=>`<tr><td>${esc(r.weapon_or_system)}</td><td>${esc(r.role)}</td><td>${badge(r.status)}</td><td>${badge(r.confidence,'confidence')}</td></tr>`).join('')}</tbody></table></div>`:'<p class="rich">当前没有匹配到结构化武器关系,不代表平台没有任务系统。</p>'}</section><section class="detail-section"><h3>公开来源</h3>${srcs.length?srcs.map(s=>`<div class="source-card" data-action="open-source" data-id="${esc(s.source_id)}"><strong>${esc(s.title)}</strong><p>${esc(s.usage)}</p></div>`).join(''):'<p>来源编号已记录或待补充。</p>'}</section><section class="detail-section"><h3>关联知识正文</h3>${relatedDocs(equipDocs(x))}</section>${technicalFields(x)}`)}
|
||||
function renderTraining(){const stages=[...DATA.training].sort((a,b)=>Number(a.stage_order)-Number(b.stage_order));$('#page-training').innerHTML=`<div class="page-head"><div><h2>训练与保障</h2><p>结构化卡片负责概览,点击后进入中文业务详情并可继续阅读训练、模拟器、维修和航材Markdown全文。</p></div></div><div class="panel"><div class="panel-head"><div><h3>飞行训练资格生成链</h3><p>点击任一阶段查看输入、学科、模拟器、实飞、输出和来源</p></div></div><div class="flow">${stages.slice(0,9).map((x,i)=>`<div class="flow-step" data-action="record-detail" data-type="training" data-index="${DATA.training.indexOf(x)}"><div class="no">${i+1}</div><h4>${esc(x.stage_name)}</h4><p>${esc(x.responsible_entity)}</p></div>`).join('')}</div></div><div class="section-title"><h3>模拟训练体系</h3><span>业务字段分组 + 关联Markdown</span></div><div class="grid cols3">${DATA.simulators.map((x,i)=>`<article class="unit-card" data-action="record-detail" data-type="simulator" data-index="${i}"><div class="top"><h4>${esc(x.platform_or_role)}</h4>${badge(x.delivery_status)}</div><div>${chips([x.category],3)}</div><p>${esc(x.evidence)}</p><div class="foot"><span>${esc(x.organization)}</span><button class="btn light sm">查看丰富详情</button></div></article>`).join('')}</div><div class="section-title"><h3>维修层级与保障能力</h3><span>点击查看责任主体、质量关口、技术依赖和全文专题</span></div><div class="grid cols2">${DATA.maintenance.map((x,i)=>`<div class="panel" data-action="record-detail" data-type="maintenance" data-index="${i}"><div class="panel-head"><div><h3>${esc(x.platform_family)}</h3><p>${esc(x.level)} · ${esc(x.task_family)}</p></div>${badge(x.status)}</div><p class="rich">${esc(x.key_outputs)}</p><div>${chips([x.responsible_entity,x.quality_gate],4)}</div></div>`).join('')}</div>`}
|
||||
function renderIndustry(){$('#page-industry').innerHTML=`<div class="page-head"><div><h2>工业链与外部依赖</h2><p>产业节点和依赖矩阵均使用中文详情分组,并链接国产工业、供应链和外部依赖Markdown全文。</p></div></div><div class="industry-stack">${[['政策与军种需求','需求、预算、采购和产业政策'],['总体设计与系统整合','汉翔、中科院及项目主承包'],['专业系统与供应商','发动机、航电、雷达、结构、材料和特殊制程'],['维修与全寿期支援','军方厂库、国内MRO、原厂/FMS和技术资料'],['外部技术与认证','设计权、软件、专用工具、出口管制和适航认证']].map((x,i)=>`<div class="industry-layer"><div><span class="badge red">产业层级 ${i+1}</span><h3 class="mt">${x[0]}</h3></div><p class="rich">${x[1]}</p></div>`).join('')}</div><div class="section-title"><h3>国内产业节点</h3><span>点击查看能力范围、平台、成熟度与关联正文</span></div><div class="grid cols3">${DATA.industry.map((x,i)=>`<article class="unit-card" data-action="record-detail" data-type="industry" data-index="${i}"><div class="top"><h4>${esc(x.organization)}</h4>${badge(x.status)}</div><div>${chips([x.node_type,x.maturity],4)}</div><p>${esc(clip(x.capabilities,150))}</p><div class="foot"><span>${esc(x.foreign_interface)}</span><button class="btn light sm">丰富详情</button></div></article>`).join('')}</div><div class="section-title"><h3>平台级外部依赖矩阵</h3><span>默认不显示原始JSON</span></div><div class="table-wrap"><table><thead><tr><th>平台或系统</th><th>依赖维度</th><th>国内能力</th><th>外部依赖</th><th>等级</th><th>详情</th></tr></thead><tbody>${DATA.externalDependencies.map((x,i)=>`<tr><td><strong>${esc(x.platform_or_system)}</strong></td><td>${esc(x.dimension)}</td><td>${esc(clip(x.domestic_capability,75))}</td><td>${esc(clip(x.foreign_dependency,75))}</td><td><span class="badge red">${esc(x.level)}</span></td><td><button class="btn light sm" data-action="record-detail" data-type="dependency" data-index="${i}">展开</button></td></tr>`).join('')}</tbody></table></div>`}
|
||||
function renderSafety(){$('#page-safety').innerHTML=`<div class="page-head"><div><h2>飞安、事故与风险治理</h2><p>风险和治理环节采用语义详情页面,并连接事故调查、人因、适航、环境和搜救Markdown专题。</p></div></div><div class="grid cols4">${DATA.safetyRisks.slice(0,11).map((x,i)=>`<article class="risk-card" data-action="record-detail" data-type="risk" data-index="${i}"><h4>${esc(x.domain)}</h4><p class="rich">${esc(x.risk)}</p><div>${chips(arr(x.controls),4)}</div></article>`).join('')}</div><div class="section-title"><h3>飞安治理闭环</h3><span>点击阶段查看输入、输出、责任主体与制度正文</span></div><div class="panel"><div class="flow">${DATA.safetyProcess.map((x,i)=>`<div class="flow-step" data-action="record-detail" data-type="process" data-index="${i}"><div class="no">${i+1}</div><h4>${esc(x.stage)}</h4><p>${esc(x.owner)}</p></div>`).join('')}</div></div><div class="section-title"><h3>公开重大飞安事件</h3><span>右侧抽屉提供业务字段和完整专题入口</span></div><div class="timeline">${DATA.safetyEvents.map((x,i)=>`<article class="event" data-action="open-event" data-index="${i}"><span class="date">${esc(x.date)}</span> <span class="badge red">${esc(labels.category[x.category]||x.category)}</span><h4>${esc(x.platform)} · ${esc(x.summary)}</h4><p>${esc(x.outcome)};${esc(x.cause_status)}</p></article>`).join('')}</div>`}
|
||||
function openEvent(i){const x=DATA.safetyEvents[Number(i)];if(!x)return;const ss=arr(x.source_ids).map(id=>sourceMap[id]).filter(Boolean);openDrawer(`${x.date} · ${x.platform}`,`<div class="record-hero"><h2>${esc(x.summary)}</h2><p>事件事实、处置、复飞和原因状态分层展示。</p></div>${infoGroup('事件概览',['date','service','platform','category','severity','outcome'],x)}${infoGroup('停飞、检查与恢复',['grounding','return_to_flight'],x)}${infoGroup('调查与原因状态',['cause_status','confidence','source_ids'],x)}<section class="detail-section"><h3>公开来源</h3>${ss.map(s=>`<div class="source-card" data-action="open-source" data-id="${esc(s.source_id)}"><strong>${esc(s.title)}</strong><p>${esc(s.usage)}</p></div>`).join('')||'<p>来源编号已记录。</p>'}</section><section class="detail-section"><h3>关联知识正文</h3>${relatedDocs(RELATED.safety)}</section><div class="notice">初始通报、监督调查和最终原因属于不同证据层级,不应混写。</div>`)}
|
||||
function renderTimeline(){const sources=DATA.sources.filter(x=>!state.sourceQ||JSON.stringify(x).toLowerCase().includes(state.sourceQ.toLowerCase())).slice(0,70);$('#page-timeline').innerHTML=`<div class="page-head"><div><h2>事件时间线与来源</h2><p>时间线与官方来源卡保持可检索,同时来源索引Markdown也可在知识专题库阅读全文。</p></div></div><div class="source-layout"><div class="panel"><div class="panel-head"><div><h3>重大事件时间线</h3><p>按公开日期倒序</p></div></div><div class="timeline">${DATA.timeline.map(x=>`<article class="event"><span class="date">${esc(x.date)}</span> <span class="badge red">${esc(x.type)}</span><h4>${esc(x.title)}</h4><p>${esc(x.detail||'公开资料未提供更多摘要')}</p></article>`).join('')}</div></div><div><div class="panel mb"><div class="panel-head"><div><h3>官方来源查询</h3><p>共 ${DATA.sources.length} 项来源</p></div></div><input id="sourceQ" class="input" value="${esc(state.sourceQ)}" placeholder="查询来源名称、用途或编号"><button class="btn line mt" data-action="open-knowledge" data-path="sources/官方来源索引_v7.md">阅读来源索引Markdown</button></div>${sources.map(s=>`<article class="source-card" data-action="open-source" data-id="${esc(s.source_id)}"><h4>${esc(s.title)}</h4><p>${esc(s.usage)}</p><div class="mt">${badge(s.confidence,'confidence')} <span class="badge gray">${esc(s.verified)}</span></div></article>`).join('')}</div></div>`;$('#sourceQ').addEventListener('input',e=>{state.sourceQ=e.target.value;renderTimeline()})}
|
||||
function openSource(id){const s=sourceMap[id];if(!s)return;const local=sourceLocalMap[id]||{},contexts=local.citation_contexts||[],mentions=local.structured_mentions||[];
|
||||
const original=local.has_original_content&&local.original_content?`<section class="offline-source-panel"><h3>本地收录的原始内容</h3><div class="md-body">${enrichKnowledgeHtml(local.original_content)}</div></section>`:'';
|
||||
const contextHtml=contexts.length?`<section class="offline-source-panel"><h3>知识库引用上下文</h3><p class="rich">以下内容来自本地Markdown中引用该来源的章节,用于离线核对来源支撑范围;它不是外部网页的完整原文。</p>${contexts.map(c=>`<article class="citation-context" data-action="open-knowledge" data-path="${esc(c.path)}"><h4>${esc(c.title)}</h4><p><strong>${esc(c.section||'相关章节')}</strong>:${esc(c.snippet)}</p></article>`).join('')}</section>`:'';
|
||||
const mentionHtml=mentions.length?`<section class="offline-source-panel"><h3>结构化数据中的使用位置</h3>${mentions.map(m=>`<article class="structured-mention"><span class="dataset">${esc(m.dataset)}</span><div><strong>${esc(m.title)}</strong><p>${esc(m.summary||'该记录引用此来源。')}</p></div></article>`).join('')}</section>`:'';
|
||||
const noOriginal=!local.has_original_content?`<div class="notice mt">本地知识库未保存该官方页面或PDF的完整原文。当前为离线部署版本,因此不显示网址,也不提供外网跳转。</div>`:'';
|
||||
openModal(`<div class="record-hero"><h2>${esc(s.title)}</h2><p>${esc(s.usage)}</p></div>${infoGroup('来源信息',['source_id','verified','confidence'],s)}<section class="offline-source-panel"><h3>离线收录状态</h3><span class="offline-status ${local.has_original_content?'available':(contexts.length||mentions.length?'context':'')}">${esc(local.local_status||'仅收录来源元数据')}</span><p class="offline-reference-note">来源用途摘要:${esc(s.usage||'未提供')}</p></section>${original}${contextHtml}${mentionHtml}${noOriginal}<div class="notice">来源只能支撑其明确记载的字段,不能由单一来源推断完整编制、实时状态或单位级兵力。</div>`)}
|
||||
function knowledgeFiltered(){return KNOWLEDGE.filter(d=>(state.knowledgeCategory==='全部'||d.category===state.knowledgeCategory)&&(!state.knowledgeQ||(d.title+' '+d.summary+' '+d.text+' '+d.path).toLowerCase().includes(state.knowledgeQ.toLowerCase())))}
|
||||
function renderKnowledge(){const cats=['全部',...uniq(KNOWLEDGE.map(x=>x.category))],list=knowledgeFiltered(),pages=Math.max(1,Math.ceil(list.length/state.knowledgeSize));state.knowledgePage=Math.min(state.knowledgePage,pages);const show=list.slice((state.knowledgePage-1)*state.knowledgeSize,state.knowledgePage*state.knowledgeSize),counts=CounterBy(KNOWLEDGE,'category');$('#page-knowledge').innerHTML=`<div class="page-head"><div><h2>知识专题库</h2><p>共 ${KNOWLEDGE.length} 篇非重复Markdown知识文件。可按主题分类、标题和正文全文检索。</p></div><div class="page-actions"><input id="knowledgeQ" class="input" style="width:330px" value="${esc(state.knowledgeQ)}" placeholder="查询标题、摘要、正文或路径"></div></div><div class="knowledge-layout"><aside class="knowledge-side"><h3 style="margin:5px 8px 12px">专题分类</h3>${cats.map(c=>`<button class="${state.knowledgeCategory===c?'active':''}" data-action="knowledge-cat" data-cat="${esc(c)}"><span>${esc(c)}</span><span>${c==='全部'?KNOWLEDGE.length:(counts[c]||0)}</span></button>`).join('')}</aside><div><div class="grid cols3">${show.map(d=>`<article class="knowledge-card" data-action="open-knowledge" data-path="${esc(d.path)}"><h4>${esc(d.title)}</h4><div class="knowledge-meta"><span class="badge red">${esc(d.category)}</span><span class="badge gray">${esc(d.type)}</span></div><p>${esc(clip(d.summary||d.when,155))}</p><div class="knowledge-path">${esc(d.path)}</div><div class="foot mt"><span>${d.sections.length} 个章节</span><button class="btn light sm">阅读全文</button></div></article>`).join('')||'<div class="empty">没有匹配的Markdown专题</div>'}</div><div class="pagination"><button class="btn line sm" data-action="knowledge-page" data-page="${state.knowledgePage-1}" ${state.knowledgePage<=1?'disabled':''}>上一页</button><span>第 ${state.knowledgePage} / ${pages} 页,共 ${list.length} 篇</span><button class="btn line sm" data-action="knowledge-page" data-page="${state.knowledgePage+1}" ${state.knowledgePage>=pages?'disabled':''}>下一页</button></div></div></div>`;$('#knowledgeQ').addEventListener('input',e=>{state.knowledgeQ=e.target.value;state.knowledgePage=1;renderKnowledge()})}
|
||||
function CounterBy(items,key){return items.reduce((a,x)=>(a[x[key]]=(a[x[key]]||0)+1,a),{})}
|
||||
const datasets={units:['单位档案',DATA.units,'unit'],organizations:['组织机构',DATA.organizations,'organization'],equipment:['装备平台',DATA.equipment,'equipment'],training:['训练阶段',DATA.training,'training'],simulators:['模拟器',DATA.simulators,'simulator'],maintenance:['维修能力',DATA.maintenance,'maintenance'],industry:['产业节点',DATA.industry,'industry'],dependencies:['外部依赖',DATA.externalDependencies,'dependency'],safety:['飞安事件',DATA.safetyEvents,'safety'],sources:['官方来源',DATA.sources,'source'],knowledge:['知识专题',KNOWLEDGE,'knowledge']};
|
||||
function openDatasetRecord(key,x){const type=datasets[key][2];if(type==='unit')openUnit(x.organization_id);else if(type==='organization')openOrg(x.organization_id);else if(type==='equipment')openEquip(x.platform_id);else if(type==='source')openSource(x.source_id);else if(type==='knowledge')openKnowledge(x.path);else openRecord(type,x)}
|
||||
function openQuery(){$('#queryPanel').classList.remove('hidden');document.body.style.overflow='hidden';$('#queryForm').innerHTML=`<h2>交互式数据查询</h2><p class="rich">结构化字段用于筛选;结果点击后打开中文业务详情或Markdown全文。</p><label>数据集</label><select id="qDataset" class="select mb">${Object.entries(datasets).map(([k,v])=>`<option value="${k}">${v[0]}</option>`).join('')}</select><label>查询字段</label><select id="qField" class="select mb"></select><label>条件</label><select id="qOp" class="select mb"><option value="contains">包含</option><option value="equals">等于</option></select><label>查询值</label><input id="qValue" class="input mb" placeholder="输入关键词"><button class="btn primary" id="qRun">执行查询</button><button class="btn light" id="qClear">清空</button><div class="notice mt">查询结果默认不显示原始JSON。</div>`;const fields=()=>{const d=datasets[$('#qDataset').value][1],ks=uniq(d.slice(0,50).flatMap(x=>Object.keys(x))).sort();$('#qField').innerHTML='<option value="__all">全部字段</option>'+ks.map(k=>`<option value="${esc(k)}">${esc(FIELD_LABELS[k]||k)}</option>`).join('')};const run=()=>{const key=$('#qDataset').value,d=datasets[key][1],f=$('#qField').value,op=$('#qOp').value,q=$('#qValue').value.trim().toLowerCase(),r=d.filter(x=>{const v=f==='__all'?JSON.stringify(x):JSON.stringify(x[f]??'');return!q||(op==='equals'?v.replace(/^"|"$/g,'').toLowerCase()===q:v.toLowerCase().includes(q))}).slice(0,100);$('#queryResult').innerHTML=`<div class="page-head"><div><h2>查询结果</h2><p>匹配 ${r.length} 条,点击查看业务详情</p></div></div>${r.map((x,i)=>`<div class="query-row" data-action="query-record" data-dataset="${key}" data-index="${d.indexOf(x)}"><strong>${esc(recordTitle(datasets[key][2],x))}</strong><p style="margin:5px 0;color:#667085">${esc(clip(x.summary||x.usage||x.evidence||x.text||JSON.stringify(x),170))}</p></div>`).join('')||'<div class="empty">没有匹配结果</div>'}`};$('#qDataset').addEventListener('change',()=>{fields();run()});$('#qField').addEventListener('change',run);$('#qOp').addEventListener('change',run);$('#qValue').addEventListener('input',run);$('#qRun').onclick=run;$('#qClear').onclick=()=>{$('#qValue').value='';run()};fields();run()}
|
||||
function renderAll(){renderOverview();renderOrganization();renderUnits();renderEquipment();renderTraining();renderIndustry();renderSafety();renderTimeline();renderKnowledge()}
|
||||
document.addEventListener('click',e=>{const el=e.target.closest('[data-action]');if(!el)return;const a=el.dataset.action;if(a==='goto-tab')setTab(el.dataset.tab);if(a==='open-unit')openUnit(el.dataset.id);if(a==='open-org')openOrg(el.dataset.id);if(a==='open-equip')openEquip(el.dataset.id);if(a==='open-event')openEvent(el.dataset.index);if(a==='open-source')openSource(el.dataset.id);if(a==='missing-source')openModal(`<div class="record-hero"><h2>来源待补充</h2><p>当前来源索引中未匹配到该编号。</p></div>${kv('来源编号',esc(el.dataset.id))}<div class="notice mt">该编号已在Markdown正文中出现,但尚未与来源索引建立映射。后续可在离线来源表中补充标题、用途、核验日期、可信度及本地原文或摘录;本页面不展示外部网址。</div>`);if(a==='open-knowledge')openKnowledge(el.dataset.path);if(a==='record-detail'){const map={training:DATA.training,simulator:DATA.simulators,maintenance:DATA.maintenance,industry:DATA.industry,dependency:DATA.externalDependencies,risk:DATA.safetyRisks,process:DATA.safetyProcess};openRecord(el.dataset.type,map[el.dataset.type][Number(el.dataset.index)])}if(a==='query-record'){const key=el.dataset.dataset;openDatasetRecord(key,datasets[key][1][Number(el.dataset.index)])}if(a==='close-modal')closeModal();if(a==='close-drawer')closeDrawer();if(a==='close-detail')closeDetail();if(a==='open-query')openQuery();if(a==='close-query')closeQuery();if(a==='org-service'){state.orgService=el.dataset.service;state.orgZoom=1;renderOrganization()}if(a==='zoom-in'){state.orgZoom=Math.min(1.45,state.orgZoom+.1);renderOrganization()}if(a==='zoom-out'){state.orgZoom=Math.max(.6,state.orgZoom-.1);renderOrganization()}if(a==='zoom-reset'){state.orgZoom=1;renderOrganization()}if(a==='unit-view'){state.unitView=el.dataset.view;renderUnits()}if(a==='unit-page'){state.unitPage=Number(el.dataset.page);renderUnits()}if(a==='clear-units'){state.unitFilters={q:'',service:'全部',level:'全部',location:'全部',status:'全部'};state.unitPage=1;renderUnits()}if(a==='equip-cat'){state.equipCat=el.dataset.cat;renderEquipment()}if(a==='knowledge-cat'){state.knowledgeCategory=el.dataset.cat;state.knowledgePage=1;renderKnowledge()}if(a==='knowledge-page'){state.knowledgePage=Number(el.dataset.page);renderKnowledge()}if(a==='reader-scroll'){const t=document.getElementById(el.dataset.target);if(t)t.scrollIntoView({behavior:'smooth',block:'start'});$$('.reader-toc button').forEach(b=>b.classList.toggle('active',b===el))}if(a==='reset'){state.unitFilters={q:'',service:'全部',level:'全部',location:'全部',status:'全部'};state.unitPage=1;state.equipCat='全部';state.orgService='air_force';state.sourceQ='';state.knowledgeCategory='全部';state.knowledgeQ='';renderAll();setTab('overview')}});
|
||||
$$('.tab').forEach(t=>t.addEventListener('click',()=>setTab(t.dataset.tab)));
|
||||
const gs=$('#globalSearch');function globalResults(q){q=q.trim().toLowerCase();if(!q)return[];const r=[];DATA.units.forEach(x=>{if(JSON.stringify(x).toLowerCase().includes(q))r.push({kind:'单位',title:x.name,desc:x.summary,action:'open-unit',id:x.organization_id})});DATA.equipment.forEach(x=>{if(JSON.stringify(x).toLowerCase().includes(q))r.push({kind:'装备',title:equipName(x),desc:`${equipCat(x)} · ${status(x.status)}`,action:'open-equip',id:x.platform_id})});KNOWLEDGE.forEach(x=>{if((x.title+' '+x.summary+' '+x.text).toLowerCase().includes(q))r.push({kind:'知识正文',title:x.title,desc:x.summary||x.path,action:'open-knowledge',id:x.path})});DATA.safetyEvents.forEach((x,i)=>{if(JSON.stringify(x).toLowerCase().includes(q))r.push({kind:'飞安事件',title:`${x.date} ${x.platform}`,desc:x.summary,action:'open-event',id:i})});DATA.sources.forEach(x=>{if(JSON.stringify(x).toLowerCase().includes(q))r.push({kind:'来源',title:x.title,desc:x.usage,action:'open-source',id:x.source_id})});return r.slice(0,25)}
|
||||
gs.addEventListener('input',()=>{const r=globalResults(gs.value),p=$('#searchPop');if(!gs.value.trim()){p.classList.add('hidden');return}p.innerHTML=r.length?r.map(x=>`<div class="search-item" data-search-action="${x.action}" data-search-id="${esc(x.id)}"><span class="search-kind">${x.kind}</span><div><strong>${esc(x.title)}</strong><small>${esc(clip(x.desc,110))}</small></div></div>`).join(''):'<div class="empty">没有匹配结果</div>';p.classList.remove('hidden')});$('#searchPop').addEventListener('click',e=>{const x=e.target.closest('[data-search-action]');if(!x)return;$('#searchPop').classList.add('hidden');gs.value='';if(x.dataset.searchAction==='open-unit')openUnit(x.dataset.searchId);if(x.dataset.searchAction==='open-equip')openEquip(x.dataset.searchId);if(x.dataset.searchAction==='open-event')openEvent(x.dataset.searchId);if(x.dataset.searchAction==='open-source')openSource(x.dataset.searchId);if(x.dataset.searchAction==='open-knowledge')openKnowledge(x.dataset.searchId)});document.addEventListener('click',e=>{if(!e.target.closest('.search'))$('#searchPop').classList.add('hidden')});renderAll();
|
||||
})();
|
||||
</script></body></html>
|
||||
+4252
File diff suppressed because it is too large.
Load diff
+3833
File diff suppressed because it is too large.
Load diff
+3484
File diff suppressed because it is too large.
Load diff
+2943
File diff suppressed because it is too large.
Load diff
+381
@@ -0,0 +1,381 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>日本涉台介入风险叙事专题研究系统</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #8f1f25;
|
||||
--bg2: #b8323a;
|
||||
--panel: #fff7f3;
|
||||
--card: #ffffff;
|
||||
--ink: #241616;
|
||||
--muted: #76605d;
|
||||
--line: rgba(120, 29, 35, .18);
|
||||
--red: #b7202e;
|
||||
--red-dark: #7b121b;
|
||||
--gold: #f3c969;
|
||||
--soft: #fff2eb;
|
||||
--green: #18724d;
|
||||
--orange: #b35b13;
|
||||
--blue: #275b91;
|
||||
--shadow: 0 18px 50px rgba(58, 9, 15, .18);
|
||||
--radius: 18px;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "PingFang SC", Arial, sans-serif;
|
||||
background: radial-gradient(circle at 20% 0%, #d94c4c 0, transparent 24%), linear-gradient(140deg, var(--bg), #641018 70%);
|
||||
color: var(--ink);
|
||||
min-height: 100vh;
|
||||
}
|
||||
.app { max-width: 1480px; margin: 0 auto; padding: 28px; }
|
||||
.hero {
|
||||
color: #fff;
|
||||
padding: 24px 26px 22px;
|
||||
border: 1px solid rgba(255,255,255,.18);
|
||||
background: linear-gradient(135deg, rgba(255,255,255,.14), rgba(255,255,255,.06));
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 26px;
|
||||
box-shadow: var(--shadow);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.hero::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
width: 420px; height: 420px;
|
||||
border: 1px solid rgba(255,255,255,.12);
|
||||
border-radius: 50%;
|
||||
right: -160px; top: -220px;
|
||||
}
|
||||
.eyebrow { font-size: 13px; letter-spacing: .18em; opacity: .86; margin-bottom: 9px; }
|
||||
h1 { margin: 0; font-size: clamp(28px, 4vw, 48px); line-height: 1.15; }
|
||||
.subtitle { max-width: 920px; margin-top: 12px; color: rgba(255,255,255,.88); line-height: 1.75; }
|
||||
.hero-meta { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 18px; }
|
||||
.pill { display:inline-flex; align-items:center; gap:6px; padding: 7px 11px; border-radius: 999px; background: rgba(255,255,255,.16); color: #fff; border: 1px solid rgba(255,255,255,.18); font-size: 13px; }
|
||||
|
||||
.toolbar {
|
||||
margin: 20px 0 14px;
|
||||
background: var(--panel);
|
||||
border-radius: 22px;
|
||||
padding: 14px;
|
||||
display: grid;
|
||||
grid-template-columns: 1.6fr .85fr .75fr .75fr;
|
||||
gap: 12px;
|
||||
box-shadow: var(--shadow);
|
||||
border: 1px solid rgba(255,255,255,.42);
|
||||
}
|
||||
input, select {
|
||||
width: 100%;
|
||||
border: 1px solid var(--line);
|
||||
background: #fff;
|
||||
border-radius: 14px;
|
||||
padding: 12px 13px;
|
||||
font-size: 14px;
|
||||
color: var(--ink);
|
||||
outline: none;
|
||||
}
|
||||
input:focus, select:focus { border-color: rgba(183,32,46,.56); box-shadow: 0 0 0 3px rgba(183,32,46,.1); }
|
||||
.tabs {
|
||||
display: flex; flex-wrap: wrap; gap: 9px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
.tab-btn {
|
||||
border: 0;
|
||||
background: rgba(255,255,255,.18);
|
||||
color: #fff;
|
||||
border: 1px solid rgba(255,255,255,.2);
|
||||
padding: 10px 13px;
|
||||
border-radius: 999px;
|
||||
cursor: pointer;
|
||||
font-weight: 700;
|
||||
transition: .18s ease;
|
||||
}
|
||||
.tab-btn.active { background: #fff; color: var(--red-dark); box-shadow: 0 10px 26px rgba(0,0,0,.13); }
|
||||
.tab-btn:hover { transform: translateY(-1px); }
|
||||
|
||||
.panel {
|
||||
background: var(--panel);
|
||||
border-radius: 26px;
|
||||
padding: 20px;
|
||||
box-shadow: var(--shadow);
|
||||
border: 1px solid rgba(255,255,255,.44);
|
||||
min-height: 520px;
|
||||
}
|
||||
.tab-head { display:flex; justify-content:space-between; align-items:flex-start; gap:18px; margin-bottom:16px; }
|
||||
.tab-title { margin: 0; font-size: 25px; color: var(--red-dark); }
|
||||
.tab-desc { margin: 6px 0 0; color: var(--muted); line-height: 1.6; }
|
||||
.count-badge { flex: 0 0 auto; padding: 8px 11px; border-radius: 999px; background:#fff; color: var(--red-dark); border:1px solid var(--line); font-weight:800; }
|
||||
|
||||
.summary-grid { display:grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; }
|
||||
.summary-card {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
padding: 18px;
|
||||
min-height: 144px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.summary-card::after { content:""; position:absolute; right:-38px; top:-42px; width: 110px; height:110px; border-radius:50%; background: rgba(183,32,46,.08); }
|
||||
.summary-card h3 { margin:0 0 8px; color:var(--red-dark); font-size:15px; }
|
||||
.summary-card .value { font-size: 25px; font-weight: 900; margin-bottom: 9px; color: #2b1114; }
|
||||
.summary-card p { margin:0; color:var(--muted); line-height: 1.62; font-size: 14px; }
|
||||
|
||||
.overview-grid { display:grid; grid-template-columns: 1.1fr .9fr; gap: 14px; margin-top: 14px; }
|
||||
.box { background:#fff; border:1px solid var(--line); border-radius:18px; padding:16px; }
|
||||
.box h3 { margin:0 0 12px; color: var(--red-dark); }
|
||||
.bar-row { display:grid; grid-template-columns: 105px 1fr 36px; align-items:center; gap:8px; margin: 9px 0; font-size:13px; color: var(--muted); }
|
||||
.bar { height: 10px; border-radius: 999px; background: #f4ded8; overflow: hidden; }
|
||||
.bar > span { display:block; height:100%; border-radius:999px; background: linear-gradient(90deg, var(--red), var(--gold)); }
|
||||
.risk-list { display:grid; gap:10px; }
|
||||
.risk-mini { border:1px solid var(--line); border-radius:14px; padding:11px; background:#fffdfb; cursor:pointer; }
|
||||
.risk-mini strong { color: var(--red-dark); }
|
||||
|
||||
.cards { display:grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; }
|
||||
.card {
|
||||
background: #fff;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
padding: 16px;
|
||||
display:flex; flex-direction:column; gap: 10px;
|
||||
min-height: 248px;
|
||||
transition: .18s ease;
|
||||
}
|
||||
.card:hover { transform: translateY(-2px); box-shadow: 0 12px 28px rgba(94, 20, 24, .12); }
|
||||
.card-top { display:flex; justify-content:space-between; align-items:flex-start; gap:12px; }
|
||||
.card-id { font-size:12px; color:#fff; background: var(--red-dark); border-radius:999px; padding:4px 8px; font-weight: 800; }
|
||||
.risk { font-size:12px; border-radius:999px; padding:5px 8px; font-weight: 800; white-space: nowrap; }
|
||||
.risk.xh { background: #ffe1de; color:#9b111c; }
|
||||
.risk.h { background: #fff0d5; color:#9a4e00; }
|
||||
.risk.m { background: #e9f2ff; color:#24527d; }
|
||||
.card h3 { margin:0; color:var(--red-dark); font-size:17px; line-height:1.35; }
|
||||
.meta { display:flex; gap:6px; flex-wrap:wrap; }
|
||||
.tag { font-size:12px; color:var(--red-dark); background: var(--soft); border:1px solid rgba(183,32,46,.15); border-radius:999px; padding:4px 8px; }
|
||||
.card p { margin:0; color:var(--muted); line-height: 1.62; font-size: 14px; }
|
||||
.card-footer { margin-top:auto; display:flex; justify-content:space-between; align-items:center; gap:12px; }
|
||||
.evidence { font-size:12px; color:#5e4d49; }
|
||||
.btn {
|
||||
background: var(--red);
|
||||
color:#fff;
|
||||
border:0;
|
||||
border-radius:12px;
|
||||
padding:9px 12px;
|
||||
cursor:pointer;
|
||||
font-weight:800;
|
||||
box-shadow: 0 8px 18px rgba(183,32,46,.22);
|
||||
}
|
||||
.btn.secondary { background:#fff; color:var(--red-dark); border:1px solid var(--line); box-shadow:none; }
|
||||
.empty { padding: 38px; text-align:center; color:var(--muted); background:#fff; border:1px dashed var(--line); border-radius:18px; }
|
||||
|
||||
.keyword-wrap { display:grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap:14px; margin-top:16px; }
|
||||
.keyword-group { background:#fff; border:1px solid var(--line); border-radius:18px; padding:15px; }
|
||||
.keyword-group h3 { margin:0 0 10px; color: var(--red-dark); }
|
||||
.kw { display:inline-block; margin:5px; padding:7px 10px; background:var(--soft); border:1px solid rgba(183,32,46,.18); color:var(--red-dark); border-radius:999px; font-size:13px; }
|
||||
|
||||
.modal-backdrop { display:none; position:fixed; inset:0; background:rgba(45, 7, 10, .62); z-index:1000; padding: 28px; overflow:auto; }
|
||||
.modal-backdrop.open { display:block; }
|
||||
.modal { max-width: 980px; margin: 0 auto; background:#fffaf7; border-radius: 24px; border:1px solid rgba(255,255,255,.45); box-shadow: 0 30px 90px rgba(0,0,0,.34); overflow:hidden; }
|
||||
.modal-head { background: linear-gradient(135deg, var(--red-dark), var(--red)); color:#fff; padding: 20px 22px; display:flex; justify-content:space-between; gap:16px; align-items:flex-start; }
|
||||
.modal-head h2 { margin:0; font-size:24px; }
|
||||
.close { background:rgba(255,255,255,.16); border:1px solid rgba(255,255,255,.25); color:#fff; border-radius:12px; font-size:22px; cursor:pointer; width:42px; height:38px; }
|
||||
.modal-body { padding: 20px 22px 24px; }
|
||||
.detail-grid { display:grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap:10px; margin-bottom:16px; }
|
||||
.detail-cell { background:#fff; border:1px solid var(--line); border-radius:14px; padding:10px; }
|
||||
.detail-cell span { display:block; font-size:12px; color:var(--muted); margin-bottom:4px; }
|
||||
.detail-cell strong { color:var(--red-dark); }
|
||||
.section { background:#fff; border:1px solid var(--line); border-radius:16px; padding:15px; margin:12px 0; }
|
||||
.section h3 { margin:0 0 8px; color:var(--red-dark); }
|
||||
.section p { margin:0; line-height:1.8; color:#3b2929; }
|
||||
|
||||
.footer-note { color:rgba(255,255,255,.78); text-align:center; padding: 16px 0 4px; font-size:13px; }
|
||||
@media (max-width: 1100px) {
|
||||
.toolbar { grid-template-columns: 1fr 1fr; }
|
||||
.summary-grid, .cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.overview-grid { grid-template-columns: 1fr; }
|
||||
.detail-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.app { padding: 14px; }
|
||||
.toolbar { grid-template-columns: 1fr; }
|
||||
.summary-grid, .cards, .keyword-wrap { grid-template-columns: 1fr; }
|
||||
.tab-head { flex-direction:column; }
|
||||
.detail-grid { grid-template-columns: 1fr; }
|
||||
.modal-backdrop { padding: 12px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
<header class="hero">
|
||||
<div class="eyebrow">NARRATIVE RISK MONITORING DATABASE</div>
|
||||
<h1>日本涉台介入风险叙事专题研究系统</h1>
|
||||
<div class="subtitle">围绕“介入战争日本祸及自身”叙事的事件、人物、组织、制度、地方、媒体、经济与民意数据库</div>
|
||||
<div class="hero-meta">
|
||||
<span class="pill">版本:1.0</span>
|
||||
<span class="pill">更新:2026-06-30</span>
|
||||
<span class="pill">离线可用 · 内嵌数据</span>
|
||||
<span class="pill">Tab切换 · 搜索筛选 · 弹框详情</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="toolbar">
|
||||
<input id="q" placeholder="搜索关键词:高市、先岛、存立危机、冲绳、旅游、认知战……" />
|
||||
<select id="narrativeFilter"><option value="">全部叙事方向</option></select>
|
||||
<select id="riskFilter"><option value="">全部风险等级</option><option value="极高">极高</option><option value="高">高</option><option value="中">中</option><option value="中低">中低</option><option value="低">低</option></select>
|
||||
<select id="evidenceFilter"><option value="">全部证据状态</option><option value="已核实">已核实</option><option value="持续更新">持续更新</option><option value="待采集">待采集</option></select>
|
||||
</section>
|
||||
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
<main class="panel" id="content"></main>
|
||||
<div class="footer-note">本页面为研究型结构化展示,不替代原始文件核验;高风险条目应回溯国会记录、政府文件、机构公告和媒体原文。</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-backdrop" id="modalBackdrop" onclick="backdropClose(event)">
|
||||
<div class="modal" role="dialog" aria-modal="true">
|
||||
<div class="modal-head">
|
||||
<div>
|
||||
<div id="modalMeta" class="eyebrow"></div>
|
||||
<h2 id="modalTitle"></h2>
|
||||
</div>
|
||||
<button class="close" onclick="closeModal()">×</button>
|
||||
</div>
|
||||
<div class="modal-body" id="modalBody"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const DATA = {"project": {"title": "日本涉台介入风险叙事专题研究系统", "subtitle": "围绕“介入战争日本祸及自身”叙事的事件、人物、组织、制度、地方、媒体、经济与民意数据库", "version": "1.0", "language": "zh-CN", "last_updated": "2026-06-30", "description": "本数据用于展示日本方向涉台介入风险叙事中的事件、人物、组织、制度、地方、媒体、经济、民意与竞争叙事。"}, "tabs": [{"id": "overview", "name": "总览仪表盘", "dataset": null, "description": "展示专题总风险、叙事分布、热点地区、重点人物和最新事件。"}, {"id": "timeline", "name": "事件时间线", "dataset": "events_timeline", "description": "展示2014年以来日本涉台安全政策、政要表态、地方避难和中日冲突节点。"}, {"id": "actors_orgs", "name": "人物组织", "dataset": ["actors_japan", "organizations"], "description": "展示日本政府、政党、地方政治、专家、媒体和社会组织。"}, {"id": "security_laws", "name": "法律制度", "dataset": "security_laws", "description": "展示存立危机、重要影响、国民保护、日美安保等制度路径。"}, {"id": "local_frontline", "name": "地方前线", "dataset": "local_frontline", "description": "展示冲绳、先岛、石垣、宫古、与那国、九州、山口等地方风险。"}, {"id": "antiwar_networks", "name": "反战护宪网络", "dataset": "antiwar_networks", "description": "展示九条之会、日弁连、冲绳和平运动、地方反导弹组织和工会网络。"}, {"id": "conservative_backlash", "name": "保守反弹", "dataset": "conservative_backlash", "description": "展示威慑、防卫、中国认知战、台湾伙伴等竞争叙事。"}, {"id": "media_platform", "name": "媒体平台", "dataset": "media_platform_samples", "description": "展示全国媒体、地方媒体、YouTube、X、Yahoo、note等传播样本。"}, {"id": "economic_spillover", "name": "经济外溢", "dataset": "economic_spillover", "description": "展示旅游、航空、半导体、供应链、出口管制等风险。"}, {"id": "public_opinion", "name": "民意受众", "dataset": "public_opinion_youth", "description": "展示台湾有事、防卫费、修宪、青年、都市无党派和冲绳地方态度。"}, {"id": "japan_taiwan", "name": "日台关系", "dataset": "japan_taiwan_relations", "description": "展示日台实务窗口、亲台议员网络、地方交流、半导体合作和智库推演。"}, {"id": "corpus_keywords", "name": "语料词库", "dataset": "source_corpus_keywords", "description": "展示原始语料来源、日文关键词、平台监测词和证据状态。"}], "dashboard": {"summary_cards": [{"title": "核心叙事", "value": "介入战争日本祸及自身", "description": "围绕日本涉台介入可能引发战争卷入、地方牺牲、经济反制和社会撕裂的风险叙事。"}, {"title": "数据条目", "value": "164", "description": "覆盖事件、人物、组织、制度、地方、媒体、经济、民意和日台关系。"}, {"title": "高风险地区", "value": "冲绳、先岛、九州", "description": "冲绳本岛、石垣、宫古、与那国、九州和山口是地方风险最集中的区域。"}, {"title": "核心法律入口", "value": "存立危机事态", "description": "台湾有事是否触发日本集体自卫权,是舆论和国会争议核心。"}, {"title": "主要竞争叙事", "value": "威慑才能防止战争", "description": "保守派和安保界常用威慑、防卫、中国威胁等逻辑反击反介入叙事。"}, {"title": "总体风险", "value": "86 / 100", "description": "综合政治触发、地方影响、经济外溢、媒体扩散和反弹强度评估。"}], "narrative_distribution": [{"label": "地方牺牲", "count": 38}, {"label": "护宪反战", "count": 22}, {"label": "威慑防战", "count": 20}, {"label": "经济代价", "count": 18}, {"label": "中性解释", "count": 17}, {"label": "台湾伙伴", "count": 15}, {"label": "战争卷入", "count": 12}, {"label": "专业治理", "count": 12}, {"label": "中国胁迫", "count": 6}, {"label": "中国威胁", "count": 4}], "hotspots": [{"location": "日本", "count": 42}, {"location": "东京", "count": 15}, {"location": "冲绳", "count": 12}, {"location": "日本全国", "count": 9}, {"location": "宫古岛", "count": 5}, {"location": "华盛顿", "count": 4}, {"location": "与那国", "count": 4}, {"location": "石垣", "count": 3}, {"location": "九州/山口", "count": 3}, {"location": "熊本", "count": 3}, {"location": "先岛/九州/山口", "count": 2}, {"location": "中日之间", "count": 2}], "top_risks": [{"id": "E016", "title_cn": "高市早苗称台湾有事可能构成存立危机事态", "category": "首相表态", "summary": "高市早苗在国会答辩中将台湾有事与存立危机事态直接相连。", "detail": "该事件将保守派长期话语推入首相级官Line truncated
|
||||
const state = { activeTab: 'overview' };
|
||||
|
||||
const tabsEl = document.getElementById('tabs');
|
||||
const contentEl = document.getElementById('content');
|
||||
const qEl = document.getElementById('q');
|
||||
const narrativeEl = document.getElementById('narrativeFilter');
|
||||
const riskEl = document.getElementById('riskFilter');
|
||||
const evidenceEl = document.getElementById('evidenceFilter');
|
||||
|
||||
function init() {
|
||||
Object.values(DATA.narrative_labels).forEach(label => {
|
||||
const opt = document.createElement('option'); opt.value = label; opt.textContent = label; narrativeEl.appendChild(opt);
|
||||
});
|
||||
renderTabs();
|
||||
render();
|
||||
[qEl, narrativeEl, riskEl, evidenceEl].forEach(el => el.addEventListener('input', render));
|
||||
}
|
||||
|
||||
function renderTabs() {
|
||||
tabsEl.innerHTML = '';
|
||||
DATA.tabs.forEach(t => {
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'tab-btn' + (state.activeTab === t.id ? ' active' : '');
|
||||
btn.textContent = t.name;
|
||||
btn.onclick = () => { state.activeTab = t.id; qEl.value=''; renderTabs(); render(); };
|
||||
tabsEl.appendChild(btn);
|
||||
});
|
||||
}
|
||||
|
||||
function getActiveTab() { return DATA.tabs.find(t => t.id === state.activeTab); }
|
||||
function getItems(tab) {
|
||||
if (!tab || !tab.dataset) return [];
|
||||
if (Array.isArray(tab.dataset)) return tab.dataset.flatMap(k => DATA.datasets[k] || []);
|
||||
return DATA.datasets[tab.dataset] || [];
|
||||
}
|
||||
function textOf(x) {
|
||||
return [x.id, x.title_cn, x.category, x.summary, x.detail, x.location, x.narrative_label, ...(x.tags||[])].join(' ').toLowerCase();
|
||||
}
|
||||
function filtered(items) {
|
||||
const q = qEl.value.trim().toLowerCase();
|
||||
const n = narrativeEl.value;
|
||||
const r = riskEl.value;
|
||||
const e = evidenceEl.value;
|
||||
return items.filter(x => (!q || textOf(x).includes(q)) && (!n || x.narrative_label === n) && (!r || x.risk_level === r) && (!e || x.evidence_status === e));
|
||||
}
|
||||
function riskClass(level) { return level === '极高' ? 'xh' : level === '高' ? 'h' : 'm'; }
|
||||
|
||||
function render() {
|
||||
const tab = getActiveTab();
|
||||
if (state.activeTab === 'overview') return renderOverview();
|
||||
const items = filtered(getItems(tab));
|
||||
const keywordBlock = state.activeTab === 'corpus_keywords' ? renderKeywords() : '';
|
||||
contentEl.innerHTML = `
|
||||
<div class="tab-head">
|
||||
<div><h2 class="tab-title">${tab.name}</h2><p class="tab-desc">${tab.description}</p></div>
|
||||
<div class="count-badge">${items.length} 条</div>
|
||||
</div>
|
||||
${items.length ? `<div class="cards">${items.map(card).join('')}</div>` : '<div class="empty">没有符合当前筛选条件的数据。</div>'}
|
||||
${keywordBlock}
|
||||
`;
|
||||
}
|
||||
|
||||
function renderOverview() {
|
||||
const d = DATA.dashboard;
|
||||
const maxNarr = Math.max(...d.narrative_distribution.map(x => x.count));
|
||||
const maxHot = Math.max(...d.hotspots.map(x => x.count));
|
||||
contentEl.innerHTML = `
|
||||
<div class="tab-head">
|
||||
<div><h2 class="tab-title">总览仪表盘</h2><p class="tab-desc">展示专题总风险、叙事分布、热点地区、重点人物和最新事件。可通过上方搜索框对全库进行粗略检索。</p></div>
|
||||
<div class="count-badge">${Object.values(DATA.datasets).filter(Array.isArray).flat().length - DATA.datasets.keywords.length} 条</div>
|
||||
</div>
|
||||
<div class="summary-grid">${d.summary_cards.map(c => `<div class="summary-card"><h3>${c.title}</h3><div class="value">${c.value}</div><p>${c.description}</p></div>`).join('')}</div>
|
||||
<div class="overview-grid">
|
||||
<div class="box"><h3>叙事分布</h3>${d.narrative_distribution.map(x => `<div class="bar-row"><span>${x.label}</span><div class="bar"><span style="width:${Math.max(8, x.count/maxNarr*100)}%"></span></div><b>${x.count}</b></div>`).join('')}</div>
|
||||
<div class="box"><h3>热点地区</h3>${d.hotspots.slice(0,10).map(x => `<div class="bar-row"><span>${x.location}</span><div class="bar"><span style="width:${Math.max(8, x.count/maxHot*100)}%"></span></div><b>${x.count}</b></div>`).join('')}</div>
|
||||
</div>
|
||||
<div class="overview-grid">
|
||||
<div class="box"><h3>高风险条目</h3><div class="risk-list">${d.top_risks.slice(0,6).map(x => `<div class="risk-mini" onclick="openModalById('${x.id}')"><strong>${x.title_cn}</strong><br><span>${x.category} · 风险 ${x.risk_score} · ${x.narrative_label}</span></div>`).join('')}</div></div>
|
||||
<div class="box"><h3>主要风险驱动</h3><div class="meta">${d.risk_drivers.map(x => `<span class="tag">${x}</span>`).join('')}</div><div class="section"><h3>页面使用建议</h3><p>先从“事件时间线”定位触发节点,再到“法律制度”查看制度路径;涉及地方影响时进入“地方前线”和“反战护宪网络”;涉及传播扩散时进入“媒体平台”;涉及成本量化时进入“经济外溢”和“民意受众”。</p></div></div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function card(x) {
|
||||
return `<article class="card">
|
||||
<div class="card-top"><span class="card-id">${x.id}</span><span class="risk ${riskClass(x.risk_level)}">${x.risk_level} · ${x.risk_score}</span></div>
|
||||
<h3>${x.title_cn}</h3>
|
||||
<div class="meta"><span class="tag">${x.category}</span><span class="tag">${x.narrative_label}</span><span class="tag">${x.location || '—'}</span></div>
|
||||
<p>${x.summary}</p>
|
||||
<div class="meta">${(x.tags || []).slice(0,4).map(t => `<span class="tag">${t}</span>`).join('')}</div>
|
||||
<div class="card-footer"><span class="evidence">证据:${x.evidence_status} · 可信度${x.confidence_level}</span><button class="btn" onclick="openModalById('${x.id}')">查看详情</button></div>
|
||||
</article>`;
|
||||
}
|
||||
|
||||
function renderKeywords() {
|
||||
return `<div class="keyword-wrap">${DATA.datasets.keywords.map(g => `<div class="keyword-group"><h3>${g.group}</h3>${g.terms.map(t => `<span class="kw">${t}</span>`).join('')}</div>`).join('')}</div>`;
|
||||
}
|
||||
|
||||
function allItems() { return Object.entries(DATA.datasets).filter(([k]) => k !== 'keywords').flatMap(([k,v]) => Array.isArray(v) ? v : []); }
|
||||
function openModalById(id) { const x = allItems().find(i => i.id === id); if (x) openModal(x); }
|
||||
function openModal(x) {
|
||||
document.getElementById('modalMeta').textContent = `${x.id} · ${x.category} · ${x.narrative_label}`;
|
||||
document.getElementById('modalTitle').textContent = x.title_cn;
|
||||
const metrics = x.metrics ? `<div class="section"><h3>关键指标</h3><p>${Object.entries(x.metrics).map(([k,v]) => `${k}:${v}`).join(';')}</p></div>` : '';
|
||||
document.getElementById('modalBody').innerHTML = `
|
||||
<div class="detail-grid">
|
||||
<div class="detail-cell"><span>风险等级</span><strong>${x.risk_level} · ${x.risk_score}</strong></div>
|
||||
<div class="detail-cell"><span>叙事方向</span><strong>${x.narrative_label}</strong></div>
|
||||
<div class="detail-cell"><span>时间</span><strong>${x.date || '持续'}</strong></div>
|
||||
<div class="detail-cell"><span>地点</span><strong>${x.location || '—'}</strong></div>
|
||||
<div class="detail-cell"><span>证据状态</span><strong>${x.evidence_status}</strong></div>
|
||||
<div class="detail-cell"><span>可信度</span><strong>${x.confidence_level}</strong></div>
|
||||
<div class="detail-cell"><span>类别</span><strong>${x.category}</strong></div>
|
||||
<div class="detail-cell"><span>编号</span><strong>${x.id}</strong></div>
|
||||
</div>
|
||||
<div class="section"><h3>摘要</h3><p>${x.summary}</p></div>
|
||||
<div class="section"><h3>详情解读</h3><p>${x.detail}</p></div>
|
||||
${metrics}
|
||||
<div class="section"><h3>关联标签</h3><p>${(x.tags || []).map(t => `#${t}`).join(' ')}</p></div>
|
||||
<div class="section"><h3>展示建议</h3><p>该条目可与同类事件、相关人物组织、地方节点、法律制度和媒体平台样本联动。若用于二级页面,建议补充时间线、争议双方观点、原始语料和平台传播样本。</p></div>
|
||||
`;
|
||||
document.getElementById('modalBackdrop').classList.add('open');
|
||||
}
|
||||
function closeModal() { document.getElementById('modalBackdrop').classList.remove('open'); }
|
||||
function backdropClose(e) { if (e.target.id === 'modalBackdrop') closeModal(); }
|
||||
window.addEventListener('keydown', e => { if(e.key === 'Escape') closeModal(); });
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+3623
File diff suppressed because it is too large.
Load diff
+1432
File diff suppressed because it is too large.
Load diff
+98
@@ -0,0 +1,98 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>菲律宾“不做美国棋子”叙事专题数据库 v0.2</title>
|
||||
<style>
|
||||
:root{--bg:#f7f1ed;--card:#fffdfb;--ink:#291817;--muted:#7a6764;--line:#eadbd4;--red:#a23434;--red2:#6f1f1f;--blue:#244b74;--blue2:#eaf2fb;--gold:#9f6a1a;--green:#477052;--shadow:0 18px 50px rgba(51,20,14,.09)}
|
||||
*{box-sizing:border-box} body{margin:0;background:linear-gradient(180deg,#f6eee9 0,#fbf7f3 100%);color:var(--ink);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",Arial,sans-serif;line-height:1.55}
|
||||
header{padding:26px 30px 18px;background:linear-gradient(135deg,#8f2929,#b6473d 62%,#d8a16f);color:white;position:sticky;top:0;z-index:20;box-shadow:0 12px 30px rgba(76,17,17,.18)}
|
||||
.topline{display:flex;justify-content:space-between;align-items:flex-start;gap:18px;max-width:1500px;margin:0 auto}.title h1{font-size:28px;margin:0 0 6px}.title p{margin:0;opacity:.88}.tools{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.search{min-width:280px;border:0;border-radius:14px;padding:12px 14px;font-size:14px;outline:none}.btn,label.btn{border:1px solid rgba(255,255,255,.55);background:rgba(255,255,255,.14);color:white;border-radius:13px;padding:10px 13px;cursor:pointer;font-size:14px}label.btn input{display:none}
|
||||
nav{background:#fff8f5;border-bottom:1px solid var(--line);position:sticky;top:105px;z-index:19}.tabs{display:flex;gap:8px;overflow:auto;padding:12px 28px;max-width:1500px;margin:0 auto}.tab{border:1px solid var(--line);background:#fff;border-radius:999px;padding:10px 15px;white-space:nowrap;cursor:pointer;color:var(--ink)}.tab.active{background:var(--red);color:white;border-color:var(--red)}
|
||||
.wrap{display:grid;grid-template-columns:280px minmax(0,1fr) 260px;gap:18px;max-width:1500px;margin:18px auto;padding:0 24px 40px}.panel,.card,.modal{background:var(--card);border:1px solid var(--line);box-shadow:var(--shadow);border-radius:22px}.filters{padding:16px;position:sticky;top:170px;align-self:start}.filters h3,.side h3{margin:0 0 12px}.field{margin:0 0 12px}.field label{display:block;color:var(--muted);font-size:12px;margin:0 0 5px}.field input,.field select{width:100%;border:1px solid var(--line);background:#fff;border-radius:12px;padding:10px 11px;outline:none}.field input:focus,.field select:focus{border-color:#ce9287}.reset{width:100%;border:1px solid var(--line);background:#fff;border-radius:12px;padding:10px;cursor:pointer}.side{padding:16px;position:sticky;top:170px;align-self:start}.summary-item{display:flex;align-items:center;justify-content:space-between;border:1px solid var(--line);border-radius:14px;padding:10px 12px;margin:8px 0;background:#fff}.summary-item strong{font-size:19px;color:var(--red)}.summary-item span{font-size:13px;color:var(--muted)}
|
||||
main{min-width:0}.section-title{display:flex;align-items:center;justify-content:space-between;gap:14px;margin:0 0 14px}.section-title h2{margin:0;font-size:24px}.section-title .sub{color:var(--muted);font-size:13px}.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:16px}.stat{padding:18px;border-radius:20px;background:#fff;border:1px solid var(--line);box-shadow:var(--shadow)}.stat .num{font-size:32px;font-weight:800;color:var(--red)}.stat .lab{color:var(--muted)}.two-col{display:grid;grid-template-columns:1.15fr .85fr;gap:14px}.cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}.card{padding:16px;cursor:pointer;transition:.18s;min-height:176px}.card:hover{transform:translateY(-2px);box-shadow:0 22px 60px rgba(51,20,14,.15);border-color:#d7b9ac}.card h3{margin:8px 0 8px;font-size:18px}.card p{margin:0 0 10px;color:#5b4744}.meta-row{display:flex;gap:7px;align-items:center;flex-wrap:wrap}.pill{display:inline-flex;align-items:center;gap:4px;border:1px solid var(--line);border-radius:999px;padding:4px 8px;font-size:12px;background:#fff;color:#5d4c49;margin:2px}.pill.red{background:#fff0ee;color:var(--red2);border-color:#ebc6bf}.pill.blue{background:var(--blue2);color:var(--blue);border-color:#cfe0ee}.pill.green{background:#eef8ef;color:var(--green);border-color:#cfe6d2}.pill.gold{background:#fff6e6;color:var(--gold);border-color:#ecd7ad}.risk-high{background:#fff0ee;color:#8b1d1d;border-color:#e8beb8}.risk-medium{background:#fff7e8;color:#8a5b08;border-color:#ead6a4}.risk-low{background:#eef9f1;color:#426f49;border-color:#cfe7d5}.small{font-size:12px;color:var(--muted)}.badge-title{font-size:12px;color:var(--muted);margin-top:12px;text-transform:uppercase;letter-spacing:.06em}.timeline{position:relative;padding-left:18px}.timeline:before{content:"";position:absolute;left:4px;top:6px;bottom:6px;width:2px;background:#e3c8c0}.titem{position:relative;margin:0 0 14px}.titem:before{content:"";position:absolute;left:-21px;top:20px;width:12px;height:12px;border-radius:50%;background:var(--red);box-shadow:0 0 0 5px #f8e8e4}.tcard{background:#fff;border:1px solid var(--line);border-radius:18px;padding:15px;cursor:pointer}.tdate{font-size:12px;color:var(--red);font-weight:700}.table-wrap{overflow:auto;background:#fff;border:1px solid var(--line);border-radius:18px}table{border-collapse:separate;border-spacing:0;width:100%;min-width:900px}th,td{border-bottom:1px solid var(--line);padding:12px 12px;text-align:left;vertical-align:top}th{background:#fff5f2;color:#6a3330;font-size:13px;position:sticky;top:0}td{font-size:14px}.viewbar{display:flex;gap:8px;justify-content:flex-end;margin:-4px 0 12px}.viewbar button, .inline-btn{border:1px solid var(--line);background:#fff;border-radius:999px;padding:8px 12px;cursor:pointer}.viewbar button.active{background:var(--red);color:#fff;border-color:var(--red)}.matrix{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}.risk-col{border:1px solid var(--line);background:#fff;border-radius:20px;padding:14px}.empty{border:1px dashed #d7bdb5;border-radius:18px;padding:35px;text-align:center;color:var(--muted);background:#fff}.linkish,.rel-card{cursor:pointer}.rel-card{border:1px solid var(--line);border-radius:14px;padding:10px;background:#fff;margin:6px 0}.rel-card strong{display:block}.rel-card span{color:var(--muted);font-size:12px}.mini-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.distance-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}.distance{background:#fff;border:1px solid var(--line);border-radius:16px;padding:12px}.distance strong{display:block;color:var(--red);font-size:22px}.distance span{font-size:12px;color:var(--muted)}
|
||||
.modal-backdrop{position:fixed;inset:0;background:rgba(38,15,12,.5);display:none;align-items:center;justify-content:center;z-index:100;padding:20px}.modal-backdrop.show{display:flex}.modal{width:min(1120px,100%);max-height:90vh;overflow:auto}.modal-head{padding:20px 24px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;gap:12px;align-items:flex-start;position:sticky;top:0;background:#fffdfb;z-index:2}.modal-title{margin:0;font-size:24px}.close{border:0;background:#f4e6e2;border-radius:12px;width:40px;height:40px;font-size:24px;cursor:pointer}.modal-body{padding:20px 24px 28px}.hero{padding:18px;border:1px solid var(--line);border-radius:20px;background:linear-gradient(135deg,#fff7f4,#fffdfb);margin-bottom:14px}.hero h3{margin:0 0 8px}.detail-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.detail-section{border:1px solid var(--line);background:#fff;border-radius:18px;padding:15px;margin-bottom:14px}.detail-section h4{margin:0 0 10px;color:var(--red2);font-size:16px}.detail-section p{margin:6px 0}.detail-section ul{margin:8px 0 0;padding-left:20px}.obj-table{width:100%;min-width:0}.obj-table th,.obj-table td{font-size:13px;padding:8px}.full{grid-column:1/-1}.note-box{background:#fff9ef;border:1px solid #ecd5ad;border-radius:16px;padding:12px}.source-list{font-size:12px;color:var(--muted);line-height:1.6}.kpi-strip{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin:12px 0}.kpi{border:1px solid var(--line);border-radius:16px;padding:12px;background:#fff}.kpi b{display:block;color:var(--red);font-size:20px}.kpi span{font-size:12px;color:var(--muted)}
|
||||
@media(max-width:1120px){.wrap{grid-template-columns:1fr}.filters,.side{position:relative;top:0}.cards{grid-template-columns:repeat(2,minmax(0,1fr))}.stats{grid-template-columns:repeat(2,minmax(0,1fr))}.two-col,.matrix,.detail-grid{grid-template-columns:1fr}nav{top:120px}.distance-grid{grid-template-columns:repeat(2,1fr)}}
|
||||
@media(max-width:680px){header{position:relative}.topline{display:block}.tools{margin-top:12px}.search{min-width:100%;width:100%}nav{position:relative;top:0}.wrap{padding:0 12px}.cards{grid-template-columns:1fr}.stats{grid-template-columns:1fr}.distance-grid,.mini-grid,.kpi-strip{grid-template-columns:1fr}.modal-backdrop{padding:6px}.modal-head{padding:16px}.modal-body{padding:14px}.tabs{padding:10px 12px}}
|
||||
@media print{header,nav,.filters,.side,.tools,.modal-backdrop{display:none!important}.wrap{display:block;max-width:none}.card,.panel,.stat{box-shadow:none}.cards{grid-template-columns:1fr 1fr}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header><div class="topline"><div class="title"><h1 id="projectTitle">专题数据库</h1><p id="projectSubtitle"></p></div><div class="tools"><input id="globalSearch" class="search" placeholder="全局搜索:EDCA / Cagayan / BAYAN / 台海 / WPS"><label class="btn">导入JSON<input id="jsonFile" type="file" accept="application/json,.json"></label><button class="btn" onclick="downloadJson()">导出JSON</button></div></div></header>
|
||||
<nav><div class="tabs" id="tabs"></div></nav>
|
||||
<div class="wrap"><aside class="panel filters"><h3>筛选器</h3><div class="field"><label>关键词</label><input id="filterKeyword" placeholder="在当前库内搜索"></div><div class="field"><label>年份</label><select id="filterYear"></select></div><div class="field"><label>事件类型</label><select id="filterCategory"></select></div><div class="field"><label>省份</label><select id="filterProvince"></select></div><div class="field"><label>阵营</label><select id="filterCamp"></select></div><div class="field"><label>风险等级</label><select id="filterRisk"></select></div><div class="field"><label>战略方向</label><select id="filterAxis"></select></div><button class="reset" onclick="resetFilters()">清空筛选</button><div class="source-list" style="margin-top:14px">说明:本页面为公开资料研究展示工具,复杂字段以详情弹框结构化展示,不再输出原始JSON。</div></aside><main id="main"></main><aside class="panel side"><h3>数据摘要</h3><div id="summaryPanel"></div><h3 style="margin-top:18px">高频标签</h3><div id="tagCloud"></div></aside></div>
|
||||
<div class="modal-backdrop" id="modalBackdrop" onclick="backdropClose(event)"><div class="modal"><div class="modal-head"><div><h2 id="modalTitle" class="modal-title"></h2><div id="modalMeta" class="meta-row"></div></div><button class="close" onclick="closeModal()">×</button></div><div id="modalBody" class="modal-body"></div></div></div>
|
||||
<script id="db-json" type="application/json">{"meta": {"project_title": "菲律宾“不做美国棋子”叙事专题数据库", "project_subtitle": "Philippines “Not a US Pawn” Narrative Research Dashboard", "version": "0.2", "last_updated": "2026-06-29", "language": "zh-CN", "description": "用于展示菲律宾“菲律宾不做美国棋子”叙事专题的结构化知识库,覆盖EDCA地点、事件线、人物组织、叙事结构、竞争叙事、风险核查和跨库关联查询。", "scope_note": "本数据库服务于公开资料研究、舆情观察、风险评估与专题分析,不用于隐蔽影响、虚假传播或操控性动员。", "revision_note": "v0.2增强版:弹框详情改为结构化页面展示,补充研究字段,尽量保留前期MD知识库中的分析内容。"}, "tabs": [{"id": "overview", "label": "专题总览", "type": "dashboard"}, {"id": "timeline", "label": "事件时间线", "type": "timeline"}, {"id": "edca_sites", "label": "EDCA地点库", "type": "cards_table"}, {"id": "actors", "label": "人物组织库", "type": "cards_table"}, {"id": "narratives", "label": "叙事结构库", "type": "cards"}, {"id": "counter_narratives", "label": "竞争叙事库", "type": "cards"}, {"id": "risks", "label": "风险核查库", "type": "risk_matrix"}, {"id": "search", "label": "综合查询", "type": "search"}], "dictionaries": {"event_categories": {"edca_signature": "EDCA签署/制度化", "edca_expansion": "EDCA扩展", "edca_infrastructure": "EDCA基建", "balikatan": "Balikatan军演", "china_coast_guard": "中国海警事件", "ph_official_protest": "菲律宾官方抗议", "us_ph_meeting": "美菲高层会晤", "anti_edca_protest": "反EDCA/反军演抗议", "multilateral_security": "多边安全合作", "wps_civil_action": "WPS民间行动"}, "strategic_axis": {"taiwan_bashi": "台海—巴士海峡方向", "wps_scs": "西菲律宾海—南海方向", "northern_luzon": "北吕宋前沿方向", "central_luzon": "中吕宋支撑方向", "central_logistics": "中部群岛后勤方向", "mindanao": "棉兰老方向", "hadr": "人道援助与灾害响应"}, "actor_camps": {"marcos_official": "马科斯官方阵营", "duterte_camp": "杜特尔特阵营", "left_anti_base": "左翼反基地阵营", "wps_sovereignty": "WPS主权派", "fact_check": "事实核查机构", "security_expert": "安全专家与智库", "external_actor": "外部行为体"}, "actor_types": {"official_person": "官方人物", "political_person": "政治人物", "organization": "组织", "party_bloc": "政党/党团", "institution": "机构", "expert": "专家", "think_tank": "智库", "media_factcheck": "事实核查/媒体"}, "stance_values": {"support": "支持", "oppose": "反对", "mixed": "复杂/混合", "neutral": "中立", "unknown": "未知"}, "risk_levels": {"low": "低", "medium": "中", "high": "高"}, "site_types": {"naval_base": "海军基地", "airport": "机场", "army_camp": "陆军营地", "air_base": "空军基地", "airfield": "机场/航空场"}, "field_labels": {"id": "编号", "name": "名称", "name_cn": "中文名", "name_en": "英文名", "title": "标题", "summary": "摘要", "brief": "简述", "description": "说明", "province": "省份", "city_or_area": "城市/区域", "designation_year": "纳入年份", "site_type": "地点类型", "strategic_axis": "战略方向", "risk_level": "风险等级", "local_position": "地方态度", "tags": "标签", "distances": "近似距离", "detail": "详情", "strategic_value": "战略意义", "local_political_positions": "地方政治人物表态", "local_reactions": "地方居民抗议或支持", "infrastructure_projects": "基建项目", "risk_controversies": "风险争议", "official_response": "官方回应", "related_events": "关联事件", "related_actors": "关联人物组织", "related_sites": "关联地点", "background": "背景", "opposition_position": "反对方立场", "ph_official_position": "菲律宾官方立场", "us_position": "美国立场", "china_position": "中国立场", "research_note": "研究备注", "category": "类别", "date": "日期", "year": "年份", "location": "地点", "actors": "相关行为体", "narrative_signal": "叙事信号", "counter_narrative": "竞争叙事/反驳框架", "current_role": "当前身份", "camp": "阵营", "type": "类型", "stance_on_edca": "对EDCA立场", "stance_on_wps": "对WPS立场", "influence_level": "影响等级", "narrative_function": "叙事功能", "typical_positions": "典型立场", "typical_keywords": "典型关键词", "risk_note": "风险备注", "profile": "画像", "monitoring_focus": "监测重点", "core_claims": "核心命题", "target_audiences": "目标受众", "typical_expressions": "典型表达", "strength": "叙事强项", "weakness": "叙事弱项", "counter_narratives": "竞争叙事", "main_speakers": "主要提出者", "used_against": "用于反驳", "evidence_types": "证据类型", "advantage": "优势", "limitation": "限制", "trigLine truncated
|
||||
<script>
|
||||
let DB = JSON.parse(document.getElementById('db-json').textContent);
|
||||
const $=s=>document.querySelector(s), $$=s=>Array.from(document.querySelectorAll(s));
|
||||
let state={tab:'overview',view:'cards',filters:{},global:''};
|
||||
const collMap={event:'events',edca_site:'edca_sites',actor:'actors',narrative:'narratives',counter_narrative:'counter_narratives',risk:'risks'};
|
||||
const tabsForType={event:'timeline',edca_site:'edca_sites',actor:'actors',narrative:'narratives',counter_narrative:'counter_narratives',risk:'risks'};
|
||||
function arr(x){return Array.isArray(x)?x:[]}
|
||||
function esc(s){return String(s??'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]))}
|
||||
function dict(group,key){return DB.dictionaries?.[group]?.[key] || key || ''}
|
||||
function label(k){return DB.dictionaries?.field_labels?.[k] || k}
|
||||
function titleOf(o){return o?.title || o?.name_cn || o?.name || o?.name_en || o?.id || ''}
|
||||
function summaryOf(o){return o?.summary || o?.brief || o?.description || o?.narrative_function || ''}
|
||||
function risk(level){return level?`<span class="pill risk-${esc(level)}">风险:${esc(dict('risk_levels',level))}</span>`:''}
|
||||
function chips(tags,cls=''){return arr(tags).map(t=>`<span class="pill ${cls}">${esc(t)}</span>`).join('')}
|
||||
function getAll(){let out=[];Object.entries(collMap).forEach(([type,key])=>arr(DB.data?.[key]).forEach(x=>out.push({...x,__type:type})));return out}
|
||||
function find(id){for(const [type,key] of Object.entries(collMap)){const x=arr(DB.data?.[key]).find(i=>i.id===id); if(x) return {...x,__type:type}}return null}
|
||||
function searchText(o){return JSON.stringify(o).toLowerCase()}
|
||||
function matchKw(o,kw){return !kw || searchText(o).includes(kw.toLowerCase())}
|
||||
function setup(){ $('#projectTitle').textContent=DB.meta.project_title; $('#projectSubtitle').textContent=(DB.meta.project_subtitle||'')+' · '+(DB.meta.revision_note||''); renderTabs(); fillFilters(); bind(); render(); }
|
||||
function renderTabs(){ $('#tabs').innerHTML=arr(DB.tabs).map(t=>`<button class="tab ${state.tab===t.id?'active':''}" data-id="${esc(t.id)}">${esc(t.label)}</button>`).join(''); $$('#tabs .tab').forEach(b=>b.onclick=()=>{state.tab=b.dataset.id;renderTabs();render();}); }
|
||||
function optAll(label){return `<option value="">${label}</option>`}
|
||||
function fillFilters(){ const years=[...new Set(arr(DB.data.events).map(e=>e.year).filter(Boolean))].sort((a,b)=>a-b); $('#filterYear').innerHTML=optAll('全部年份')+years.map(y=>`<option>${y}</option>`).join(''); $('#filterCategory').innerHTML=optAll('全部类型')+Object.entries(DB.dictionaries.event_categories||{}).map(([k,v])=>`<option value="${esc(k)}">${esc(v)}</option>`).join(''); const ps=[...new Set(arr(DB.data.edca_sites).map(s=>s.province).filter(Boolean))].sort(); $('#filterProvince').innerHTML=optAll('全部省份')+ps.map(p=>`<option>${esc(p)}</option>`).join(''); $('#filterCamp').innerHTML=optAll('全部阵营')+Object.entries(DB.dictionaries.actor_camps||{}).map(([k,v])=>`<option value="${esc(k)}">${esc(v)}</option>`).join(''); $('#filterRisk').innerHTML=optAll('全部风险')+Object.entries(DB.dictionaries.risk_levels||{}).map(([k,v])=>`<option value="${esc(k)}">${esc(v)}</option>`).join(''); $('#filterAxis').innerHTML=optAll('全部方向')+Object.entries(DB.dictionaries.strategic_axis||{}).map(([k,v])=>`<option value="${esc(k)}">${esc(v)}</option>`).join(''); }
|
||||
function bind(){ ['filterKeyword','filterYear','filterCategory','filterProvince','filterCamp','filterRisk','filterAxis'].forEach(id=>{$('#'+id).oninput=collect;$('#'+id).onchange=collect}); $('#globalSearch').oninput=e=>{state.global=e.target.value.trim(); if(state.global){state.tab='search';renderTabs()} render()}; $('#jsonFile').onchange=importJson; window.onkeydown=e=>{if(e.key==='Escape')closeModal()}; }
|
||||
function collect(){ state.filters={keyword:$('#filterKeyword').value.trim(),year:$('#filterYear').value,category:$('#filterCategory').value,province:$('#filterProvince').value,camp:$('#filterCamp').value,risk:$('#filterRisk').value,axis:$('#filterAxis').value}; render(); }
|
||||
function resetFilters(){['filterKeyword','filterYear','filterCategory','filterProvince','filterCamp','filterRisk','filterAxis','globalSearch'].forEach(id=>$('#'+id).value='');state.filters={};state.global='';render()}
|
||||
function commonFilter(items){const f=state.filters||{};return items.filter(x=>{if(f.keyword&&!matchKw(x,f.keyword))return false;if(f.risk&&x.risk_level!==f.risk)return false;if(f.year&&x.year&&String(x.year)!==String(f.year))return false;if(f.category&&x.category&&x.category!==f.category)return false;if(f.province&&x.province&&x.province!==f.province)return false;if(f.camp&&x.camp&&x.camp!==f.camp)return false;if(f.axis&&x.strategic_axis&&!arr(x.strategic_axis).includes(f.axis))return false;return true})}
|
||||
function render(){renderSummary();const t=state.tab;if(t==='overview')overview();if(t==='timeline')timeline();if(t==='edca_sites')sites();if(t==='actors')actors();if(t==='narratives')narratives();if(t==='counter_narratives')counters();if(t==='risks')risks();if(t==='search')search();}
|
||||
function renderSummary(){const d=DB.data;const rows=[['EDCA地点',arr(d.edca_sites).length],['事件',arr(d.events).length],['人物组织',arr(d.actors).length],['叙事结构',arr(d.narratives).length],['竞争叙事',arr(d.counter_narratives).length],['风险项',arr(d.risks).length],['高风险地点',arr(d.edca_sites).filter(x=>x.risk_level==='high').length],['高风险事件',arr(d.events).filter(x=>x.risk_level==='high').length]];$('#summaryPanel').innerHTML=rows.map(([k,v])=>`<div class="summary-item"><strong>${v}</strong><span>${k}</span></div>`).join(''); const tags={}; getAll().forEach(x=>arr(x.tags).forEach(t=>tags[t]=(tags[t]||0)+1)); $('#tagCloud').innerHTML=Object.entries(tags).sort((a,b)=>b[1]-a[1]).slice(0,20).map(([t,n])=>`<span class="pill">${esc(t)} · ${n}</span>`).join('');}
|
||||
function overview(){const d=DB.data;const high=arr(d.edca_sites).filter(x=>x.risk_level==='high');const eventCats={};arr(d.events).forEach(e=>eventCats[e.category]=(eventCats[e.category]||0)+1); const camps={};arr(d.actors).forEach(a=>camps[a.camp]=(camps[a.camp]||0)+1); $('#main').innerHTML=`<div class="section-title"><div><h2>专题总览</h2><div class="sub">${esc(DB.meta.description)}</div></div><span class="pill red">${esc(DB.meta.version)} · ${esc(DB.meta.last_updated)}</span></div><div class="stats"><div class="stat"><div class="num">${arr(d.edca_sites).length}</div><div class="lab">EDCA地点</div></div><div class="stat"><div class="num">${arr(d.events).length}</div><div class="lab">事件线节点</div></div><div class="stat"><div class="num">${arr(d.actors).length}</div><div class="lab">人物组织</div></div><div class="stat"><div class="num">${high.length}</div><div class="lab">高风险地点</div></div></div><div class="two-col"><div class="panel" style="padding:18px"><h3>核心问题</h3><p>本页面围绕“菲律宾不做美国棋子 / not a US pawn”这一叙事,展示其与EDCA、美菲同盟、Balikatan军演、西菲律宾海主权、杜特尔特—马科斯政治竞争、地方风险和事实核查之间的关系。</p><p class="small">${esc(DB.meta.scope_note||'')}</p>${chips(DB.indexes?.common_tags)}</div><div class="panel" style="padding:18px"><h3>事件类型分布</h3>${Object.entries(eventCats).map(([k,v])=>`<div class="summary-item"><strong>${v}</strong><span>${esc(dict('event_categories',k))}</span></div>`).join('')}</div></div><div style="height:14px"></div><div class="two-col"><div class="panel" style="padding:18px"><h3>阵营分布</h3>${Object.entries(camps).map(([k,v])=>`<div class="summary-item"><strong>${v}</strong><span>${esc(dict('actor_camps',k))}</span></div>`).join('')}</div><div class="panel" style="padding:18px"><h3>展示原则</h3><ul><li>卡片只看摘要,弹框展示完整知识结构。</li><li>长字段按模块呈现,不再显示原始JSON。</li><li>所有关联对象支持点击跳转。</li><li>风险内容同时展示核查重点和边界。</li></ul></div></div><div style="height:14px"></div><div class="section-title"><h2>高风险EDCA地点</h2><button class="inline-btn" onclick="state.tab='edca_sites';renderTabs();render()">查看全部</button></div><div class="cards">${high.map(siteCard).join('')}</div>`}
|
||||
function timeline(){let items=commonFilter(arr(DB.data.events)).sort((a,b)=>String(b.date).localeCompare(String(a.date))); if(state.filters.province){const ids=arr(DB.data.edca_sites).filter(s=>s.province===state.filters.province).map(s=>s.id);items=items.filter(e=>arr(e.related_sites).some(id=>ids.includes(id))||matchKw(e,state.filters.province));} $('#main').innerHTML=`<div class="section-title"><h2>事件时间线</h2><span class="pill blue">命中 ${items.length} 条</span></div>`+(items.length?`<div class="timeline">${items.map(e=>`<div class="titem"><div class="tcard" onclick="openModal('event','${esc(e.id)}')"><div class="tdate">${esc(e.date)} · ${esc(dict('event_categories',e.category))}</div><h3>${esc(e.title)}</h3><p>${esc(e.summary)}</p><div class="meta-row">${risk(e.risk_level)}${chips(e.tags)}</div></div></div>`).join('')}</div>`:empty())}
|
||||
function sites(){let items=commonFilter(arr(DB.data.edca_sites)); $('#main').innerHTML=`<div class="section-title"><h2>EDCA九个地点库</h2><span class="pill blue">命中 ${items.length} 条</span></div>${viewbar('sites')} ${state.view==='table'?siteTable(items):`<div class="cards">${items.map(siteCard).join('')}</div>`}`}
|
||||
function siteCard(s){return `<div class="card" onclick="openModal('edca_site','${esc(s.id)}')"><div class="meta-row"><span class="pill red">${esc(s.province)}</span>${risk(s.risk_level)}</div><h3>${esc(s.name)}</h3><p>${esc(s.brief)}</p><div class="badge-title">战略方向</div><div>${arr(s.strategic_axis).map(a=>`<span class="pill blue">${esc(dict('strategic_axis',a))}</span>`).join('')}</div><div class="badge-title">标签</div>${chips(s.tags)}</div>`}
|
||||
function siteTable(items){return `<div class="table-wrap"><table><thead><tr><th>地点</th><th>省份</th><th>年份</th><th>类型</th><th>战略方向</th><th>地方态度</th><th>风险</th><th>详情</th></tr></thead><tbody>${items.map(s=>`<tr><td><b>${esc(s.name)}</b><br><span class="small">${esc(s.city_or_area)}</span></td><td>${esc(s.province)}</td><td>${esc(s.designation_year)}</td><td>${esc(dict('site_types',s.site_type))}</td><td>${arr(s.strategic_axis).map(a=>esc(dict('strategic_axis',a))).join('<br>')}</td><td>${esc(s.local_position)}</td><td>${risk(s.risk_level)}</td><td><button class="inline-btn" onclick="openModal('edca_site','${esc(s.id)}')">打开</button></td></tr>`).join('')}</tbody></table></div>`}
|
||||
function actors(){let items=commonFilter(arr(DB.data.actors)); $('#main').innerHTML=`<div class="section-title"><h2>人物组织库</h2><span class="pill blue">命中 ${items.length} 条</span></div>${viewbar('actors')} ${state.view==='table'?actorTable(items):`<div class="cards">${items.map(actorCard).join('')}</div>`}`}
|
||||
function actorCard(a){return `<div class="card" onclick="openModal('actor','${esc(a.id)}')"><div class="meta-row"><span class="pill red">${esc(dict('actor_camps',a.camp))}</span><span class="pill">${esc(dict('actor_types',a.type))}</span></div><h3>${esc(a.name_cn||a.name_en)}</h3><p>${esc(a.brief)}</p><div class="badge-title">叙事功能</div><p>${esc(a.narrative_function||'')}</p>${chips(a.tags)}</div>`}
|
||||
function actorTable(items){return `<div class="table-wrap"><table><thead><tr><th>名称</th><th>类型</th><th>阵营</th><th>当前角色</th><th>EDCA立场</th><th>WPS立场</th><th>影响</th><th>详情</th></tr></thead><tbody>${items.map(a=>`<tr><td><b>${esc(a.name_cn||a.name_en)}</b><br><span class="small">${esc(a.name_en||'')}</span></td><td>${esc(dict('actor_types',a.type))}</td><td>${esc(dict('actor_camps',a.camp))}</td><td>${esc(a.current_role)}</td><td>${esc(dict('stance_values',a.stance_on_edca))}</td><td>${esc(dict('stance_values',a.stance_on_wps))}</td><td>${esc(a.influence_level)}</td><td><button class="inline-btn" onclick="openModal('actor','${esc(a.id)}')">打开</button></td></tr>`).join('')}</tbody></table></div>`}
|
||||
function narratives(){const items=commonFilter(arr(DB.data.narratives)); $('#main').innerHTML=`<div class="section-title"><h2>叙事结构库</h2><span class="pill blue">命中 ${items.length} 条</span></div><div class="cards">${items.map(n=>`<div class="card" onclick="openModal('narrative','${esc(n.id)}')"><div class="meta-row"><span class="pill red">${esc(n.category)}</span>${risk(n.risk_level)}</div><h3>${esc(n.title)}</h3><p>${esc(n.summary)}</p>${chips(n.tags)}</div>`).join('')}</div>`}
|
||||
function counters(){const items=commonFilter(arr(DB.data.counter_narratives)); $('#main').innerHTML=`<div class="section-title"><h2>竞争叙事库</h2><span class="pill blue">命中 ${items.length} 条</span></div><div class="cards">${items.map(c=>`<div class="card" onclick="openModal('counter_narrative','${esc(c.id)}')"><div class="meta-row"><span class="pill blue">竞争叙事</span>${risk(c.risk_level)}</div><h3>${esc(c.title)}</h3><p>${esc(c.summary)}</p>${chips(c.tags)}</div>`).join('')}</div>`}
|
||||
function risks(){const items=commonFilter(arr(DB.data.risks)); const levels=['high','medium','low']; $('#main').innerHTML=`<div class="section-title"><h2>风险与事实核查库</h2><span class="pill blue">命中 ${items.length} 条</span></div><div class="matrix">${levels.map(l=>`<div class="risk-col"><h3>${esc(dict('risk_levels',l))}风险</h3>${items.filter(r=>r.risk_level===l).map(r=>`<div class="card" style="min-height:auto;margin-bottom:10px" onclick="openModal('risk','${esc(r.id)}')"><h3>${esc(r.title)}</h3><p>${esc(r.description)}</p>${chips(r.tags)}</div>`).join('')||'<div class="empty">暂无</div>'}</div>`).join('')}</div>`}
|
||||
function search(){const kw=state.global||state.filters.keyword||'';let items=getAll().filter(x=>matchKw(x,kw));items=commonFilter(items); const names={event:'事件',edca_site:'EDCA地点',actor:'人物组织',narrative:'叙事结构',counter_narrative:'竞争叙事',risk:'风险'}; $('#main').innerHTML=`<div class="section-title"><div><h2>综合查询中心</h2><div class="sub">${kw?'关键词:'+esc(kw):'可在顶部或左侧输入关键词,跨库检索所有对象。'}</div></div><span class="pill blue">命中 ${items.length} 条</span></div>`+(items.length?`<div class="table-wrap"><table><thead><tr><th>类型</th><th>标题/名称</th><th>摘要</th><th>标签</th><th>风险</th><th>详情</th></tr></thead><tbody>${items.map(i=>`<tr><td><span class="pill red">${esc(names[i.__type])}</span></td><td><b>${esc(titleOf(i))}</b></td><td>${esc(summaryOf(i)).slice(0,260)}</td><td>${chips(i.tags)}</td><td>${risk(i.risk_level)}</td><td><button class="inline-btn" onclick="openModal('${esc(i.__type)}','${esc(i.id)}')">打开</button></td></tr>`).join('')}</tbody></table></div>`:empty('暂无查询结果。'))}
|
||||
function viewbar(){return `<div class="viewbar"><button class="${state.view==='cards'?'active':''}" onclick="state.view='cards';render()">卡片</button><button class="${state.view==='table'?'active':''}" onclick="state.view='table';render()">表格</button></div>`}
|
||||
function empty(t='没有匹配结果。'){return `<div class="empty">${esc(t)}</div>`}
|
||||
function openModal(type,id){const item=find(id); if(!item)return; $('#modalTitle').textContent=titleOf(item); $('#modalMeta').innerHTML=modalMeta(item); $('#modalBody').innerHTML=modalBody(item,type); $('#modalBackdrop').classList.add('show')}
|
||||
function closeModal(){$('#modalBackdrop').classList.remove('show')}
|
||||
function backdropClose(e){if(e.target.id==='modalBackdrop')closeModal()}
|
||||
function modalMeta(o){let bits=[]; if(o.date)bits.push(`<span class="pill">${esc(o.date)}</span>`); if(o.category)bits.push(`<span class="pill blue">${esc(dict('event_categories',o.category))}</span>`); if(o.province)bits.push(`<span class="pill red">${esc(o.province)}</span>`); if(o.camp)bits.push(`<span class="pill red">${esc(dict('actor_camps',o.camp))}</span>`); if(o.risk_level)bits.push(risk(o.risk_level)); return bits.join('')+chips(o.tags)}
|
||||
function section(title,content,cls=''){if(!content)return''; return `<section class="detail-section ${cls}"><h4>${esc(title)}</h4>${content}</section>`}
|
||||
function paragraph(v){return v?`<p>${esc(v)}</p>`:''}
|
||||
function list(v){if(!v||!arr(v).length)return''; return `<ul>${arr(v).map(x=>`<li>${renderVal(x)}</li>`).join('')}</ul>`}
|
||||
function objGrid(o){if(!o||typeof o!=='object')return''; return `<div class="mini-grid">${Object.entries(o).filter(([k,v])=>v!==undefined&&v!==null&&v!==''&&!(Array.isArray(v)&&!v.length)).map(([k,v])=>`<div class="rel-card"><span>${esc(label(k))}</span><strong>${renderVal(v)}</strong></div>`).join('')}</div>`}
|
||||
function objTable(items){if(!arr(items).length)return''; if(typeof items[0]!=='object')return list(items); const keys=[...new Set(items.flatMap(o=>Object.keys(o)))]; return `<div class="table-wrap"><table class="obj-table"><thead><tr>${keys.map(k=>`<th>${esc(label(k))}</th>`).join('')}</tr></thead><tbody>${items.map(o=>`<tr>${keys.map(k=>`<td>${renderVal(o[k])}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`}
|
||||
function renderVal(v){if(v===undefined||v===null)return''; if(Array.isArray(v)){if(v.length&&typeof v[0]==='object')return objTable(v); return arr(v).map(x=>renderVal(x)).join('<br>')} if(typeof v==='object')return objGrid(v); const s=String(v); const x=find(s); if(x)return `<span class="linkish pill blue" onclick="jump('${esc(s)}')">${esc(titleOf(x))}</span>`; return esc(s)}
|
||||
function rels(ids){return arr(ids).map(id=>{const x=find(id); return x?`<div class="rel-card" onclick="jump('${esc(id)}')"><strong>${esc(titleOf(x))}</strong><span>${esc(typeName(x.__type))} · ${esc(summaryOf(x)).slice(0,88)}</span></div>`:`<div class="rel-card"><strong>${esc(id)}</strong></div>`}).join('')}
|
||||
function typeName(t){return {event:'事件',edca_site:'EDCA地点',actor:'人物组织',narrative:'叙事结构',counter_narrative:'竞争叙事',risk:'风险'}[t]||t}
|
||||
function distances(d){if(!d)return''; return `<div class="distance-grid">${Object.entries(d).map(([k,v])=>`<div class="distance"><strong>${esc(v)} km</strong><span>${esc(label(k))}</span></div>`).join('')}</div>`}
|
||||
function modalBody(o,type){
|
||||
let d=o.detail||{};
|
||||
if(type==='edca_site') return `<div class="hero"><h3>${esc(o.name)}</h3><p>${esc(o.brief)}</p><div class="kpi-strip"><div class="kpi"><b>${esc(o.designation_year)}</b><span>纳入年份</span></div><div class="kpi"><b>${esc(o.province)}</b><span>省份</span></div><div class="kpi"><b>${esc(dict('site_types',o.site_type))}</b><span>地点类型</span></div><div class="kpi"><b>${esc(dict('risk_levels',o.risk_level))}</b><span>风险等级</span></div></div></div><div class="detail-grid">${section('基本信息',objGrid({province:o.province,city_or_area:o.city_or_area,designation_year:o.designation_year,site_type:dict('site_types',o.site_type),strategic_axis:arr(o.strategic_axis).map(a=>dict('strategic_axis',a)).join(' / '),local_position:o.local_position}),'full')}${section('近似距离与战略方向',distances(o.distances),'full')}${section('战略意义',paragraph(d.strategic_value))}${section('叙事解读',list(d.narrative_interpretation))}${section('地方政治人物表态',objTable(d.local_political_positions),'full')}${section('地方居民抗议或支持',objGrid(d.local_reactions))}${section('基建项目',list(d.infrastructure_projects))}${section('风险争议',list(d.risk_controversies))}${section('官方回应',paragraph(d.official_response))}${section('竞争性解释',list(d.counter_reading))}${section('证据线索',list(d.evidence_clues))}${section('展示提示',`<div class="note-box">${esc(d.display_warning||'')}</div>`)}${section('研究缺口',list(d.research_gaps),'full')}${section('关联事件',rels(d.related_events),'full')}${section('关联人物组织',rels(d.related_actors),'full')}</div>`;
|
||||
if(type==='event') return `<div class="hero"><h3>${esc(o.title)}</h3><p>${esc(o.summary)}</p></div><div class="detail-grid">${section('时间地点',objGrid({date:o.date,year:o.year,location:o.location,category:dict('event_categories',o.category)}),'full')}${section('事件背景',paragraph(d.background))}${section('为什么重要',paragraph(d.why_it_matters||o.narrative_signal))}${section('叙事信号',paragraph(o.narrative_signal))}${section('竞争叙事/反驳框架',paragraph(o.counter_narrative))}${section('菲律宾官方立场',paragraph(d.ph_official_position))}${section('美国立场',paragraph(d.us_position))}${section('中国立场',paragraph(d.china_position))}${section('反对方立场',paragraph(d.opposition_position))}${section('叙事复杂性',paragraph(d.narrative_complication))}${section('研究备注',paragraph(d.research_note),'full')}${section('相关行为体',rels(o.actors),'full')}${section('关联地点',rels(o.related_sites),'full')}</div>`;
|
||||
if(type==='actor') return `<div class="hero"><h3>${esc(o.name_cn||o.name_en)}</h3><p>${esc(o.brief)}</p></div><div class="detail-grid">${section('基本信息',objGrid({name_en:o.name_en,type:dict('actor_types',o.type),camp:dict('actor_camps',o.camp),current_role:o.current_role,stance_on_edca:dict('stance_values',o.stance_on_edca),stance_on_wps:dict('stance_values',o.stance_on_wps),influence_level:o.influence_level}),'full')}${section('人物/组织画像',paragraph(d.profile))}${section('叙事功能',paragraph(o.narrative_function))}${section('典型立场',list(d.typical_positions))}${section('典型关键词',list(d.typical_keywords))}${section('监测重点',list(d.monitoring_focus),'full')}${section('风险备注',paragraph(d.risk_note))}${section('研究备注',paragraph(d.research_note))}${section('关联事件',rels(d.related_events),'full')}${section('关联地点',rels(d.related_sites),'full')}</div>`;
|
||||
if(type==='narrative') return `<div class="hero"><h3>${esc(o.title)}</h3><p>${esc(o.summary)}</p></div><div class="detail-grid">${section('核心命题',list(o.core_claims),'full')}${section('目标受众',list(o.target_audiences))}${section('典型表达',list(o.typical_expressions))}${section('适用场景',list(d.application_scenarios))}${section('叙事强项',paragraph(d.strength))}${section('叙事弱项',paragraph(d.weakness))}${section('分析备注',paragraph(d.analysis_note),'full')}${section('待补数据',list(d.data_to_collect))}${section('关联事件',rels(o.related_events),'full')}${section('关联人物组织',rels(o.related_actors),'full')}${section('竞争叙事',rels(d.counter_narratives),'full')}</div>`;
|
||||
if(type==='counter_narrative') return `<div class="hero"><h3>${esc(o.title)}</h3><p>${esc(o.summary)}</p></div><div class="detail-grid">${section('主要提出者',list(o.main_speakers))}${section('证据类型',list(o.evidence_types))}${section('优势',paragraph(d.advantage))}${section('限制',paragraph(d.limitation))}${section('观察场景',list(d.where_to_observe))}${section('对“美国棋子”叙事的影响',paragraph(d.impact_on_proxy_narrative),'full')}${section('用于反驳',rels(o.used_against),'full')}${section('关联事件',rels(d.related_events),'full')}</div>`;
|
||||
if(type==='risk') return `<div class="hero"><h3>${esc(o.title)}</h3><p>${esc(o.description)}</p></div><div class="detail-grid">${section('触发场景',list(o.trigger_scenarios),'full')}${section('事实核查重点',list(o.fact_check_focus),'full')}${section('风险边界与处理建议',list(o.mitigation_guidelines),'full')}${section('展示提示',`<div class="note-box">${esc(o.display_note||'')}</div>`)}${section('关联地点',rels(o.related_sites),'full')}${section('关联人物组织',rels(o.related_actors),'full')}</div>`;
|
||||
return section('详情',renderVal(o),'full')
|
||||
}
|
||||
function jump(id){const x=find(id); if(!x)return; closeModal(); state.tab=tabsForType[x.__type]||'search'; renderTabs(); render(); setTimeout(()=>openModal(x.__type,id),80)}
|
||||
function importJson(e){const file=e.target.files[0]; if(!file)return; const r=new FileReader(); r.onload=ev=>{try{DB=JSON.parse(ev.target.result);fillFilters();renderTabs();render();alert('JSON导入成功')}catch(err){alert('JSON解析失败:'+err.message)}}; r.readAsText(file,'utf-8')}
|
||||
function downloadJson(){const blob=new Blob([JSON.stringify(DB,null,2)],{type:'application/json;charset=utf-8'});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download='philippines_not_us_pawn_narrative_db_v2_export.json';a.click();URL.revokeObjectURL(url)}
|
||||
setup();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+899
@@ -0,0 +1,899 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>台湾陆军机动打击部队知识数据展示平台</title>
|
||||
<style>
|
||||
:root {
|
||||
--red-900:#8f1020;
|
||||
--red-800:#a51324;
|
||||
--red-700:#bf1f2f;
|
||||
--red-600:#d12b3b;
|
||||
--red-soft:#fff1f2;
|
||||
--red-soft-2:#fde7e9;
|
||||
--ink:#17202a;
|
||||
--text:#263241;
|
||||
--muted:#667085;
|
||||
--muted-2:#8a94a6;
|
||||
--line:#e3e7ee;
|
||||
--bg:#f4f7fb;
|
||||
--card:#ffffff;
|
||||
--shadow:0 8px 24px rgba(16, 24, 40, .06);
|
||||
--shadow-2:0 18px 55px rgba(16, 24, 40, .14);
|
||||
--radius:16px;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body{
|
||||
margin:0;
|
||||
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei","Noto Sans CJK SC",Arial,sans-serif;
|
||||
color:var(--ink);
|
||||
background:
|
||||
radial-gradient(circle at 20% 5%, rgba(191,31,47,.08), transparent 30%),
|
||||
linear-gradient(180deg,#f8fafc 0%, var(--bg) 240px, var(--bg) 100%);
|
||||
}
|
||||
.app-header{
|
||||
height:104px;
|
||||
background:linear-gradient(135deg,var(--red-900),var(--red-800) 54%,var(--red-700));
|
||||
color:#fff;
|
||||
display:flex;
|
||||
align-items:center;
|
||||
justify-content:space-between;
|
||||
padding:0 36px;
|
||||
box-shadow:0 8px 24px rgba(143,16,32,.22);
|
||||
position:sticky;
|
||||
top:0;
|
||||
z-index:20;
|
||||
}
|
||||
.brand{
|
||||
display:flex;
|
||||
align-items:center;
|
||||
gap:18px;
|
||||
min-width:420px;
|
||||
}
|
||||
.logo{
|
||||
width:58px;
|
||||
height:58px;
|
||||
border:2px solid rgba(255,255,255,.8);
|
||||
border-radius:18px;
|
||||
display:grid;
|
||||
place-items:center;
|
||||
font-size:28px;
|
||||
font-weight:900;
|
||||
box-shadow:inset 0 0 0 1px rgba(255,255,255,.16);
|
||||
}
|
||||
.brand h1{
|
||||
margin:0;
|
||||
font-size:28px;
|
||||
line-height:1.1;
|
||||
font-weight:900;
|
||||
letter-spacing:-.03em;
|
||||
}
|
||||
.brand p{
|
||||
margin:7px 0 0;
|
||||
font-size:14px;
|
||||
color:rgba(255,255,255,.78);
|
||||
font-weight:600;
|
||||
}
|
||||
.header-actions{
|
||||
display:flex;
|
||||
align-items:center;
|
||||
gap:12px;
|
||||
min-width:420px;
|
||||
justify-content:flex-end;
|
||||
}
|
||||
.global-search{
|
||||
width:min(520px,42vw);
|
||||
height:58px;
|
||||
border:1px solid rgba(255,255,255,.24);
|
||||
background:rgba(255,255,255,.13);
|
||||
border-radius:14px;
|
||||
color:#fff;
|
||||
padding:0 48px 0 18px;
|
||||
outline:none;
|
||||
font-size:16px;
|
||||
font-weight:700;
|
||||
}
|
||||
.global-search::placeholder{color:rgba(255,255,255,.72)}
|
||||
.search-wrap{position:relative}
|
||||
.search-icon{
|
||||
position:absolute;
|
||||
right:17px;
|
||||
top:50%;
|
||||
transform:translateY(-50%);
|
||||
color:#fff;
|
||||
opacity:.88;
|
||||
font-size:20px;
|
||||
}
|
||||
.ai-btn{
|
||||
height:58px;
|
||||
border:0;
|
||||
border-radius:14px;
|
||||
padding:0 22px;
|
||||
background:#fff;
|
||||
color:var(--red-800);
|
||||
font-weight:900;
|
||||
font-size:17px;
|
||||
cursor:pointer;
|
||||
box-shadow:0 8px 22px rgba(0,0,0,.12);
|
||||
white-space:nowrap;
|
||||
}
|
||||
.tabbar-wrap{
|
||||
background:#fff;
|
||||
border-bottom:1px solid var(--line);
|
||||
position:sticky;
|
||||
top:104px;
|
||||
z-index:15;
|
||||
}
|
||||
.tabbar{
|
||||
display:flex;
|
||||
align-items:center;
|
||||
gap:0;
|
||||
padding:0 36px;
|
||||
overflow-x:auto;
|
||||
}
|
||||
.tab-btn{
|
||||
position:relative;
|
||||
border:0;
|
||||
background:transparent;
|
||||
color:#344054;
|
||||
height:72px;
|
||||
padding:0 23px;
|
||||
font-size:17px;
|
||||
font-weight:900;
|
||||
cursor:pointer;
|
||||
white-space:nowrap;
|
||||
}
|
||||
.tab-btn:hover{color:var(--red-800)}
|
||||
.tab-btn.active{color:var(--red-800)}
|
||||
.tab-btn.active::after{
|
||||
content:"";
|
||||
position:absolute;
|
||||
left:18px;
|
||||
right:18px;
|
||||
bottom:0;
|
||||
height:4px;
|
||||
border-radius:4px 4px 0 0;
|
||||
background:var(--red-700);
|
||||
}
|
||||
main{
|
||||
padding:32px 36px 58px;
|
||||
max-width:1800px;
|
||||
margin:0 auto;
|
||||
}
|
||||
.panel{display:none}
|
||||
.panel.active{display:block}
|
||||
.page-title{
|
||||
display:flex;
|
||||
align-items:flex-end;
|
||||
justify-content:space-between;
|
||||
gap:20px;
|
||||
margin:0 0 26px;
|
||||
}
|
||||
.page-title h2{
|
||||
margin:0;
|
||||
font-size:30px;
|
||||
letter-spacing:-.03em;
|
||||
}
|
||||
.page-title p{
|
||||
margin:12px 0 0;
|
||||
color:#667085;
|
||||
font-size:17px;
|
||||
line-height:1.6;
|
||||
}
|
||||
.page-actions{
|
||||
display:flex;
|
||||
gap:12px;
|
||||
flex-wrap:wrap;
|
||||
}
|
||||
.outline-btn,.solid-btn{
|
||||
height:54px;
|
||||
border-radius:12px;
|
||||
padding:0 22px;
|
||||
font-size:16px;
|
||||
font-weight:900;
|
||||
cursor:pointer;
|
||||
}
|
||||
.outline-btn{
|
||||
background:#fff;
|
||||
color:var(--red-800);
|
||||
border:1px solid rgba(191,31,47,.32);
|
||||
}
|
||||
.solid-btn{
|
||||
background:var(--red-800);
|
||||
color:#fff;
|
||||
border:1px solid var(--red-800);
|
||||
box-shadow:0 10px 22px rgba(191,31,47,.18);
|
||||
}
|
||||
.stat-row{
|
||||
display:grid;
|
||||
grid-template-columns:repeat(6,minmax(210px,1fr));
|
||||
gap:20px;
|
||||
overflow-x:auto;
|
||||
padding-bottom:4px;
|
||||
}
|
||||
.stat-card{
|
||||
min-height:158px;
|
||||
background:#fff;
|
||||
border:1px solid var(--line);
|
||||
border-radius:16px;
|
||||
padding:26px 24px 22px;
|
||||
position:relative;
|
||||
box-shadow:var(--shadow);
|
||||
overflow:hidden;
|
||||
}
|
||||
.stat-card::before{
|
||||
content:"";
|
||||
position:absolute;
|
||||
left:0;right:0;top:0;
|
||||
height:6px;
|
||||
background:linear-gradient(90deg,var(--red-800),var(--red-600));
|
||||
}
|
||||
.stat-label{
|
||||
color:#667085;
|
||||
font-weight:800;
|
||||
font-size:15px;
|
||||
}
|
||||
.stat-value{
|
||||
margin-top:12px;
|
||||
font-size:42px;
|
||||
font-weight:950;
|
||||
letter-spacing:-.04em;
|
||||
color:#1d2430;
|
||||
}
|
||||
.stat-note{
|
||||
margin-top:8px;
|
||||
color:#98a2b3;
|
||||
font-size:14px;
|
||||
}
|
||||
.section-title{
|
||||
margin:34px 0 16px;
|
||||
display:flex;
|
||||
justify-content:space-between;
|
||||
align-items:flex-end;
|
||||
gap:14px;
|
||||
}
|
||||
.section-title h3{
|
||||
margin:0;
|
||||
font-size:23px;
|
||||
}
|
||||
.section-title span{
|
||||
color:#667085;
|
||||
font-size:14px;
|
||||
}
|
||||
.grid-3{
|
||||
display:grid;
|
||||
grid-template-columns:repeat(3,minmax(0,1fr));
|
||||
gap:22px;
|
||||
}
|
||||
.grid-2{
|
||||
display:grid;
|
||||
grid-template-columns:repeat(2,minmax(0,1fr));
|
||||
gap:22px;
|
||||
}
|
||||
.grid-4{
|
||||
display:grid;
|
||||
grid-template-columns:repeat(4,minmax(0,1fr));
|
||||
gap:22px;
|
||||
}
|
||||
.topic-card,.card{
|
||||
background:#fff;
|
||||
border:1px solid var(--line);
|
||||
border-radius:18px;
|
||||
box-shadow:var(--shadow);
|
||||
padding:26px;
|
||||
position:relative;
|
||||
overflow:hidden;
|
||||
}
|
||||
.topic-card::after{
|
||||
content:"";
|
||||
position:absolute;
|
||||
right:-34px;
|
||||
top:-48px;
|
||||
width:150px;
|
||||
height:150px;
|
||||
border-radius:50%;
|
||||
background:rgba(191,31,47,.08);
|
||||
}
|
||||
.icon-box{
|
||||
width:54px;
|
||||
height:54px;
|
||||
display:grid;
|
||||
place-items:center;
|
||||
border-radius:12px;
|
||||
background:var(--red-700);
|
||||
color:#fff;
|
||||
font-size:24px;
|
||||
font-weight:950;
|
||||
margin-bottom:20px;
|
||||
}
|
||||
.topic-card h4,.card h4{
|
||||
margin:0;
|
||||
font-size:21px;
|
||||
letter-spacing:-.02em;
|
||||
}
|
||||
.topic-card p,.card p{
|
||||
color:#667085;
|
||||
line-height:1.72;
|
||||
margin:14px 0 0;
|
||||
font-size:15px;
|
||||
}
|
||||
.pill-row{
|
||||
display:flex;
|
||||
flex-wrap:wrap;
|
||||
gap:8px;
|
||||
margin-top:18px;
|
||||
}
|
||||
.pill{
|
||||
display:inline-flex;
|
||||
align-items:center;
|
||||
border-radius:999px;
|
||||
padding:7px 11px;
|
||||
background:var(--red-soft);
|
||||
color:var(--red-800);
|
||||
border:1px solid rgba(191,31,47,.08);
|
||||
font-size:13px;
|
||||
font-weight:900;
|
||||
}
|
||||
.pill.gray{
|
||||
background:#f2f4f7;
|
||||
color:#667085;
|
||||
border-color:#eaecf0;
|
||||
}
|
||||
.card-head{
|
||||
display:flex;
|
||||
justify-content:space-between;
|
||||
align-items:flex-start;
|
||||
gap:14px;
|
||||
margin-bottom:12px;
|
||||
}
|
||||
.detail-btn{
|
||||
border:1px solid rgba(191,31,47,.25);
|
||||
background:#fff;
|
||||
color:var(--red-800);
|
||||
border-radius:10px;
|
||||
padding:8px 12px;
|
||||
font-weight:900;
|
||||
cursor:pointer;
|
||||
white-space:nowrap;
|
||||
}
|
||||
.detail-btn:hover{background:var(--red-soft)}
|
||||
.toolbar{
|
||||
display:flex;
|
||||
flex-wrap:wrap;
|
||||
gap:12px;
|
||||
margin:0 0 18px;
|
||||
}
|
||||
.search,.select{
|
||||
height:48px;
|
||||
border:1px solid var(--line);
|
||||
border-radius:12px;
|
||||
background:#fff;
|
||||
padding:0 14px;
|
||||
font-size:15px;
|
||||
outline:none;
|
||||
color:#263241;
|
||||
}
|
||||
.search{flex:1;min-width:260px}
|
||||
.search:focus,.select:focus{
|
||||
border-color:rgba(191,31,47,.55);
|
||||
box-shadow:0 0 0 4px rgba(191,31,47,.08);
|
||||
}
|
||||
.table-wrap{
|
||||
overflow:auto;
|
||||
background:#fff;
|
||||
border:1px solid var(--line);
|
||||
border-radius:18px;
|
||||
box-shadow:var(--shadow);
|
||||
}
|
||||
table{
|
||||
width:100%;
|
||||
min-width:980px;
|
||||
border-collapse:collapse;
|
||||
}
|
||||
th,td{
|
||||
padding:16px 18px;
|
||||
border-bottom:1px solid var(--line);
|
||||
vertical-align:top;
|
||||
text-align:left;
|
||||
line-height:1.68;
|
||||
font-size:14px;
|
||||
}
|
||||
th{
|
||||
background:#fbfcfe;
|
||||
color:#475467;
|
||||
font-size:13px;
|
||||
font-weight:900;
|
||||
position:sticky;
|
||||
top:0;
|
||||
}
|
||||
tbody tr:hover td{background:#fff7f8}
|
||||
.timeline{
|
||||
display:grid;
|
||||
gap:16px;
|
||||
}
|
||||
.time-item{
|
||||
background:#fff;
|
||||
border:1px solid var(--line);
|
||||
border-left:6px solid var(--red-700);
|
||||
border-radius:16px;
|
||||
padding:20px 22px;
|
||||
box-shadow:var(--shadow);
|
||||
}
|
||||
.time-label{
|
||||
color:var(--red-800);
|
||||
font-size:15px;
|
||||
font-weight:950;
|
||||
margin-bottom:6px;
|
||||
}
|
||||
.list{
|
||||
margin:12px 0 0;
|
||||
padding-left:19px;
|
||||
color:#667085;
|
||||
line-height:1.75;
|
||||
font-size:14px;
|
||||
}
|
||||
.empty{
|
||||
grid-column:1/-1;
|
||||
padding:32px;
|
||||
text-align:center;
|
||||
color:#667085;
|
||||
border:1px dashed var(--line);
|
||||
border-radius:16px;
|
||||
background:#fff;
|
||||
}
|
||||
.safety-card{
|
||||
margin-top:20px;
|
||||
background:#fff;
|
||||
border:1px solid #fed6d9;
|
||||
border-radius:16px;
|
||||
padding:18px 20px;
|
||||
color:#5f2730;
|
||||
line-height:1.75;
|
||||
}
|
||||
.modal-mask{
|
||||
position:fixed;
|
||||
inset:0;
|
||||
background:rgba(15,23,42,.55);
|
||||
display:none;
|
||||
align-items:center;
|
||||
justify-content:center;
|
||||
z-index:100;
|
||||
padding:24px;
|
||||
}
|
||||
.modal-mask.show{display:flex}
|
||||
.modal{
|
||||
width:min(1120px,96vw);
|
||||
max-height:88vh;
|
||||
overflow:auto;
|
||||
background:#fff;
|
||||
border-radius:22px;
|
||||
box-shadow:var(--shadow-2);
|
||||
}
|
||||
.modal-head{
|
||||
position:sticky;
|
||||
top:0;
|
||||
z-index:2;
|
||||
background:#fff;
|
||||
border-bottom:1px solid var(--line);
|
||||
padding:22px 26px;
|
||||
display:flex;
|
||||
justify-content:space-between;
|
||||
gap:18px;
|
||||
align-items:flex-start;
|
||||
}
|
||||
.modal-kicker{
|
||||
display:inline-flex;
|
||||
padding:7px 12px;
|
||||
border-radius:999px;
|
||||
color:var(--red-800);
|
||||
background:var(--red-soft);
|
||||
font-size:13px;
|
||||
font-weight:900;
|
||||
margin-bottom:10px;
|
||||
}
|
||||
.modal-title{
|
||||
margin:0;
|
||||
font-size:27px;
|
||||
letter-spacing:-.03em;
|
||||
}
|
||||
.close{
|
||||
width:40px;
|
||||
height:40px;
|
||||
border:0;
|
||||
border-radius:12px;
|
||||
color:#fff;
|
||||
background:var(--red-800);
|
||||
font-size:26px;
|
||||
line-height:1;
|
||||
cursor:pointer;
|
||||
}
|
||||
.modal-body{
|
||||
padding:24px 26px 30px;
|
||||
}
|
||||
.detail-grid{
|
||||
display:grid;
|
||||
grid-template-columns:repeat(2,minmax(0,1fr));
|
||||
gap:16px;
|
||||
}
|
||||
.detail-box{
|
||||
border:1px solid var(--line);
|
||||
background:#fff;
|
||||
border-radius:16px;
|
||||
padding:18px;
|
||||
}
|
||||
.detail-box.full{grid-column:1/-1}
|
||||
.detail-box h5{
|
||||
margin:0 0 12px;
|
||||
font-size:16px;
|
||||
color:var(--red-800);
|
||||
}
|
||||
.detail-box p{
|
||||
margin:0;
|
||||
color:#667085;
|
||||
line-height:1.75;
|
||||
}
|
||||
.detail-box ul{
|
||||
margin:0;
|
||||
padding-left:18px;
|
||||
color:#667085;
|
||||
line-height:1.75;
|
||||
}
|
||||
.footer-note{
|
||||
color:#667085;
|
||||
line-height:1.75;
|
||||
font-size:13px;
|
||||
margin-top:22px;
|
||||
}
|
||||
@media(max-width:1320px){
|
||||
.stat-row{grid-template-columns:repeat(3,minmax(210px,1fr));}
|
||||
.grid-4{grid-template-columns:repeat(2,minmax(0,1fr));}
|
||||
.grid-3{grid-template-columns:repeat(2,minmax(0,1fr));}
|
||||
}
|
||||
@media(max-width:880px){
|
||||
.app-header{height:auto;position:relative;flex-direction:column;align-items:flex-start;padding:22px;gap:16px}
|
||||
.brand,.header-actions{min-width:0;width:100%}
|
||||
.global-search{width:100%}
|
||||
.tabbar-wrap{top:0;position:sticky}
|
||||
.tabbar{padding:0 18px}
|
||||
main{padding:24px 18px 44px}
|
||||
.page-title{flex-direction:column;align-items:flex-start}
|
||||
.stat-row,.grid-2,.grid-3,.grid-4{grid-template-columns:1fr}
|
||||
.detail-grid{grid-template-columns:1fr}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="app-header">
|
||||
<div class="brand">
|
||||
<div class="logo">陆</div>
|
||||
<div>
|
||||
<h1>台湾陆军机动打击部队知识数据展示平台</h1>
|
||||
<p>结构化数据检索 + 单位档案 + 装备体系 + 人员生态</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<div class="search-wrap">
|
||||
<input id="globalSearch" class="global-search" placeholder="查询单位、装备、人员、改革或来源">
|
||||
<span class="search-icon">⌕</span>
|
||||
</div>
|
||||
<button class="ai-btn" onclick="jumpToSearch()">交互查询</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav class="tabbar-wrap">
|
||||
<div class="tabbar" id="tabbar"></div>
|
||||
</nav>
|
||||
|
||||
<main>
|
||||
<section id="panel-overview" class="panel active"></section>
|
||||
<section id="panel-brigades" class="panel"></section>
|
||||
<section id="panel-reform" class="panel"></section>
|
||||
<section id="panel-equipment" class="panel"></section>
|
||||
<section id="panel-personnel" class="panel"></section>
|
||||
<section id="panel-matrix" class="panel"></section>
|
||||
</main>
|
||||
|
||||
<div class="modal-mask" id="modalMask">
|
||||
<div class="modal">
|
||||
<div class="modal-head">
|
||||
<div>
|
||||
<div class="modal-kicker" id="modalBadge">详情</div>
|
||||
<h2 class="modal-title" id="modalTitle"></h2>
|
||||
</div>
|
||||
<button class="close" onclick="closeModal()">×</button>
|
||||
</div>
|
||||
<div class="modal-body" id="modalBody"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const DATA = {"metadata": {"title": "台湾陆军机动打击部队公开资料专题库", "subtitle": "联合兵种旅、联合兵种营、装备现代化与人员生态", "version": "v1.0", "language": "zh-CN", "scope": "公开资料研究、专题展示、结构化分析", "safety_note": "本数据集仅整理公开、宏观、非操作性资料;不包含实时部署、精确坐标、营区细节、车号、油弹水电节点、通信频率、战备规律或可用于现实攻击的战术信息。", "recommended_tabs": ["总览", "七旅画像", "联兵改革", "装备现代化", "人员生态", "能力压力矩阵", "资料边界"]}, "overview": {"summary_cards": [{"标题": "研究对象", "数值": "7个联合兵种旅", "说明": "原4个装甲旅与3个机械化步兵旅,2026年起统一更衔为联合兵种旅。"}, {"标题": "核心主题", "数值": "旅 / 营 / 装备 / 人员", "说明": "重点展示七旅画像、联兵旅/营改革、装备现代化、人员生态和制度压力。"}, {"标题": "资料层级", "数值": "A-D四级", "说明": "官方、主流媒体、智库期刊、社群线索分级管理。"}, {"标题": "展示原则", "数值": "公开 / 宏观 / 可核验", "说明": "保留研究价值,同时避免输出可操作军事敏感信息。"}], "研究边界": ["可展示:番号、原性质、隶属军团方向、队名传统、历史沿革、公开演训、公开装备类型、制度性压力。", "可展示:联合兵种营改革逻辑、火力连/监侦排/反甲排/迫炮排等公开概念、联络官机制、装备现代化趋势。", "不展示:精确营区坐标、实时驻地、车辆具体分配、车组个人信息、油弹储量、通信频率、战备规律、攻击路径。"], "建议页面结构": ["顶部仪表盘:显示7个旅、3个方向、主要装备类别、资料可信度和安全边界。", "横向Tab:总览、七旅画像、联兵改革、装备现代化、人员生态、能力压力矩阵、资料边界。", "详情弹框:用中文字段、分组卡片、标签和来源说明展示,不直接弹出原始JSON。"]}, "brigades": [{"番号": "联合兵种第542旅", "队名": "迅雷部队", "原性质": "原陆军装甲第542旅", "隶属方向": "第六军团 / 北部方向", "研究定位": "北部装甲传统单位;旧式战车与联兵营改革结合样本。", "历史源流": ["公开队史称,其源流可追溯至装甲兵第2师。", "后经历装甲独立第2旅、装甲独立第13旅、独立第42旅等阶段。", "1998年“精实案”后编成陆军装甲第542旅;2026年更衔为联合兵种第542旅。"], "传统符号": ["“迅雷”强调装甲兵快速机动、步战炮协同和装甲突击传统。", "公开队史中三角形队徽被解释为步、战、炮协同作战象征。"], "公开组织重点": ["可按旅部、联合兵种营、炮兵、通资、工兵、保修、后勤支援等模块展示。", "不展示营区、连队驻地、车辆具体数量或实时部署。"], "装备画像": ["公开训练报道可见CM11战车、装步车辆、营外战备训练等素材。", "适合作为旧式战车、装甲传统、联兵营改革过渡的展示样本。"], "演训线索": ["公开报道曾涉及联兵营作战计划演练。", "可归入战力保存、反击、再整补、战备训练等宏观课目。"], "人员生态关注": ["战车车组、保修士官、通信人员、后勤人员的复合压力。", "旧平台保修与新式联兵营训练叠加。"], "制度压力": ["旧式战车平台延寿压力。", "联兵营改革后多兵种协同训练压力。", "基层士官与保修专业人员压力。"], "数据缺口": ["联兵营完整公开编成不足。", "无人机、反无人机和联络官训练公开资料不足。", "M1A2T是否全面替换旧式战车不能自行推断。"], "标签": ["北部", "装甲传统", "迅雷", "CM11", "联兵营改革"], "来源提示": ["国防部公开队史", "陆军公开新闻", "公开媒体报道"]}, {"番号": "联合兵种第584旅", "队名": "登步部队", "原性质": "原陆军装甲第584旅", "隶属方向": "第六军团 / 北部方向", "研究定位": "北部重装甲现代化核心样本;M1A2T换装关联度高。", "历史源流": ["公开队史将其前身与陆军219师、登步岛战役传统相连。", "队史叙事强调从步枪部队发展为装甲劲旅。", "2026年更衔后成为联合兵种第584旅。"], "传统符号": ["“登步”来自登步岛战役历史记忆。", "该传统是其队史教育、荣誉叙事和部队识别的重要来源。"], "公开组织重点": ["适合展示为北部重装甲现代化核心样本。", "只展示旅级和营级公开结构,不细化到实时连队部署。"], "装备画像": ["与M1A2T换装主题高度关联。", "M1A2T交付后需要接装训练、射击验证、维修保障、重拖救济等配套。"], "演训线索": ["可补充接装训练、换装训练、成军典礼、战Line truncated
|
||||
|
||||
const tabConfig = [
|
||||
['overview','总览'],
|
||||
['brigades','七旅画像'],
|
||||
['reform','联兵改革'],
|
||||
['equipment','装备现代化'],
|
||||
['personnel','人员生态'],
|
||||
['matrix','能力压力矩阵']
|
||||
];
|
||||
|
||||
function escapeHtml(v){
|
||||
return String(v ?? '').replace(/[&<>"']/g, s => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[s]));
|
||||
}
|
||||
function listHtml(arr){
|
||||
if(!arr || !arr.length) return '<p>暂无公开资料。</p>';
|
||||
return '<ul class="list">' + arr.map(x=>'<li>'+escapeHtml(x)+'</li>').join('') + '</ul>';
|
||||
}
|
||||
function pills(arr, gray=false){
|
||||
if(!arr || !arr.length) return '';
|
||||
return '<div class="pill-row">' + arr.map(t=>'<span class="pill '+(gray?'gray':'')+'">'+escapeHtml(t)+'</span>').join('') + '</div>';
|
||||
}
|
||||
function matchText(item, q){
|
||||
if(!q) return true;
|
||||
return JSON.stringify(item).toLowerCase().includes(q.toLowerCase());
|
||||
}
|
||||
function renderTabs(){
|
||||
const wrap = document.getElementById('tabbar');
|
||||
wrap.innerHTML = '';
|
||||
tabConfig.forEach(([id,label],idx)=>{
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'tab-btn' + (idx===0 ? ' active' : '');
|
||||
btn.textContent = label;
|
||||
btn.onclick = () => switchTab(id, btn);
|
||||
wrap.appendChild(btn);
|
||||
});
|
||||
}
|
||||
function switchTab(id, btn){
|
||||
document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
document.querySelectorAll('.panel').forEach(p=>p.classList.remove('active'));
|
||||
document.getElementById('panel-'+id).classList.add('active');
|
||||
window.scrollTo({top:0, behavior:'smooth'});
|
||||
}
|
||||
function jumpToSearch(){
|
||||
const active = document.querySelector('.panel.active');
|
||||
const box = active.querySelector('.search');
|
||||
if(box){ box.focus(); box.scrollIntoView({behavior:'smooth', block:'center'}); }
|
||||
else {
|
||||
document.querySelector('[data-tab="brigades"]')?.click();
|
||||
}
|
||||
}
|
||||
document.getElementById('globalSearch').addEventListener('input', e=>{
|
||||
const q = e.target.value;
|
||||
const activeId = document.querySelector('.panel.active')?.id || '';
|
||||
['brigadeSearch','equipSearch','roleSearch','matrixSearch'].forEach(id=>{
|
||||
const box = document.getElementById(id);
|
||||
if(box && activeId.includes(id.replace('Search','').replace('equip','equipment').replace('role','personnel'))) {
|
||||
box.value = q;
|
||||
box.dispatchEvent(new Event('input'));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function pageTitle(title, desc, actions=''){
|
||||
return `<div class="page-title"><div><h2>${title}</h2><p>${desc}</p></div><div class="page-actions">${actions}</div></div>`;
|
||||
}
|
||||
function renderOverview(){
|
||||
const p = document.getElementById('panel-overview');
|
||||
const stats = [
|
||||
['联兵旅档案', DATA.brigades.length, '七个联合兵种旅'],
|
||||
['装备平台', DATA.equipment.length, '装备与支撑能力'],
|
||||
['人员类型', DATA.personnel.人员结构.length, '军官、士官、志愿役等'],
|
||||
['岗位生态', DATA.personnel.典型岗位生态.length, '典型岗位群'],
|
||||
['压力维度', DATA.capability_pressure_matrix.length, '能力—制度压力矩阵'],
|
||||
['改革节点', DATA.reform.改革时间线.length, '联兵改革时间线']
|
||||
];
|
||||
p.innerHTML = `
|
||||
${pageTitle('全库态势总览','结构化JSON用于检索、筛选和关联;正文内容作为详情页面主要内容源,尽量保留知识深度。',
|
||||
'<button class="outline-btn" onclick="openSafety()">安全边界</button><button class="solid-btn" onclick="switchTo(\'brigades\')">进入七旅画像</button>')}
|
||||
<div class="stat-row">
|
||||
${stats.map(s=>`<div class="stat-card"><div class="stat-label">${escapeHtml(s[0])}</div><div class="stat-value">${escapeHtml(s[1])}</div><div class="stat-note">${escapeHtml(s[2])}</div></div>`).join('')}
|
||||
</div>
|
||||
|
||||
<div class="section-title"><h3>专题入口</h3><span>详情默认采用中文业务字段展示</span></div>
|
||||
<div class="grid-3">
|
||||
<div class="topic-card" onclick="switchTo('brigades')"><div class="icon-box">旅</div><h4>七旅画像</h4><p>逐旅查看番号、队名、历史源流、装备画像、人员生态、制度压力和数据缺口。</p>${pills(['完整单位档案'])}</div>
|
||||
<div class="topic-card" onclick="switchTo('reform')"><div class="icon-box">改</div><h4>联兵改革</h4><p>展示联合兵种旅/营改革时间线、战车型/机步型联兵营模型和火力连结构。</p>${pills(['改革时间线','联兵营模型'])}</div>
|
||||
<div class="topic-card" onclick="switchTo('equipment')"><div class="icon-box">装</div><h4>装备现代化</h4><p>结构化关联M1A2T、CM34、炮兵、反甲、防空、无人机、救济与重拖装备。</p>${pills(['装备数据库'])}</div>
|
||||
<div class="topic-card" onclick="switchTo('personnel')"><div class="icon-box">人</div><h4>人员生态</h4><p>按照军官、士官、志愿役、义务役、后备、技术支援和典型岗位群整理。</p>${pills(['岗位生态','人力压力'])}</div>
|
||||
<div class="topic-card" onclick="switchTo('matrix')"><div class="icon-box">矩</div><h4>能力压力矩阵</h4><p>从火力、机动、防护、情报、指挥、后勤、人力、后备、采购、地方关系分析。</p>${pills(['能力画像','观察指标'])}</div>
|
||||
<div class="topic-card" onclick="openSafety()"><div class="icon-box">界</div><h4>研究边界说明</h4><p>不再作为独立栏目,仅保留为弹框说明,用于提示公开资料和安全展示规则。</p>${pills(['非操作性','公开资料'])}</div>
|
||||
</div>
|
||||
|
||||
<div class="section-title"><h3>七个联兵旅速览</h3><span>点击卡片详情查看二级档案</span></div>
|
||||
<div class="grid-3">
|
||||
${DATA.brigades.map((b,i)=>brigadeCard(b,i)).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
function switchTo(id){
|
||||
const idx = tabConfig.findIndex(x=>x[0]===id);
|
||||
if(idx>=0) document.querySelectorAll('.tab-btn')[idx].click();
|
||||
}
|
||||
function brigadeCard(b,i){
|
||||
return `<div class="card">
|
||||
<div class="card-head">
|
||||
<div><h4>${escapeHtml(b.番号)}</h4><p>${escapeHtml(b.队名)}|${escapeHtml(b.隶属方向)}</p></div>
|
||||
<button class="detail-btn" onclick="openBrigade(${i})">详情</button>
|
||||
</div>
|
||||
<p><b>原性质:</b>${escapeHtml(b.原性质)}</p>
|
||||
<p><b>定位:</b>${escapeHtml(b.研究定位)}</p>
|
||||
${pills(b.标签)}
|
||||
</div>`;
|
||||
}
|
||||
function renderBrigades(){
|
||||
const p = document.getElementById('panel-brigades');
|
||||
p.innerHTML = `
|
||||
${pageTitle('七个联兵旅逐旅画像','以公开资料整理单位番号、队名传统、历史源流、装备画像、人员生态、制度压力和数据缺口。')}
|
||||
<div class="toolbar">
|
||||
<input class="search" id="brigadeSearch" placeholder="搜索番号、队名、方向、装备、制度压力……">
|
||||
<select class="select" id="brigadeDirection"><option value="">全部方向</option><option value="北部">北部 / 第六军团</option><option value="中部">中部 / 第十军团</option><option value="南部">南部 / 第八军团</option></select>
|
||||
<select class="select" id="brigadeType"><option value="">全部原性质</option><option value="装甲">原装甲旅</option><option value="机械化步兵">原机械化步兵旅</option></select>
|
||||
</div>
|
||||
<div class="grid-3" id="brigadeList"></div>
|
||||
`;
|
||||
const update = ()=>{
|
||||
const q = document.getElementById('brigadeSearch').value;
|
||||
const dir = document.getElementById('brigadeDirection').value;
|
||||
const typ = document.getElementById('brigadeType').value;
|
||||
const list = DATA.brigades.filter(b=>matchText(b,q)&&(!dir||b.隶属方向.includes(dir))&&(!typ||b.原性质.includes(typ)));
|
||||
document.getElementById('brigadeList').innerHTML = list.length ? list.map(b=>brigadeCard(b,DATA.brigades.indexOf(b))).join('') : '<div class="empty">没有匹配结果。</div>';
|
||||
};
|
||||
['brigadeSearch','brigadeDirection','brigadeType'].forEach(id=>document.getElementById(id).addEventListener(id==='brigadeSearch'?'input':'change',update));
|
||||
update();
|
||||
}
|
||||
function renderReform(){
|
||||
const r = DATA.reform;
|
||||
document.getElementById('panel-reform').innerHTML = `
|
||||
${pageTitle('联合兵种旅 / 营改革数据','围绕改革逻辑、时间线、联兵营模型、火力连结构和观察指标进行结构化展示。')}
|
||||
<div class="grid-2">
|
||||
<div class="card"><h4>${escapeHtml(r.改革概述.名称)}</h4><p>${escapeHtml(r.改革概述.核心逻辑)}</p><p><b>展示重点:</b>${escapeHtml(r.改革概述.展示重点)}</p></div>
|
||||
<div class="card"><h4>核心变化</h4>${listHtml(r.关键变化)}</div>
|
||||
</div>
|
||||
<div class="section-title"><h3>改革时间线</h3><span>以公开资料为线索</span></div>
|
||||
<div class="timeline">${r.改革时间线.map(x=>`<div class="time-item"><div class="time-label">${escapeHtml(x.时间)}|${escapeHtml(x.节点)}</div><p>${escapeHtml(x.说明)}</p>${pills([x.资料等级],true)}</div>`).join('')}</div>
|
||||
<div class="section-title"><h3>联兵营公开模型</h3><span>战车型 / 机步型 / 火力连</span></div>
|
||||
<div class="grid-3">${r.联兵营模型.map(m=>`<div class="card"><h4>${escapeHtml(m.类型)}</h4><p><b>功能定位:</b>${escapeHtml(m.功能定位)}</p>${pills(m.基本构成)}<p><b>展示提示:</b>${escapeHtml(m.展示提示)}</p></div>`).join('')}</div>
|
||||
<div class="section-title"><h3>主要争议与观察指标</h3><span>制度性压力,不做战术推演</span></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>议题</th><th>观察指标</th></tr></thead><tbody>${r.主要争议与观察指标.map(x=>`<tr><td><b>${escapeHtml(x.议题)}</b></td><td>${pills(x.观察指标,true)}</td></tr>`).join('')}</tbody></table></div>
|
||||
`;
|
||||
}
|
||||
function equipCard(e,i){
|
||||
return `<div class="card">
|
||||
<div class="card-head">
|
||||
<div><h4>${escapeHtml(e.装备名称)}</h4><p>${escapeHtml(e.类别)}|${escapeHtml(e.来源类型)}</p></div>
|
||||
<button class="detail-btn" onclick="openEquipment(${i})">详情</button>
|
||||
</div>
|
||||
<p><b>公开状态:</b>${escapeHtml(e.公开状态)}</p>
|
||||
<p><b>现代化意义:</b>${escapeHtml(e.现代化意义)}</p>
|
||||
${pills(e.标签)}
|
||||
</div>`;
|
||||
}
|
||||
function renderEquipment(){
|
||||
const cats = [...new Set(DATA.equipment.map(e=>e.类别))];
|
||||
const p = document.getElementById('panel-equipment');
|
||||
p.innerHTML = `
|
||||
${pageTitle('装备现代化数据库','按装备类别、来源类型、主要用途、训练需求、后勤需求、关联人员和制度压力组织。')}
|
||||
<div class="toolbar">
|
||||
<input class="search" id="equipSearch" placeholder="搜索装备、用途、训练需求、关联人员、制度压力……">
|
||||
<select class="select" id="equipCategory"><option value="">全部类别</option>${cats.map(c=>`<option>${escapeHtml(c)}</option>`).join('')}</select>
|
||||
<select class="select" id="equipSource"><option value="">全部来源</option><option value="美国军售">美国军售</option><option value="台湾国产">台湾国产</option><option value="既有">既有/旧式</option><option value="改革">改革配套</option></select>
|
||||
</div>
|
||||
<div class="grid-3" id="equipmentList"></div>
|
||||
<div class="section-title"><h3>装备数据库总表</h3><span>便于导出与二次入库</span></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>装备</th><th>类别</th><th>主要用途</th><th>训练需求</th><th>后勤需求</th><th>制度压力</th></tr></thead><tbody id="equipTable"></tbody></table></div>
|
||||
`;
|
||||
const update = ()=>{
|
||||
const q = document.getElementById('equipSearch').value;
|
||||
const cat = document.getElementById('equipCategory').value;
|
||||
const src = document.getElementById('equipSource').value;
|
||||
const list = DATA.equipment.filter(e=>matchText(e,q)&&(!cat||e.类别===cat)&&(!src||e.来源类型.includes(src)||(src==='既有'&&(e.来源类型.includes('既有')||e.来源类型.includes('旧式')))||(src==='改革'&&e.来源类型.includes('改革'))));
|
||||
document.getElementById('equipmentList').innerHTML = list.length ? list.map(e=>equipCard(e,DATA.equipment.indexOf(e))).join('') : '<div class="empty">没有匹配结果。</div>';
|
||||
document.getElementById('equipTable').innerHTML = list.map(e=>`<tr><td><b>${escapeHtml(e.装备名称)}</b></td><td>${escapeHtml(e.类别)}</td><td>${(e.主要用途||[]).map(escapeHtml).join('、')}</td><td>${(e.训练需求||[]).map(escapeHtml).join('、')}</td><td>${(e.后勤需求||[]).map(escapeHtml).join('、')}</td><td>${(e.制度压力||[]).map(escapeHtml).join('、')}</td></tr>`).join('');
|
||||
};
|
||||
['equipSearch','equipCategory','equipSource'].forEach(id=>document.getElementById(id).addEventListener(id==='equipSearch'?'input':'change',update));
|
||||
update();
|
||||
}
|
||||
function renderPersonnel(){
|
||||
const p = document.getElementById('panel-personnel');
|
||||
p.innerHTML = `
|
||||
${pageTitle('人员生态数据','从人员结构、背景议题和典型岗位群三个层次展示军官、士官、志愿役、义务役、后备与技术支援。')}
|
||||
<div class="section-title"><h3>人员结构分层</h3><span>角色与制度压力</span></div>
|
||||
<div class="grid-3">${DATA.personnel.人员结构.map(x=>`<div class="card"><h4>${escapeHtml(x.人员类型)}</h4><p>${escapeHtml(x.角色)}</p><p><b>展示字段</b></p>${pills(x.展示字段,true)}<p><b>制度压力</b></p>${pills(x.制度压力)}</div>`).join('')}</div>
|
||||
<div class="section-title"><h3>人力背景议题</h3><span>公开制度与趋势层面</span></div>
|
||||
<div class="grid-2">${DATA.personnel.人力背景议题.map(x=>`<div class="card"><h4>${escapeHtml(x.议题)}</h4><p><b>公开背景:</b>${escapeHtml(x.公开背景)}</p><p><b>对联兵旅影响:</b>${escapeHtml(x.对联兵旅影响)}</p>${pills(x.标签)}</div>`).join('')}</div>
|
||||
<div class="section-title"><h3>典型岗位生态</h3><span>岗位职责、压力来源与关联装备</span></div>
|
||||
<div class="toolbar"><input class="search" id="roleSearch" placeholder="搜索岗位、装备、职责或压力来源……"></div>
|
||||
<div class="grid-3" id="roleList"></div>
|
||||
`;
|
||||
const update = ()=>{
|
||||
const q = document.getElementById('roleSearch').value;
|
||||
const list = DATA.personnel.典型岗位生态.filter(x=>matchText(x,q));
|
||||
document.getElementById('roleList').innerHTML = list.length ? list.map(x=>`<div class="card"><h4>${escapeHtml(x.岗位群)}</h4><p><b>主要职责</b></p>${listHtml(x.主要职责)}<p><b>压力来源</b></p>${listHtml(x.压力来源)}<p><b>关联装备:</b>${(x.关联装备||[]).map(escapeHtml).join('、')}</p>${pills(x.标签)}</div>`).join('') : '<div class="empty">没有匹配结果。</div>';
|
||||
};
|
||||
document.getElementById('roleSearch').addEventListener('input',update);
|
||||
update();
|
||||
}
|
||||
function renderMatrix(){
|
||||
const p = document.getElementById('panel-matrix');
|
||||
p.innerHTML = `
|
||||
${pageTitle('能力—制度压力矩阵','将火力、机动、防护、情报、指挥、后勤、人力、后备、采购和地方关系转化为可观察指标。')}
|
||||
<div class="toolbar"><input class="search" id="matrixSearch" placeholder="搜索火力、机动、后勤、人力、采购、地方关系等……"></div>
|
||||
<div class="grid-2" id="matrixGrid"></div>
|
||||
<div class="section-title"><h3>矩阵总表</h3><span>能力画像 × 制度压力 × 观察指标</span></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>维度</th><th>能力画像</th><th>制度压力</th><th>观察指标</th></tr></thead><tbody id="matrixTable"></tbody></table></div>
|
||||
`;
|
||||
const update = ()=>{
|
||||
const q = document.getElementById('matrixSearch').value;
|
||||
const list = DATA.capability_pressure_matrix.filter(x=>matchText(x,q));
|
||||
document.getElementById('matrixGrid').innerHTML = list.length ? list.map(x=>`<div class="card"><h4>${escapeHtml(x.维度)}</h4><p><b>能力画像:</b>${escapeHtml(x.能力画像)}</p><p><b>制度压力:</b>${escapeHtml(x.制度压力)}</p>${pills(x.观察指标)}</div>`).join('') : '<div class="empty">没有匹配结果。</div>';
|
||||
document.getElementById('matrixTable').innerHTML = list.map(x=>`<tr><td><b>${escapeHtml(x.维度)}</b></td><td>${escapeHtml(x.能力画像)}</td><td>${escapeHtml(x.制度压力)}</td><td>${pills(x.观察指标,true)}</td></tr>`).join('');
|
||||
};
|
||||
document.getElementById('matrixSearch').addEventListener('input',update);
|
||||
update();
|
||||
}
|
||||
function openBrigade(i){
|
||||
const b = DATA.brigades[i];
|
||||
document.getElementById('modalBadge').textContent = b.队名 + '|' + b.原性质;
|
||||
document.getElementById('modalTitle').textContent = b.番号;
|
||||
document.getElementById('modalBody').innerHTML = `
|
||||
<div class="detail-grid">
|
||||
<div class="detail-box"><h5>基础信息</h5><p><b>隶属方向:</b>${escapeHtml(b.隶属方向)}</p><p><b>研究定位:</b>${escapeHtml(b.研究定位)}</p>${pills(b.标签)}</div>
|
||||
<div class="detail-box"><h5>传统符号</h5>${listHtml(b.传统符号)}</div>
|
||||
<div class="detail-box full"><h5>历史源流</h5>${listHtml(b.历史源流)}</div>
|
||||
<div class="detail-box"><h5>公开组织重点</h5>${listHtml(b.公开组织重点)}</div>
|
||||
<div class="detail-box"><h5>装备画像</h5>${listHtml(b.装备画像)}</div>
|
||||
<div class="detail-box"><h5>演训 / 地方线索</h5>${listHtml(b.演训线索 || b.地方关系 || [])}</div>
|
||||
<div class="detail-box"><h5>人员生态关注</h5>${listHtml(b.人员生态关注)}</div>
|
||||
<div class="detail-box"><h5>制度压力</h5>${listHtml(b.制度压力)}</div>
|
||||
<div class="detail-box"><h5>数据缺口</h5>${listHtml(b.数据缺口)}</div>
|
||||
<div class="detail-box"><h5>来源提示</h5>${pills(b.来源提示,true)}</div>
|
||||
</div>`;
|
||||
showModal();
|
||||
}
|
||||
function openEquipment(i){
|
||||
const e = DATA.equipment[i];
|
||||
document.getElementById('modalBadge').textContent = e.类别 + '|' + e.来源类型;
|
||||
document.getElementById('modalTitle').textContent = e.装备名称;
|
||||
document.getElementById('modalBody').innerHTML = `
|
||||
<div class="detail-grid">
|
||||
<div class="detail-box full"><h5>公开状态</h5><p>${escapeHtml(e.公开状态)}</p></div>
|
||||
<div class="detail-box"><h5>主要用途</h5>${listHtml(e.主要用途)}</div>
|
||||
<div class="detail-box"><h5>现代化意义</h5><p>${escapeHtml(e.现代化意义)}</p></div>
|
||||
<div class="detail-box"><h5>训练需求</h5>${listHtml(e.训练需求)}</div>
|
||||
<div class="detail-box"><h5>后勤需求</h5>${listHtml(e.后勤需求)}</div>
|
||||
<div class="detail-box"><h5>关联人员</h5>${pills(e.关联人员,true)}</div>
|
||||
<div class="detail-box"><h5>制度压力</h5>${listHtml(e.制度压力)}</div>
|
||||
<div class="detail-box"><h5>关联单位</h5>${pills(e.关联单位,true)}</div>
|
||||
<div class="detail-box"><h5>标签</h5>${pills(e.标签)}</div>
|
||||
</div>`;
|
||||
showModal();
|
||||
}
|
||||
function openSafety(){
|
||||
document.getElementById('modalBadge').textContent = '说明|公开资料与展示边界';
|
||||
document.getElementById('modalTitle').textContent = '研究边界说明';
|
||||
document.getElementById('modalBody').innerHTML = `
|
||||
<div class="detail-grid">
|
||||
<div class="detail-box"><h5>可展示内容</h5>${listHtml(DATA.overview.研究边界.slice(0,2))}</div>
|
||||
<div class="detail-box"><h5>必须排除或模糊化</h5>${listHtml(DATA.overview.研究边界.slice(2))}</div>
|
||||
<div class="detail-box full"><h5>资料分级</h5><p>资料可按官方、主流媒体、智库期刊、社群线索分级。页面不再单独设置“资料边界”栏目,但保留该说明弹框,便于后续入库时统一口径。</p></div>
|
||||
</div>`;
|
||||
showModal();
|
||||
}
|
||||
function showModal(){document.getElementById('modalMask').classList.add('show')}
|
||||
function closeModal(){document.getElementById('modalMask').classList.remove('show')}
|
||||
document.getElementById('modalMask').addEventListener('click',e=>{if(e.target.id==='modalMask')closeModal()});
|
||||
document.addEventListener('keydown',e=>{if(e.key==='Escape')closeModal()});
|
||||
|
||||
renderTabs();
|
||||
renderOverview();
|
||||
renderBrigades();
|
||||
renderReform();
|
||||
renderEquipment();
|
||||
renderPersonnel();
|
||||
renderMatrix();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>台湾民进党政要与政治生态知识展示平台|三圈人物增强版</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg1:#7f1d1d; --bg2:#450a0a; --card:#fffaf7; --card2:#ffffff; --text:#1f2937; --muted:#6b7280;
|
||||
--red:#b91c1c; --red2:#dc2626; --gold:#b45309; --green:#047857; --blue:#1d4ed8; --purple:#7e22ce;
|
||||
--line:#ead7d0; --soft:#fff1f2; --shadow:0 18px 45px rgba(69,10,10,.22);
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;font-family:"Microsoft YaHei", "PingFang SC", system-ui, -apple-system, sans-serif;background:radial-gradient(circle at 15% 10%, #b91c1c 0%, var(--bg1) 34%, var(--bg2) 100%);color:var(--text);min-height:100vh}
|
||||
body::before{content:"";position:fixed;inset:0;background:linear-gradient(135deg,rgba(255,255,255,.08),transparent 35%),radial-gradient(circle at 85% 15%,rgba(255,255,255,.10),transparent 28%);pointer-events:none}
|
||||
.header{position:sticky;top:0;z-index:20;backdrop-filter:blur(18px);background:rgba(69,10,10,.72);border-bottom:1px solid rgba(255,255,255,.16);padding:16px 28px;color:#fff}
|
||||
.header-inner{display:flex;gap:18px;align-items:center;justify-content:space-between;max-width:1500px;margin:0 auto}
|
||||
.title h1{margin:0;font-size:22px;letter-spacing:.04em}
|
||||
.title p{margin:5px 0 0;font-size:12px;opacity:.78}
|
||||
.search{display:flex;align-items:center;gap:8px;background:rgba(255,255,255,.14);border:1px solid rgba(255,255,255,.25);border-radius:999px;padding:8px 12px;min-width:340px}
|
||||
.search input{background:transparent;border:none;outline:none;color:#fff;width:100%;font-size:14px}
|
||||
.search input::placeholder{color:rgba(255,255,255,.68)}
|
||||
.container{max-width:1500px;margin:24px auto 42px;padding:0 22px;position:relative;z-index:1}
|
||||
.dashboard{display:grid;grid-template-columns:repeat(7,minmax(120px,1fr));gap:14px;margin-bottom:18px}
|
||||
.stat{background:linear-gradient(180deg,rgba(255,255,255,.94),rgba(255,245,245,.92));border:1px solid rgba(255,255,255,.78);border-radius:18px;padding:14px 16px;box-shadow:var(--shadow)}
|
||||
.stat .k{font-size:12px;color:var(--muted)}.stat .v{font-size:28px;font-weight:800;color:var(--red);margin-top:4px}
|
||||
.tabs{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0 18px}
|
||||
.tab{border:none;border-radius:999px;background:rgba(255,255,255,.9);color:#7f1d1d;padding:10px 15px;font-weight:700;cursor:pointer;box-shadow:0 8px 18px rgba(0,0,0,.08)}
|
||||
.tab.active{background:#7f1d1d;color:#fff;border:1px solid rgba(255,255,255,.5)}
|
||||
.panel{background:rgba(255,250,247,.96);border:1px solid rgba(255,255,255,.7);border-radius:26px;box-shadow:var(--shadow);overflow:hidden}
|
||||
.module-head{padding:22px 24px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;gap:12px;align-items:flex-start;background:linear-gradient(90deg,#fff8f8,#fff)}
|
||||
.module-head h2{margin:0;color:#7f1d1d;font-size:24px}.module-head p{margin:8px 0 0;color:var(--muted);line-height:1.6}
|
||||
.notice{font-size:12px;color:#7f1d1d;background:#fff1f2;border:1px solid #fecdd3;padding:10px 12px;border-radius:14px;max-width:520px}
|
||||
.subtabs{display:flex;gap:8px;flex-wrap:wrap;padding:14px 18px;border-bottom:1px solid var(--line);background:#fff}
|
||||
.subtab{border:1px solid var(--line);background:#fff;border-radius:12px;padding:8px 12px;cursor:pointer;color:#7f1d1d;font-weight:700}
|
||||
.subtab.active{background:#7f1d1d;color:#fff;border-color:#7f1d1d}
|
||||
.toolbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;padding:14px 18px;background:#fffdfb;border-bottom:1px solid var(--line)}
|
||||
.toolbar select,.toolbar input{border:1px solid var(--line);background:#fff;border-radius:12px;padding:8px 10px;min-height:38px;outline:none}
|
||||
.toolbar .hint{color:var(--muted);font-size:12px;margin-left:auto}
|
||||
.content{padding:20px}
|
||||
.circle-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}
|
||||
.circle-col{background:#fff;border:1px solid var(--line);border-radius:22px;padding:15px;min-height:500px}
|
||||
.circle-col h3{margin:0 0 8px;color:#7f1d1d;display:flex;align-items:center;justify-content:space-between}
|
||||
.circle-col .desc{font-size:12px;color:var(--muted);line-height:1.5;margin-bottom:12px}
|
||||
.person-card{background:linear-gradient(180deg,#fff,#fff7f7);border:1px solid #f3d5d5;border-radius:16px;padding:12px;margin:10px 0;cursor:pointer;transition:.16s transform,.16s box-shadow}
|
||||
.person-card:hover{transform:translateY(-2px);box-shadow:0 12px 24px rgba(127,29,29,.14)}
|
||||
.person-card .name{font-weight:800;font-size:16px;color:#7f1d1d;display:flex;justify-content:space-between;gap:8px}
|
||||
.person-card .role{font-size:12px;color:#374151;line-height:1.5;margin-top:5px}
|
||||
.tags{display:flex;gap:5px;flex-wrap:wrap;margin-top:8px}
|
||||
.tag{font-size:11px;border-radius:999px;padding:3px 8px;background:#fee2e2;color:#991b1b;border:1px solid #fecaca}
|
||||
.tag.levelA{background:#064e3b;color:#fff;border-color:#064e3b}.tag.levelB{background:#d1fae5;color:#065f46;border-color:#a7f3d0}.tag.levelC{background:#ecfdf5;color:#047857;border-color:#d1fae5}
|
||||
.tag.risk{background:#fee2e2;color:#b91c1c}.tag.blue{background:#dbeafe;color:#1d4ed8;border-color:#bfdbfe}.tag.gold{background:#fef3c7;color:#92400e;border-color:#fde68a}
|
||||
.table-wrap{overflow:auto;background:#fff;border:1px solid var(--line);border-radius:18px}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px}th,td{border-bottom:1px solid #f1e2df;padding:10px 11px;text-align:left;vertical-align:top}th{position:sticky;top:0;background:#fff1f2;color:#7f1d1d;z-index:1;white-space:nowrap}td{max-width:320px;line-height:1.45}tr:hover td{background:#fff9f9}
|
||||
.cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px}.card{background:#fff;border:1px solid var(--line);border-radius:18px;padding:14px;cursor:pointer}.card h3{margin:0 0 8px;color:#7f1d1d}.card p{font-size:13px;color:#4b5563;line-height:1.55}
|
||||
.network-layout{display:grid;grid-template-columns:minmax(620px,1.3fr) minmax(350px,.7fr);gap:18px}
|
||||
.network-box{background:#fff;border:1px solid var(--line);border-radius:20px;overflow:hidden;min-height:680px}
|
||||
.network-svg{width:100%;height:680px;display:block;background:linear-gradient(180deg,#fff,#fff8f8)}
|
||||
.node{cursor:pointer}.node text{font-size:11px;paint-order:stroke;stroke:#fff;stroke-width:4px;stroke-linejoin:round;fill:#1f2937}
|
||||
.edge{stroke:#9ca3af;stroke-opacity:.5}.edge.high{stroke:#dc2626;stroke-opacity:.7;stroke-dasharray:5 4}
|
||||
.edge.strong{stroke-width:2.2}.edge.weak{stroke-width:1}
|
||||
.rel-list{background:#fff;border:1px solid var(--line);border-radius:20px;max-height:680px;overflow:auto;padding:12px}
|
||||
.rel-item{border:1px solid #f1d7d7;border-radius:14px;padding:10px;margin-bottom:9px;background:#fffafa;cursor:pointer}
|
||||
.rel-item b{color:#7f1d1d}.rel-item p{margin:6px 0;color:#4b5563;font-size:12px;line-height:1.5}
|
||||
.gallery{display:grid;grid-template-columns:260px 1fr;gap:18px}
|
||||
.map-list{display:flex;flex-direction:column;gap:10px}.map-thumb{background:#fff;border:1px solid var(--line);border-radius:16px;padding:10px;cursor:pointer}.map-thumb.active{border-color:#7f1d1d;background:#fff1f2}.map-thumb img{width:100%;border-radius:10px;border:1px solid #eee}
|
||||
.map-view{background:#fff;border:1px solid var(--line);border-radius:20px;padding:14px;overflow:auto}.map-view img{width:100%;min-width:720px;border-radius:14px;border:1px solid #eee}
|
||||
.legend{background:#fff7ed;border:1px solid #fed7aa;color:#7c2d12;padding:12px;border-radius:14px;font-size:12px;line-height:1.7;margin-top:12px}
|
||||
.timeline{display:grid;gap:12px}.timeline-item{border-left:4px solid #b91c1c;background:#fff;border-radius:14px;padding:12px 14px}
|
||||
.chart{background:#fff;border:1px solid var(--line);border-radius:18px;padding:16px}
|
||||
.chart-row{display:flex;align-items:center;gap:8px;margin:8px 0}.chart-label{width:140px;font-size:12px;color:#4b5563}.bar{height:16px;border-radius:999px;background:#fee2e2;overflow:hidden;flex:1}.bar span{display:block;height:100%;background:#b91c1c;border-radius:999px}
|
||||
.modal{position:fixed;inset:0;background:rgba(17,24,39,.56);display:none;align-items:center;justify-content:center;z-index:50;padding:22px}.modal.show{display:flex}
|
||||
.modal-card{background:#fff;border-radius:24px;max-width:940px;width:100%;max-height:86vh;overflow:auto;box-shadow:0 30px 80px rgba(0,0,0,.34)}.modal-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;padding:18px 22px;border-bottom:1px solid var(--line);background:#fff1f2}.modal-head h2{margin:0;color:#7f1d1d}.close{border:none;background:#7f1d1d;color:#fff;border-radius:999px;width:32px;height:32px;cursor:pointer;font-size:18px}
|
||||
.detail-grid{display:grid;grid-template-columns:180px 1fr;gap:0;border-top:1px solid #f2e0de}.detail-grid .k{background:#fff8f8;color:#7f1d1d;font-weight:700;padding:10px;border-bottom:1px solid #f2e0de}.detail-grid .v{padding:10px;border-bottom:1px solid #f2e0de;line-height:1.6;white-space:pre-wrap;word-break:break-word}
|
||||
.empty{padding:24px;color:var(--muted);text-align:center;background:#fff;border:1px dashed var(--line);border-radius:18px}
|
||||
@media(max-width:1100px){.dashboard{grid-template-columns:repeat(3,1fr)}.circle-grid,.network-layout,.gallery{grid-template-columns:1fr}.search{min-width:260px}}
|
||||
@media(max-width:700px){.dashboard{grid-template-columns:repeat(2,1fr)}.header-inner{flex-direction:column;align-items:stretch}.content{padding:14px}}
|
||||
|
||||
/* 后五栏页面化增强:保持第一栏设计不变,仅增强其他栏目 */
|
||||
.compact-head{align-items:center;padding:18px 24px}.compact-head h2{font-size:23px}.compact-head p{display:none}
|
||||
.module-summary{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.mini-stat{background:#fff1f2;border:1px solid #fecdd3;color:#7f1d1d;border-radius:999px;padding:6px 10px;font-size:12px}.mini-stat b{font-size:16px;margin-right:4px}
|
||||
.rich-cards{grid-template-columns:repeat(auto-fill,minmax(330px,1fr))}.rich-card{cursor:pointer;min-height:190px;display:flex;flex-direction:column;gap:8px;transition:.16s transform,.16s box-shadow;background:linear-gradient(180deg,#fff,#fff9f9)}.rich-card:hover{transform:translateY(-2px);box-shadow:0 14px 28px rgba(127,29,29,.13)}
|
||||
.card-top{display:flex;justify-content:space-between;gap:10px;align-items:flex-start}.card-top h3{line-height:1.35}.pill{white-space:nowrap;border-radius:999px;background:#eef2ff;color:#3730a3;border:1px solid #c7d2fe;padding:3px 9px;font-size:12px;font-weight:700}.risk-pill{background:#fee2e2;color:#991b1b;border-color:#fecaca}.meta-line{font-size:12px;color:#6b7280;line-height:1.5}.summary{font-size:13px;color:#374151;line-height:1.65;margin:4px 0 0}.bullet-box{background:#fff7f7;border:1px solid #f7dada;border-radius:12px;padding:8px 12px;font-size:13px;color:#374151}.bullet-box ul{margin:0;padding-left:18px;line-height:1.65}.label-row{margin-top:6px}.label-row b{font-size:12px;color:#7f1d1d}
|
||||
.mini-fields{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:8px;margin-top:auto}.mini-fields div{background:#fff7f7;border:1px solid #f1d7d7;border-radius:10px;padding:7px 9px}.mini-fields span{display:block;font-size:11px;color:#7f1d1d;font-weight:700;margin-bottom:3px}.mini-fields b{font-size:12px;color:#374151;font-weight:600;line-height:1.5}
|
||||
.risk-bars{display:grid;gap:6px;margin:8px 0}.risk-row{display:grid;grid-template-columns:92px 1fr 36px;align-items:center;gap:8px;font-size:12px;color:#4b5563}.riskbar{height:9px;background:#fee2e2;border-radius:999px;overflow:hidden}.riskbar i{display:block;height:100%;background:linear-gradient(90deg,#f59e0b,#dc2626);border-radius:999px}.risk-row b{text-align:right;color:#7f1d1d}.inline-tags{margin:0}.rich-table td{font-size:12px}.mini-btn{border:1px solid #fecaca;background:#fff1f2;color:#991b1b;border-radius:999px;padding:5px 9px;cursor:pointer;font-weight:700}.mini-btn:hover{background:#991b1b;color:#fff}.muted{color:#9ca3af}.rich-timeline .timeline-item{cursor:pointer;position:relative;border-left:none;border:1px solid #f1d7d7}.time-dot{display:inline-block;background:#7f1d1d;color:#fff;border-radius:999px;padding:3px 9px;font-size:12px;margin-bottom:8px}.legend-row{font-size:12px;color:#6b7280;margin-bottom:10px;display:flex;gap:8px;align-items:center}.legend-dot{width:10px;height:10px;border-radius:50%;display:inline-block}.legend-dot.approve{background:#b91c1c}.legend-dot.disapprove{background:#f59e0b}.bar.two{position:relative}.bar.two span{background:#b91c1c}.bar.two em{display:block;height:100%;background:#f59e0b;border-radius:999px;position:absolute;right:0;top:0;opacity:.75}.chart-row small{width:92px;color:#6b7280}.edge-card-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:14px}.edge-card{background:#fff;border:1px solid #f1d7d7;border-radius:18px;padding:14px;cursor:pointer}.edge-title{display:flex;justify-content:space-between;gap:8px;color:#7f1d1d}.rich-detail{display:grid;gap:14px}.detail-section{border:1px solid #f1d7d7;background:#fff;border-radius:16px;padding:14px}.detail-section.emphasis{background:linear-gradient(180deg,#fff8f8,#fff)}.detail-section h3{margin:0 0 8px;color:#7f1d1d}.detail-section p{margin:0;line-height:1.75;color:#374151}.tag-group{margin:9px 0}.tag-group b{display:block;color:#7f1d1d;font-size:12px;margin-bottom:5px}.info-list{display:grid;gap:8px}.info-row{display:grid;grid-template-columns:170px 1fr;gap:10px;border-bottom:1px dashed #f1d7d7;padding-bottom:8px}.info-row b{color:#7f1d1d}.info-row span{line-height:1.65;color:#374151}.source-section{background:#fffdf5}
|
||||
@media (max-width:900px){.rich-cards{grid-template-columns:1fr}.module-summary{justify-content:flex-start}.info-row{grid-template-columns:1fr}.risk-row{grid-template-columns:80px 1fr 32px}}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="header"><div class="header-inner"><div class="title"><h1>台湾民进党政要与政治生态知识展示平台</h1><p>三圈人物增强版|A/B/C 159人|关系边表重建|6张关系图原图</p></div><div class="search"><span>🔎</span><input id="globalSearch" placeholder="搜索人物、事件、派系、地区、关系、政策标签……" /></div></div></header>
|
||||
<div class="container">
|
||||
<div id="dashboard" class="dashboard"></div>
|
||||
<div id="tabs" class="tabs"></div>
|
||||
<section id="main" class="panel"></section>
|
||||
</div>
|
||||
<div id="modal" class="modal"><div class="modal-card"><div class="modal-head"><div><h2 id="modalTitle"></h2><div id="modalSub" class="muted"></div></div><button class="close" onclick="closeModal()">×</button></div><div id="modalBody" style="padding:18px 22px"></div></div></div>
|
||||
<script id="app-data" type="application/json">{"meta": {"project_name": "台湾民进党政要与政治生态知识展示平台", "version": "1.1-enhanced-three-circle-network", "language": "zh-CN", "description": "用于展示台湾民进党政要、派系、事件、制度、民调、舆情与认知域传播力量的结构化知识库。", "last_updated": "2026-06-24", "data_status": "prototype_ready", "source_workbook": "dpp_risk_database_with_relationships.xlsx", "notes": "本页面为研究型知识库原型。风险等级表示核验优先级,不代表定罪或违法事实。", "source_workbooks": ["dpp_politicians_overview.xlsx", "dpp_risk_database_with_relationships.xlsx", "dpp_network_maps_package.zip"], "enhancement_note": "已用三圈人物总览表补齐159名人物,并按姓名重建关系表映射,加入6张关系图原图。"}, "global_config": {"default_tab": "people_network", "enable_global_search": true, "enable_filters": true, "enable_modal_detail": true, "enable_secondary_pages": true, "enable_relation_jump": true, "enable_source_trace": true}, "dictionaries": {"entity_types": ["人物", "机构", "政党", "派系", "事件", "法规", "地区", "研究成果", "平台", "舆情主体"], "risk_levels": ["低", "中", "中高", "高", "极高"], "evidence_levels": ["S", "A", "B", "C", "D", "A/S", "A/B"], "parties": ["民进党", "国民党", "民众党", "时代力量", "无党籍", "其他"], "platforms": ["Facebook", "Threads", "PTT", "Dcard", "YouTube", "LINE", "TikTok", "电视政论", "新闻媒体"]}, "dashboard": {"人物数量": 159, "政治事件": 17, "高风险地区": 9, "研究成果": 7, "民调条目": 14, "认知域主体": 10, "第一圈A": 15, "第二圈B": 73, "第三圈C": 71, "关系数量": 60, "关系节点": 73, "关系图原图": 6}, "modules": [{"module_id": "people_network", "module_name": "政要人物与派系网络", "description": "展示民进党三圈人物(A/B/C)、职务经历、所属系统、派系倾向、核心人脉、政策标签,以及规范化关系图谱和6张关系图原图。", "icon": "人物", "datasets": [{"key": "people_full", "name": "三圈人物", "type": "people_circles", "idField": "人物ID", "titleField": "姓名"}, {"key": "people_full", "name": "人物总表", "type": "table", "idField": "人物ID", "titleField": "姓名"}, {"key": "relationships_enhanced", "name": "互动关系图", "type": "network", "idField": "关系ID", "titleField": "关系细类"}, {"key": "relationships_enhanced", "name": "关系边表", "type": "table", "idField": "关系ID", "titleField": "关系细类"}, {"key": "network_maps", "name": "关系图原图", "type": "map_gallery", "idField": "map_id", "titleField": "title"}], "filters": ["层级", "圈层", "地区", "所属系统", "派系倾向", "政策标签", "可信度"], "detail_mode": "modal_or_network_detail"}, {"module_id": "risk_business_judicial_region", "module_name": "政商司法与地区风险", "description": "展示政治献金、标案、企业组织、司法监察、地区风险评分与地方选举风险。", "icon": "风险", "datasets": [{"key": "region_risks", "name": "地区风险", "type": "cards", "idField": "地区ID", "titleField": "县市"}, {"key": "judicial_records", "name": "司法监察", "type": "table", "idField": "记录ID", "titleField": "人物"}, {"key": "donations", "name": "政治献金", "type": "table", "idField": "献金ID", "titleField": "候选人/政党"}, {"key": "bids", "name": "标案资料", "type": "table", "idField": "标案ID", "titleField": "标案名称/关键词"}], "filters": ["地区", "风险等级", "证据等级", "核验状态", "产业类别"], "detail_mode": "modal_or_detail"}, {"module_id": "political_system_laws", "module_name": "台湾政治制度与法规机制", "description": "展示台湾政治制度、政党制度、选举制度、独统议题、政策法规、权力机构和特殊政治机制。", "icon": "制度", "datasets": [{"key": "political_systems", "name": "制度总览", "type": "cards", "idField": "system_id", "titleField": "制度名称"}, {"key": "institutions", "name": "权力机构", "type": "cards", "idField": "institution_id", "titleField": "机构名称"}, {"key": "laws", "name": "政策法规", "type": "table", "idField": "law_id", "titleField": "法规名称"}, {"key": "election_mechanisms", "name": "选举与公投", "type": "table", "idField": "mechanism_id", "titleField": "机制名称"}, {"key": "cross_strait_policies", "name": "独统与两岸", "type": "cards", "idField": "cross_id", "titleField": "议题"}, {"key": "dpp_primary_mechanisms", "name": "党内初选与派系机制", "type": "table", "idField": "dpp_mech_id", "titleField": "机制名称"}, {"key": "special_mechanisms", "name": "特殊政治机制", "type": "cards", "idField": "spm_id", "titleField": "机制名称"}], "filters": ["风险等级", "关联栏目", "适用对象"], "detail_mode": "secondary_page"}, {"module_id": "reseaLine truncated
|
||||
<script>
|
||||
const DATA = JSON.parse(document.getElementById('app-data').textContent);
|
||||
const state = { module: 'people_network', viewKey: null, query: '', filters: {}, relCategory:'全部', relMin:4, relRisk:false, relFocus:'' };
|
||||
const $ = s => document.querySelector(s);
|
||||
const el = (tag, cls='', html='') => { const e=document.createElement(tag); if(cls)e.className=cls; if(html!==undefined)e.innerHTML=html; return e; };
|
||||
function esc(x){ return String(x ?? '').replace(/[&<>'"]/g, m=>({'&':'&','<':'<','>':'>',"'":''','"':'"'}[m])); }
|
||||
function isEmpty(v){ return v===undefined || v===null || v==='' || (Array.isArray(v)&&v.length===0); }
|
||||
function flatText(v){
|
||||
if(Array.isArray(v)) return v.map(flatText).filter(Boolean).join('、');
|
||||
if(v && typeof v==='object') return Object.entries(v).filter(([k,val])=>!isEmpty(val)&&k!=='data_uri').map(([k,val])=>`${k}:${flatText(val)}`).join(';');
|
||||
return String(v ?? '');
|
||||
}
|
||||
function arrText(v){ return flatText(v); }
|
||||
function getTitle(item, cfg){ return item?.[cfg?.titleField] || item?.['姓名'] || item?.['事件名'] || item?.['名称'] || item?.['标题'] || item?.['机制名称'] || item?.['主体名称'] || item?.['关系细类'] || item?.['title'] || item?.['name'] || '未命名'; }
|
||||
function currentModule(){ return DATA.modules.find(m=>m.module_id===state.module) || DATA.modules[0]; }
|
||||
function currentDatasetCfg(){ const m=currentModule(); return (m.datasets||[]).find(d=>d.key===state.viewKey) || (m.datasets||[])[0]; }
|
||||
function splitTags(v){
|
||||
if(Array.isArray(v)) return v.filter(Boolean).map(String);
|
||||
if(isEmpty(v)) return [];
|
||||
return String(v).split(/[、,,;;\/|]/).map(s=>s.trim()).filter(Boolean).slice(0,12);
|
||||
}
|
||||
function tagHtml(tags, cls='') { return splitTags(tags).map(t=>`<span class="tag ${cls}">${esc(t)}</span>`).join(''); }
|
||||
function val(item, keys, fallback=''){
|
||||
for(const k of keys){ if(!isEmpty(item[k])) return item[k]; }
|
||||
return fallback;
|
||||
}
|
||||
function init(){ renderDashboard(); renderTabs(); bindSearch(); renderModule(); }
|
||||
function renderDashboard(){
|
||||
const d=DATA.dashboard||{}; const keys=['人物数量','第一圈A','第二圈B','第三圈C','关系数量','关系节点','关系图原图'];
|
||||
$('#dashboard').innerHTML = keys.map(k=>`<div class="stat"><div class="k">${esc(k)}</div><div class="v">${esc(d[k]??0)}</div></div>`).join('');
|
||||
}
|
||||
function renderTabs(){
|
||||
$('#tabs').innerHTML = DATA.modules.map(m=>`<button class="tab ${m.module_id===state.module?'active':''}" data-id="${m.module_id}">${esc(m.module_name)}</button>`).join('');
|
||||
document.querySelectorAll('.tab').forEach(b=>b.onclick=()=>{state.module=b.dataset.id; state.viewKey=null; state.filters={}; renderTabs(); renderModule();});
|
||||
}
|
||||
function bindSearch(){ $('#globalSearch').oninput = e=>{state.query=e.target.value.trim(); renderModuleBody();}; }
|
||||
function renderModule(){
|
||||
const m=currentModule(); if(!state.viewKey) state.viewKey=(m.datasets&&m.datasets[0]&&m.datasets[0].key)||'';
|
||||
if(m.module_id==='people_network'){
|
||||
$('#main').innerHTML = `<div class="module-head"><div><h2>${esc(m.module_name)}</h2><p>${esc(m.description||'')}</p></div><div class="notice">风险线与关系线仅表示研究型关联、职务/派系/事件/议题连接,不等于违法认定。关系表已按姓名重建三圈人物ID,并保留原始ID作为溯源字段。</div></div><div id="subtabs" class="subtabs"></div><div id="toolbar" class="toolbar"></div><div id="content" class="content"></div>`;
|
||||
} else {
|
||||
$('#main').innerHTML = `<div class="module-head compact-head"><div><h2>${esc(m.module_name)}</h2></div><div id="moduleSummary" class="module-summary"></div></div><div id="subtabs" class="subtabs"></div><div id="toolbar" class="toolbar"></div><div id="content" class="content"></div>`;
|
||||
}
|
||||
renderSubtabs(); renderModuleBody();
|
||||
}
|
||||
function renderSubtabs(){
|
||||
const m=currentModule(); $('#subtabs').innerHTML=(m.datasets||[]).map(d=>`<button class="subtab ${d.key===state.viewKey?'active':''}" data-key="${d.key}">${esc(d.name)}</button>`).join('');
|
||||
document.querySelectorAll('.subtab').forEach(b=>b.onclick=()=>{state.viewKey=b.dataset.key; state.filters={}; renderSubtabs(); renderModuleBody();});
|
||||
}
|
||||
function renderModuleSummary(raw, cfg){
|
||||
const box=$('#moduleSummary'); if(!box) return;
|
||||
const m=currentModule();
|
||||
if(m.module_id==='people_network') return;
|
||||
const fields = {
|
||||
risk_business_judicial_region: ['region_risks','judicial_records','donations','bids'],
|
||||
political_system_laws: ['political_systems','institutions','laws','special_mechanisms'],
|
||||
research_outputs: ['research_outputs'],
|
||||
events_opinion_polling: ['events','poll_time_series','platform_metrics','impact_assessments'],
|
||||
cognitive_public_opinion_forces: ['cognitive_actors','party_comm_units','gov_info_units','fact_check_network']
|
||||
}[m.module_id] || [];
|
||||
box.innerHTML = fields.map(k=>`<span class="mini-stat"><b>${esc((DATA.datasets[k]||[]).length)}</b>${esc(datasetLabel(k))}</span>`).join('');
|
||||
}
|
||||
function datasetLabel(k){ return ({region_risks:'地区',judicial_records:'司法',donations:'献金',bids:'标案',political_systems:'制度',institutions:'机构',laws:'法规',special_mechanisms:'特殊机制',research_outputs:'研究',events:'事件',poll_time_series:'民调',platform_metrics:'平台',impact_assessments:'影响',cognitive_actors:'主体',party_comm_units:'传播部门',gov_info_units:'信息机构',fact_check_network:'查核组织'}[k]||k); }
|
||||
function renderToolbar(data, cfg){
|
||||
const m=currentModule(); const fields = m.filters || [];
|
||||
let html = '';
|
||||
if(cfg.type==='network' && (cfg.key==='relationships_enhanced' || state.module==='people_network')){
|
||||
const cats=[...new Set((DATA.datasets.relationships_enhanced||[]).map(r=>r['关系大类']).filter(Boolean))];
|
||||
html += `<select id="relCategory"><option>全部</option>${cats.map(c=>`<option ${state.relCategory===c?'selected':''}>${esc(c)}</option>`).join('')}</select>`;
|
||||
html += `<select id="relMin"><option value="1">强度≥1</option><option value="3" ${state.relMin==3?'selected':''}>强度≥3</option><option value="4" ${state.relMin==4?'selected':''}>强度≥4</option><option value="5" ${state.relMin==5?'selected':''}>强度=5</option></select>`;
|
||||
html += `<label style="display:flex;gap:6px;align-items:center"><input id="relRisk" type="checkbox" ${state.relRisk?'checked':''}>只看高风险</label>`;
|
||||
html += `<input id="relFocus" placeholder="聚焦人物/节点,如 赖清德、台南" value="${esc(state.relFocus)}" />`;
|
||||
html += `<span class="hint">互动图默认显示强度≥4,可调低强度查看更多关系。</span>`;
|
||||
$('#toolbar').innerHTML=html;
|
||||
$('#relCategory').onchange=e=>{state.relCategory=e.target.value; renderModuleBody();};
|
||||
$('#relMin').onchange=e=>{state.relMin=+e.target.value; renderModuleBody();};
|
||||
$('#relRisk').onchange=e=>{state.relRisk=e.target.checked; renderModuleBody();};
|
||||
$('#relFocus').oninput=e=>{state.relFocus=e.target.value.trim(); renderModuleBody(false);};
|
||||
return;
|
||||
}
|
||||
fields.forEach(f=>{
|
||||
const vals=[...new Set(data.map(x=>x[f]).filter(v=>v!==undefined&&v!==null&&v!==''))].slice(0,200);
|
||||
if(vals.length>1 && vals.length<80) html += `<select data-filter="${esc(f)}"><option value="">${esc(f)}:全部</option>${vals.map(v=>`<option value="${esc(v)}" ${state.filters[f]===String(v)?'selected':''}>${esc(v)}</option>`).join('')}</select>`;
|
||||
});
|
||||
html += `<span class="hint">当前:${esc(data.length)} 条;搜索与筛选在当前子页内生效。</span>`;
|
||||
$('#toolbar').innerHTML=html;
|
||||
document.querySelectorAll('[data-filter]').forEach(s=>s.onchange=e=>{state.filters[e.target.dataset.filter]=e.target.value; renderModuleBody();});
|
||||
}
|
||||
function filterData(data){
|
||||
const q=state.query.toLowerCase();
|
||||
return data.filter(item=>{
|
||||
const passFilters=Object.entries(state.filters).every(([k,v])=>!v || String(item[k]??'')===v);
|
||||
if(!passFilters) return false;
|
||||
if(!q) return true;
|
||||
return flatText(item).toLowerCase().includes(q);
|
||||
});
|
||||
}
|
||||
function renderModuleBody(updateToolbar=true){
|
||||
const cfg=currentDatasetCfg(); const raw=DATA.datasets[cfg.key] || [];
|
||||
renderModuleSummary(raw,cfg);
|
||||
if(updateToolbar) renderToolbar(raw, cfg);
|
||||
let data=filterData(raw);
|
||||
if(cfg.type==='people_circles') return renderPeopleCircles(data);
|
||||
if(cfg.type==='network'){
|
||||
if(cfg.key==='event_entity_edges') return renderEventEntityNetwork(data,cfg);
|
||||
return renderNetwork();
|
||||
}
|
||||
if(cfg.type==='map_gallery') return renderMapGallery(data);
|
||||
if(cfg.type==='cards') return renderCards(data,cfg);
|
||||
if(cfg.type==='timeline') return renderTimeline(data,cfg);
|
||||
if(cfg.type==='chart_table') return renderPollChart(data,cfg);
|
||||
return renderTable(data,cfg);
|
||||
}
|
||||
function levelClass(l){return l==='A'?'levelA':(l==='B'?'levelB':'levelC')}
|
||||
function renderPeopleCircles(data){
|
||||
const groups={A:[],B:[],C:[]}; data.forEach(p=>{ if(groups[p['层级']]) groups[p['层级']].push(p); });
|
||||
const desc={A:'总统府、行政院、党主席、地方执政与国会核心。',B:'中常委、地方首长、立委、党务/传播/国安关键节点。',C:'地方立委、专业不分区、党务节点、历史人物与风险案例。'};
|
||||
$('#content').innerHTML = `<div class="circle-grid">${['A','B','C'].map(level=>`<div class="circle-col"><h3>${esc(DATA.datasets.people_circles.find(x=>x.level===level)?.label||level)}<span class="tag ${levelClass(level)}">${groups[level].length}人</span></h3><div class="desc">${desc[level]}</div>${groups[level].map(personCard).join('')}</div>`).join('')}</div>`;
|
||||
document.querySelectorAll('[data-person]').forEach(x=>x.onclick=()=>openDetail(DATA.datasets.people_full.find(p=>p['人物ID']===x.dataset.person), '人物详情'));
|
||||
}
|
||||
function personCard(p){
|
||||
const tags=[p['地区'], p['所属系统'], p['派系倾向']].filter(Boolean).slice(0,3).map(t=>`<span class="tag">${esc(t)}</span>`).join('');
|
||||
const rel=p['关系数量']?`<span class="tag blue">关系${p['关系数量']}</span>`:'';
|
||||
const risk=p['高风险关系数量']?`<span class="tag risk">高风险${p['高风险关系数量']}</span>`:'';
|
||||
return `<div class="person-card" data-person="${esc(p['人物ID'])}"><div class="name"><span>${esc(p['姓名'])}</span><span class="tag ${levelClass(p['层级'])}">${esc(p['层级'])}</span></div><div class="role">${esc(p['当前身份'])}</div><div class="tags">${tags}${rel}${risk}</div></div>`;
|
||||
}
|
||||
function renderCards(data,cfg){
|
||||
if(state.module==='people_network'){
|
||||
$('#content').innerHTML = data.length?`<div class="cards">${data.map(it=>`<div class="card" data-id="${esc(it[cfg.idField]||'')}"><h3>${esc(getTitle(it,cfg))}</h3><p>${esc(Object.entries(it).filter(([k,v])=>v&&k!==cfg.titleField&&k!==cfg.idField).slice(0,5).map(([k,v])=>`${k}:${arrText(v)}`).join('\n'))}</p></div>`).join('')}</div>`:`<div class="empty">没有匹配数据</div>`;
|
||||
document.querySelectorAll('.card').forEach((x,i)=>x.onclick=()=>openDetail(data[i], getTitle(data[i],cfg)));
|
||||
return;
|
||||
}
|
||||
$('#content').innerHTML = data.length?`<div class="cards rich-cards">${data.map((it,i)=>richCard(it,cfg,i)).join('')}</div>`:`<div class="empty">没有匹配数据</div>`;
|
||||
document.querySelectorAll('.rich-card').forEach(x=>x.onclick=()=>openDetail(data[+x.dataset.i], getTitle(data[+x.dataset.i],cfg)));
|
||||
}
|
||||
function richCard(it,cfg,i){
|
||||
const key=cfg.key, title=getTitle(it,cfg);
|
||||
if(key==='region_risks') return regionCard(it,i);
|
||||
if(key==='political_systems'||key==='institutions'||key==='cross_strait_policies'||key==='special_mechanisms') return systemCard(it,cfg,i);
|
||||
if(key==='research_outputs') return researchCard(it,i);
|
||||
if(key==='person_opinion_profiles'||key==='impact_assessments') return opinionCard(it,cfg,i);
|
||||
if(key==='cognitive_actors'||key==='gov_info_units'||key==='fact_check_network'||key==='platform_mechanisms') return actorCard(it,cfg,i);
|
||||
return genericCard(it,cfg,i);
|
||||
}
|
||||
function genericCard(it,cfg,i){
|
||||
const title=getTitle(it,cfg); const subtitle=val(it,['类型','阵营','机构','地区','功能定位','当前状态','年份','风险等级'],'');
|
||||
const tags=[...splitTags(val(it,['主题标签','主要平台','核心功能','主要风险类型','关联栏目','平台/渠道','内容特征'],''))].slice(0,6);
|
||||
const desc=val(it,['核心内容','说明','风险摘要','主要职能','核心结论','政治影响','典型任务','认知域相关职责','短期影响'],'');
|
||||
return `<article class="card rich-card" data-i="${i}"><div class="card-top"><h3>${esc(title)}</h3>${subtitle?`<span class="pill">${esc(subtitle)}</span>`:''}</div>${tags.length?`<div class="tags">${tagHtml(tags)}</div>`:''}${desc?`<p class="summary">${esc(flatText(desc))}</p>`:''}${miniFields(it,['证据等级','可信度','核验状态','风险等级','数据用途','适用对象'])}</article>`;
|
||||
}
|
||||
function regionCard(it,i){
|
||||
const score=Number(it['综合分']||0); const risk=it['风险等级']||'';
|
||||
const people=splitTags(it['核心人物']).slice(0,8);
|
||||
const risks=splitTags(it['主要风险类型']).slice(0,8);
|
||||
const bars=['司法风险(30%)','资金风险(20%)','土地/产业风险(20%)','派系/地方风险(15%)','舆情风险(10%)'].map(k=>riskBar(k,it[k])).join('');
|
||||
return `<article class="card rich-card region-card" data-i="${i}"><div class="card-top"><h3>${esc(it['县市'])}</h3><span class="pill risk-pill">${esc(risk)}|${esc(it['综合分'])}</span></div><div class="meta-line">${esc(it['执政状态/政治属性']||'')}</div><div class="tags">${people.map(x=>`<span class="tag blue">${esc(x)}</span>`).join('')}${risks.map(x=>`<span class="tag risk">${esc(x)}</span>`).join('')}</div><div class="risk-bars">${bars}</div><p class="summary"><b>2026影响:</b>${esc(it['2026选举影响']||'待补充')}</p></article>`;
|
||||
}
|
||||
function riskBar(label,value){ const n=Math.max(0,Math.min(5,Number(value)||0)); return `<div class="risk-row"><span>${esc(label.replace(/\(.+?\)/,''))}</span><div class="riskbar"><i style="width:${n*20}%"></i></div><b>${n}/5</b></div>`; }
|
||||
function systemCard(it,cfg,i){
|
||||
const title=getTitle(it,cfg); const desc=val(it,['核心内容','主要职能','核心规则','触发条件','政治含义'],'');
|
||||
const tags=val(it,['标签','关联栏目','适用对象','风险等级'],'');
|
||||
return `<article class="card rich-card system-card" data-i="${i}"><div class="card-top"><h3>${esc(title)}</h3>${it['风险等级']?`<span class="pill risk-pill">${esc(it['风险等级'])}</span>`:''}</div>${tags?`<div class="tags">${tagHtml(tags)}</div>`:''}<p class="summary">${esc(flatText(desc))}</p>${miniFields(it,['机构定位','主管/适用','程序门槛','数据用途','来源'])}</article>`;
|
||||
}
|
||||
function researchCard(it,i){
|
||||
return `<article class="card rich-card research-card" data-i="${i}"><div class="card-top"><h3>${esc(it['标题'])}</h3><span class="pill">${esc(it['可信度']||'')}</span></div><div class="meta-line">${esc(it['机构']||'')}|${esc(it['年份']||'')}|${esc(it['类型']||'')}</div><div class="tags">${tagHtml(it['主题标签'])}</div><div class="bullet-box">${toBullets(it['核心结论'])}</div>${miniFields(it,['可下载性','适用栏目'])}</article>`;
|
||||
}
|
||||
function opinionCard(it,cfg,i){
|
||||
const title=getTitle(it,cfg); const risk=it['舆情风险']||it['风险评分']||'';
|
||||
const pos=it['正面形象'], neg=it['负面标签'];
|
||||
return `<article class="card rich-card opinion-card" data-i="${i}"><div class="card-top"><h3>${esc(title)}</h3>${risk?`<span class="pill risk-pill">风险 ${esc(risk)}</span>`:''}</div>${pos?`<div class="label-row"><b>正面形象</b><div class="tags">${tagHtml(pos,'blue')}</div></div>`:''}${neg?`<div class="label-row"><b>负面标签</b><div class="tags">${tagHtml(neg,'risk')}</div></div>`:''}<p class="summary">${esc(flatText(val(it,['短期影响','长期影响','平台敏感性','观察指标'],'')))}</p></article>`;
|
||||
}
|
||||
function actorCard(it,cfg,i){
|
||||
const title=getTitle(it,cfg);
|
||||
return `<article class="card rich-card actor-card" data-i="${i}"><div class="card-top"><h3>${esc(title)}</h3><span class="pill">${esc(val(it,['类型','功能定位','政党/阵营'],'主体'))}</span></div>${val(it,['阵营','政党'])?`<div class="meta-line">${esc(val(it,['阵营','政党']))}</div>`:''}<div class="tags">${tagHtml(val(it,['核心功能','主要平台','平台/渠道','平台'],''))}</div><p class="summary">${esc(flatText(val(it,['认知域相关职责','主要功能','政治传播作用','内容特征','争议风险'],'')))}</p>${miniFields(it,['典型场景','适合关联事件','数据可得性','关键指标','关联栏目'])}</article>`;
|
||||
}
|
||||
function miniFields(it, keys){ return `<div class="mini-fields">${keys.filter(k=>!isEmpty(it[k])).map(k=>`<div><span>${esc(k)}</span><b>${esc(flatText(it[k]))}</b></div>`).join('')}</div>`; }
|
||||
function toBullets(v){ const arr=Array.isArray(v)?v:splitTags(v); if(!arr.length) return ''; return `<ul>${arr.slice(0,5).map(x=>`<li>${esc(x)}</li>`).join('')}</ul>`; }
|
||||
function renderTable(data,cfg){
|
||||
if(!data.length) return $('#content').innerHTML='<div class="empty">没有匹配数据</div>';
|
||||
const keyMap={
|
||||
judicial_records:['记录ID','人物','机关','类型','阶段','主要争点','结果/状态','证据等级','下一步跟踪'],
|
||||
donations:['献金ID','年度/选举','候选人/政党','捐款人/企业','捐款人类型','产业类别','核验状态','风险信号'],
|
||||
bids:['标案ID','标案名称/关键词','机关','地区','产业类别','得标厂商','关联人物','风险信号'],
|
||||
laws:['law_id','法规名称','主管/适用','核心条款摘要','关联栏目','详情展示'],
|
||||
election_mechanisms:['mechanism_id','机制名称','核心规则','适用对象','数据用途'],
|
||||
dpp_primary_mechanisms:['dpp_mech_id','机制名称','核心内容','数据用途'],
|
||||
narrative_frames:['frame_id','event_id','行动方','话术类型','核心话术','对抗话术'],
|
||||
platform_metrics:['metric_id','event_id','平台范围','量化数据','说明','可信度'],
|
||||
party_comm_units:['unit_id','政党','部门/机制','公开可见功能','典型任务','关联人物'],
|
||||
party_media_matrix:['matrix_id','政党/阵营','主要平台','传播形态','主要受众','内容特征','观察指标'],
|
||||
cognitive_risks:['risk_id','风险类型','相关主体','表现','评估指标','备注']
|
||||
};
|
||||
const priority=['人物ID','姓名','层级','圈层','当前身份','所属系统','派系倾向','地区','关系ID','Source_名称','Target_名称','关系大类','关系细类','关系强度(1-5)','是否高风险','证据等级','简要说明'];
|
||||
let keys=keyMap[cfg.key] || [...new Set([...priority.filter(k=>k in data[0]), ...Object.keys(data[0])])].filter(k=>k!=='data_uri').slice(0,10);
|
||||
$('#content').innerHTML = `<div class="table-wrap rich-table"><table><thead><tr>${keys.map(k=>`<th>${esc(k)}</th>`).join('')}<th>详情</th></tr></thead><tbody>${data.map((row,idx)=>`<tr data-row="${idx}">${keys.map(k=>`<td>${cellHtml(row[k],k)}</td>`).join('')}<td><button class="mini-btn" data-detail="${idx}">查看</button></td></tr>`).join('')}</tbody></table></div>`;
|
||||
document.querySelectorAll('[data-detail]').forEach(btn=>btn.onclick=(e)=>{e.stopPropagation(); openDetail(data[+btn.dataset.detail], getTitle(data[+btn.dataset.detail],cfg));});
|
||||
document.querySelectorAll('tbody tr').forEach(tr=>tr.onclick=()=>openDetail(data[+tr.dataset.row], getTitle(data[+tr.dataset.row],cfg)));
|
||||
}
|
||||
function cellHtml(v,k){
|
||||
if(isEmpty(v)) return '<span class="muted">—</span>';
|
||||
if(Array.isArray(v)) return `<div class="tags inline-tags">${tagHtml(v)}</div>`;
|
||||
const s=String(v);
|
||||
if(['证据等级','可信度','风险等级','核验状态','是否高风险'].some(x=>k.includes(x))) return `<span class="tag ${s.includes('高')||s==='是'?'risk':'blue'}">${esc(s)}</span>`;
|
||||
return esc(s.length>95?s.slice(0,95)+'…':s);
|
||||
}
|
||||
function renderTimeline(data,cfg){
|
||||
$('#content').innerHTML = data.length?`<div class="timeline rich-timeline">${data.map((it,i)=>timelineItem(it,cfg,i)).join('')}</div>`:`<div class="empty">没有匹配数据</div>`;
|
||||
document.querySelectorAll('.timeline-item').forEach(x=>x.onclick=()=>openDetail(data[+x.dataset.i], getTitle(data[+x.dataset.i],cfg)));
|
||||
}
|
||||
function timelineItem(it,cfg,i){
|
||||
const title=getTitle(it,cfg); const time=val(it,['起始/关键日期','时间','publish_date','start_date'],'');
|
||||
const meta=[val(it,['类型','攻防主题','地区'],''), val(it,['当前状态','平台','司法/监察阶段'],'')].filter(Boolean).join('|');
|
||||
const summary=val(it,['风险摘要','主要框架','核心争议','说明','2026选举影响'],'');
|
||||
return `<div class="timeline-item" data-i="${i}"><div class="time-dot">${esc(time||'时间待补')}</div><b>${esc(title)}</b>${meta?`<div class="meta-line">${esc(meta)}</div>`:''}<p>${esc(flatText(summary))}</p>${tagHtml(val(it,['涉及人物','参与主体','舆情标签','平台'],''))}</div>`;
|
||||
}
|
||||
function renderPollChart(data,cfg){
|
||||
const series=data.filter(x=>x.approve_value!==undefined && x.approve_value!=='' && !isNaN(+x.approve_value)); const max=Math.max(1,...series.map(x=>Math.max(+x.approve_value,+x.disapprove_value||0)));
|
||||
const rows=series.slice(0,80).map((x,i)=>`<div class="chart-row" data-i="${i}"><div class="chart-label">${esc(x.publish_date||x.source)}<br>${esc(x.target||'')}</div><div class="bar two"><span style="width:${(+x.approve_value/max)*100}%"></span><em style="width:${((+x.disapprove_value||0)/max)*100}%"></em></div><b>${esc(x.approve_value)}%</b><small>不满意 ${esc(x.disapprove_value??'—')}%</small></div>`).join('');
|
||||
const table=data.length?pollTable(data):'';
|
||||
$('#content').innerHTML = `<div class="chart rich-chart"><h3 style="margin-top:0;color:#7f1d1d">民调趋势</h3><div class="legend-row"><span class="legend-dot approve"></span>满意/支持 <span class="legend-dot disapprove"></span>不满意/不支持</div>${rows||'<div class="empty">暂无可绘制数值</div>'}</div>${table}`;
|
||||
document.querySelectorAll('.chart-row').forEach(x=>x.onclick=()=>openDetail(series[+x.dataset.i], '民调详情'));
|
||||
document.querySelectorAll('[data-poll]').forEach(btn=>btn.onclick=(e)=>{e.stopPropagation();openDetail(data[+btn.dataset.poll],'民调详情');});
|
||||
}
|
||||
function pollTable(data){ const keys=['poll_id','source','publish_date','indicator_type','target','approve_value','disapprove_value','neutral_value','related_event_id','method','credibility_level']; return `<div class="table-wrap rich-table" style="margin-top:16px"><table><thead><tr>${keys.map(k=>`<th>${esc(k)}</th>`).join('')}<th>详情</th></tr></thead><tbody>${data.map((r,i)=>`<tr>${keys.map(k=>`<td>${cellHtml(r[k],k)}</td>`).join('')}<td><button class="mini-btn" data-poll="${i}">查看</button></td></tr>`).join('')}</tbody></table></div>`; }
|
||||
function renderEventEntityNetwork(data,cfg){
|
||||
if(!data.length) return $('#content').innerHTML='<div class="empty">没有匹配数据</div>';
|
||||
$('#content').innerHTML=`<div class="edge-card-grid">${data.map((e,i)=>`<div class="edge-card" data-i="${i}"><div class="edge-title"><b>${esc(e.source_entity_name)} → ${esc(e.target_entity_name)}</b><span class="tag blue">强度${esc(e.relation_strength)}</span></div><div class="tags"><span class="tag">${esc(e.source_entity_type)}</span><span class="tag">${esc(e.target_entity_type)}</span><span class="tag risk">${esc(e.relation_type)}</span></div><p>${esc(e.relation_description||'')}</p><p class="summary"><b>风险影响:</b>${esc(e.risk_effect||'')}</p></div>`).join('')}</div>`;
|
||||
document.querySelectorAll('.edge-card').forEach(x=>x.onclick=()=>openDetail(data[+x.dataset.i],'联动关系详情'));
|
||||
}
|
||||
function renderNetwork(){
|
||||
const rels0=DATA.datasets.relationships_enhanced||[]; let rels=rels0.filter(r=>r['关系强度数值']>=state.relMin);
|
||||
if(state.relCategory && state.relCategory!=='全部') rels=rels.filter(r=>r['关系大类']===state.relCategory);
|
||||
if(state.relRisk) rels=rels.filter(r=>r['是否高风险布尔']);
|
||||
const focus=(state.relFocus||state.query||'').toLowerCase(); if(focus) rels=rels.filter(r=>flatText(r).toLowerCase().includes(focus));
|
||||
const nodesMap=new Map(); const allNodes=new Map((DATA.datasets.relationship_nodes||[]).map(n=>[n.node_id,n]));
|
||||
rels.forEach(r=>{ [r.source_norm_id,r.target_norm_id].forEach(id=>{ if(allNodes.has(id)) nodesMap.set(id, allNodes.get(id)); }); });
|
||||
const nodes=[...nodesMap.values()];
|
||||
const svg=buildNetworkSVG(nodes, rels);
|
||||
$('#content').innerHTML=`<div class="network-layout"><div class="network-box">${svg}</div><div class="rel-list"><h3 style="margin-top:0;color:#7f1d1d">关系边表摘要</h3><p style="color:#6b7280;font-size:12px">当前显示 ${rels.length} 条关系、${nodes.length} 个节点。点击节点可聚焦。</p>${rels.map((r,i)=>`<div class="rel-item" data-ri="${i}"><b>${esc(r.Source_名称)} → ${esc(r.Target_名称)}</b><div class="tags"><span class="tag">${esc(r['关系大类'])}</span><span class="tag blue">强度${esc(r['关系强度(1-5)'])}</span>${r['是否高风险']==='是'?'<span class="tag risk">高风险</span>':''}</div><p>${esc(r['关系细类']||'')}:${esc(r['简要说明']||'')}</p></div>`).join('')}</div></div>`;
|
||||
document.querySelectorAll('.rel-item').forEach(x=>x.onclick=()=>openDetail(rels[+x.dataset.ri], '关系详情'));
|
||||
document.querySelectorAll('.node').forEach(n=>n.onclick=()=>{state.relFocus=n.dataset.name; renderModuleBody(false);});
|
||||
}
|
||||
function nodeColor(n){ if(n.type.includes('地区')) return '#f59e0b'; if(n.type.includes('组织')||n.type.includes('机构')) return '#2563eb'; if(n.type.includes('事件')||n.type.includes('议题')) return '#dc2626'; if(n.type.includes('派系')) return '#7e22ce'; if(n.level==='A') return '#065f46'; if(n.level==='B') return '#10b981'; if(n.level==='C') return '#86efac'; return '#9ca3af'; }
|
||||
function buildNetworkSVG(nodes, rels){
|
||||
const w=1200,h=680,cx=w/2,cy=h/2; const rings={A:120,B:210,C:300,other:370}; const by={A:[],B:[],C:[],other:[]};
|
||||
nodes.forEach(n=>{ if(n.level==='A')by.A.push(n); else if(n.level==='B')by.B.push(n); else if(n.level==='C')by.C.push(n); else by.other.push(n); });
|
||||
const pos={}; Object.entries(by).forEach(([key,arr],ri)=>{ const r=rings[key]; const offset=(ri*.31); arr.forEach((n,i)=>{ const a=(Math.PI*2*i/Math.max(1,arr.length))+offset; pos[n.node_id]={x:cx+r*Math.cos(a),y:cy+r*Math.sin(a)}; }); });
|
||||
const edgeEls=rels.map(r=>{ const a=pos[r.source_norm_id], b=pos[r.target_norm_id]; if(!a||!b)return ''; const cls=`edge ${r['是否高风险']==='是'?'high':''} ${r['关系强度数值']>=4?'strong':'weak'}`; return `<line class="${cls}" x1="${a.x.toFixed(1)}" y1="${a.y.toFixed(1)}" x2="${b.x.toFixed(1)}" y2="${b.y.toFixed(1)}"/>`; }).join('');
|
||||
const nodeEls=nodes.map(n=>{ const p=pos[n.node_id]; if(!p)return ''; const color=nodeColor(n), rad=n.level==='A'?12:(n.level==='B'?9:(n.level==='C'?7:8)); const label=n.name.length>7?n.name.slice(0,7)+'…':n.name; return `<g class="node" data-name="${esc(n.name)}"><circle cx="${p.x.toFixed(1)}" cy="${p.y.toFixed(1)}" r="${rad}" fill="${color}" stroke="#fff" stroke-width="2"/><text x="${(p.x+rad+3).toFixed(1)}" y="${(p.y+4).toFixed(1)}">${esc(label)}</text><title>${esc(n.name+'|'+n.type+'|'+(n.circle||''))}</title></g>`; }).join('');
|
||||
const legend=`<g transform="translate(24,22)"><rect width="245" height="112" rx="14" fill="rgba(255,255,255,.88)" stroke="#f1d5d5"/><text x="14" y="24" font-size="13" font-weight="700" fill="#7f1d1d">节点图例</text><circle cx="18" cy="46" r="7" fill="#065f46"/><text x="32" y="50" font-size="11">A核心</text><circle cx="92" cy="46" r="7" fill="#10b981"/><text x="106" y="50" font-size="11">B关键</text><circle cx="168" cy="46" r="7" fill="#86efac"/><text x="182" y="50" font-size="11">C外围</text><circle cx="18" cy="73" r="7" fill="#2563eb"/><text x="32" y="77" font-size="11">机构</text><circle cx="92" cy="73" r="7" fill="#dc2626"/><text x="106" y="77" font-size="11">事件/风险</text><circle cx="18" cy="100" r="7" fill="#7e22ce"/><text x="32" y="104" font-size="11">派系/系统</text></g>`;
|
||||
return `<svg class="network-svg" viewBox="0 0 ${w} ${h}" xmlns="http://www.w3.org/2000/svg">${legend}<g>${edgeEls}</g><g>${nodeEls}</g></svg>`;
|
||||
}
|
||||
function renderMapGallery(data){
|
||||
const maps=data||[]; if(!maps.length)return $('#content').innerHTML='<div class="empty">没有关系图原图</div>';
|
||||
const active=maps[0];
|
||||
$('#content').innerHTML=`<div class="gallery"><div><div class="map-list">${maps.map((m,i)=>`<div class="map-thumb ${i===0?'active':''}" data-mi="${i}"><b>${esc(m.title)}</b><p style="font-size:12px;color:#6b7280">${esc(m.description)}</p><img src="${m.data_uri}"></div>`).join('')}</div><div class="legend"><b>图例说明</b><br>${esc((DATA.datasets.network_map_legend&&DATA.datasets.network_map_legend[0]&&DATA.datasets.network_map_legend[0].readme)||'')}</div></div><div class="map-view"><h3 id="mapTitle" style="margin-top:0;color:#7f1d1d">${esc(active.title)}</h3><p id="mapDesc" style="color:#6b7280">${esc(active.description)}</p><img id="mapImg" src="${active.data_uri}"></div></div>`;
|
||||
document.querySelectorAll('.map-thumb').forEach(x=>x.onclick=()=>{document.querySelectorAll('.map-thumb').forEach(y=>y.classList.remove('active'));x.classList.add('active');const m=maps[+x.dataset.mi];$('#mapTitle').textContent=m.title;$('#mapDesc').textContent=m.description;$('#mapImg').src=m.data_uri;});
|
||||
}
|
||||
function openDetail(obj,title='详情'){
|
||||
if(!obj)return; $('#modalTitle').textContent=title || getTitle(obj,{});
|
||||
if(state.module==='people_network'){
|
||||
$('#modalSub').textContent='点击右上角关闭;字段名称保持原始中文。';
|
||||
$('#modalBody').innerHTML=`<div class="detail-grid">${Object.entries(obj).filter(([k,v])=>v!==''&&v!==null&&v!==undefined&&k!=='data_uri').map(([k,v])=>`<div class="k">${esc(k)}</div><div class="v">${esc(arrText(v))}</div>`).join('')}</div>`;
|
||||
} else {
|
||||
$('#modalSub').textContent='结构化详情;已将原始字段转为页面语言展示。';
|
||||
$('#modalBody').innerHTML=richDetail(obj,title);
|
||||
}
|
||||
$('#modal').classList.add('show');
|
||||
}
|
||||
function richDetail(obj,title){
|
||||
const important=['风险摘要','核心内容','主要争点','核心条款摘要','政治影响','2026选举影响','短期影响','长期影响','说明','核心规则','触发条件','程序门槛','核心话术','对抗话术','认知域相关职责','争议风险','主要功能','风险信号'];
|
||||
const summary=important.filter(k=>!isEmpty(obj[k])).map(k=>`<section class="detail-section emphasis"><h3>${esc(k)}</h3><p>${esc(flatText(obj[k]))}</p></section>`).join('');
|
||||
const tags=Object.entries(obj).filter(([k,v])=>/(标签|平台|人物|地区|阵营|类型|等级|状态|可信度|风险)/.test(k)&&!important.includes(k)&&!isEmpty(v)).slice(0,12).map(([k,v])=>`<div class="tag-group"><b>${esc(k)}</b><div class="tags">${tagHtml(v)}</div></div>`).join('');
|
||||
const source=Object.entries(obj).filter(([k,v])=>/(来源|URL|链接|证据|核验|更新|备注|ID)/.test(k)&&!isEmpty(v)&&k!=='data_uri').map(([k,v])=>`<div><span>${esc(k)}</span><b>${esc(flatText(v))}</b></div>`).join('');
|
||||
const rest=Object.entries(obj).filter(([k,v])=>!isEmpty(v)&&k!=='data_uri'&&!important.includes(k)&&!/(标签|平台|人物|地区|阵营|类型|等级|状态|可信度|风险|来源|URL|链接|证据|核验|更新|备注|ID)/.test(k)).map(([k,v])=>`<div class="info-row"><b>${esc(k)}</b><span>${esc(flatText(v))}</span></div>`).join('');
|
||||
return `<div class="rich-detail">${summary||`<section class="detail-section emphasis"><h3>概要</h3><p>${esc(flatText(obj).slice(0,800))}</p></section>`}${tags?`<section class="detail-section"><h3>标签与关联</h3>${tags}</section>`:''}${rest?`<section class="detail-section"><h3>详细字段</h3><div class="info-list">${rest}</div></section>`:''}${source?`<section class="detail-section source-section"><h3>来源与核验</h3><div class="mini-fields">${source}</div></section>`:''}</div>`;
|
||||
}
|
||||
function closeModal(){ $('#modal').classList.remove('show'); }
|
||||
$('#modal').addEventListener('click',e=>{if(e.target.id==='modal')closeModal();});
|
||||
init();
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>台湾公务员群体知识数据展示系统 v2</title>
|
||||
<style>
|
||||
:root{
|
||||
--red:#b4232d;--red2:#d94a54;--red3:#fff1f2;--red4:#78202a;--red5:#5d1420;
|
||||
--cream:#fff8f6;--paper:#fffdfa;--bg:#f4f6f8;--white:#fff;--text:#20252d;--muted:#667085;
|
||||
--line:#ead7d3;--line2:#e5e7eb;--soft:#f8fafc;--amber:#b4690e;--green:#14804a;--blue:#1d5f99;
|
||||
--shadow:0 12px 36px rgba(31,41,55,.09);
|
||||
}
|
||||
*{box-sizing:border-box}html,body{margin:0;min-height:100%;font-family:"Microsoft YaHei","PingFang SC","Noto Sans CJK SC",Arial,sans-serif;color:var(--text);background:radial-gradient(circle at 20% 0%,rgba(180,35,45,.12),transparent 30%),linear-gradient(135deg,#f7eeee,#f6f7f9 45%,#fff7f5)}
|
||||
button,input,select{font:inherit}button{cursor:pointer}a{color:var(--red);text-decoration:none}.hidden{display:none!important}
|
||||
.app{min-height:100vh;display:flex;flex-direction:column}.header{height:82px;background:linear-gradient(120deg,var(--red5),var(--red));color:#fff;display:flex;align-items:center;justify-content:space-between;padding:0 30px;box-shadow:0 6px 22px rgba(126,22,32,.25);position:sticky;top:0;z-index:100}.brand{display:flex;align-items:center;gap:14px}.brand-mark{width:48px;height:48px;border:2px solid rgba(255,255,255,.75);border-radius:14px;display:grid;place-items:center;font-weight:900;font-size:22px;background:rgba(255,255,255,.12)}.brand h1{font-size:22px;margin:0 0 5px;letter-spacing:.3px}.brand p{font-size:12px;margin:0;color:rgba(255,255,255,.78)}.header-actions{display:flex;align-items:center;gap:10px}.search{position:relative}.search input{width:360px;border:1px solid rgba(255,255,255,.25);background:rgba(255,255,255,.15);color:#fff;border-radius:12px;padding:11px 42px 11px 15px;outline:none}.search input::placeholder{color:rgba(255,255,255,.72)}.search .icon{position:absolute;right:13px;top:10px;font-size:18px}.search-pop{position:absolute;right:0;top:50px;width:min(560px,92vw);max-height:480px;overflow:auto;background:#fff;color:var(--text);border:1px solid var(--line);border-radius:14px;box-shadow:var(--shadow);padding:8px;z-index:200}.search-item{display:flex;gap:12px;padding:12px;border-radius:10px;border-bottom:1px dashed #eee}.search-item:hover{background:var(--red3)}.search-kind{min-width:70px;color:var(--red);font-size:12px;font-weight:800}.search-item strong{display:block;font-size:14px;margin-bottom:4px}.search-item small{color:var(--muted);line-height:1.45}.btn{border:0;border-radius:10px;padding:10px 15px;font-weight:800;transition:.18s}.btn.white{background:#fff;color:var(--red)}.btn.ghost{background:rgba(255,255,255,.12);color:#fff;border:1px solid rgba(255,255,255,.25)}.btn.primary{background:var(--red);color:#fff}.btn.light{background:var(--red3);color:var(--red)}.btn.line{background:#fff;color:var(--red);border:1px solid #efb7bc}.btn.sm{padding:7px 10px;font-size:12px}.tabs{height:60px;background:#fff;display:flex;align-items:end;gap:2px;padding:0 24px;border-bottom:1px solid var(--line);position:sticky;top:82px;z-index:90;overflow-x:auto}.tab{border:0;background:transparent;color:#4b5563;font-weight:800;padding:18px 19px 15px;white-space:nowrap;border-bottom:3px solid transparent}.tab:hover{color:var(--red)}.tab.active{color:var(--red);border-bottom-color:var(--red)}.main{width:min(1540px,100%);margin:auto;padding:24px 28px 56px;flex:1}.page{display:none}.page.active{display:block}.page-head{display:flex;justify-content:space-between;gap:18px;align-items:flex-start;margin-bottom:20px}.page-head h2{margin:0 0 7px;font-size:26px;color:#531520}.page-head p{margin:0;color:var(--muted);line-height:1.65}.page-actions{display:flex;gap:9px;flex-wrap:wrap}.notice{background:linear-gradient(120deg,#fff4f4,#fff);border:1px solid #f2c6ca;border-left:5px solid var(--red);border-radius:13px;padding:14px 16px;line-height:1.75;color:#5e3034}.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:14px}.stat{background:rgba(255,255,255,.94);border:1px solid var(--line);border-top:4px solid var(--red);border-radius:15px;padding:18px;box-shadow:0 6px 18px rgba(31,41,55,.045)}.stat .label{color:var(--muted);font-size:13px}.stat .num{font-size:30px;font-weight:900;margin:9px 0 3px;color:#54151e}.stat .hint{font-size:12px;color:#98a2b3}.grid{display:grid;gap:15px}.grid.cols2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid.cols3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid.cols4{grid-template-columns:repeat(4,minmax(0,1fr))}.panel,.card{background:rgba(255,255,255,.96);border:1px solid var(--line);border-radius:16px;box-shadow:0 6px 22px rgba(31,41,55,.045);padding:18px}.panel-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}.panel h3,.panel h4{margin:0}.section-title{display:flex;justify-content:space-between;align-items:end;margin:25px 0 13px}.section-title h3{font-size:18px;margin:0;color:#5f1822}.section-title span{color:var(--muted);font-size:12px}.badge,.chip{display:inline-flex;align-items:center;border-radius:999px;padding:5px 9px;font-size:12px;font-weight:800;margin:2px 4px 2px 0}.badge.red,.chip.red{background:var(--red3);color:var(--red)}.badge.green{background:#e9f8ef;color:var(--green)}.badge.amber{background:#fff5e6;color:var(--amber)}.badge.blue{background:#e9f2fb;color:var(--blue)}.badge.gray{background:#f1f3f5;color:#667085}.filters{display:grid;grid-template-columns:1.4fr repeat(4,1fr) auto;gap:10px;background:#fff;border:1px solid var(--line);border-radius:14px;padding:13px;margin-bottom:16px}.input,.select{width:100%;border:1px solid #d8dde4;border-radius:10px;padding:10px 11px;background:#fff;outline:none}.input:focus,.select:focus{border-color:var(--red);box-shadow:0 0 0 3px rgba(180,35,45,.08)}.card-item{background:#fff;border:1px solid var(--line);border-radius:16px;padding:17px;min-height:210px;display:flex;flex-directionLine truncated
|
||||
@media(max-width:1120px){.stats{grid-template-columns:repeat(2,1fr)}.grid.cols3,.grid.cols4{grid-template-columns:repeat(2,1fr)}.filters{grid-template-columns:1fr 1fr 1fr}.two-col{grid-template-columns:1fr}.detail-hero{grid-template-columns:1fr}}
|
||||
@media(max-width:760px){.header{height:auto;padding:14px 16px;align-items:flex-start}.brand p{display:none}.header-actions{display:none}.tabs{top:70px;padding-left:8px}.main{padding:17px 12px 45px}.stats,.grid.cols2,.grid.cols3,.grid.cols4{grid-template-columns:1fr}.filters{grid-template-columns:1fr}.modal-card{margin:3vh auto;max-height:94vh}.footer{display:block;line-height:1.8}.kv{grid-template-columns:1fr}.brand h1{font-size:18px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
<header class="header"><div class="brand"><div class="brand-mark">公</div><div><h1>台湾公务员群体知识数据展示系统</h1><p>基础画像 · 政策法规 · 研究成果 · 近月议题 · 动态监测</p></div></div><div class="header-actions"><div class="search"><input id="globalSearch" placeholder="搜索:考绩、年金、基层公务员、职场霸凌"><span class="icon">⌕</span><div id="searchPop" class="search-pop hidden"></div></div><button class="btn white" id="sourceBtn">来源索引</button><button class="btn ghost" id="resetBtn">重置</button></div></header>
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
<main class="main" id="main"></main>
|
||||
<footer class="footer"><span>单文件离线原型 v2 · 中文字段与富详情版</span><span>数据用途:公共治理研究与政策分析;不用于针对个体或群体的操纵性应用</span></footer>
|
||||
</div>
|
||||
<div id="modal" class="modal hidden"><div class="backdrop" onclick="closeModal()"></div><div class="modal-card"><button class="close" onclick="closeModal()">×</button><div id="modalBody"></div></div></div>
|
||||
<div id="detail" class="detail hidden"></div>
|
||||
<script>
|
||||
const EXTERNAL_JSON_URL = ""; // 后续可改为 "./taiwan_civil_service_display_data_v2.json"
|
||||
let DATA = {"meta": {"title": "台湾公务员群体知识数据展示系统", "version": "2.0-rich-ui", "data_update_time": "2026-06-23", "observation_period": "2026-05-24 至 2026-06-23", "scope": "台湾公务员群体基础画像、政策法规、研究成果、关注议题与近月动态", "source_note": "基于已整理的台湾公务员群体技能文档、政策文献、研究成果与近月公开资料构建。", "usage_note": "本页面用于公共治理研究、政策分析和资料展示。涉及群体敏感点时,统一表述为制度敏感点、治理风险点和政策观察点。", "ui_note": "v2 修复字段英文化、详情空白和研究成果内容过少问题;前端以中文字段和富文本详情展示。"}, "navigation": {"tabs": [{"id": "basic_knowledge", "label": "公务员基础知识", "description": "定义、数量、任用、官等职等、薪资、年龄、性别、法规"}, {"id": "policy_changes", "label": "政策法规变动", "description": "赖清德上任后涉公务员政策法规时间线"}, {"id": "research_outputs", "label": "报告与研究成果", "description": "研究成果、文献索引、核心发现和治理敏感点"}, {"id": "recent_issues", "label": "近月关注议题", "description": "近一个月关注议题的来龙去脉、诉求和态度结构"}, {"id": "monthly_dynamics", "label": "近月动态监测", "description": "新闻、组织、公务员社群、大V与官方动态"}]}, "global_query": {"enabled": true, "search_fields": ["title", "summary", "description", "keywords", "tags", "affected_groups", "source_type", "policy_name", "issue_name", "research_title", "actor", "event_title", "page_summary", "governance_sensitivity", "group_demands"], "filter_dimensions": ["date", "topic_type", "source_type", "affected_groups", "evidence_level", "importance", "status", "heat_level", "policy_type", "issue_type", "theme_cluster"]}, "data": {"basic_knowledge": {"tab_title": "公务员基础知识", "layout": "dashboard", "summary_cards": [{"id": "total_count", "label": "公务员总数", "value": 360080, "unit": "人", "description": "全國公務人員口径,民国114年/2025年"}, {"id": "average_age", "label": "平均年龄", "value": 43.75, "unit": "岁", "description": "民国114年/2025年统计"}, {"id": "male_ratio", "label": "男性占比", "value": "56.34%", "description": "全國公務人員性别结构"}, {"id": "female_ratio", "label": "女性占比", "value": "43.66%", "description": "全國公務人員性别结构"}], "definition": {"title": "台湾公务员群体定义", "summary": "台湾公务员通常指依法考试、任用、铨叙或特别人事制度进入公部门并承担公共行政职责的人员。页面采用全國公務人員总口径。", "included_groups": ["行政机关公务人员", "公营事业机构相关公务人员", "卫生医疗机构职员", "公立学校职员", "特殊职系公务人员"], "excluded_groups": ["政务人员", "民选地方行政首长", "民意代表", "公立学校教师"], "detail_display": "modal"}, "identity_comparison": {"title": "政务官与事务官区分", "display": "comparison_table", "items": [{"dimension": "基本性质", "political_official": "政治任命或政策领导人员", "career_civil_servant": "职业文官、常任公务人员"}, {"dimension": "进入方式", "political_official": "任命、特任、特派、提名同意", "career_civil_servant": "考试及格、铨叙合格、升等合格"}, {"dimension": "主要功能", "political_official": "制定政策、决定施政方向、承担政治责任", "career_civil_servant": "执行政策、处理行政事务、承担行政责任"}, {"dimension": "任期稳定性", "political_official": "通常随执政团队或政治任命变化而进退", "career_civil_servant": "具有身份保障,非因法定原因不得任意免职"}, {"dimension": "行政中立", "political_official": "一般不是行政中立法的主要适用对象", "career_civil_servant": "行政中立法的核心适用对象"}, {"dimension": "典型职位", "political_official": "部会首长、政务次长、政务委员", "career_civil_servant": "科员、专员、科长、司长、常务次长"}], "detail": {"政务人员": "政策制定层,承担政治责任,随执政团队和政治任命变化。", "事务官": "职业文官体系主体,强调依法行政、行政中立、身份保障和长期行政执行。", "边界类别": ["机要人员", "约聘雇人员", "行政契约人员"]}, "detail_display": "secondary_page"}, "appointment_modes": [{"name": "考试任用", "description": "通过国家考试进入公务体系,是事务官的典型进入路径。"}, {"name": "铨叙任用", "description": "依法取得任用资格并经铨叙程序确认。"}, {"name": "升等任用", "description": "依资历、考绩、训练或升等考试取得更高职等任用资格。"}, {"name": "政务任用", "description": "政治任命性质,主要对应Line truncated
|
||||
let activeTab = DATA.navigation.tabs[0].id;
|
||||
let filterState = {};
|
||||
const FIELD_LABELS = DATA.ui?.field_labels || {};
|
||||
const THEME_LABELS = DATA.ui?.theme_labels || {};
|
||||
const TAB_KIND = {basic_knowledge:'基础知识',policy_changes:'政策法规',research_outputs:'研究成果',recent_issues:'关注议题',monthly_dynamics:'动态监测'};
|
||||
function esc(x){return String(x ?? '').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}
|
||||
function arr(x){return Array.isArray(x)?x:(x? [x]:[])}
|
||||
function label(k){return FIELD_LABELS[k] || THEME_LABELS[k] || k}
|
||||
function textOf(x){ if(x==null) return ''; if(typeof x==='string'||typeof x==='number'||typeof x==='boolean') return String(x); if(Array.isArray(x)) return x.map(textOf).join(' '); if(typeof x==='object') return Object.values(x).map(textOf).join(' '); return '' }
|
||||
function tagList(xs, cls='red'){ return arr(xs).map(x=>`<span class="badge ${cls}">${esc(label(x))}</span>`).join('') }
|
||||
function chips(xs){ return arr(xs).map(x=>`<span class="pill">${esc(label(x))}</span>`).join('') }
|
||||
function sourceButton(url){ return url ? `<a class="source-link" target="_blank" href="${esc(url)}">打开来源</a>` : `<span class="badge gray">暂无来源链接</span>` }
|
||||
function detailBlocks(sections){ return arr(sections).filter(s=>textOf(s.content).trim()).map(s=>`<div class="detail-block"><h4>${esc(s.title)}</h4><p>${esc(s.content)}</p></div>`).join('') }
|
||||
function kv(labelText, value){ if(value==null || value==='' || (Array.isArray(value)&&!value.length)) return ''; return `<div class="kv"><div class="k">${esc(labelText)}</div><div class="v">${Array.isArray(value)?tagList(value):esc(label(value))}</div></div>`}
|
||||
function setup(){renderTabs(); renderPage(); bindGlobalSearch(); document.getElementById('resetBtn').onclick=()=>{filterState={}; document.getElementById('globalSearch').value=''; renderPage();}; document.getElementById('sourceBtn').onclick=showSources;}
|
||||
function renderTabs(){const box=document.getElementById('tabs'); box.innerHTML=DATA.navigation.tabs.map(t=>`<button class="tab ${t.id===activeTab?'active':''}" data-id="${t.id}">${esc(t.label)}</button>`).join(''); box.querySelectorAll('button').forEach(b=>b.onclick=()=>{activeTab=b.dataset.id; filterState={}; document.getElementById('searchPop').classList.add('hidden'); renderTabs(); renderPage();});}
|
||||
function pageHead(title,desc){return `<div class="page-head"><div><h2>${esc(title)}</h2><p>${esc(desc||'')}</p></div><div class="page-actions"><button class="btn line sm" onclick="showSources()">来源索引</button><button class="btn primary sm" onclick="exportCurrentJSON()">导出本栏JSON</button></div></div>`}
|
||||
function renderPage(){const main=document.getElementById('main'); const tab=DATA.navigation.tabs.find(t=>t.id===activeTab); let html=pageHead(tab.label, tab.description); if(activeTab==='basic_knowledge') html+=renderBasic(); if(activeTab==='policy_changes') html+=renderPolicy(); if(activeTab==='research_outputs') html+=renderResearch(); if(activeTab==='recent_issues') html+=renderIssues(); if(activeTab==='monthly_dynamics') html+=renderDynamics(); main.innerHTML=html; bindFilters();}
|
||||
function renderBasic(){const d=DATA.data.basic_knowledge; const cards=d.summary_cards||[]; let html=`<div class="notice mb">${esc(d.rich_note?.paragraphs?.[0]||'')}</div>`; html+=`<div class="stats mb">${cards.map(c=>`<div class="stat"><div class="label">${esc(c.label)}</div><div class="num">${esc(c.value)}${c.unit?`<small style="font-size:14px"> ${esc(c.unit)}</small>`:''}</div><div class="hint">${esc(c.description||'')}</div></div>`).join('')}</div>`; html+=`<div class="grid cols2"><div class="panel"><div class="panel-head"><h3>台湾公务员群体定义</h3><button class="btn light sm" onclick="openBasicDetail('definition')">详情</button></div><p>${esc(d.definition.summary||d.definition.official_scope||'')}</p><h4>包含群体</h4><div>${tagList(d.definition.included_groups,'green')}</div><h4 class="mt">排除群体</h4><div>${tagList(d.definition.excluded_groups,'gray')}</div></div>`;
|
||||
html+=`<div class="panel"><div class="panel-head"><h3>政务官与事务官区分</h3><button class="btn light sm" onclick="openBasicDetail('identity')">二级详情</button></div><div class="table-wrap"><table class="compare-table"><thead><tr><th>比较维度</th><th>政务官 / 政务人员</th><th>事务官 / 常任文官</th></tr></thead><tbody>${(d.identity_comparison.items||[]).map(r=>`<tr><td>${esc(r.dimension)}</td><td>${esc(r.political_official)}</td><td>${esc(r.career_civil_servant)}</td></tr>`).join('')}</tbody></table></div></div></div>`;
|
||||
html+=`<div class="section-title"><h3>任用方式与官等职等</h3><span>点击卡片可查看说明</span></div><div class="grid cols3">${(d.appointment_modes||[]).map(m=>`<div class="card-item" onclick="openModalHTML('${esc(m.name)}','<p>${esc(m.description)}</p>')"><h4>${esc(m.name)}</h4><p>${esc(m.description)}</p></div>`).join('')}</div>`;
|
||||
html+=`<div class="grid cols2 mt"><div class="panel"><div class="panel-head"><h3>官等职等结构</h3></div>${(d.rank_structure||[]).map(r=>`<div class="rank"><strong>${esc(r.rank)}</strong><p>${esc(r.grade_range)}|${esc(arr(r.typical_positions).join('、'))}</p></div>`).join('')}</div><div class="panel"><div class="panel-head"><h3>薪资待遇结构</h3></div>${(d.salary_structure||[]).map(s=>`<div class="detail-block"><h4>${esc(s.name)}</h4><p>${esc(s.description)}</p></div>`).join('')}</div></div>`;
|
||||
html+=`<div class="grid cols2 mt"><div class="panel"><div class="panel-head"><h3>年龄结构</h3><span class="badge red">平均 ${esc(d.summary_cards?.find(c=>c.id==='average_age')?.value||'43.75')} 岁</span></div>${(d.age_structure||[]).map(a=>`<div class="bar-row"><span>${esc(a.age_group)}</span><div class="bar-track"><div class="bar-fill" style="width:${Math.max(2,a.ratio*4)}%"></div></div><b>${esc(a.ratio)}%</b></div>`).join('')}</div><div class="panel"><div class="panel-head"><h3>性别结构与法规框架</h3></div>${(d.gender_structure||[]).map(g=>`<div class="bar-row"><span>${esc(g.gender)}</span><div class="bar-track"><div class="bar-fill" style="width:${g.ratio}%"></div></div><b>${g.ratio}%</b></div>`).join('')}<h4>适用法规</h4><div class="law-grid">${tagList(d.legal_framework,'blue')}</div></div></div>`;
|
||||
html+=`<div class="panel mt"><h3>结构性判断</h3><div class="grid cols3 mt">${(d.structure_judgement||[]).map(j=>`<div class="detail-block"><h4>${esc(j.label||j.observation||'观察项')}</h4><p>${esc(j.explanation||j.description||j.value||textOf(j))}</p></div>`).join('')}</div></div>`;
|
||||
return html;}
|
||||
function openBasicDetail(kind){const d=DATA.data.basic_knowledge; if(kind==='definition'){openModalHTML('台湾公务员群体定义', `<p>${esc(d.definition.summary||'')}</p><h4>包含群体</h4><div>${tagList(d.definition.included_groups,'green')}</div><h4>排除群体</h4><div>${tagList(d.definition.excluded_groups,'gray')}</div>${detailBlocks((d.rich_note?.paragraphs||[]).map((p,i)=>({title:'说明 '+(i+1),content:p})))}`)} else {openDetailPage('政务官与事务官区分', d.identity_comparison.title, `<div class="notice">政务官偏向政治任命与政策责任,事务官偏向考试任用、行政执行与身份保障。机要人员和约聘雇人员应作为边界类别单独识别。</div><div class="table-wrap mt"><table><thead><tr><th>比较维度</th><th>政务官 / 政务人员</th><th>事务官 / 常任文官</th></tr></thead><tbody>${d.identity_comparison.items.map(r=>`<tr><td>${esc(r.dimension)}</td><td>${esc(r.political_official)}</td><td>${esc(r.career_civil_servant)}</td></tr>`).join('')}</tbody></table></div>`)}}
|
||||
function filterUI(type, selects){return `<div class="filters"><input class="input" data-filter="q" placeholder="在本栏搜索关键词" value="${esc(filterState.q||'')}">${selects.map(s=>selectHTML(s.key,s.label,s.options)).join('')}<button class="btn primary" onclick="applyFilters()">查询</button></div>`}
|
||||
function selectHTML(key,labelText,options){return `<select class="select" data-filter="${key}"><option value="">${esc(labelText)}:全部</option>${options.map(o=>`<option ${filterState[key]===o?'selected':''} value="${esc(o)}">${esc(label(o))}</option>`).join('')}</select>`}
|
||||
function bindFilters(){document.querySelectorAll('[data-filter]').forEach(el=>{el.onchange=()=>{filterState[el.dataset.filter]=el.value; renderPage();}; el.onkeydown=e=>{if(e.key==='Enter'){filterState[el.dataset.filter]=el.value; renderPage();}}});}
|
||||
function applyFilters(){document.querySelectorAll('[data-filter]').forEach(el=>filterState[el.dataset.filter]=el.value); renderPage();}
|
||||
function unique(items, getter){return [...new Set(items.flatMap(x=>arr(getter(x))).filter(Boolean))]}
|
||||
function filterList(items, cfg){let q=(filterState.q||'').trim().toLowerCase(); return items.filter(it=>{if(q && !textOf(it).toLowerCase().includes(q)) return false; for(const [k,getter] of Object.entries(cfg||{})){if(filterState[k]){let vals=arr(getter(it)).map(String); if(!vals.includes(filterState[k])) return false;}} return true;})}
|
||||
function renderPolicy(){const d=DATA.data.policy_changes, items=d.items||[]; const filtered=filterList(items,{type:x=>x.policy_type,status:x=>x.status,group:x=>x.affected_groups,importance:x=>x.importance}); let html=filterUI('policy',[{key:'type',label:'政策类型',options:unique(items,x=>x.policy_type)},{key:'status',label:'政策状态',options:unique(items,x=>x.status)},{key:'group',label:'影响群体',options:unique(items,x=>x.affected_groups)},{key:'importance',label:'重要性',options:unique(items,x=>x.importance)}]); html+=`<div class="stats mb"><div class="stat"><div class="label">政策总数</div><div class="num">${items.length}</div><div class="hint">赖清德上任至今</div></div><div class="stat"><div class="label">当前命中</div><div class="num">${filtered.length}</div><div class="hint">按筛选条件</div></div><div class="stat"><div class="label">高重要性</div><div class="num">${items.filter(x=>x.importance==='高').length}</div><div class="hint">重点跟踪</div></div><div class="stat"><div class="label">草案/审议</div><div class="num">${items.filter(x=>/草案|审议|函送/.test(x.status+x.summary)).length}</div><div class="hint">需后续观察</div></div></div>`; html+=`<div class="grid cols2"><div class="panel"><h3>政策法规时间线</h3><div class="timeline mt">${filtered.map(it=>eventHTML(it.date,it.policy_name,it.summary,`openPolicy('${it.id}')`)).join('')||'<div class="empty">无匹配数据</div>'}</div></div><div class="panel"><h3>政策卡片</h3><div class="grid cols2 mt">${filtered.map(policyCard).join('')||'<div class="empty">无匹配数据</div>'}</div></div></div>`; return html;}
|
||||
function eventHTML(date,title,summary,click){return `<div class="event" onclick="${click}"><div class="date">${esc(date)}</div><h4>${esc(title)}</h4><p>${esc(summary)}</p></div>`}
|
||||
function policyCard(it){return `<div class="card-item"><h4>${esc(it.policy_name)}</h4><div>${tagList([it.policy_type,it.status,it.importance])}</div><p>${esc(it.summary)}</p><div>${tagList(it.affected_groups,'gray')}</div><div class="card-foot"><button class="btn light sm" onclick="openPolicy('${it.id}')">弹框详情</button><button class="btn line sm" onclick="openPolicyPage('${it.id}')">二级详情</button></div></div>`}
|
||||
function openPolicy(id){const it=DATA.data.policy_changes.items.find(x=>x.id===id); openModalHTML(it.policy_name, renderRecord(it, 'policy'))}
|
||||
function openPolicyPage(id){const it=DATA.data.policy_changes.items.find(x=>x.id===id); openDetailPage('政策法规二级详情', it.policy_name, renderRecord(it,'policy',true))}
|
||||
function renderResearch(){const d=DATA.data.research_outputs, items=d.items||[]; const filtered=filterList(items,{theme:x=>x.theme_cluster,source:x=>x.source_type,evidence:x=>x.evidence_strength,group:x=>x.target_groups}); let html=filterUI('research',[{key:'theme',label:'主题簇',options:unique(items,x=>x.theme_cluster)},{key:'source',label:'来源类型',options:unique(items,x=>x.source_type)},{key:'evidence',label:'证据强度',options:unique(items,x=>x.evidence_strength)},{key:'group',label:'对应群体',options:unique(items,x=>x.target_groups)}]); html+=`<div class="grid cols4 mb">${(d.theme_clusters||[]).map(c=>`<div class="panel" onclick="filterState.theme='${esc(c.id)}'; renderPage();"><h4>${esc(c.label)}</h4><p>${esc((c.keywords||[]).join('、'))}</p><span class="badge red">${esc(c.count||items.filter(x=>x.theme_cluster===c.id).length)} 条</span></div>`).join('')}</div>`; html+=`<div class="grid cols3">${filtered.map(researchCard).join('')||'<div class="empty">无匹配数据</div>'}</div>`; html+=`<div class="section-title"><h3>研究结论图谱</h3><span>点击查看支撑研究</span></div><div class="grid cols3">${(d.insight_map||[]).map(i=>`<div class="panel"><h4>${esc(i.theme)}</h4><p>${esc(i.core_conclusion)}</p><div>${tagList(i.related_groups,'gray')}</div><button class="btn light sm mt" onclick="openInsight('${esc(i.theme)}')">查看关联</button></div>`).join('')}</div>`; return html;}
|
||||
function researchCard(it){return `<div class="card-item"><h4>${esc(it.title)}</h4><div>${tagList([THEME_LABELS[it.theme_cluster]||it.theme_cluster,it.source_type,it.evidence_strength])}</div><p>${esc(it.page_summary||it.core_finding)}</p><div>${tagList(it.target_groups,'gray')}</div><div class="card-foot"><button class="btn light sm" onclick="openResearch('${it.id}')">弹框详情</button><button class="btn line sm" onclick="openResearchPage('${it.id}')">二级详情</button></div></div>`}
|
||||
function openResearch(id){const it=DATA.data.research_outputs.items.find(x=>x.id===id); openModalHTML(it.title, renderRecord(it,'research') + `<div class="mt">${sourceButton(it.source_url)}</div>`)}
|
||||
function openResearchPage(id){const it=DATA.data.research_outputs.items.find(x=>x.id===id); openDetailPage('研究成果二级详情', it.title, renderRecord(it,'research',true)+`<div class="mt">${sourceButton(it.source_url)}</div>`)}
|
||||
function openInsight(theme){const i=DATA.data.research_outputs.insight_map.find(x=>x.theme===theme); const rs=arr(i.related_research_ids).map(id=>DATA.data.research_outputs.items.find(x=>x.id===id)).filter(Boolean); openModalHTML(theme, `<p class="modal-sub">${esc(i.core_conclusion)}</p><div>${tagList(i.related_groups,'gray')}</div><div class="grid cols2 mt">${rs.map(researchCard).join('')}</div>`)}
|
||||
function renderIssues(){const d=DATA.data.recent_issues, items=d.items||[]; const filtered=filterList(items,{heat:x=>x.heat_level,type:x=>x.issue_type,group:x=>x.affected_groups,evidence:x=>x.evidence_level}); let html=filterUI('issues',[{key:'heat',label:'热度',options:unique(items,x=>x.heat_level)},{key:'type',label:'议题类型',options:unique(items,x=>x.issue_type)},{key:'group',label:'影响群体',options:unique(items,x=>x.affected_groups)},{key:'evidence',label:'证据等级',options:unique(items,x=>x.evidence_level)}]); html+=`<div class="notice mb">近月议题栏展示的是“事件链—群体诉求—态度结构—制度敏感点”,不是简单榜单。</div><div class="grid cols3">${filtered.map(issueCard).join('')||'<div class="empty">无匹配数据</div>'}</div>`; const dm=d.demand_map||[]; if(dm.length) html+=`<div class="section-title"><h3>群体诉求图谱</h3></div><div class="grid cols4">${dm.map(x=>`<div class="panel"><h4>${esc(x.demand_type||x.type||x.title)}</h4><p>${esc(x.content||x.description||textOf(x))}</p></div>`).join('')}</div>`; return html;}
|
||||
function issueCard(it){return `<div class="card-item"><h4>${esc(it.issue_name)}</h4><div>${tagList([it.heat_level,it.issue_type,it.evidence_level])}</div><p>${esc(it.page_summary)}</p><div>${tagList(it.affected_groups,'gray')}</div><div class="card-foot"><button class="btn light sm" onclick="openIssue('${it.id}')">弹框详情</button><button class="btn line sm" onclick="openIssuePage('${it.id}')">二级详情</button></div></div>`}
|
||||
function openIssue(id){const it=DATA.data.recent_issues.items.find(x=>x.id===id); openModalHTML(it.issue_name, renderRecord(it,'issue') + `<div class="mt">${sourceButton(it.source_url)}</div>`)}
|
||||
function openIssuePage(id){const it=DATA.data.recent_issues.items.find(x=>x.id===id); openDetailPage('议题深度二级详情', it.issue_name, renderRecord(it,'issue',true)+`<div class="mt">${sourceButton(it.source_url)}</div>`)}
|
||||
function renderDynamics(){const d=DATA.data.monthly_dynamics, items=d.items||[]; const filtered=filterList(items,{source:x=>x.source_type,issue:x=>x.related_issue,importance:x=>x.importance,evidence:x=>x.evidence_level}); let html=filterUI('dynamics',[{key:'source',label:'来源类型',options:unique(items,x=>x.source_type)},{key:'issue',label:'关联议题',options:unique(items,x=>x.related_issue)},{key:'importance',label:'重要性',options:unique(items,x=>x.importance)},{key:'evidence',label:'证据等级',options:unique(items,x=>x.evidence_level)}]); html+=`<div class="grid cols2"><div class="panel"><h3>动态时间线</h3><div class="timeline mt">${filtered.map(it=>eventHTML(it.date,it.event_title,it.event_summary,`openDynamic('${it.id}')`)).join('')||'<div class="empty">无匹配数据</div>'}</div></div><div class="panel"><h3>月度综合判断</h3>${(d.monthly_summary?.main_lines||[]).map(x=>`<div class="detail-block"><h4>${esc(x.line)}</h4><p>${esc(x.summary)}</p></div>`).join('')}</div></div>`; html+=`<div class="section-title"><h3>动态卡片流</h3><span>${filtered.length} 条</span></div><div class="grid cols3">${filtered.map(dynamicCard).join('')}</div>`; return html;}
|
||||
function dynamicCard(it){return `<div class="card-item"><h4>${esc(it.event_title)}</h4><div>${tagList([it.date,it.source_type,it.importance])}</div><p>${esc(it.page_summary||it.event_summary)}</p><div>${tagList(it.related_issue,'gray')}</div><div class="card-foot"><button class="btn light sm" onclick="openDynamic('${it.id}')">弹框详情</button><button class="btn line sm" onclick="openDynamicPage('${it.id}')">二级详情</button></div></div>`}
|
||||
function openDynamic(id){const it=DATA.data.monthly_dynamics.items.find(x=>x.id===id); openModalHTML(it.event_title, renderRecord(it,'dynamic') + `<div class="mt">${sourceButton(it.source_url)}</div>`)}
|
||||
function openDynamicPage(id){const it=DATA.data.monthly_dynamics.items.find(x=>x.id===id); openDetailPage('动态监测二级详情', it.event_title, renderRecord(it,'dynamic',true)+`<div class="mt">${sourceButton(it.source_url)}</div>`)}
|
||||
function renderRecord(it, type, full=false){let top=''; if(type==='policy') top+=kv('编号',it.id)+kv('日期',it.date)+kv('政策类型',it.policy_type)+kv('政策状态',it.status)+kv('主管机关',it.authority)+kv('重要性',it.importance)+kv('影响群体',it.affected_groups); if(type==='research') top+=kv('编号',it.id)+kv('来源类型',it.source_type)+kv('机构',it.institution)+kv('作者',it.author)+kv('年份',it.year)+kv('文献类型',it.document_type)+kv('主题簇',THEME_LABELS[it.theme_cluster]||it.theme_cluster)+kv('对应群体',it.target_groups)+kv('证据强度',it.evidence_strength); if(type==='issue') top+=kv('编号',it.id)+kv('热度',it.heat_level)+kv('议题类型',it.issue_type)+kv('时间范围',it.time_range)+kv('影响群体',it.affected_groups)+kv('证据等级',it.evidence_level); if(type==='dynamic') top+=kv('编号',it.id)+kv('日期',it.date)+kv('来源类型',it.source_type)+kv('主体',it.actor)+kv('重要性',it.importance)+kv('关联议题',it.related_issue)+kv('影响群体',it.affected_groups)+kv('证据等级',it.evidence_level);
|
||||
let html=`<div class="detail-block"><h4>基本信息</h4>${top||'<p>无基本信息</p>'}</div>`; html += detailBlocks(it.rich_detail||[]);
|
||||
if(it.event_chain){ html+=`<div class="detail-block"><h4>事件链</h4><div class="timeline">${it.event_chain.map(e=>eventHTML(e.date,e.event,e.event,'')).join('')}</div></div>`}
|
||||
if(it.attitude_structure){ html+=`<div class="detail-block"><h4>态度结构</h4>${it.attitude_structure.map(a=>`<p><b>${esc(a.attitude)}:</b>${esc(a.description)}</p>`).join('')}</div>`}
|
||||
if(it.tags) html += `<div class="detail-block"><h4>标签</h4>${tagList(it.tags,'gray')}</div>`; return html;}
|
||||
function openModalHTML(title, html){document.getElementById('modalBody').innerHTML=`<h2 class="modal-title">${title}</h2>${html}`; document.getElementById('modal').classList.remove('hidden')}
|
||||
function closeModal(){document.getElementById('modal').classList.add('hidden')}
|
||||
function openDetailPage(kind,title,html){document.getElementById('detail').innerHTML=`<div class="detail-top"><strong>${esc(kind)}</strong><button class="btn white" onclick="closeDetail()">返回</button></div><div class="detail-body"><div class="detail-hero"><div><h2>${esc(title)}</h2><p>本页用于展示较长字段、事件链、研究解释和关联信息,避免主列表过度拥挤。</p></div><div class="detail-summary"><b>展示原则</b><p>主卡片只显示摘要;本页显示完整结构化内容。字段均已中文化,不再直接展示技术字段名。</p></div></div><div class="mt">${html}</div></div>`; document.getElementById('detail').classList.remove('hidden')}
|
||||
function closeDetail(){document.getElementById('detail').classList.add('hidden')}
|
||||
function showSources(){const sources=DATA.source_index||[]; openModalHTML('来源索引', `<p class="modal-sub">本页保留来源索引,便于后续回溯和外部 JSON 长期更新。</p>${sources.map(s=>`<div class="source-card"><h4>${esc(s.name)}</h4><p>${esc(s.type||'')}|${esc(s.note||'')}</p><div class="mt">${sourceButton(s.url)}</div></div>`).join('')}`)}
|
||||
function exportCurrentJSON(){const obj=DATA.data[activeTab]; const blob=new Blob([JSON.stringify(obj,null,2)],{type:'application/json'}); const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download=activeTab+'.json'; a.click(); URL.revokeObjectURL(a.href)}
|
||||
function bindGlobalSearch(){const inp=document.getElementById('globalSearch'), pop=document.getElementById('searchPop'); inp.addEventListener('input',()=>{const q=inp.value.trim().toLowerCase(); if(!q){pop.classList.add('hidden');return;} const rows=[]; for(const tab of DATA.navigation.tabs){const sec=DATA.data[tab.id]; let items=[]; if(tab.id==='basic_knowledge'){items=[{id:'basic',title:'公务员基础知识',summary:textOf(sec),tab:tab.id}];} else items=sec.items||[]; items.forEach(it=>{if(textOf(it).toLowerCase().includes(q)){rows.push({tab:tab.id, kind:tab.label, item:it, title:itemTitle(it,tab.id), summary:itemSummary(it,tab.id)});}})} pop.innerHTML=rows.slice(0,30).map((r,i)=>`<div class="search-item" onclick="openSearchResult('${r.tab}','${esc(r.item.id||'basic')}')"><div class="search-kind">${esc(r.kind)}</div><div><strong>${esc(r.title)}</strong><small>${esc(r.summary).slice(0,120)}</small></div></div>`).join('') || '<div class="empty">无匹配结果</div>'; pop.classList.remove('hidden');});}
|
||||
function itemTitle(it,tab){return it.policy_name||it.title||it.issue_name||it.event_title||'基础知识'} function itemSummary(it,tab){return it.summary||it.page_summary||it.core_finding||it.event_summary||textOf(it)}
|
||||
function openSearchResult(tab,id){activeTab=tab; filterState={}; renderTabs(); renderPage(); document.getElementById('searchPop').classList.add('hidden'); if(tab==='policy_changes') openPolicy(id); else if(tab==='research_outputs') openResearch(id); else if(tab==='recent_issues') openIssue(id); else if(tab==='monthly_dynamics') openDynamic(id); else openBasicDetail('definition')}
|
||||
async function tryExternal(){ if(!EXTERNAL_JSON_URL) return; try{const r=await fetch(EXTERNAL_JSON_URL); if(r.ok){DATA=await r.json();}}catch(e){console.warn('外部JSON读取失败,继续使用内置数据',e);} }
|
||||
tryExternal().then(setup);
|
||||
</script>
|
||||
</body></html>
|
||||
+326
@@ -0,0 +1,326 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>台湾后备力量与全社会防卫韧性专题库 v2</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg0:#4a1013;
|
||||
--bg1:#6b181c;
|
||||
--bg2:#8a2428;
|
||||
--card:#fffaf7;
|
||||
--card2:#fff5ee;
|
||||
--ink:#211617;
|
||||
--muted:#6f5959;
|
||||
--line:#ead5cc;
|
||||
--line2:#d6b8ac;
|
||||
--accent:#a83b3f;
|
||||
--accent2:#f3d3c5;
|
||||
--gold:#b88a45;
|
||||
--green:#617a51;
|
||||
--blue:#496f8f;
|
||||
--shadow:0 18px 50px rgba(40,0,0,.22);
|
||||
--radius:18px;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
html,body{margin:0;padding:0;font-family:"Microsoft YaHei","PingFang SC",Arial,sans-serif;color:var(--ink);background:linear-gradient(145deg,var(--bg0),var(--bg1) 45%,#3b0d10);}
|
||||
body{min-height:100vh;}
|
||||
.header{position:relative;overflow:hidden;padding:34px 34px 26px;color:#fff;border-bottom:1px solid rgba(255,255,255,.18);}
|
||||
.header:before{content:"";position:absolute;inset:-80px -80px auto auto;width:300px;height:300px;border-radius:50%;background:rgba(255,255,255,.08)}
|
||||
.header:after{content:"";position:absolute;left:35px;bottom:-65px;width:180px;height:180px;border:1px solid rgba(255,255,255,.18);border-radius:50%;}
|
||||
.header-inner{position:relative;z-index:2;max-width:1440px;margin:0 auto;}
|
||||
.kicker{display:inline-flex;align-items:center;gap:8px;border:1px solid rgba(255,255,255,.32);border-radius:999px;padding:7px 12px;font-size:12px;letter-spacing:.08em;background:rgba(255,255,255,.08)}
|
||||
.kicker .dot{width:8px;height:8px;background:#f7d4c3;border-radius:50%;display:inline-block;}
|
||||
h1{margin:18px 0 8px;font-size:34px;letter-spacing:.04em;line-height:1.25}
|
||||
.subtitle{max-width:1060px;color:#f7ddd3;font-size:15px;line-height:1.75}
|
||||
.boundary{margin-top:16px;display:flex;flex-wrap:wrap;gap:10px;}
|
||||
.boundary span{background:rgba(255,255,255,.10);border:1px solid rgba(255,255,255,.18);padding:7px 10px;border-radius:12px;font-size:12px;color:#fff1eb}
|
||||
.shell{max-width:1440px;margin:0 auto;padding:20px 24px 42px;}
|
||||
.panel{background:rgba(255,250,247,.96);border:1px solid rgba(255,255,255,.45);box-shadow:var(--shadow);border-radius:24px;overflow:hidden;}
|
||||
.controls{padding:18px;display:grid;grid-template-columns:2.1fr 1fr 1fr 1fr auto;gap:12px;border-bottom:1px solid var(--line);background:linear-gradient(180deg,#fffaf8,#fff3ec);}
|
||||
.input,select{width:100%;border:1px solid var(--line2);border-radius:14px;background:#fff;color:var(--ink);font-size:14px;padding:12px 13px;outline:none;}
|
||||
.input:focus,select:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(168,59,63,.12)}
|
||||
.btn{border:1px solid var(--accent);background:var(--accent);color:#fff;border-radius:14px;padding:11px 14px;font-weight:700;cursor:pointer;white-space:nowrap}
|
||||
.btn.secondary{background:#fff;color:var(--accent)}
|
||||
.btn:hover{filter:brightness(.98)}
|
||||
.stats{display:grid;grid-template-columns:repeat(6,1fr);gap:10px;padding:14px 18px;border-bottom:1px solid var(--line);background:#fffaf7;}
|
||||
.stat{border:1px solid var(--line);border-radius:16px;padding:12px;background:#fff;}
|
||||
.stat b{display:block;font-size:22px;color:var(--accent);}
|
||||
.stat span{font-size:12px;color:var(--muted)}
|
||||
.tabs{display:flex;gap:8px;overflow-x:auto;padding:12px 14px;border-bottom:1px solid var(--line);background:#fbefe7;}
|
||||
.tab{border:1px solid var(--line2);background:#fff;border-radius:999px;padding:10px 14px;cursor:pointer;white-space:nowrap;font-weight:700;color:#5a3d3e;}
|
||||
.tab.active{background:var(--accent);color:#fff;border-color:var(--accent);box-shadow:0 8px 18px rgba(168,59,63,.22)}
|
||||
.tab small{display:block;font-weight:500;opacity:.75;font-size:10px;margin-top:2px}
|
||||
.tab-head{display:flex;justify-content:space-between;gap:16px;align-items:flex-start;padding:18px 18px 10px;}
|
||||
.tab-title h2{margin:0;font-size:24px;color:#321b1d}
|
||||
.tab-title p{margin:6px 0 0;color:var(--muted);line-height:1.7}
|
||||
.tab-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}
|
||||
.toolbar{padding:10px 18px 16px;display:grid;grid-template-columns:2fr repeat(3,1fr);gap:10px;border-bottom:1px solid var(--line);}
|
||||
.subfilters{display:flex;flex-wrap:wrap;gap:9px;padding:13px 18px;background:#fffaf7;border-bottom:1px solid var(--line);}
|
||||
.chip{border:1px solid var(--line2);background:#fff;border-radius:999px;padding:8px 12px;cursor:pointer;font-size:13px;color:#5d4444;}
|
||||
.chip.active{background:#3f2225;color:#fff;border-color:#3f2225}
|
||||
.content{padding:18px;}
|
||||
.flow{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:18px;}
|
||||
.flow-node{background:linear-gradient(180deg,#fff,#fff5ee);border:1px solid var(--line);border-radius:18px;padding:14px;position:relative;min-height:92px;}
|
||||
.flow-node:after{content:"→";position:absolute;right:-13px;top:34px;color:var(--accent);font-weight:900;}
|
||||
.flow-node:last-child:after{content:""}
|
||||
.flow-node b{display:block;color:var(--accent);font-size:15px;margin-bottom:6px}
|
||||
.flow-node span{font-size:12px;color:var(--muted);line-height:1.5}
|
||||
.cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;}
|
||||
.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:0 8px 20px rgba(76,25,18,.06);display:flex;flex-direction:column;gap:12px;min-height:230px;}
|
||||
.card:hover{border-color:#c69d8d;transform:translateY(-1px);transition:.15s ease}
|
||||
.card h3{margin:0;font-size:18px;line-height:1.35;color:#2b1719}
|
||||
.meta-row{display:flex;flex-wrap:wrap;gap:7px;}
|
||||
.badge{font-size:12px;border:1px solid var(--line2);background:#fff;border-radius:999px;padding:5px 8px;color:#684d4d;}
|
||||
.badge.red{background:#fff0ee;border-color:#e5b6ae;color:#913135}
|
||||
.badge.green{background:#f1f6ed;border-color:#c6d5bf;color:#516e3d}
|
||||
.badge.blue{background:#eff6fb;border-color:#bfd2df;color:#426886}
|
||||
.summary{color:#604a4a;font-size:13px;line-height:1.68;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden;}
|
||||
.section-mini{background:#fff;border:1px solid var(--line);border-radius:14px;padding:10px;}
|
||||
.section-mini b{font-size:12px;color:#8c3337;display:block;margin-bottom:6px}
|
||||
.section-mini ul{margin:0;padding-left:18px;color:#5e4a4a;font-size:12px;line-height:1.55}
|
||||
.card-footer{margin-top:auto;display:flex;justify-content:space-between;gap:10px;align-items:center}
|
||||
.link-btn{border:0;background:transparent;color:var(--accent);font-weight:800;cursor:pointer;padding:6px 0}
|
||||
.warning{font-size:12px;color:#805f40}
|
||||
.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:18px;background:#fff}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px;}
|
||||
th{position:sticky;top:0;background:#f5e3d9;color:#4b292a;text-align:left;padding:12px;border-bottom:1px solid var(--line2);white-space:nowrap}
|
||||
td{padding:11px 12px;border-bottom:1px solid var(--line);vertical-align:top}
|
||||
tr:hover td{background:#fff8f4}
|
||||
.timeline{position:relative;padding-left:26px;display:grid;gap:14px}
|
||||
.timeline:before{content:"";position:absolute;left:9px;top:5px;bottom:5px;width:2px;background:#d9b8ac}
|
||||
.titem{position:relative;background:#fff;border:1px solid var(--line);border-radius:18px;padding:15px;}
|
||||
.titem:before{content:"";position:absolute;left:-24px;top:18px;width:12px;height:12px;background:var(--accent);border-radius:50%;border:3px solid #fff}
|
||||
.empty{text-align:center;color:var(--muted);padding:48px;border:1px dashed var(--line2);border-radius:18px;background:#fffaf7}
|
||||
.modal-mask{position:fixed;inset:0;background:rgba(32,10,10,.62);display:none;align-items:center;justify-content:center;z-index:20;padding:26px;}
|
||||
.modal{width:min(1060px,96vw);max-height:90vh;overflow:auto;background:#fffaf7;border-radius:24px;box-shadow:0 30px 90px rgba(0,0,0,.45);border:1px solid #fff;}
|
||||
.modal-head{position:sticky;top:0;background:linear-gradient(180deg,#fffaf7,#fff2ea);border-bottom:1px solid var(--line);padding:18px;z-index:2;display:flex;justify-content:space-between;gap:14px;align-items:flex-start}
|
||||
.modal-head h2{margin:0;font-size:24px}
|
||||
.close{border:1px solid var(--line2);background:#fff;border-radius:12px;font-size:20px;width:40px;height:40px;cursor:pointer}
|
||||
.modal-body{padding:18px;display:grid;gap:14px}
|
||||
.detail-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
|
||||
.detail-block{background:#fff;border:1px solid var(--line);border-radius:16px;padding:14px}
|
||||
.detail-block h4{margin:0 0 10px;color:#8b3035;font-size:15px}
|
||||
.detail-block p{margin:0;color:#4f3b3b;line-height:1.75}
|
||||
.detail-block ul{margin:0;padding-left:20px;color:#4f3b3b;line-height:1.65}
|
||||
.source-list a{color:#8b3035;text-decoration:none;border-bottom:1px dotted #8b3035}
|
||||
.source-item{padding:9px 0;border-bottom:1px solid var(--line)}
|
||||
.source-item:last-child{border-bottom:0}
|
||||
.notice{border:1px solid #e2bd9a;background:#fff6e8;color:#74512b;border-radius:14px;padding:12px;line-height:1.6}
|
||||
@media(max-width:1100px){.controls{grid-template-columns:1fr 1fr}.toolbar{grid-template-columns:1fr 1fr}.cards{grid-template-columns:repeat(2,1fr)}.stats{grid-template-columns:repeat(3,1fr)}.flow{grid-template-columns:repeat(2,1fr)}.flow-node:after{display:none}}
|
||||
@media(max-width:720px){.header{padding:26px 18px}h1{font-size:26px}.shell{padding:14px}.controls,.toolbar{grid-template-columns:1fr}.cards{grid-template-columns:1fr}.stats{grid-template-columns:repeat(2,1fr)}.detail-grid{grid-template-columns:1fr}.flow{grid-template-columns:1fr}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="header">
|
||||
<div class="header-inner">
|
||||
<div class="kicker"><span class="dot"></span>公开资料专题库 · v2 综合重构版</div>
|
||||
<h1>台湾后备力量与全社会防卫韧性专题库</h1>
|
||||
<div class="subtitle">本版根据最新栏目思路重新生成:不新增栏目12,而是将“军种官科、装备类别、晋任制度、教召权益、退辅福利、制度短板”全部补充进「军方后备体系」栏目,形成更完整的军方后备主体数据库。</div>
|
||||
<div class="boundary"><span>仅展示公开资料</span><span>不展示营区坐标、集结点、动员路线</span><span>不展示具体装备数量与仓储位置</span><span>不展示个人资料</span></div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="shell">
|
||||
<div class="panel">
|
||||
<div class="controls">
|
||||
<input id="globalSearch" class="input" placeholder="全局搜索:概念、组织、法规、教召、装备、福利、争议……" />
|
||||
<select id="circleFilter"><option value="">全部圈层</option></select>
|
||||
<select id="reliabilityFilter"><option value="">全部可信度</option></select>
|
||||
<select id="displayFilter"><option value="">全部展示等级</option></select>
|
||||
<button id="resetBtn" class="btn secondary">重置</button>
|
||||
</div>
|
||||
<div class="stats" id="stats"></div>
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
<div class="tab-head">
|
||||
<div class="tab-title"><h2 id="tabTitle"></h2><p id="tabSubtitle"></p></div>
|
||||
<div class="tab-actions"><button class="btn secondary" id="exportBtn">导出当前筛选 JSON</button><button class="btn" id="topBtn">回到顶部</button></div>
|
||||
</div>
|
||||
<div class="toolbar">
|
||||
<input id="localSearch" class="input" placeholder="当前栏目内搜索……" />
|
||||
<select id="typeFilter"><option value="">全部类型</option></select>
|
||||
<select id="agencyFilter"><option value="">全部机关/机构</option></select>
|
||||
<select id="yearFilter"><option value="">全部年份</option></select>
|
||||
</div>
|
||||
<div class="subfilters" id="subfilters"></div>
|
||||
<main class="content" id="content"></main>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-mask" id="modalMask">
|
||||
<div class="modal">
|
||||
<div class="modal-head"><div><h2 id="modalTitle"></h2><div class="meta-row" id="modalBadges"></div></div><button class="close" id="closeModal">×</button></div>
|
||||
<div class="modal-body" id="modalBody"></div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const DATA = {"meta": {"title": "台湾后备力量与全社会防卫韧性专题库", "version": "v2.0-integrated", "language": "zh-CN", "lastUpdated": "2026-06-24", "description": "围绕台湾后备军人、后备部队、教召制度、全民防卫动员、民防体系、社会韧性、地方执行、研究成果、舆情争议、装备类别、军种官科、晋任制度与退辅福利建立的公开资料专题库。", "displayBoundary": ["仅展示公开资料、制度信息、政策分析、社会影响与来源审查。", "不展示具体营区坐标、集结地点、动员路线、个人名单、具体战术部署、关键设施脆弱点。", "社交平台资料仅作为舆情样本,不代表整体民意。"]}, "tabs": [{"id": "conceptDefinitions", "name": "概念界定", "subtitle": "官方定义、研究边界与三圈模型", "viewType": "cards", "filters": ["概念层级", "对应圈层", "是否官方定义", "可信度"]}, {"id": "militaryReserveSystem", "name": "军方后备体系", "subtitle": "组织体系、后备人员、军种官科、装备类别、晋任制度、权益福利、退辅制度与制度短板", "viewType": "military-integrated", "filters": ["二级分类", "对象类型", "层级", "可信度", "展示等级"], "searchFields": ["名称", "类别", "摘要", "标签", "对象类型", "二级分类", "军种", "官科兵科", "公开数据", "制度短板", "社会争议"]}, {"id": "trainingAndMobilization", "name": "教召训练", "subtitle": "教召制度、14天新制、训练流程、权益与争议", "viewType": "timeline-cards", "filters": ["制度类型", "适用对象", "年份", "争议等级", "可信度"]}, {"id": "policyEvolution", "name": "政策沿革", "subtitle": "后备改革时间线、改革逻辑与政策关键词", "viewType": "timeline", "filters": ["年份", "政策类型", "政策主体", "核心关键词", "可信度"]}, {"id": "legalFramework", "name": "法规图谱", "subtitle": "兵役、后备管理、召集、动员、民防、灾防法规", "viewType": "law-table", "filters": ["法规类型", "主管机关", "对应圈层", "涉及地方政府", "可信度"]}, {"id": "civilDefensePublicSafety", "name": "民防公共安全", "subtitle": "民防、警消、替代役、医疗、工程与公用事业支援", "viewType": "matrix-cards", "filters": ["对象类型", "主管机关", "功能类型", "对应圈层", "可信度"]}, {"id": "societalResilienceNetwork", "name": "社会韧性网络", "subtitle": "民间组织、社区、学校、企业、宗教慈善、媒体与资安网络", "viewType": "network-cards", "filters": ["组织类型", "是否官方组织", "政治标签", "可信度"]}, {"id": "localImplementation", "name": "地方执行", "subtitle": "县市差异、地方动员、民防、灾防与城镇韧性演习", "viewType": "region-cards", "filters": ["区域类型", "县市", "演习年份", "主要议题", "可信度"]}, {"id": "researchExpertViews", "name": "研究成果", "subtitle": "官方报告、智库研究、学术论文、媒体深度报道与国际比较", "viewType": "research-list", "filters": ["资料类型", "机构", "年份", "主题", "可信度"]}, {"id": "publicOpinionControversies", "name": "舆情争议", "subtitle": "教召、女性后备、民防政治化、企业成本、社交平台反应", "viewType": "issue-cards", "filters": ["议题类型", "平台", "情绪标签", "影响人群", "可信度"]}, {"id": "sourceAudit", "name": "来源审查", "subtitle": "来源分级、可信度、交叉验证与展示限制", "viewType": "source-table", "filters": ["来源类型", "可信度评级", "是否原始来源", "是否交叉验证", "可公开展示等级"]}], "sharedDictionaries": {"circles": ["第一圈:军方后备力量", "第二圈:守备民防与公共安全支援", "第三圈:社会韧性网络", "跨圈"], "reliabilityLevels": ["高", "中高", "中", "中低", "低"], "sourceRatings": ["A1", "A2", "B1", "B2", "C1", "C2", "D"], "displayLevels": ["可公开", "摘要展示", "不展示细节"], "controversyTypes": ["制度公平", "民生成本", "训练成效", "政治标签", "社会军事化", "女性后备", "企业负担", "地方执行", "假讯息"], "militarySubcategories": ["全部", "组织体系", "后备人员", "军种官科", "装备类别", "晋任制度", "权益福利", "退辅制度", "制度短板"]}, "conceptDefinitions": [{"ID": "concept_001", "名称": "后备军人", "类别": "官方概念", "摘要": "依法转入后备役并接受后备管理的人员,是后备力量专题的狭义核心。", "标签": ["兵役", "后备役", "后备管理"], "对应圈层": "第一圈:军方后备力量", "可信度": "高", "展示等级": "可公开", "资料来源": [{"标题": "《兵役法》", "类型": "法规", "URL": "https://law.moj.gov.tw/LawClass/LawAll.aspx?PCode=F0040001", "可信度": "A1"}, {"标题": "《后备军人管理规则》", "类型": "法规", "URL": "httpLine truncated
|
||||
const TAB_MAP = {
|
||||
conceptDefinitions:'conceptDefinitions', militaryReserveSystem:'militaryReserveSystem', trainingAndMobilization:'trainingAndMobilization',
|
||||
policyEvolution:'policyEvolution', legalFramework:'legalFramework', civilDefensePublicSafety:'civilDefensePublicSafety', societalResilienceNetwork:'societalResilienceNetwork',
|
||||
localImplementation:'localImplementation', researchExpertViews:'researchExpertViews', publicOpinionControversies:'publicOpinionControversies', sourceAudit:'sourceAudit'
|
||||
};
|
||||
const state = { tab:'conceptDefinitions', global:'', local:'', circle:'', reliability:'', display:'', type:'', agency:'', year:'', sub:'全部' };
|
||||
const militarySubs = ['全部','组织体系','后备人员','军种官科','装备类别','晋任制度','权益福利','退辅制度','制度短板'];
|
||||
function $(id){return document.getElementById(id)}
|
||||
function arr(v){ if(!v) return []; if(Array.isArray(v)) return v; if(typeof v==='object') return Object.values(v).flatMap(arr); return [String(v)]; }
|
||||
function txt(v){ return arr(v).join(' '); }
|
||||
function titleOf(item){ return item['名称']||item['标题']||item['法规名称']||item['组织名称']||item['县市']||item['议题名称']||item['资料标题']||item['sourceTitle']||item.name||item.title||'未命名条目'; }
|
||||
function summaryOf(item){ return item['摘要']||item['定义或说明']||item['核心目的']||item['触发原因']||item['核心观点']?.[0]||item['description']||item['研究价值']||item['制度短板']?.[0]||'点击查看详情。'; }
|
||||
function categoryOf(item){ return item['二级分类']||item['对象类型']||item['类别']||item['资料类型']||item['事件类型']||item['组织类型']||item['法规类型']||item['区域类型']||''; }
|
||||
function circleOf(item){ return item['对应圈层']||item['相关圈层']||item['relatedCircle']||item['circle']||''; }
|
||||
function reliabilityOf(item){ return item['可信度']||item['可信度评级']||item['credibilityRating']||item['reliability']||''; }
|
||||
function displayOf(item){ return item['展示等级']||item['可公开展示等级']||item['displayLevel']||''; }
|
||||
function yearOf(item){ const s=txt([item['发布时间'],item['发表时间'],item['时间'],item['年份'],item['事件时间'],item['更新时间'],item['publishYear'],item['year']]); const m=s.match(/20\d{2}|19\d{2}|11[0-9]年|民国\d+年/); return m?m[0]:''; }
|
||||
function agencyOf(item){ return txt(item['主管机关']||item['competentAgency']||item['主管或关联机关']||item['机构']||item['institution']||item['执行机关']||item['权责机关']).split(' / ')[0]; }
|
||||
function itemText(item){ return JSON.stringify(item).toLowerCase(); }
|
||||
function isMilitaryOrg(item){ const t=item['对象类型']||item['类别']||''; return ['中央主管机关','动员整合机关','业务处室','后备监督机关','地区管理机关','地方执行机关','后备部队','训练支撑单位','服务协力组织'].some(x=>t.includes(x)); }
|
||||
function militarySubOf(item){ if(item['二级分类']) return item['二级分类']; if(isMilitaryOrg(item)) return '组织体系'; return '组织体系'; }
|
||||
function tabConfig(){ return DATA.tabs.find(t=>t.id===state.tab)||DATA.tabs[0]; }
|
||||
function currentData(){ return DATA[TAB_MAP[state.tab]]||[]; }
|
||||
function initSelects(){
|
||||
const circles = new Set(), rels = new Set(), displays = new Set();
|
||||
Object.keys(TAB_MAP).forEach(k=> (DATA[TAB_MAP[k]]||[]).forEach(item=>{ if(circleOf(item)) circles.add(circleOf(item)); if(reliabilityOf(item)) rels.add(reliabilityOf(item)); if(displayOf(item)) displays.add(displayOf(item)); }));
|
||||
fillSelect('circleFilter', circles); fillSelect('reliabilityFilter', rels); fillSelect('displayFilter', displays);
|
||||
}
|
||||
function fillSelect(id, values){ const el=$(id); const first=el.options[0].outerHTML; el.innerHTML=first; [...values].filter(Boolean).sort().forEach(v=>{ const o=document.createElement('option'); o.value=v; o.textContent=v; el.appendChild(o); }); }
|
||||
function renderStats(){
|
||||
const total = Object.keys(TAB_MAP).reduce((s,k)=>s+(DATA[TAB_MAP[k]]||[]).length,0);
|
||||
const mil = (DATA.militaryReserveSystem||[]).length;
|
||||
const laws = (DATA.legalFramework||[]).length;
|
||||
const local = (DATA.localImplementation||[]).length;
|
||||
const issues = (DATA.publicOpinionControversies||[]).length;
|
||||
const sources = (DATA.sourceAudit||[]).length;
|
||||
$('stats').innerHTML = [ ['总条目',total], ['军方后备体系',mil], ['法规资料',laws], ['县市数据',local], ['争议议题',issues], ['来源审查',sources] ].map(x=>`<div class="stat"><b>${x[1]}</b><span>${x[0]}</span></div>`).join('');
|
||||
}
|
||||
function renderTabs(){
|
||||
$('tabs').innerHTML = DATA.tabs.map(t=>`<button class="tab ${t.id===state.tab?'active':''}" data-tab="${t.id}">${t.name}<small>${(DATA[TAB_MAP[t.id]]||[]).length}条</small></button>`).join('');
|
||||
document.querySelectorAll('.tab').forEach(b=>b.onclick=()=>{state.tab=b.dataset.tab; state.local=''; state.type=''; state.agency=''; state.year=''; state.sub='全部'; $('localSearch').value=''; render();})
|
||||
}
|
||||
function refreshDynamicFilters(data){
|
||||
const types=new Set(), agencies=new Set(), years=new Set();
|
||||
data.forEach(item=>{ const c=categoryOf(item); if(c) types.add(Array.isArray(c)?c.join('、'):c); const a=agencyOf(item); if(a) agencies.add(a); const y=yearOf(item); if(y) years.add(y); });
|
||||
fillSelect('typeFilter', types); fillSelect('agencyFilter', agencies); fillSelect('yearFilter', years);
|
||||
$('typeFilter').value=state.type; $('agencyFilter').value=state.agency; $('yearFilter').value=state.year;
|
||||
}
|
||||
function filteredData(){
|
||||
const g=state.global.trim().toLowerCase(), l=state.local.trim().toLowerCase();
|
||||
return currentData().filter(item=>{
|
||||
const hay=itemText(item);
|
||||
if(g && !hay.includes(g)) return false;
|
||||
if(l && !hay.includes(l)) return false;
|
||||
if(state.circle && !txt(circleOf(item)).includes(state.circle)) return false;
|
||||
if(state.reliability && reliabilityOf(item)!==state.reliability) return false;
|
||||
if(state.display && displayOf(item)!==state.display) return false;
|
||||
if(state.type && !txt(categoryOf(item)).includes(state.type)) return false;
|
||||
if(state.agency && !txt(agencyOf(item)).includes(state.agency)) return false;
|
||||
if(state.year && yearOf(item)!==state.year) return false;
|
||||
if(state.tab==='militaryReserveSystem' && state.sub && state.sub!=='全部' && militarySubOf(item)!==state.sub) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
function renderSubfilters(){
|
||||
const box=$('subfilters');
|
||||
if(state.tab==='militaryReserveSystem'){
|
||||
const all=DATA.militaryReserveSystem||[];
|
||||
box.innerHTML=militarySubs.map(s=>{ const count=s==='全部'?all.length:all.filter(i=>militarySubOf(i)===s).length; return `<button class="chip ${state.sub===s?'active':''}" data-sub="${s}">${s} · ${count}</button>`; }).join('');
|
||||
box.querySelectorAll('.chip').forEach(ch=>ch.onclick=()=>{state.sub=ch.dataset.sub; renderContent(); renderSubfilters();});
|
||||
} else { box.innerHTML='<span class="badge red">当前栏目支持全局搜索、栏目搜索、类型/机关/年份筛选,点击卡片可打开详情。</span>'; }
|
||||
}
|
||||
function renderFlow(){
|
||||
if(state.tab!=='militaryReserveSystem') return '';
|
||||
const nodes=[['谁在管','国防部、全动署、后备指挥部、地区/县市后备系统'],['管哪些人','后备军官、后备士官、后备士兵、教召人员'],['用什么支撑','军种官科、公开装备类别、晋任制度、权益福利'],['看哪些风险','装备整备、干部储备、专长相符、企业家庭成本']];
|
||||
return `<div class="flow">${nodes.map(n=>`<div class="flow-node"><b>${n[0]}</b><span>${n[1]}</span></div>`).join('')}</div>`;
|
||||
}
|
||||
function renderContent(){
|
||||
const data=filteredData();
|
||||
$('content').innerHTML = renderFlow() + (data.length? renderByView(data): `<div class="empty">没有找到匹配条目。请调整搜索词或筛选条件。</div>`);
|
||||
}
|
||||
function renderByView(data){
|
||||
const cfg=tabConfig();
|
||||
if(['law-table','source-table'].includes(cfg.viewType)) return renderTable(data);
|
||||
if(cfg.viewType==='timeline') return renderTimeline(data);
|
||||
return `<div class="cards">${data.map(renderCard).join('')}</div>`;
|
||||
}
|
||||
function renderCard(item, idx){
|
||||
const id = encodeURIComponent(item.ID||item.id||titleOf(item));
|
||||
const tags=arr(item['标签']||item.tags).slice(0,5);
|
||||
const rel=reliabilityOf(item), disp=displayOf(item), cat=categoryOf(item), cir=circleOf(item);
|
||||
const minis=[];
|
||||
const fields=['主要功能','公开数据','训练模块','法律依据','制度短板','社会争议','研究问题','涉及权益'];
|
||||
fields.forEach(f=>{ if(item[f]) minis.push(`<div class="section-mini"><b>${f}</b><ul>${arr(item[f]).slice(0,3).map(v=>`<li>${escapeHTML(v)}</li>`).join('')}</ul></div>`); });
|
||||
return `<article class="card">
|
||||
<div><h3>${escapeHTML(titleOf(item))}</h3><div class="meta-row">${cat?`<span class="badge red">${escapeHTML(cat)}</span>`:''}${cir?`<span class="badge blue">${escapeHTML(cir)}</span>`:''}${rel?`<span class="badge green">可信度:${escapeHTML(rel)}</span>`:''}</div></div>
|
||||
<div class="meta-row">${tags.map(t=>`<span class="badge">${escapeHTML(t)}</span>`).join('')}</div>
|
||||
<div class="summary">${escapeHTML(txt(summaryOf(item)))}</div>
|
||||
${minis.slice(0,2).join('')}
|
||||
<div class="card-footer"><span class="warning">${disp?escapeHTML(disp):'可公开'}</span><button class="link-btn" onclick="openModalByKey('${id}')">查看详情 →</button></div>
|
||||
</article>`;
|
||||
}
|
||||
function renderTable(data){
|
||||
const rows=data.map(item=>`<tr onclick="openModalByKey('${encodeURIComponent(item.ID||item.id||titleOf(item))}')"><td><b>${escapeHTML(titleOf(item))}</b></td><td>${escapeHTML(categoryOf(item))}</td><td>${escapeHTML(agencyOf(item))}</td><td>${escapeHTML(reliabilityOf(item))}</td><td>${escapeHTML(txt(summaryOf(item)).slice(0,160))}</td></tr>`).join('');
|
||||
return `<div class="table-wrap"><table><thead><tr><th>名称</th><th>类型</th><th>机关/机构</th><th>可信度</th><th>摘要</th></tr></thead><tbody>${rows}</tbody></table></div>`;
|
||||
}
|
||||
function renderTimeline(data){
|
||||
return `<div class="timeline">${data.map(item=>`<div class="titem"><div class="meta-row"><span class="badge red">${escapeHTML(yearOf(item)||'时间未标注')}</span><span class="badge">${escapeHTML(categoryOf(item))}</span></div><h3>${escapeHTML(titleOf(item))}</h3><p class="summary">${escapeHTML(txt(summaryOf(item)))}</p><button class="link-btn" onclick="openModalByKey('${encodeURIComponent(item.ID||item.id||titleOf(item))}')">查看详情 →</button></div>`).join('')}</div>`;
|
||||
}
|
||||
function openModalByKey(key){
|
||||
const decoded=decodeURIComponent(key);
|
||||
let found=null;
|
||||
Object.keys(TAB_MAP).some(k=> (DATA[TAB_MAP[k]]||[]).some(item=>{ const itemKey=item.ID||item.id||titleOf(item); if(itemKey===decoded){found=item; return true} return false; }));
|
||||
if(found) openModal(found);
|
||||
}
|
||||
function openModal(item){
|
||||
$('modalTitle').textContent=titleOf(item);
|
||||
const badges=[categoryOf(item), circleOf(item), reliabilityOf(item)?'可信度:'+reliabilityOf(item):'', displayOf(item)].filter(Boolean);
|
||||
$('modalBadges').innerHTML=badges.map((b,i)=>`<span class="badge ${i===0?'red':i===1?'blue':'green'}">${escapeHTML(b)}</span>`).join('');
|
||||
$('modalBody').innerHTML=renderDetail(item);
|
||||
$('modalMask').style.display='flex';
|
||||
}
|
||||
function renderDetail(item){
|
||||
const priority=['摘要','定义或说明','官方定义','核心目的','触发原因','主管机关','上级单位','下级单位','层级','对象类型','二级分类','适用对象','军种','官科兵科','专业方向','装备类别','取得方式','训练关联','主要功能','公开数据','法律依据','关联制度','评选条件','作业流程','权责机关','涉及权益','福利边界','社会争议','制度短板','治理风险','研究问题','展示限制'];
|
||||
const blocks=[];
|
||||
priority.forEach(k=>{ if(item[k]) blocks.push(detailBlock(k,item[k])); });
|
||||
const rest=Object.keys(item).filter(k=>!priority.includes(k)&&!['ID','id','名称','标题','标签','资料来源','publicSources','更新时间','可信度','展示等级','对应圈层','类别'].includes(k)&&item[k]);
|
||||
rest.slice(0,8).forEach(k=>blocks.push(detailBlock(k,item[k])));
|
||||
const sources=item['资料来源']||item.publicSources||item['来源']||[];
|
||||
if(sources.length) blocks.push(sourceBlock(sources));
|
||||
blocks.push(`<div class="notice"><b>展示边界:</b>本页面仅展示公开制度、公开类别和政策研究信息;涉及具体营区、集结点、动员路线、个人资料、具体装备数量、仓储位置、单位配属和可操作性脆弱信息的内容不予展示。</div>`);
|
||||
return `<div class="detail-grid">${blocks.join('')}</div>`;
|
||||
}
|
||||
function detailBlock(k,v){
|
||||
let content='';
|
||||
if(Array.isArray(v)) content=`<ul>${v.map(x=>`<li>${escapeHTML(txt(x))}</li>`).join('')}</ul>`;
|
||||
else if(typeof v==='object') content=objectToHTML(v);
|
||||
else content=`<p>${escapeHTML(String(v))}</p>`;
|
||||
return `<section class="detail-block"><h4>${escapeHTML(k)}</h4>${content}</section>`;
|
||||
}
|
||||
function objectToHTML(obj){
|
||||
return `<ul>${Object.entries(obj).map(([k,v])=>`<li><b>${escapeHTML(k)}:</b>${Array.isArray(v)?v.map(x=>escapeHTML(txt(x))).join('、'):escapeHTML(txt(v))}</li>`).join('')}</ul>`;
|
||||
}
|
||||
function sourceBlock(sources){
|
||||
const html=sources.map(s=>{ if(typeof s==='string') return `<div class="source-item">${escapeHTML(s)}</div>`; const url=s.URL||s.url||''; const name=s.标题||s.title||s.sourceTitle||s.来源名称||'来源'; return `<div class="source-item"><b>${escapeHTML(name)}</b> <span class="badge">${escapeHTML(s.类型||s.type||'')}</span> <span class="badge green">${escapeHTML(s.可信度||s.rating||'')}</span>${url?`<br><a href="${escapeAttr(url)}" target="_blank" rel="noopener">打开来源</a>`:''}</div>`; }).join('');
|
||||
return `<section class="detail-block source-list" style="grid-column:1/-1"><h4>资料来源</h4>${html}</section>`;
|
||||
}
|
||||
function escapeHTML(s){ return String(s??'').replace(/[&<>"]/g, c=>({'&':'&','<':'<','>':'>','"':'"'}[c])); }
|
||||
function escapeAttr(s){ return escapeHTML(s).replace(/'/g,'''); }
|
||||
function render(){
|
||||
renderTabs();
|
||||
const cfg=tabConfig(); $('tabTitle').textContent=cfg.name; $('tabSubtitle').textContent=cfg.subtitle||'';
|
||||
refreshDynamicFilters(currentData()); renderSubfilters(); renderContent();
|
||||
}
|
||||
['globalSearch','localSearch'].forEach(id=>$(id).addEventListener('input',e=>{ if(id==='globalSearch') state.global=e.target.value; else state.local=e.target.value; renderContent(); }));
|
||||
$('circleFilter').onchange=e=>{state.circle=e.target.value; renderContent();};
|
||||
$('reliabilityFilter').onchange=e=>{state.reliability=e.target.value; renderContent();};
|
||||
$('displayFilter').onchange=e=>{state.display=e.target.value; renderContent();};
|
||||
$('typeFilter').onchange=e=>{state.type=e.target.value; renderContent();};
|
||||
$('agencyFilter').onchange=e=>{state.agency=e.target.value; renderContent();};
|
||||
$('yearFilter').onchange=e=>{state.year=e.target.value; renderContent();};
|
||||
$('resetBtn').onclick=()=>{Object.assign(state,{global:'',local:'',circle:'',reliability:'',display:'',type:'',agency:'',year:'',sub:'全部'}); ['globalSearch','localSearch','circleFilter','reliabilityFilter','displayFilter','typeFilter','agencyFilter','yearFilter'].forEach(id=>$(id).value=''); render();};
|
||||
$('closeModal').onclick=()=>$('modalMask').style.display='none';
|
||||
$('modalMask').onclick=e=>{ if(e.target.id==='modalMask') $('modalMask').style.display='none'; };
|
||||
$('topBtn').onclick=()=>window.scrollTo({top:0,behavior:'smooth'});
|
||||
$('exportBtn').onclick=()=>{ const blob=new Blob([JSON.stringify(filteredData(),null,2)],{type:'application/json'}); const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download=`${state.tab}_filtered.json`; a.click(); URL.revokeObjectURL(a.href); };
|
||||
initSelects(); renderStats(); render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>台湾民防与全社会防卫韧性知识展示平台 v3 横向Tab版</title>
|
||||
<style>
|
||||
:root{
|
||||
--red-950:#4f0b16;--red-900:#68111f;--red-800:#7f1829;--red-700:#a11f35;--red-600:#bb3148;--red-100:#fff0f2;--red-50:#fff7f8;
|
||||
--ink:#1f2937;--muted:#667085;--line:#e5e7eb;--soft:#f7f8fb;--card:#fff;--green:#166534;--orange:#9a3412;--blue:#1d4ed8;
|
||||
--shadow:0 18px 45px rgba(38, 23, 31, .18);--radius:22px;
|
||||
}
|
||||
*{box-sizing:border-box} html{scroll-behavior:smooth}
|
||||
body{margin:0;font-family:"Microsoft YaHei","PingFang SC","Noto Sans CJK SC",Arial,sans-serif;background:radial-gradient(circle at 10% 0%, #d66275 0, transparent 30%),linear-gradient(135deg,var(--red-950),var(--red-700));color:var(--ink);min-height:100vh;}
|
||||
.page{max-width:1500px;margin:0 auto;padding:26px 22px 48px}.hero{color:#fff;border-radius:30px;border:1px solid rgba(255,255,255,.24);background:linear-gradient(135deg,rgba(255,255,255,.15),rgba(255,255,255,.06));box-shadow:var(--shadow);padding:24px 26px}.hero-top{display:flex;justify-content:space-between;gap:20px;align-items:flex-start}.hero h1{margin:0 0 10px;font-size:31px;letter-spacing:.4px}.hero p{margin:0;line-height:1.72;color:rgba(255,255,255,.92);max-width:1000px}.badge-line{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}.badge{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;border-radius:999px;font-size:12px;font-weight:700;background:rgba(255,255,255,.16);border:1px solid rgba(255,255,255,.22);color:#fff}.safe{margin-top:14px;padding:12px 14px;border-radius:16px;background:rgba(255,255,255,.13);font-size:13px;line-height:1.65;color:#fff}.layout{margin-top:18px;display:grid;grid-template-columns:1fr;gap:18px}.sidebar{position:relative;top:0;align-self:stretch;background:#fff;border:1px solid rgba(255,255,255,.35);border-radius:var(--radius);box-shadow:var(--shadow);padding:14px 16px}.nav-title{font-size:13px;color:var(--muted);font-weight:900;margin:2px 4px 10px;letter-spacing:.08em}#tabs{display:flex;flex-wrap:wrap;gap:10px;align-items:center}
|
||||
.tab{width:auto;min-width:138px;border:1px solid #f0d7dc;background:#fff;color:var(--ink);border-radius:999px;padding:11px 14px;margin:0;cursor:pointer;text-align:center;font-weight:900;display:flex;align-items:center;justify-content:center;gap:8px;white-space:nowrap;box-shadow:0 4px 12px rgba(15,23,42,.035)}.tab:hover{background:var(--red-50);border-color:#ffd8df;transform:translateY(-1px)}.tab.active{background:var(--red-700);color:#fff;border-color:var(--red-700);box-shadow:0 8px 18px rgba(161,31,53,.22)}.tab-count{font-size:11px;border-radius:999px;padding:2px 8px;background:#f3f4f6;color:#374151}.tab.active .tab-count{background:rgba(255,255,255,.2);color:#fff}.main{min-width:0}.panel{background:#fff;border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;border:1px solid rgba(255,255,255,.45)}.toolbar{display:grid;grid-template-columns:minmax(250px,1fr) 180px 180px 160px 140px;gap:11px;padding:16px;border-bottom:1px solid var(--line);background:#fff}.input,.select,.viewbtn{width:100%;border:1px solid var(--line);border-radius:14px;padding:11px 12px;font-size:14px;outline:none;background:#fff}.viewbtn{font-weight:800;cursor:pointer;color:var(--red-700)}.input:focus,.select:focus{border-color:var(--red-600);box-shadow:0 0 0 3px rgba(187,49,72,.12)}.content{padding:20px;background:#f7f8fa;min-height:670px}.section-title{display:flex;justify-content:space-between;align-items:flex-start;gap:20px;margin-bottom:16px}.section-title h2{margin:0 0 8px;font-size:23px;color:#111827}.section-title .desc{max-width:760px;text-align:right;color:var(--muted);font-size:13px;line-height:1.65}.count{font-size:13px;color:var(--muted)}.metrics{display:grid;grid-template-columns:repeat(6,1fr);gap:13px;margin-bottom:16px}.metric{background:#fff;border:1px solid var(--line);border-radius:18px;padding:16px;box-shadow:0 8px 20px rgba(15,23,42,.04)}.metric .label{font-size:13px;color:var(--muted);margin-bottom:8px}.metric .value{font-size:31px;font-weight:900;color:var(--red-700)}.metric .sub{font-size:12px;color:#697386;line-height:1.48;margin-top:8px}.grid-2{display:grid;grid-template-columns:1fr 1fr;gap:14px}.box{background:#fff;border:1px solid var(--line);border-radius:18px;padding:16px}.box h3{margin:0 0 12px;font-size:16px}.bar-row{display:grid;grid-template-columns:175px 1fr 44px;gap:9px;align-items:center;margin:9px 0;font-size:13px}.bar{height:10px;border-radius:999px;background:#f1f5f9;overflow:hidden}.bar span{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,var(--red-700),#e96f82)}.cards{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.card{position:relative;background:#fff;border:1px solid var(--line);border-radius:20px;padding:16px;cursor:pointer;transition:.18s;min-height:230px;display:flex;flex-direction:column;overflow:hidden}.card:before{content:"";position:absolute;left:0;top:0;bottom:0;width:5px;background:var(--red-700);opacity:.88}.card:hover{transform:translateY(-2px);box-shadow:0 14px 30px rgba(15,23,42,.11);border-color:#e8b7c0}.card h3{margin:0 0 8px;padding-left:2px;font-size:17px;line-height:1.35;color:#111827}.card .subtitle{font-size:13px;color:#4b5563;line-height:1.55;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}.mini-fields{margin:12px 0 8px;border-top:1px dashed #edf0f3;padding-top:10px}.mini{display:grid;grid-template-columns:72px 1fr;gap:8px;font-size:12.5px;line-height:1.45;margin:5px 0}.mini .mk{color:#7a8291;font-weight:800}.mini .mv{color:#374151;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:auto;padding-top:12px}.chip{font-size:12px;border:1px solid #ead1d6;background:var(--red-50);color:var(--red-800);border-radius:999px;padding:4px 8px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.chip.gray{border-color:#e5e7eb;background:#f9fafb;color:#4b5563}.chip.high{border-color:#fecaca;background:#fef2f2;color:#991b1b}.chip.mid{border-color:#fed7aa;background:#fff7ed;color:#9a3412}.chip.ok{border-color:#bbf7d0;background:#f0fdf4;color:#166534}.table-wrap{overflow:auto;border-radius:18px;border:1px solid var(--line);background:#fff}table{width:100%;border-collapse:collapse;min-width:880px}th,td{padding:12px;border-bottom:1px solid var(--line);font-size:13px;text-align:left;vertical-align:top}th{background:#fbfbfc;color:#374151;font-weight:900;position:sticky;top:0}tr:last-child td{border-bottom:0}tr:hover td{background:#fff8f9}.empty{padding:44px;text-align:center;color:var(--muted);background:#fff;border:1px dashed #d1d5db;border-radius:18px}.modal-backdrop{position:fixed;inset:0;background:rgba(15,23,42,.60);display:none;align-items:center;justify-content:center;padding:24px;z-index:60}.modal-backdrop.show{display:flex}.modal{width:min(1160px,96vw);max-height:91vh;overflow:auto;background:#fff;border-radius:24px;box-shadow:0 30px 80px rgba(0,0,0,.36)}.modal-header{position:sticky;top:0Line truncated
|
||||
@media(max-width:1180px){.toolbar{grid-template-columns:1fr 1fr}.metrics{grid-template-columns:repeat(3,1fr)}.cards{grid-template-columns:repeat(2,1fr)}}
|
||||
@media(max-width:760px){.page{padding:14px}.hero-top{display:block}.hero h1{font-size:23px}.toolbar{grid-template-columns:1fr}.metrics{grid-template-columns:1fr}.cards{grid-template-columns:1fr}.grid-2,.kv-grid,.mini-card-grid,.columns{grid-template-columns:1fr}.section-title{display:block}.section-title .desc{text-align:left;margin-top:8px}.bar-row{grid-template-columns:1fr}.bar-row .bar{height:10px}.modal-backdrop{padding:10px}.modal-header{padding:15px}.modal-body{padding:14px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<header class="hero">
|
||||
<div class="hero-top">
|
||||
<div>
|
||||
<h1 id="appTitle">台湾民防与全社会防卫韧性知识展示平台</h1>
|
||||
<p id="appDesc"></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="badge-line" id="heroBadges"></div>
|
||||
<div class="safe" id="safeNotice"></div>
|
||||
</header>
|
||||
|
||||
<div class="layout">
|
||||
<aside class="sidebar">
|
||||
<div class="nav-title">横向栏目导航</div>
|
||||
<nav id="tabs"></nav>
|
||||
<div class="view-note">提示:点击任意卡片可进入结构化详情页,查看中文字段、标签、时间线、观点对照、风险边界和来源列表。</div>
|
||||
</aside>
|
||||
|
||||
<main class="main panel">
|
||||
<div class="toolbar">
|
||||
<input id="searchInput" class="input" type="search" placeholder="输入关键词:组织、政策、争议、风险、来源……" />
|
||||
<select id="categoryFilter" class="select"><option value="">全部分类</option></select>
|
||||
<select id="levelFilter" class="select"><option value="">全部等级/层级</option></select>
|
||||
<select id="evidenceFilter" class="select"><option value="">全部证据强度</option></select>
|
||||
<button id="viewToggle" class="viewbtn" type="button">卡片视图</button>
|
||||
</div>
|
||||
<section class="content" id="content"></section>
|
||||
</main>
|
||||
</div>
|
||||
<div class="footer-note">安全边界:仅展示公开资料研究、政策法源、组织画像、舆情争议和风险评估;不展示训练动作、敏感设施点位、私人信息、攻击破坏方法、定向影响或骚扰策略。</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-backdrop" id="modalBackdrop">
|
||||
<article class="modal">
|
||||
<div class="modal-header">
|
||||
<div>
|
||||
<h2 id="modalTitle"></h2>
|
||||
<p id="modalSub"></p>
|
||||
<div class="chips" id="modalChips"></div>
|
||||
</div>
|
||||
<button class="close" id="modalClose" aria-label="关闭">×</button>
|
||||
</div>
|
||||
<div class="modal-body" id="modalBody"></div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<script id="PAGE_DATA" type="application/json">{"meta": {"title": "台湾民防与全社会防卫韧性知识展示平台", "version": "v2.0-rich-display", "generated_at": "2026-06-24", "language": "zh-CN", "description": "增强版页面展示 JSON:中文字段名、分区详情弹框、标签化摘要、时间线、观点对照、传播链和风险卡片。", "safe_display_notice": "本页面用于公开资料研究、政策展示与风险评估,不展示训练操作、敏感设施、个人隐私、定向影响或可用于攻击破坏的信息。", "data_boundary": ["仅展示公开资料研究、政策法源、组织画像、舆情争议和风险评估。", "不展示训练操作、敏感设施点位、个人隐私、攻击破坏方法、定向影响或骚扰策略。"]}, "overview": {"dataset_name": "taiwan_civil_defense_page_overview_metrics", "created_at": "2026-06-24", "last_verified_hint": "部分公共资料核验至2026-06-24;页面上线前应再次核验官方来源。", "core_metrics": {"organization_system_records": 35, "civil_group_profiles": 14, "policy_cases": 12, "controversy_cases": 16, "risk_assessment_items": 18, "source_catalog_items": 16}, "category_distribution": {"organizations_by_category": {"关键基础设施防护编组": 9, "民间训练组织": 8, "地方政府动员体系": 7, "法定民防团队": 6, "企业学校防护编组": 5}, "civil_groups_by_category": {"民防教育训练型": 1, "社会韧性与应急训练型": 1, "地方自训网络枢纽型": 1, "社区韧性与宗教网络型": 1, "去中心化地方自训型": 1, "地方自训组织案例": 1, "灾难医疗与救援型": 1, "人道救援与急救培训型": 1, "宗教慈善与灾害支援型": 1, "宗教社区网络型": 1, "资讯与国际传播韧性型": 1, "资讯韧性与民主研究型": 1, "资安与关键网络韧性型": 1, "全民国防教育型": 1}, "risks_by_level": {"高": 6, "中高": 10, "中": 2}, "policies_by_type": {"法律": 2, "施行细则": 1, "行政规则/办法": 1, "总统府任务编组/政策平台": 1, "演习机制": 1, "公众安全指引": 1, "教育/动员准备机制": 1, "教育法制": 1, "灾害治理法制": 1, "资安/关键系统治理": 1, "地方公众指引/手册体系": 1}}, "top_display_cards": [{"card_title": "组织体系", "value": 35, "subtitle": "法定民防、地方动员、关键设施、企业学校、民间训练五层结构"}, {"card_title": "政策法源", "value": 12, "subtitle": "法律、办法、委员会、演习、安全指引与地方手册"}, {"card_title": "民间组织", "value": 14, "subtitle": "教育训练、社会韧性、人道救援、资讯韧性等组织画像"}, {"card_title": "舆情争议", "value": 16, "subtitle": "学生服勤、军事化争议、资金争议、标签化、人道中立等"}, {"card_title": "风险评估", "value": 18, "subtitle": "国际人道法、隐私、社会心理、关键设施和治理风险"}, {"card_title": "资料来源", "value": 16, "subtitle": "官方法源、总统府资料、国防部资料、教育部澄清、国际人道法与媒体资料"}], "frontend_data_files": ["taiwan_civil_defense_overview_metrics_v1.json", "taiwan_civil_defense_policy_legal_cases_v1.json", "taiwan_civil_defense_organization_system_enriched_v1.json", "taiwan_civil_defense_risk_assessments_v1.json", "taiwan_civil_defense_controversy_propagation_v1.json", "taiwan_civil_groups_activity_funding_v1.json"], "recommended_home_sections": ["统计卡片", "五层组织体系图", "政策时间线", "高风险议题Top列表", "重点争议列表", "来源可信度说明"], "safe_display_notice": "本页面用于公开资料研究、政策展示与风险评估,不展示训练操作、敏感设施、个人隐私、定向影响或可用于攻击破坏的信息。"}, "global_query": {"enabled": true, "query_mode": "client_side_fuzzy_search", "supports": ["关键词搜索", "Tab 内筛选", "证据强度筛选", "风险/层级筛选", "详情弹框查看", "JSON 字段递归展示"]}, "tabs": [{"id": "overview", "label": "首页总览", "description": "展示核心统计、分类分布、重点卡片和安全边界说明。", "record_count": 1, "default_view": "dashboard", "records": [{"dataset_name": "taiwan_civil_defense_page_overview_metrics", "created_at": "2026-06-24", "last_verified_hint": "部分公共资料核验至2026-06-24;页面上线前应再次核验官方来源。", "core_metrics": {"organization_system_records": 35, "civil_group_profiles": 14, "policy_cases": 12, "controversy_cases": 16, "risk_assessment_items": 18, "source_catalog_items": 16}, "category_distribution": {"organizations_by_category": {"关键基础设施防护编组": 9, "民间训练组织": 8, "地方政府动员体系": 7, "法定民防团队": 6, "企业学校防护编组": 5}, "civil_groups_by_category": {"民防教育训练型": 1, "社会韧性与应急训练型": 1, "地方自训网络枢纽型": 1, "社区韧性与宗教网络型": 1, "Line truncated
|
||||
<script>
|
||||
const DATA = JSON.parse(document.getElementById('PAGE_DATA').textContent);
|
||||
const LABELS = DATA.field_labels || {};
|
||||
const LAYOUTS = DATA.detail_layouts || {};
|
||||
const state = {activeTab:'overview', query:'', category:'', level:'', evidence:'', view:'cards'};
|
||||
const $ = s => document.querySelector(s);
|
||||
const tabsEl=$('#tabs'), contentEl=$('#content'), searchInput=$('#searchInput'), categoryFilter=$('#categoryFilter'), levelFilter=$('#levelFilter'), evidenceFilter=$('#evidenceFilter'), viewToggle=$('#viewToggle');
|
||||
function esc(s){return String(s ?? '').replace(/[&<>\'\"]/g,c=>({'&':'&','<':'<','>':'>',"'":''','"':'"'}[c]));}
|
||||
function label(k){return LABELS[k] || humanize(k)}
|
||||
function humanize(k){return String(k).replace(/_/g,' ').replace(/\b\w/g,m=>m.toUpperCase())}
|
||||
function textify(x){if(x==null)return''; if(['string','number','boolean'].includes(typeof x))return String(x); if(Array.isArray(x))return x.map(textify).join(' '); if(typeof x==='object')return Object.values(x).map(textify).join(' '); return String(x)}
|
||||
function truncate(s,n=120){s=String(s||'');return s.length>n?s.slice(0,n)+'…':s}
|
||||
function activeTab(){return DATA.tabs.find(t=>t.id===state.activeTab)||DATA.tabs[0]}
|
||||
function recordsOf(t){return t.records||[]}
|
||||
function unique(arr){return [...new Set(arr.filter(Boolean).map(String))]}
|
||||
function chipClass(v){v=String(v||''); if(/高|重大|严重|high|高争议|易复燃/.test(v)) return 'high'; if(/中|mixed|medium|中高/.test(v)) return 'mid'; if(/低|low|confirmed/.test(v)) return 'ok'; return 'gray'}
|
||||
function renderChips(arr,limit=12){return (arr||[]).filter(Boolean).slice(0,limit).map(t=>`<span class="chip ${chipClass(t)}">${esc(t)}</span>`).join('')}
|
||||
function renderIdPills(arr){if(!arr)return '—'; if(!Array.isArray(arr))arr=[arr]; return `<div class="pill-list">${arr.map(x=>`<span class="id-pill">${esc(x)}</span>`).join('')}</div>`}
|
||||
|
||||
function init(){
|
||||
$('#appTitle').textContent=DATA.meta.title;
|
||||
$('#appDesc').textContent=DATA.meta.description;
|
||||
$('#safeNotice').textContent=DATA.meta.safe_display_notice || (DATA.meta.data_boundary||[]).join(' ');
|
||||
const metrics=(DATA.overview.top_display_cards||[]).slice(0,6);
|
||||
$('#heroBadges').innerHTML=metrics.map(m=>`<span class="badge">${esc(m.card_title)}:${esc(m.value)}</span>`).join('') + `<span class="badge">版本:${esc(DATA.meta.version)}</span>`;
|
||||
buildTabs(); updateFilters(); render();
|
||||
}
|
||||
function buildTabs(){
|
||||
tabsEl.innerHTML=DATA.tabs.map(t=>`<button class="tab ${t.id===state.activeTab?'active':''}" data-tab="${esc(t.id)}"><span>${esc(t.label)}</span><span class="tab-count">${esc(t.record_count ?? (t.records||[]).length)}</span></button>`).join('');
|
||||
tabsEl.querySelectorAll('.tab').forEach(btn=>btn.onclick=()=>{state.activeTab=btn.dataset.tab; state.category='';state.level='';state.evidence=''; buildTabs();updateFilters();render();});
|
||||
}
|
||||
function updateFilters(){
|
||||
const tab=activeTab(), recs=recordsOf(tab);
|
||||
const getVals=id=>tab.filters?.find(f=>f.id===id)?.values || unique(recs.map(r=>r[id]));
|
||||
fillSelect(categoryFilter,'全部分类',getVals('category'),state.category);
|
||||
fillSelect(levelFilter,'全部等级/层级',getVals('level'),state.level);
|
||||
fillSelect(evidenceFilter,'全部证据强度',getVals('evidence'),state.evidence);
|
||||
const ov=tab.id==='overview'; [categoryFilter,levelFilter,evidenceFilter].forEach(el=>el.disabled=ov); viewToggle.disabled=ov;
|
||||
}
|
||||
function fillSelect(el,first,vals,val){el.innerHTML=`<option value="">${first}</option>`+vals.map(v=>`<option value="${esc(v)}">${esc(v)}</option>`).join(''); el.value=val||'';}
|
||||
function filteredRecords(){
|
||||
const tab=activeTab(); if(tab.id==='overview')return recordsOf(tab);
|
||||
const q=state.query.trim().toLowerCase();
|
||||
return recordsOf(tab).filter(r=>(!q||textify(r).toLowerCase().includes(q))&&(!state.category||String(r.category||'')===state.category)&&(!state.level||String(r.level||'')===state.level)&&(!state.evidence||String(r.evidence||'')===state.evidence));
|
||||
}
|
||||
function render(){
|
||||
buildTabs(); updateFilters(); const tab=activeTab(); if(tab.id==='overview') return renderOverview();
|
||||
const recs=filteredRecords();
|
||||
contentEl.innerHTML=`<div class="section-title"><div><h2>${esc(tab.label)}</h2><div class="count">当前显示 ${recs.length} / ${recordsOf(tab).length} 条记录</div></div><div class="desc">${esc(tab.description||'')}</div></div>` +
|
||||
(recs.length ? (state.view==='cards'?`<div class="cards">${recs.map(cardHTML).join('')}</div>`:tableHTML(recs)) : `<div class="empty">没有匹配结果。请调整关键词或筛选条件。</div>`);
|
||||
contentEl.querySelectorAll('[data-open-id]').forEach(el=>el.onclick=()=>openModal(el.dataset.openId));
|
||||
}
|
||||
function cardFieldsForTab(tabId){
|
||||
return {
|
||||
organizations:['类型','主管/协调体系','主要功能','证据强度'],
|
||||
policies:['类型','状态','主管机关','风险提示'],
|
||||
civil_groups:['分类','组织类型','核心功能','风险提示'],
|
||||
controversies:['时间范围','状态','相关组织','风险等级'],
|
||||
risks:['风险类型','风险等级','影响对象','触发条件']
|
||||
}[tabId] || [];
|
||||
}
|
||||
function cardHTML(r){
|
||||
const fields=cardFieldsForTab(state.activeTab);
|
||||
const mini=fields.map(k=>`<div class="mini"><div class="mk">${esc(k)}</div><div class="mv">${esc(truncate(textify((r.summary||{})[k]),90))}</div></div>`).join('');
|
||||
return `<article class="card" data-open-id="${esc(r.id)}"><h3>${esc(r.title)}</h3><div class="subtitle">${esc(truncate(r.subtitle,185))}</div><div class="mini-fields">${mini}</div><div class="chips">${renderChips(r.tags||[],5)}${r.evidence?`<span class="chip ${chipClass(r.evidence)}">证据:${esc(r.evidence)}</span>`:''}</div></article>`;
|
||||
}
|
||||
function tableHTML(recs){
|
||||
return `<div class="table-wrap"><table><thead><tr><th>编号</th><th>标题</th><th>分类</th><th>状态</th><th>层级/等级</th><th>证据强度</th><th>摘要</th></tr></thead><tbody>${recs.map(r=>`<tr data-open-id="${esc(r.id)}"><td>${esc(r.id)}</td><td><b>${esc(r.title)}</b></td><td>${esc(r.category)}</td><td>${esc(r.status)}</td><td>${esc(r.level)}</td><td>${esc(r.evidence)}</td><td>${esc(truncate(r.subtitle,160))}</td></tr>`).join('')}</tbody></table></div>`
|
||||
}
|
||||
function renderOverview(){
|
||||
const ov=DATA.overview, cards=ov.top_display_cards||[], dist=ov.category_distribution||{};
|
||||
contentEl.innerHTML=`<div class="section-title"><div><h2>首页总览</h2><div class="count">生成日期:${esc(ov.created_at)}|${esc(ov.last_verified_hint)}</div></div><div class="desc">展示核心统计、分类分布、重点卡片和安全边界说明。</div></div>
|
||||
<div class="metrics">${cards.map(c=>`<div class="metric"><div class="label">${esc(c.card_title)}</div><div class="value">${esc(c.value)}</div><div class="sub">${esc(c.subtitle)}</div></div>`).join('')}</div>
|
||||
<div class="grid-2">${distributionBox('组织分类分布',dist.organizations_by_category)}${distributionBox('风险等级分布',dist.risks_by_level)}${distributionBox('政策类型分布',dist.policies_by_type)}${distributionBox('民间组织分类分布',dist.civil_groups_by_category)}</div>
|
||||
<div class="box" style="margin-top:14px"><h3>推荐首页区块</h3>${renderValue(ov.recommended_home_sections||[])}</div>`;
|
||||
}
|
||||
function distributionBox(title,obj){obj=obj||{}; const max=Math.max(...Object.values(obj).map(Number),1); const rows=Object.entries(obj).map(([k,v])=>`<div class="bar-row"><div>${esc(k)}</div><div class="bar"><span style="width:${Math.max(4,Number(v)/max*100)}%"></span></div><div>${esc(v)}</div></div>`).join('');return `<div class="box"><h3>${esc(title)}</h3>${rows||'<div class="empty">暂无数据</div>'}</div>`}
|
||||
|
||||
function openModal(id){
|
||||
const tab=activeTab(); const rec=recordsOf(tab).find(r=>String(r.id)===String(id)); if(!rec)return;
|
||||
$('#modalTitle').textContent=rec.title||rec.id; $('#modalSub').textContent=rec.subtitle||''; $('#modalChips').innerHTML=renderChips(rec.tags||[],12);
|
||||
$('#modalBody').innerHTML=renderDetail(tab.id,rec.detail||rec); $('#modalBackdrop').classList.add('show');
|
||||
}
|
||||
function renderDetail(tabId, detail){
|
||||
const layout=LAYOUTS[tabId]||[]; const used=new Set();
|
||||
const sections=layout.map(sec=>{const body=sec.keys.map(k=>{used.add(k); return renderField(k,detail[k],tabId)}).filter(Boolean).join(''); return body?section(sec.title,body):''}).join('');
|
||||
const extras=Object.keys(detail).filter(k=>!used.has(k) && !/^_/.test(k));
|
||||
const extraHtml=extras.length?section('其他补充信息',extras.map(k=>renderField(k,detail[k],tabId)).filter(Boolean).join('')):'';
|
||||
return sections + extraHtml;
|
||||
}
|
||||
function section(title,body){return `<section class="detail-section"><div class="section-head"><h3>${esc(title)}</h3></div><div class="section-content">${body}</div></section>`}
|
||||
function renderField(k,v,tabId){
|
||||
if(v==null || v==='' || (Array.isArray(v)&&!v.length)) return '';
|
||||
const val = specialized(k,v,tabId) || renderValue(v,k);
|
||||
return `<div class="kv"><div class="k">${esc(label(k))}</div><div class="v">${val}</div></div>`;
|
||||
}
|
||||
function specialized(k,v,tabId){
|
||||
if(k==='source_url' && v) return `<a class="source-link" href="${esc(v)}" target="_blank" rel="noopener">${esc(v)}</a>`;
|
||||
if(['related_policy_ids','related_risk_ids','related_org_ids','related_controversy_ids','controversy_links','frontend_tags','source_ids'].includes(k)) return renderIdPills(v);
|
||||
if(k==='sources' && Array.isArray(v)) return v.map(s=>typeof s==='string'?`<span class="id-pill">${esc(s)}</span>`:`<a class="source-link" href="${esc(s.url||'#')}" target="_blank" rel="noopener"><b>${esc(s.title||s.url||'资料来源')}</b><br>${esc(s.source_type||'')} ${s.confidence?`|可信度:${esc(s.confidence)}`:''}</a>`).join('');
|
||||
if(k==='public_key_persons' && Array.isArray(v)) return `<div class="mini-card-grid">${v.map(p=>`<div class="mini-card"><div class="mini-title">${esc(p.name)}</div><div>${esc(p.public_role||'')}</div><div class="view-note">${esc(p.notes||'')}</div></div>`).join('')}</div>`;
|
||||
if(k==='training_topics' && Array.isArray(v)) return `<div class="mini-card-grid">${v.map(t=>`<div class="mini-card"><div class="mini-title">${esc(t.topic)}</div><div>${esc(t.public_description||'')}</div><div class="chips"><span class="chip ${chipClass(t.operational_sensitivity)}">敏感度:${esc(t.operational_sensitivity||'')}</span></div></div>`).join('')}</div>`;
|
||||
if(k==='policy_links' && Array.isArray(v)) return `<div class="mini-card-grid">${v.map(p=>`<div class="mini-card"><div class="mini-title">${esc(p.policy_or_agency)}</div><div>${esc(p.relationship_type||'')}</div><div class="view-note">${esc(p.evidence||'')}</div><div class="chips"><span class="chip ${chipClass(p.evidence_strength)}">${esc(p.evidence_strength||'')}</span></div></div>`).join('')}</div>`;
|
||||
if(k==='controversies' && Array.isArray(v)) return `<div class="timeline">${v.map(c=>`<div class="tl-item"><div class="tl-date">${esc(c.date||c.event||'争议')}</div><div class="tl-text"><b>${esc(c.event||'')}</b><br>${esc(c.issue||'')}${c.public_response?`<br>公开回应:${esc(c.public_response)}`:''}</div><div class="chips">${c.risk_tag?`<span class="chip high">${esc(c.risk_tag)}</span>`:''}</div></div>`).join('')}</div>`;
|
||||
if(k==='factual_anchors' && Array.isArray(v)) return `<div class="timeline">${v.map(a=>`<div class="tl-item"><div class="tl-date">${esc(a.date||'时间未明')}</div><div class="tl-text">${esc(a.fact||'')}</div><div>${renderIdPills(a.source_ids||[])}</div><div class="chips"><span class="chip ${chipClass(a.evidence_status)}">${esc(a.evidence_status||'')}</span></div></div>`).join('')}</div>`;
|
||||
if(k==='position_map' && typeof v==='object') return `<div class="columns">${Object.entries(v).map(([kk,vv])=>`<div class="mini-card"><div class="mini-title">${esc(label(kk))}</div><div>${renderValue(vv,kk)}</div></div>`).join('')}</div>`;
|
||||
if(k==='public_opinion_signals' && typeof v==='object') return `<div class="mini-card-grid">${Object.entries(v).map(([kk,vv])=>`<div class="mini-card"><div class="mini-title">${esc(label(kk))}</div>${Array.isArray(vv)?renderChips(vv,30):renderValue(vv,kk)}</div>`).join('')}</div>`;
|
||||
if(k==='propagation' && typeof v==='object') return renderPropagation(v);
|
||||
if(k==='activity_funding' && typeof v==='object') return renderActivityFunding(v);
|
||||
if(k==='risk_assessment' && typeof v==='object') return `<div class="mini-card-grid">${Object.entries(v).map(([kk,vv])=>`<div class="mini-card"><div class="mini-title">${esc(label(kk))}</div>${renderValue(vv,kk)}</div>`).join('')}</div>`;
|
||||
return null;
|
||||
}
|
||||
function renderPropagation(v){
|
||||
const chain=v.propagation_chain||[]; const chainHtml=Array.isArray(chain)?`<div class="timeline">${chain.map(c=>`<div class="tl-item"><div class="tl-date">${esc(c.stage||c.date||'阶段')}</div><div class="tl-text">${renderValue(c)}</div></div>`).join('')}</div>`:renderValue(chain);
|
||||
return `<div class="mini-card"><div class="mini-title">传播链</div>${chainHtml}</div><div class="mini-card"><div class="mini-title">可能平台扩散模式</div>${renderValue(v.likely_platform_pattern)}</div><div class="mini-card"><div class="mini-title">关联风险</div>${renderIdPills(v.related_risk_ids||[])}</div><div class="mini-card"><div class="mini-title">展示边界</div>${esc(v.safe_display_notes||'')}</div>`;
|
||||
}
|
||||
function renderActivityFunding(v){
|
||||
const keys=['activity_records','funding_records','cooperation_records','media_exposure_records','related_controversy_ids','related_risk_ids','missing_fields_to_fill_next','safe_display_notes'];
|
||||
return `<div class="mini-card-grid">${keys.filter(k=>v[k]!=null).map(k=>`<div class="mini-card"><div class="mini-title">${esc(label(k))}</div>${renderValue(v[k],k)}</div>`).join('')}</div>`;
|
||||
}
|
||||
function renderValue(v,k){
|
||||
if(v==null || v==='') return '—';
|
||||
if(typeof v==='string' || typeof v==='number' || typeof v==='boolean'){
|
||||
const s=String(v);
|
||||
if(/^https?:\/\//.test(s)) return `<a class="source-link" href="${esc(s)}" target="_blank" rel="noopener">${esc(s)}</a>`;
|
||||
return esc(s);
|
||||
}
|
||||
if(Array.isArray(v)){
|
||||
if(!v.length)return '—';
|
||||
if(v.every(x=>typeof x==='string'||typeof x==='number')){
|
||||
const asIds=v.every(x=>/^[A-Z]{2,}_|^TC_|^CON_|^POL_|^ORG_|^RISK_|^SRC_/.test(String(x)));
|
||||
return asIds ? renderIdPills(v) : `<ul class="list">${v.map(x=>`<li>${esc(x)}</li>`).join('')}</ul>`;
|
||||
}
|
||||
return `<div class="mini-card-grid">${v.map(item=>`<div class="mini-card">${renderValue(item)}</div>`).join('')}</div>`;
|
||||
}
|
||||
if(typeof v==='object'){
|
||||
return Object.entries(v).map(([kk,vv])=>`<div class="kv"><div class="k">${esc(label(kk))}</div><div class="v">${renderValue(vv,kk)}</div></div>`).join('');
|
||||
}
|
||||
return esc(v);
|
||||
}
|
||||
|
||||
$('#modalClose').onclick=()=>$('#modalBackdrop').classList.remove('show');
|
||||
$('#modalBackdrop').onclick=e=>{if(e.target.id==='modalBackdrop')$('#modalBackdrop').classList.remove('show')};
|
||||
searchInput.oninput=e=>{state.query=e.target.value;render()};
|
||||
categoryFilter.onchange=e=>{state.category=e.target.value;render()};
|
||||
levelFilter.onchange=e=>{state.level=e.target.value;render()};
|
||||
evidenceFilter.onchange=e=>{state.evidence=e.target.value;render()};
|
||||
viewToggle.onclick=()=>{state.view=state.view==='cards'?'table':'cards'; viewToggle.textContent=state.view==='cards'?'卡片视图':'表格视图'; render()};
|
||||
document.addEventListener('keydown',e=>{if(e.key==='Escape')$('#modalBackdrop').classList.remove('show')});
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>美国左翼退伍军人与关联组织专题展示平台</title>
|
||||
<style>
|
||||
:root{
|
||||
--bg:#f6f1eb;
|
||||
--panel:#fffaf4;
|
||||
--panel2:#fffdf9;
|
||||
--text:#251b17;
|
||||
--muted:#776963;
|
||||
--line:#d9c9bb;
|
||||
--heavy:#4b241b;
|
||||
--accent:#a33a2b;
|
||||
--accent2:#cf7a45;
|
||||
--soft:#f1dfd2;
|
||||
--soft2:#ead1c0;
|
||||
--green:#627b58;
|
||||
--blue:#4f6f86;
|
||||
--purple:#6f5d83;
|
||||
--shadow:0 18px 50px rgba(66,35,20,.13);
|
||||
--radius:22px;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;font-family:"Microsoft YaHei","Noto Sans SC",system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:linear-gradient(180deg,#f8f1e8 0%,#f3e9dc 55%,#efe0d2 100%);color:var(--text);}
|
||||
.app{max-width:1480px;margin:0 auto;padding:26px 24px 56px;}
|
||||
.hero{position:relative;overflow:hidden;border:1px solid var(--line);border-radius:30px;background:radial-gradient(circle at 10% 10%,rgba(207,122,69,.24),transparent 28%),radial-gradient(circle at 90% 0%,rgba(163,58,43,.15),transparent 34%),linear-gradient(135deg,#fffaf4,#f3dfcd);box-shadow:var(--shadow);padding:34px 36px;margin-bottom:22px;}
|
||||
.hero:before{content:"";position:absolute;right:-90px;top:-130px;width:310px;height:310px;border:32px solid rgba(163,58,43,.08);border-radius:50%;}
|
||||
.hero:after{content:"";position:absolute;right:120px;bottom:-130px;width:260px;height:260px;border:1px solid rgba(75,36,27,.14);border-radius:50%;}
|
||||
.hero-inner{position:relative;z-index:2;display:grid;grid-template-columns:minmax(0,1.25fr) minmax(360px,.75fr);gap:24px;align-items:end;}
|
||||
.eyebrow{display:inline-flex;gap:8px;align-items:center;font-size:13px;letter-spacing:.12em;color:var(--accent);font-weight:800;text-transform:uppercase;margin-bottom:10px;}
|
||||
.eyebrow:before{content:"";width:34px;height:2px;background:var(--accent);display:block;}
|
||||
h1{font-size:38px;line-height:1.16;margin:0 0 12px;font-weight:900;letter-spacing:-.02em;color:#3e2018;}
|
||||
.lead{font-size:16px;line-height:1.85;color:#5f4f48;max-width:980px;margin:0;}
|
||||
.hero-actions{display:flex;gap:12px;flex-wrap:wrap;margin-top:22px;}
|
||||
.btn{border:1px solid var(--heavy);border-radius:999px;background:#fffdf9;color:var(--heavy);padding:10px 16px;font-weight:800;cursor:pointer;transition:.18s;display:inline-flex;align-items:center;gap:8px;text-decoration:none;font-size:14px;}
|
||||
.btn:hover{transform:translateY(-1px);box-shadow:0 8px 18px rgba(66,35,20,.12);background:var(--heavy);color:#fffaf4;}
|
||||
.btn.accent{background:var(--accent);color:#fffaf4;border-color:var(--accent);}
|
||||
.quick{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;}
|
||||
.quick-card{border:1px solid rgba(75,36,27,.16);background:rgba(255,255,255,.58);border-radius:18px;padding:16px;backdrop-filter:blur(6px);}
|
||||
.quick-card b{display:block;font-size:24px;color:var(--accent);margin-bottom:2px;}
|
||||
.quick-card span{font-size:12px;color:var(--muted);line-height:1.45;}
|
||||
.toolbar{position:sticky;top:0;z-index:10;margin:0 0 20px;padding:12px;border:1px solid var(--line);border-radius:24px;background:rgba(255,250,244,.86);backdrop-filter:blur(18px);box-shadow:0 12px 30px rgba(66,35,20,.08);display:flex;gap:12px;align-items:center;}
|
||||
.tabs{display:flex;gap:8px;overflow-x:auto;padding:2px;flex:1;}
|
||||
.tab{white-space:nowrap;border:1px solid transparent;background:transparent;border-radius:999px;padding:10px 14px;font-weight:800;color:#5a453c;cursor:pointer;transition:.16s;font-size:14px;}
|
||||
.tab:hover{background:#f2dfd0;}
|
||||
.tab.active{background:#4b241b;color:#fffaf4;box-shadow:0 7px 18px rgba(75,36,27,.18);}
|
||||
.search{min-width:270px;display:flex;align-items:center;gap:8px;border:1px solid var(--line);background:#fffdf9;border-radius:999px;padding:9px 12px;}
|
||||
.search input{border:0;outline:0;background:transparent;width:100%;font-size:14px;color:var(--text);}
|
||||
.panel{display:none;animation:fade .22s ease;}
|
||||
.panel.active{display:block;}
|
||||
@keyframes fade{from{opacity:.5;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}
|
||||
.section-title{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;margin:24px 0 14px;}
|
||||
.section-title h2{margin:0;font-size:24px;color:#3e2018;}
|
||||
.section-title p{margin:6px 0 0;color:var(--muted);line-height:1.7;max-width:920px;}
|
||||
.grid{display:grid;gap:16px;}
|
||||
.cols-2{grid-template-columns:repeat(2,minmax(0,1fr));}.cols-3{grid-template-columns:repeat(3,minmax(0,1fr));}.cols-4{grid-template-columns:repeat(4,minmax(0,1fr));}
|
||||
.card{border:1px solid var(--line);background:var(--panel2);border-radius:var(--radius);padding:20px;box-shadow:0 8px 28px rgba(66,35,20,.06);}
|
||||
.card h3{margin:0 0 10px;font-size:18px;color:#44231a;line-height:1.35;}
|
||||
.card p{margin:0;color:#66564f;line-height:1.75;font-size:14px;}
|
||||
.mini{font-size:12px;color:var(--muted);line-height:1.6;}
|
||||
.metric{position:relative;overflow:hidden;padding:18px;border-radius:20px;border:1px solid rgba(75,36,27,.16);background:linear-gradient(180deg,#fffdf9,#f5e7dc);}
|
||||
.metric .value{font-size:27px;font-weight:900;color:var(--accent);margin-bottom:5px;}
|
||||
.metric .label{font-size:13px;font-weight:800;color:#4b241b;margin-bottom:4px;}
|
||||
.metric .desc{font-size:12px;line-height:1.45;color:var(--muted);}
|
||||
.pill-row{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px;}
|
||||
.pill{display:inline-flex;align-items:center;border:1px solid rgba(75,36,27,.18);border-radius:999px;padding:6px 10px;background:#fff8f2;color:#5a433b;font-size:12px;font-weight:700;}
|
||||
.pill.red{background:#f5dfd9;color:#7d251a;border-color:#e7bdb4}.pill.green{background:#e8eadb;color:#536b49;border-color:#c6cdb4}.pill.blue{background:#e4ecf0;color:#405f75;border-color:#bfd0d9}.pill.purple{background:#e8e0ed;color:#5f4f72;border-color:#d0c3da}
|
||||
.org-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;}
|
||||
.org-card{border:1px solid var(--line);background:#fffdf9;border-radius:24px;padding:18px;position:relative;overflow:hidden;cursor:pointer;transition:.18s;min-height:270px;display:flex;flex-direction:column;}
|
||||
.org-card:hover{transform:translateY(-3px);box-shadow:var(--shadow);border-color:#bd927c;}
|
||||
.org-card:before{content:"";position:absolute;right:-40px;top:-48px;width:120px;height:120px;background:rgba(163,58,43,.08);border-radius:50%;}
|
||||
.org-card .top{position:relative;display:flex;gap:12px;align-items:flex-start;margin-bottom:12px;}
|
||||
.avatar{width:48px;height:48px;border-radius:50%;border:1px solid var(--heavy);display:grid;place-items:center;font-weight:900;color:#4b241b;background:#f4e0d1;flex:0 0 auto;}
|
||||
.org-name{font-size:17px;font-weight:900;color:#3d2118;line-height:1.3;}.org-zh{font-size:12px;color:var(--muted);margin-top:3px;}
|
||||
.org-card .summary{font-size:13px;line-height:1.7;color:#66564f;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden;margin-bottom:12px;}
|
||||
.org-meta{display:flex;flex-wrap:wrap;gap:7px;margin-top:auto;}
|
||||
.badge{font-size:11px;font-weight:800;border-radius:999px;padding:5px 8px;border:1px solid rgba(75,36,27,.18);background:#f8ecdf;color:#5a433b;}
|
||||
.badge.hot{background:#7d2e22;color:#fff;border-color:#7d2e22}.badge.ok{background:#607a55;color:#fff;border-color:#607a55}.badge.warn{background:#cf7a45;color:#fff;border-color:#cf7a45}
|
||||
.timeline{position:relative;margin-top:14px;padding-left:24px;}
|
||||
.timeline:before{content:"";position:absolute;left:8px;top:0;bottom:0;width:2px;background:linear-gradient(var(--accent),rgba(163,58,43,.1));}
|
||||
.t-item{position:relative;border:1px solid var(--line);background:#fffdf9;border-radius:18px;margin:0 0 12px;padding:14px 15px;cursor:pointer;transition:.16s;}
|
||||
.t-item:hover{transform:translateX(4px);box-shadow:0 8px 20px rgba(66,35,20,.08);}
|
||||
.t-item:before{content:"";position:absolute;left:-22px;top:20px;width:11px;height:11px;border-radius:50%;background:var(--accent);border:3px solid #f8f1e8;}
|
||||
.t-year{font-size:12px;font-weight:900;color:var(--accent);letter-spacing:.05em}.t-title{font-size:16px;font-weight:900;margin-top:2px;color:#422319}.t-meaning{font-size:13px;color:#66564f;margin-top:4px;line-height:1.55;}
|
||||
table{width:100%;border-collapse:separate;border-spacing:0;overflow:hidden;border:1px solid var(--line);border-radius:18px;background:#fffdf9;}
|
||||
th,td{padding:13px 14px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top;font-size:13px;line-height:1.6;}
|
||||
th{background:#4b241b;color:#fffaf4;font-size:12px;letter-spacing:.04em;}
|
||||
tr:last-child td{border-bottom:0} tr:nth-child(even) td{background:#fff7ef;}
|
||||
.matrix-card{border:1px solid var(--line);border-radius:20px;background:#fffdf9;padding:16px;cursor:pointer;transition:.16s;}
|
||||
.matrix-card:hover{transform:translateY(-2px);box-shadow:0 8px 20px rgba(66,35,20,.08);}
|
||||
.matrix-card h3{font-size:16px;margin:0 0 6px;}.matrix-card .orgs{font-size:12px;color:var(--accent);font-weight:900;margin-bottom:8px;}.matrix-card p{font-size:13px;line-height:1.7;color:#66564f;}
|
||||
.route{border-left:5px solid var(--accent);padding:18px;border-radius:18px;background:#fffdf9;border-top:1px solid var(--line);border-right:1px solid var(--line);border-bottom:1px solid var(--line);}
|
||||
.route h3{margin:0 0 8px;font-size:18px;}.route .orgs{font-size:12px;font-weight:900;color:var(--accent);margin-bottom:8px;}.route p{font-size:13px;line-height:1.75;color:#66564f;}
|
||||
.notice{border:1px dashed rgba(75,36,27,.35);background:#fff6ed;border-radius:22px;padding:18px;color:#5f4f48;line-height:1.75;}
|
||||
.source-box{font-size:13px;line-height:1.8;color:#5f4f48;}
|
||||
.modal-backdrop{position:fixed;inset:0;background:rgba(39,26,20,.48);display:none;z-index:90;align-items:center;justify-content:center;padding:24px;}
|
||||
.modal-backdrop.open{display:flex;}
|
||||
.modal{width:min(1060px,96vw);max-height:88vh;overflow:auto;border-radius:28px;background:#fffdf9;border:1px solid #c7a995;box-shadow:0 30px 100px rgba(0,0,0,.28);}
|
||||
.modal-head{position:sticky;top:0;background:linear-gradient(135deg,#4b241b,#7c2f24);color:#fffaf4;padding:22px 26px;z-index:3;display:flex;gap:16px;align-items:flex-start;justify-content:space-between;}
|
||||
.modal-title h2{font-size:24px;line-height:1.25;margin:0 0 4px;}.modal-title p{margin:0;color:#f5d5c7;line-height:1.5;}
|
||||
.close{background:rgba(255,255,255,.12);color:#fff;border:1px solid rgba(255,255,255,.3);width:40px;height:40px;border-radius:50%;font-size:22px;cursor:pointer;}
|
||||
.modal-body{padding:24px 26px 30px;}
|
||||
.detail-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin:16px 0;}
|
||||
.detail-box{border:1px solid var(--line);border-radius:18px;padding:14px;background:#fff8f1;}
|
||||
.detail-box .k{font-size:12px;font-weight:900;color:var(--accent);margin-bottom:4px;}.detail-box .v{font-size:14px;color:#4e3f38;line-height:1.6;}
|
||||
.modal-section{margin:22px 0 0;}.modal-section h3{font-size:18px;margin:0 0 10px;color:#44231a;border-bottom:1px solid var(--line);padding-bottom:8px;}
|
||||
.list{margin:0;padding-left:18px;color:#5f4f48;line-height:1.8;font-size:14px;}.list li{margin:4px 0;}
|
||||
.empty{padding:28px;border:1px dashed var(--line);border-radius:20px;text-align:center;color:var(--muted);background:#fffaf4;}
|
||||
@media (max-width:1100px){.hero-inner{grid-template-columns:1fr}.quick{grid-template-columns:repeat(3,1fr)}.cols-4,.cols-3{grid-template-columns:repeat(2,1fr)}.org-grid{grid-template-columns:repeat(2,1fr)}.search{min-width:190px}}
|
||||
@media (max-width:760px){.app{padding:14px}.hero{padding:24px}.toolbar{align-items:stretch;flex-direction:column}.search{min-width:0}.quick,.cols-4,.cols-3,.cols-2,.org-grid,.detail-grid{grid-template-columns:1fr}h1{font-size:28px}.modal-backdrop{padding:10px}.modal-head{padding:18px}.modal-body{padding:18px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
<header class="hero">
|
||||
<div class="hero-inner">
|
||||
<div>
|
||||
<div class="eyebrow">Research Dashboard</div>
|
||||
<h1 id="pageTitle"></h1>
|
||||
<p class="lead" id="pageSubtitle"></p>
|
||||
<div class="hero-actions">
|
||||
<button class="btn accent" onclick="switchTab('orgs')">查看组织资料库</button>
|
||||
<button class="btn" onclick="switchTab('china')">查看涉中涉台分化</button>
|
||||
<button class="btn" onclick="switchTab('narrative')">查看叙事框架</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="quick" id="quickMetrics"></div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav class="toolbar">
|
||||
<div class="tabs" id="tabs"></div>
|
||||
<label class="search"><span>⌕</span><input id="globalSearch" placeholder="搜索组织、议题、路线、关键词..." /></label>
|
||||
</nav>
|
||||
|
||||
<main>
|
||||
<section id="panel-overview" class="panel active"></section>
|
||||
<section id="panel-ecology" class="panel"></section>
|
||||
<section id="panel-orgs" class="panel"></section>
|
||||
<section id="panel-history" class="panel"></section>
|
||||
<section id="panel-identity" class="panel"></section>
|
||||
<section id="panel-issues" class="panel"></section>
|
||||
<section id="panel-china" class="panel"></section>
|
||||
<section id="panel-narrative" class="panel"></section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<div class="modal-backdrop" id="modalBackdrop" onclick="backdropClose(event)">
|
||||
<article class="modal" id="modal"></article>
|
||||
</div>
|
||||
|
||||
<script id="DATA" type="application/json">{"meta": {"title": "美国左翼退伍军人与关联组织专题展示平台", "subtitle": "组织生态 · 历史谱系 · 人员身份 · 议题矩阵 · 涉中涉台分化 · 爱国主义重构", "version": "enhanced_v1.0", "source_basis": ["us_left_wing_veterans_skill/SKILL.md", "docs/full_reference_current_version.md", "docs/answer_bank_three_priority_questions.md", "examples/veterans_for_peace_china_taiwan_profile.md", "examples/votevets_common_defense_compare.md", "本轮对话中补充的8个栏目研究数据"], "safety_note": "本专题仅用于公开资料研究、组织生态分析、政策与舆论研究,不包含定向影响、骚扰、欺骗、操纵或针对个人的行动建议。"}, "overview": {"definition": "美国左翼退伍军人群体不是一个统一组织,而是一个以退伍军人身份为共同象征资源,围绕反战、进步派政治、民主保护、劳工、福利、身份平权、人权与难民、反新冷战等议题形成的松散议题生态。", "judgments": ["该群体更像“议题联盟”,不是统一组织群体。", "其影响力不主要来自人数,而来自退伍军人身份在美国政治文化中的象征权威。", "它们共同挑战“军人天然保守、爱国等于支持战争”的传统叙事。", "它们在VA福利、反永久战争、反威权、民主保护、军属支持、心理健康等议题上有交集。", "它们在涉中涉台、人权、对华竞争、台湾民主、美国军事介入问题上存在明显分歧。"], "metrics": [{"label": "2023年美国退伍军人", "value": "约1580万", "desc": "占18岁及以上平民人口约6.1%"}, {"label": "2023年女性退伍军人", "value": "约170万", "desc": "约占退伍军人总数10.9%"}, {"label": "VA预测FY2024", "value": "约1790万", "desc": "VA VetPop2023预测口径"}, {"label": "VA预测FY2053", "value": "约1120万", "desc": "总体人数下降,结构更女性化、多元化"}, {"label": "2024退伍军人选民", "value": "63%偏共和党", "desc": "左翼退伍军人属于少数派反叙事力量"}, {"label": "VFP分会", "value": "120+", "desc": "美国各州和多个国家拥有成员与分会"}], "layers": [{"name": "反战和平主义圈", "orgs": "Veterans For Peace、VVAW、About Face", "logic": "反永久战争、反军事主义、反军工复合体"}, {"name": "民主党进步派圈", "orgs": "VoteVets、Common Defense", "logic": "选举动员、反威权、保护民主、保护VA"}, {"name": "服务福利圈", "orgs": "Swords to Plowshares", "logic": "住房、医疗、就业、法律和退伍军人服务"}, {"name": "身份平权圈", "orgs": "Minority Veterans of America", "logic": "少数族裔、女性、LGBTQ+、残障退伍军人权益"}, {"name": "劳工/人权/军属外围圈", "orgs": "UVC、VFAI、MFSO、Gold Star Families", "logic": "工会、人权、难民、军属和阵亡家庭反战"}], "comparison": [{"dimension": "组织属性", "traditional": "全国会员组织、福利服务、纪念传统", "left": "PAC、501(c)(3)/(c)(4)、工会项目、服务组织、军属网络并存"}, {"dimension": "核心话语", "traditional": "服务国家、荣誉、纪念、福利", "left": "支持军人不等于支持战争;誓言没有过期;VA不是商品"}, {"dimension": "政治取向", "traditional": "整体更接近主流退伍军人政治,偏保守", "left": "内部差异大,但更偏反战、进步派、劳工与平权"}, {"dimension": "研究重点", "traditional": "主流退伍军人政治与福利", "left": "少数派如何争夺爱国主义、国家安全和军人形象解释权"}]}, "ecology": {"core_judgment": "美国左翼退伍军人生态由反战、选举、服务、身份平权、劳工、人权、军属和社会主义外围网络构成。共同点是使用退伍军人身份参与公共议题,差异在于法律形态、行动方式、对外政策和政治路线。", "layers": [{"name": "老牌反战和平主义", "representative": "Veterans For Peace、VVAW", "nature": "会员制、分会型、和平主义退伍军人组织", "issues": ["反战", "反军事化", "反核", "反军工", "反新冷战"], "value": "研究涉中涉台反介入路线的核心入口。"}, {"name": "后9·11反永久战争", "representative": "About Face", "nature": "后9·11军人与退伍军人运动组织", "issues": ["伊拉克", "阿富汗", "永久战争", "国内军事化"], "value": "代表年轻一代左翼退伍军人运动。"}, {"name": "民主党/进步派选举", "representative": "VoteVets、Common Defense", "nature": "PAC、501(c)(4)、基层运动平台", "issues": ["候选人背书", "国家安全叙事", "保护民主", "保护VA"], "value": "解释退伍军人身份如何成为民主党和进步派政治资源。"}, {"name": "服务福利型", "representative": "Swords to Plowshares", "nature": "退伍军人服务型非营利组织", "issues": ["住房", "就业", "医疗", "法律援助"Line truncated
|
||||
<script>
|
||||
const DATA = JSON.parse(document.getElementById('DATA').textContent);
|
||||
const tabs = [
|
||||
['overview','群体总览'],['ecology','组织生态'],['orgs','组织资料库'],['history','历史演化'],['identity','人员画像'],['issues','议题主张'],['china','涉中涉台'],['narrative','叙事重构']
|
||||
];
|
||||
function esc(s){return String(s ?? '').replace(/[&<>"']/g, m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}
|
||||
function list(items, cls='list'){return `<ul class="${cls}">${(items||[]).map(x=>`<li>${esc(x)}</li>`).join('')}</ul>`}
|
||||
function pills(items, color=''){return `<div class="pill-row">${(items||[]).map(x=>`<span class="pill ${color}">${esc(x)}</span>`).join('')}</div>`}
|
||||
function kv(k,v){return `<div class="detail-box"><div class="k">${esc(k)}</div><div class="v">${esc(v)}</div></div>`}
|
||||
function section(title, html){return `<div class="modal-section"><h3>${esc(title)}</h3>${html}</div>`}
|
||||
function table(headers, rows){return `<table><thead><tr>${headers.map(h=>`<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.map(r=>`<tr>${r.map(c=>`<td>${c}</td>`).join('')}</tr>`).join('')}</tbody></table>`}
|
||||
function norm(s){return String(s||'').toLowerCase();}
|
||||
function includesDeep(obj,q){return norm(JSON.stringify(obj)).includes(norm(q));}
|
||||
function init(){
|
||||
document.getElementById('pageTitle').textContent = DATA.meta.title;
|
||||
document.getElementById('pageSubtitle').textContent = DATA.meta.subtitle + '。' + DATA.meta.safety_note;
|
||||
document.getElementById('quickMetrics').innerHTML = DATA.overview.metrics.slice(0,4).map(m=>`<div class="quick-card"><b>${esc(m.value)}</b><span>${esc(m.label)}|${esc(m.desc)}</span></div>`).join('');
|
||||
document.getElementById('tabs').innerHTML = tabs.map(([id,name])=>`<button class="tab ${id==='overview'?'active':''}" data-tab="${id}" onclick="switchTab('${id}')">${name}</button>`).join('');
|
||||
renderAll();
|
||||
document.getElementById('globalSearch').addEventListener('input', renderAll);
|
||||
}
|
||||
function switchTab(id){
|
||||
document.querySelectorAll('.panel').forEach(p=>p.classList.remove('active'));
|
||||
document.getElementById('panel-'+id).classList.add('active');
|
||||
document.querySelectorAll('.tab').forEach(t=>t.classList.toggle('active',t.dataset.tab===id));
|
||||
window.scrollTo({top:0,behavior:'smooth'});
|
||||
}
|
||||
function q(){return document.getElementById('globalSearch')?.value.trim() || ''}
|
||||
function renderAll(){renderOverview();renderEcology();renderOrgs();renderHistory();renderIdentity();renderIssues();renderChina();renderNarrative();}
|
||||
function renderOverview(){
|
||||
const o = DATA.overview;
|
||||
const rows = o.comparison.map(r=>[esc(r.dimension),esc(r.traditional),esc(r.left)]);
|
||||
document.getElementById('panel-overview').innerHTML = `
|
||||
<div class="section-title"><div><h2>群体总览与概念界定</h2><p>${esc(o.definition)}</p></div></div>
|
||||
<div class="grid cols-3">${o.judgments.map(j=>`<div class="card"><h3>核心判断</h3><p>${esc(j)}</p></div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>关键人口与政治背景</h2><p>这一部分用于说明:左翼退伍军人并非美国退伍军人主流,但其身份符号具有高传播权威。</p></div></div>
|
||||
<div class="grid cols-3">${o.metrics.map(m=>`<div class="metric"><div class="value">${esc(m.value)}</div><div class="label">${esc(m.label)}</div><div class="desc">${esc(m.desc)}</div></div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>议题联盟分层</h2><p>专题不把它们当成单一阵营,而是按议题、组织形态和行动方式分层展示。</p></div></div>
|
||||
<div class="grid cols-3">${o.layers.map(l=>`<div class="card"><h3>${esc(l.name)}</h3><p><b>代表组织:</b>${esc(l.orgs)}</p><p><b>核心逻辑:</b>${esc(l.logic)}</p></div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>与传统退伍军人组织的区别</h2></div></div>${table(['对比维度','传统退伍军人组织','左翼退伍军人生态'], rows)}
|
||||
`;
|
||||
}
|
||||
function renderEcology(){
|
||||
const e = DATA.ecology;
|
||||
document.getElementById('panel-ecology').innerHTML = `
|
||||
<div class="section-title"><div><h2>组织生态与类型分层</h2><p>${esc(e.core_judgment)}</p></div></div>
|
||||
<div class="grid cols-3">${e.layers.map((l,i)=>`<div class="card"><h3>${esc(l.name)}</h3><p><b>代表组织:</b>${esc(l.representative)}</p><p><b>组织性质:</b>${esc(l.nature)}</p>${pills(l.issues,['red','blue','green'][i%3])}<p style="margin-top:12px"><b>研究价值:</b>${esc(l.value)}</p></div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>组织关系类型</h2><p>这些关系可用于后续生成关系图谱,而不是简单的组织列表。</p></div></div>
|
||||
<div class="grid cols-3">${e.relationship_types.map(r=>`<div class="card"><h3>${esc(r.type)}</h3><p>${esc(r.explain)}</p><div class="pill-row"><span class="pill red">${esc(r.example)}</span></div></div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>关系网络文字版</h2></div></div>
|
||||
<div class="notice"><b>核心反战谱系:</b>VVAW → Veterans For Peace → About Face,并与MFSO、Gold Star Families形成战争代价网络。<br><b>选举与进步派谱系:</b>VoteVets ↔ Common Defense,连接民主党候选人、国会、州级选举和基层动员。<br><b>服务与福利谱系:</b>Swords to Plowshares连接VA、地方政府、住房、法律和医疗网络。<br><b>人权与劳工谱系:</b>VFAI连接难民与人权,UVC连接工会、公共部门、VA就业与服务。</div>
|
||||
`;
|
||||
}
|
||||
function renderOrgs(){
|
||||
const query = q();
|
||||
const orgs = DATA.organizations.filter(o=>!query || includesDeep(o,query));
|
||||
document.getElementById('panel-orgs').innerHTML = `
|
||||
<div class="section-title"><div><h2>核心组织资料库</h2><p>点击组织卡片进入结构化详情页。弹框不再展示JSON,而是按“基础资料—核心特征—议题—涉中涉台—叙事—研究重点—注意事项”展示。</p></div><span class="pill red">${orgs.length} 个结果</span></div>
|
||||
<div class="org-grid">${orgs.map(o=>orgCard(o)).join('')}</div>
|
||||
${orgs.length? '' : '<div class="empty">没有匹配的组织,请换一个关键词。</div>'}
|
||||
`;
|
||||
}
|
||||
function orgCard(o){
|
||||
const initials = o.abbr.split(/\s|\//)[0].slice(0,4);
|
||||
const b = o.priority.includes('第一')?'hot':(o.priority.includes('第二')?'warn':'');
|
||||
return `<div class="org-card" onclick="showOrg('${o.id}')"><div class="top"><div class="avatar">${esc(initials)}</div><div><div class="org-name">${esc(o.name)}</div><div class="org-zh">${esc(o.zh)}</div></div></div><div class="summary">${esc(o.positioning)}</div><div class="pill-row">${o.issues.slice(0,5).map(x=>`<span class="pill">${esc(x)}</span>`).join('')}</div><div class="org-meta"><span class="badge ${b}">${esc(o.priority)}</span><span class="badge ok">数据${esc(o.completeness)}</span><span class="badge">${esc(o.category)}</span></div></div>`
|
||||
}
|
||||
function showOrg(id){
|
||||
const o = DATA.organizations.find(x=>x.id===id); if(!o) return;
|
||||
openModal(`<div class="modal-head"><div class="modal-title"><h2>${esc(o.name)}</h2><p>${esc(o.zh)}|${esc(o.category)}|${esc(o.priority)}|数据完备度 ${esc(o.completeness)}</p></div><button class="close" onclick="closeModal()">×</button></div><div class="modal-body">
|
||||
<div class="detail-grid">${kv('法律形态',o.legal)+kv('成立时间',o.founded)+kv('活动地区',o.area)+kv('规模口径',o.scale)}</div>
|
||||
${section('基本定位', `<p>${esc(o.positioning)}</p>`)}
|
||||
${section('核心特点', list(o.features))}
|
||||
${section('核心议题', pills(o.issues,'red'))}
|
||||
${section('涉中涉台与对外政策价值', `<p>${esc(o.china_taiwan)}</p>`)}
|
||||
${section('政治叙事', `<p>${esc(o.narrative)}</p>`)}
|
||||
${section('后续研究重点', list(o.research_focus))}
|
||||
${section('研究注意事项', list(o.cautions))}
|
||||
</div>`)
|
||||
}
|
||||
function renderHistory(){
|
||||
const h = DATA.history;
|
||||
document.getElementById('panel-history').innerHTML = `
|
||||
<div class="section-title"><div><h2>历史演化与运动谱系</h2><p>${esc(h.core_judgment)}</p></div></div>
|
||||
<div class="grid cols-3">${h.stages.map(s=>`<div class="card"><h3>${esc(s.name)}</h3><div class="pill-row"><span class="pill red">${esc(s.period)}</span>${s.orgs.map(o=>`<span class="pill">${esc(o)}</span>`).join('')}</div><p style="margin-top:12px">${esc(s.summary)}</p><p style="margin-top:8px"><b>核心叙事:</b>${esc(s.narrative)}</p></div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>关键事件时间线</h2><p>点击事件查看历史意义和可入库字段。</p></div></div>
|
||||
<div class="timeline">${h.events.map((ev,i)=>`<div class="t-item" onclick="showEvent(${i})"><div class="t-year">${esc(ev.year)}|${esc(ev.org)}</div><div class="t-title">${esc(ev.title)}</div><div class="t-meaning">${esc(ev.meaning)}</div></div>`).join('')}</div>
|
||||
`;
|
||||
}
|
||||
function showEvent(i){const ev=DATA.history.events[i]; openModal(`<div class="modal-head"><div class="modal-title"><h2>${esc(ev.title)}</h2><p>${esc(ev.year)}|${esc(ev.org)}</p></div><button class="close" onclick="closeModal()">×</button></div><div class="modal-body">${section('阶段意义',`<p>${esc(ev.meaning)}</p>`)}${section('事件说明',`<p>${esc(ev.details)}</p>`)}${section('可入库字段', table(['字段','内容'], [['时间',esc(ev.year)],['组织',esc(ev.org)],['事件',esc(ev.title)],['意义',esc(ev.meaning)]]))}</div>`)}
|
||||
function renderIdentity(){
|
||||
const d = DATA.identity;
|
||||
document.getElementById('panel-identity').innerHTML = `
|
||||
<div class="section-title"><div><h2>人员结构与身份画像</h2><p>${esc(d.core_judgment)}</p></div></div>
|
||||
<div class="grid cols-3">${d.metrics.map(m=>`<div class="metric"><div class="value">${esc(m.value)}</div><div class="label">${esc(m.label)}</div></div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>重点人群分层</h2></div></div>
|
||||
<div class="grid cols-3">${d.groups.map(g=>`<div class="card"><h3>${esc(g.name)}</h3><p><b>代表组织:</b>${esc(g.orgs)}</p><p><b>画像特征:</b>${esc(g.traits)}</p><p><b>议题倾向:</b>${esc(g.issues)}</p></div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>心理结构</h2><p>这一部分用于解释为什么退伍军人身份能够转化为反战、福利、民主保护或身份平权叙事。</p></div></div>
|
||||
<div class="grid cols-3">${d.psychology.map(p=>`<div class="card"><h3>${esc(p.name)}</h3><p>${esc(p.explain)}</p></div>`).join('')}</div>
|
||||
`;
|
||||
}
|
||||
function renderIssues(){
|
||||
const d = DATA.issues;
|
||||
document.getElementById('panel-issues').innerHTML = `
|
||||
<div class="section-title"><div><h2>核心议题与政策主张</h2><p>${esc(d.core_judgment)}</p></div></div>
|
||||
<div class="notice"><b>最强共识议题:</b>${d.consensus.map(esc).join('、')}。<br><b>最易分歧议题:</b>${d.divisive.map(esc).join('、')}。</div>
|
||||
<div class="section-title"><div><h2>组织—议题矩阵</h2><p>点击卡片查看该议题的组织分布、主张方向和分歧点。</p></div></div>
|
||||
<div class="grid cols-3">${d.matrix.map((m,i)=>`<div class="matrix-card" onclick="showIssue(${i})"><h3>${esc(m.issue)}</h3><div class="orgs">${esc(m.orgs)}</div><p>${esc(m.position)}</p><div class="pill-row"><span class="pill ${m.consensus==='最高'?'green':m.consensus==='低'?'red':'blue'}">共识度:${esc(m.consensus)}</span></div></div>`).join('')}</div>
|
||||
`;
|
||||
}
|
||||
function showIssue(i){const m=DATA.issues.matrix[i]; openModal(`<div class="modal-head"><div class="modal-title"><h2>${esc(m.issue)}</h2><p>${esc(m.orgs)}|共识度:${esc(m.consensus)}</p></div><button class="close" onclick="closeModal()">×</button></div><div class="modal-body">${section('主张方向',`<p>${esc(m.position)}</p>`)}${section('主要组织',`<p>${esc(m.orgs)}</p>`)}${section('潜在分歧',`<p>${esc(m.friction)}</p>`)}${section('页面展示建议',`<p>可在此议题下继续挂接组织声明、国会倡导、社媒发声、候选人广告、公开信和政策文件。</p>`)}</div>`)}
|
||||
function renderChina(){
|
||||
const d = DATA.china_taiwan;
|
||||
document.getElementById('panel-china').innerHTML = `
|
||||
<div class="section-title"><div><h2>涉中涉台与对外政策立场</h2><p>${esc(d.core_judgment)}</p></div></div>
|
||||
<div class="grid cols-2">${d.routes.map(r=>`<div class="route"><h3>${esc(r.route)}</h3><div class="orgs">${esc(r.orgs)}</div><p><b>主要立场:</b>${esc(r.stance)}</p><p><b>重点事件:</b>${esc(r.events)}</p><p><b>研究风险:</b>${esc(r.risk)}</p></div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>事件级数据库字段</h2><p>涉中涉台不能只按组织印象判断,后续应逐事件收集原文证据。</p></div></div>
|
||||
${pills(d.event_fields,'blue')}
|
||||
<div class="section-title"><div><h2>需要重点补充的事件类别</h2></div></div>
|
||||
<div class="grid cols-3">${d.event_types.map(t=>`<div class="card"><h3>${esc(t.type)}</h3><p>${esc(t.need)}</p></div>`).join('')}</div>
|
||||
`;
|
||||
}
|
||||
function renderNarrative(){
|
||||
const d = DATA.narratives;
|
||||
document.getElementById('panel-narrative').innerHTML = `
|
||||
<div class="section-title"><div><h2>爱国主义重构与政治叙事</h2><p>${esc(d.core_judgment)}</p></div></div>
|
||||
<div class="grid cols-3">${d.frames.map((f,i)=>`<div class="matrix-card" onclick="showNarrative(${i})"><h3>${esc(f.frame)}</h3><div class="orgs">${esc(f.orgs)}</div><p>${esc(f.meaning)}</p>${pills(f.keywords,'purple')}</div>`).join('')}</div>
|
||||
<div class="section-title"><div><h2>传统爱国主义 vs 左翼退伍军人叙事</h2></div></div>
|
||||
${table(['对比项','传统爱国主义叙事','左翼退伍军人叙事'], d.comparison.map(x=>[esc(x.dimension),esc(x.traditional),esc(x.left)]))}
|
||||
<div class="section-title"><div><h2>社交媒体、认知安全、地方社会与趋势</h2><p>这些内容来自技能文件的扩展模块,用于增强页面信息密度。</p></div></div>
|
||||
<div class="grid cols-3">
|
||||
<div class="card"><h3>社交媒体生态</h3>${DATA.media_security_future.media_ecology.map(x=>`<p><b>${esc(x.type)}:</b>${esc(x.platforms)};${esc(x.style)}</p>`).join('')}</div>
|
||||
<div class="card"><h3>认知安全风险</h3>${list(DATA.media_security_future.cognitive_security)}</div>
|
||||
<div class="card"><h3>未来十年趋势</h3>${list(DATA.media_security_future.future_trends)}</div>
|
||||
</div>
|
||||
<div class="section-title"><div><h2>来源与核验提示</h2></div></div>
|
||||
<div class="notice source-box">${DATA.sources.map(s=>`<b>${esc(s.name)}:</b>${s.items.map(esc).join('、')}`).join('<br>')}</div>
|
||||
`;
|
||||
}
|
||||
function showNarrative(i){const f=DATA.narratives.frames[i]; openModal(`<div class="modal-head"><div class="modal-title"><h2>${esc(f.frame)}</h2><p>${esc(f.orgs)}</p></div><button class="close" onclick="closeModal()">×</button></div><div class="modal-body">${section('叙事含义',`<p>${esc(f.meaning)}</p>`)}${section('关键词',pills(f.keywords,'purple'))}${section('适合挂接的数据',`<p>可继续挂接组织口号、广告文本、官网使命表述、社媒高频词、演讲、公开信、活动海报和退伍军人证言。</p>`)}</div>`)}
|
||||
function openModal(html){document.getElementById('modal').innerHTML = html; document.getElementById('modalBackdrop').classList.add('open'); document.body.style.overflow='hidden';}
|
||||
function closeModal(){document.getElementById('modalBackdrop').classList.remove('open'); document.body.style.overflow='';}
|
||||
function backdropClose(e){if(e.target.id==='modalBackdrop') closeModal();}
|
||||
document.addEventListener('keydown',e=>{if(e.key==='Escape') closeModal();});
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>台湾涉两岸政治叙事监测专题</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f6f2ee;
|
||||
--panel: #fffaf6;
|
||||
--panel2: #ffffff;
|
||||
--ink: #201815;
|
||||
--muted: #6f625c;
|
||||
--line: #dbcfc8;
|
||||
--line2: #bdaaa0;
|
||||
--accent: #8f1f1b;
|
||||
--accent2: #b63a2f;
|
||||
--soft: #f1e2dc;
|
||||
--soft2: #ead6cf;
|
||||
--warn: #8c5a13;
|
||||
--shadow: 0 16px 42px rgba(74, 37, 29, 0.12);
|
||||
--radius: 18px;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html { scroll-behavior:smooth; }
|
||||
body {
|
||||
margin:0; font-family: "Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC", Arial, sans-serif;
|
||||
color:var(--ink); background:
|
||||
radial-gradient(circle at 12% -8%, rgba(143,31,27,.20), transparent 28%),
|
||||
radial-gradient(circle at 95% 2%, rgba(182,58,47,.11), transparent 24%),
|
||||
linear-gradient(180deg, #fff8f3 0%, var(--bg) 42%, #f4ece8 100%);
|
||||
}
|
||||
header.hero {
|
||||
padding: 34px 34px 18px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.hero-inner { max-width: 1500px; margin:0 auto; }
|
||||
.eyebrow {
|
||||
display:inline-flex; gap:8px; align-items:center; padding:7px 12px; border:1px solid var(--line2);
|
||||
border-radius:999px; background:rgba(255,255,255,.72); color:var(--accent); font-weight:700; font-size:13px;
|
||||
}
|
||||
h1 { margin:14px 0 10px; font-size:34px; letter-spacing:.5px; line-height:1.16; }
|
||||
.subtitle { max-width:1050px; color:var(--muted); line-height:1.75; font-size:15px; }
|
||||
.boundary {
|
||||
margin-top:14px; padding:14px 16px; border-left:5px solid var(--accent); background:rgba(255,255,255,.72);
|
||||
border-radius:14px; color:#4a332d; line-height:1.7;
|
||||
}
|
||||
.top-meta { display:flex; flex-wrap:wrap; gap:10px; margin-top:18px; }
|
||||
.chip {
|
||||
display:inline-flex; align-items:center; gap:6px; border:1px solid var(--line); background:var(--panel2);
|
||||
color:#4b3933; border-radius:999px; padding:7px 11px; font-size:12px; font-weight:650;
|
||||
}
|
||||
.toolbar-wrap { position:sticky; top:0; z-index:20; background:rgba(246,242,238,.92); backdrop-filter: blur(10px); border-bottom:1px solid var(--line); }
|
||||
.toolbar { max-width:1500px; margin:0 auto; padding:12px 34px; display:flex; gap:12px; align-items:center; flex-wrap:wrap; }
|
||||
.tabs { display:flex; gap:8px; overflow:auto; flex:1; padding-bottom:2px; }
|
||||
.tab-btn {
|
||||
border:1px solid var(--line2); background:var(--panel); color:#3a2a25; border-radius:999px; padding:10px 15px;
|
||||
cursor:pointer; white-space:nowrap; font-weight:750; font-size:13px; transition:.18s ease;
|
||||
}
|
||||
.tab-btn.active, .tab-btn:hover { background:var(--accent); color:white; border-color:var(--accent); }
|
||||
.searchbar { display:flex; gap:8px; align-items:center; min-width:290px; }
|
||||
.searchbar input, select {
|
||||
width:100%; border:1px solid var(--line2); border-radius:12px; padding:10px 12px; background:#fff; color:var(--ink);
|
||||
}
|
||||
main { max-width:1500px; margin:0 auto; padding:24px 34px 54px; }
|
||||
.tab-pane { display:none; animation: fadeIn .18s ease; }
|
||||
.tab-pane.active { display:block; }
|
||||
@keyframes fadeIn { from {opacity:.35; transform:translateY(4px)} to {opacity:1; transform:none} }
|
||||
.section-title { display:flex; align-items:flex-end; justify-content:space-between; gap:18px; margin:0 0 15px; }
|
||||
.section-title h2 { margin:0; font-size:24px; }
|
||||
.section-title p { margin:6px 0 0; color:var(--muted); line-height:1.7; }
|
||||
.grid { display:grid; gap:16px; }
|
||||
.grid.cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.grid.cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.grid.cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.card {
|
||||
background:rgba(255,255,255,.86); border:1px solid var(--line); border-radius:var(--radius); padding:18px; box-shadow: var(--shadow);
|
||||
}
|
||||
.card.plain { box-shadow:none; background:var(--panel); }
|
||||
.card h3 { margin:0 0 10px; font-size:18px; }
|
||||
.card h4 { margin:0 0 8px; font-size:15px; }
|
||||
.card p { color:#4e3e38; line-height:1.75; margin:8px 0; }
|
||||
.kpi { min-height:120px; position:relative; overflow:hidden; }
|
||||
.kpi::after { content:""; position:absolute; width:110px; height:110px; right:-40px; top:-45px; border-radius:50%; background:rgba(143,31,27,.08); }
|
||||
.kpi .num { font-size:32px; font-weight:900; color:var(--accent); margin-top:8px; }
|
||||
.kpi .label { color:var(--muted); font-size:13px; line-height:1.5; }
|
||||
.tagrow { display:flex; flex-wrap:wrap; gap:7px; margin-top:10px; }
|
||||
.tag { display:inline-flex; padding:5px 9px; border-radius:999px; background:var(--soft); border:1px solid #e3cbc2; color:#5a2b25; font-size:12px; font-weight:650; }
|
||||
.tag.risk5 { background:#8f1f1b; color:#fff; border-color:#8f1f1b; }
|
||||
.tag.risk4 { background:#c46845; color:#fff; border-color:#c46845; }
|
||||
.tag.risk3 { background:#e5bd76; color:#3c2a14; border-color:#e5bd76; }
|
||||
.tag.risk2 { background:#ede0bd; color:#3c2a14; }
|
||||
.tag.risk1 { background:#e5efe1; color:#21401d; }
|
||||
.filters { display:flex; gap:10px; flex-wrap:wrap; margin:0 0 16px; }
|
||||
.filters select, .filters input { width:auto; min-width:190px; }
|
||||
.timeline { position:relative; margin-left:8px; }
|
||||
.timeline::before { content:""; position:absolute; left:15px; top:0; bottom:0; width:2px; background:var(--line2); }
|
||||
.event-card { display:grid; grid-template-columns:42px 1fr; gap:13px; margin-bottom:14px; }
|
||||
.event-dot { width:32px; height:32px; border-radius:50%; background:var(--accent); color:white; display:flex; align-items:center; justify-content:center; font-size:12px; font-weight:900; position:relative; z-index:1; box-shadow:0 6px 18px rgba(143,31,27,.22); }
|
||||
.event-body { background:#fff; border:1px solid var(--line); border-radius:17px; padding:16px; box-shadow: 0 10px 26px rgba(74, 37, 29, 0.08); }
|
||||
.event-head { display:flex; gap:10px; justify-content:space-between; align-items:flex-start; }
|
||||
.event-date { color:var(--accent); font-weight:850; font-size:13px; white-space:nowrap; }
|
||||
.btn {
|
||||
border:1px solid var(--accent); background:var(--accent); color:#fff; border-radius:11px; padding:8px 11px; cursor:pointer; font-weight:750;
|
||||
}
|
||||
.btn.ghost { background:#fff; color:var(--accent); }
|
||||
.detail-grid { display:grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap:12px; margin-top:12px; }
|
||||
.detail-box { border:1px solid var(--line); border-radius:14px; padding:12px; background:#fffaf7; }
|
||||
.detail-box b { color:var(--accent); display:block; margin-bottom:6px; }
|
||||
ul.clean { margin:8px 0 0 18px; padding:0; }
|
||||
ul.clean li { margin:5px 0; line-height:1.65; }
|
||||
.matrix-table, .data-table { width:100%; border-collapse:separate; border-spacing:0; overflow:hidden; border:1px solid var(--line); border-radius:16px; background:#fff; }
|
||||
.matrix-table th, .matrix-table td, .data-table th, .data-table td { border-bottom:1px solid var(--line); border-right:1px solid var(--line); padding:12px; vertical-align:top; line-height:1.65; }
|
||||
.matrix-table th, .data-table th { background:#6f1714; color:#fff; text-align:left; }
|
||||
.matrix-table tr:last-child td, .data-table tr:last-child td { border-bottom:none; }
|
||||
.matrix-table td:last-child, .matrix-table th:last-child, .data-table td:last-child, .data-table th:last-child { border-right:none; }
|
||||
.level-cell { font-weight:800; color:var(--accent); white-space:nowrap; }
|
||||
.narrative-card { min-height: 330px; display:flex; flex-direction:column; }
|
||||
.narrative-card .grow { flex:1; }
|
||||
.two-col-list { display:grid; grid-template-columns:1fr 1fr; gap:10px; }
|
||||
.mini-title { font-weight:850; color:var(--accent); margin-bottom:5px; }
|
||||
.source-level { width:46px; height:46px; border-radius:50%; display:flex; align-items:center; justify-content:center; background:var(--accent); color:#fff; font-weight:900; }
|
||||
.actor-icon { width:44px; height:44px; border-radius:14px; background:var(--soft); color:var(--accent); display:flex; align-items:center; justify-content:center; font-weight:900; border:1px solid #dfc7bf; }
|
||||
.actor-row { display:flex; gap:12px; align-items:flex-start; }
|
||||
.modal-backdrop { position:fixed; inset:0; display:none; align-items:center; justify-content:center; background:rgba(30,18,14,.56); z-index:50; padding:24px; }
|
||||
.modal-backdrop.active { display:flex; }
|
||||
.modal { width:min(980px, 96vw); max-height:88vh; overflow:auto; background:#fffdfa; border-radius:22px; border:1px solid var(--line); box-shadow:0 30px 90px rgba(0,0,0,.32); }
|
||||
.modal-head { position:sticky; top:0; background:#fffdfa; border-bottom:1px solid var(--line); padding:18px 20px; display:flex; justify-content:space-between; gap:12px; align-items:flex-start; }
|
||||
.modal-head h3 { margin:0; font-size:21px; }
|
||||
.modal-content { padding:20px; }
|
||||
.close { border:0; background:var(--soft); color:var(--accent); border-radius:999px; padding:8px 12px; font-weight:900; cursor:pointer; }
|
||||
.empty { padding:28px; border:1px dashed var(--line2); border-radius:18px; background:#fff; color:var(--muted); text-align:center; }
|
||||
.schema-code { white-space:pre-wrap; word-break:break-word; background:#231b18; color:#fff8ef; border-radius:16px; padding:16px; line-height:1.65; font-size:13px; max-height:460px; overflow:auto; }
|
||||
.badge-line { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
|
||||
.notice { border:1px solid #e6c7aa; background:#fff7e9; color:#5a371d; border-radius:15px; padding:14px 16px; line-height:1.7; }
|
||||
footer { max-width:1500px; margin:0 auto; padding:0 34px 40px; color:var(--muted); font-size:12px; line-height:1.8; }
|
||||
@media (max-width: 980px) {
|
||||
header.hero, .toolbar, main, footer { padding-left:18px; padding-right:18px; }
|
||||
.grid.cols-2, .grid.cols-3, .grid.cols-4, .detail-grid, .two-col-list { grid-template-columns:1fr; }
|
||||
.searchbar { min-width:100%; }
|
||||
.event-head { flex-direction:column; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="hero">
|
||||
<div class="hero-inner">
|
||||
<div class="eyebrow">专题研究平台 · 精简栏目版 v0.3</div>
|
||||
<h1>台湾涉两岸政治叙事监测专题</h1>
|
||||
<div class="subtitle">公开资料监测、叙事结构拆解、平台传播观察、群体匿名反应、竞争叙事识别与主体节点观察</div>
|
||||
<div class="boundary"><b>研究边界:</b>仅用于公开资料研究和舆情态势理解;不生成定向影响、群体操控、个人画像或宣传执行方案。</div>
|
||||
<div class="top-meta" id="topMeta"></div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="toolbar-wrap">
|
||||
<div class="toolbar">
|
||||
<div class="tabs" id="tabs"></div>
|
||||
<div class="searchbar"><input id="globalSearch" placeholder="全局搜索:事件、叙事、平台、主体、关键词" /></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<main>
|
||||
<section class="tab-pane active" id="pane-overview"></section>
|
||||
<section class="tab-pane" id="pane-events"></section>
|
||||
<section class="tab-pane" id="pane-narratives"></section>
|
||||
<section class="tab-pane" id="pane-structures"></section>
|
||||
<section class="tab-pane" id="pane-platforms"></section>
|
||||
<section class="tab-pane" id="pane-audiences"></section>
|
||||
<section class="tab-pane" id="pane-competing"></section>
|
||||
<section class="tab-pane" id="pane-actors"></section>
|
||||
</main>
|
||||
|
||||
<div class="modal-backdrop" id="modalBackdrop">
|
||||
<div class="modal">
|
||||
<div class="modal-head"><div><h3 id="modalTitle"></h3><div id="modalSub" class="subtitle"></div></div><button class="close" onclick="closeModal()">关闭</button></div>
|
||||
<div class="modal-content" id="modalContent"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
本页面为单文件离线版,已移除来源审查、风险评估与 Schema 栏目。建议正式研究时继续补充每条事件的原始链接、样本截图、平台互动量和跨平台传播链。
|
||||
</footer>
|
||||
|
||||
<script id="DATA" type="application/json">{"metadata":{"title":"台湾涉两岸政治叙事监测专题","version":"v0.3-content-only","generated_at":"2026-06-25 16:10 JST","time_range":"2024-01-13 至 2026-06-25","timezone":"Asia/Tokyo","orientation":"公开资料监测、叙事结构拆解、平台传播观察、群体匿名反应、竞争叙事识别与主体节点观察","safety_boundary":"仅用于公开资料研究和舆情态势理解;不生成定向影响、群体操控、个人画像或宣传执行方案。","recommended_columns":["专题总览","核心叙事库","叙事结构拆解","触发事件时间线","平台传播生态","受众反应观察","竞争叙事分析","反弹机制观察","关键主体与传播节点"],"update_cycle":"建议日报记录事件与样本,周报比较平台与叙事变化,月报归纳趋势与栏目数据缺口。","display_principles":["字段中文化","信息卡片化","长字段弹窗化","研究边界显性化","数据缺口可追踪"]},"dashboard":{"summary_cards":[{"label":"事件样本","value":"16","note":"覆盖选举、演训、国会、国安、国防预算等触发点"},{"label":"核心叙事","value":"10","note":"含疑美、战争风险、绿色威权、维持现状等"},{"label":"观察平台","value":"9","note":"覆盖公开平台、私域转传样本与跨境平台"},{"label":"受众群体","value":"12","note":"以匿名群体层级呈现关切、共鸣与反弹逻辑"},{"label":"主体节点","value":"16","note":"覆盖官方机构、政党、媒体、研究与事实查核组织"}],"current_focus":["赖清德政府两岸与国安表述变化","台海军事演训与灰色地带活动对战争风险叙事的激活","国会改革、罢免、司法案件带来的绿色威权/程序正义叙事对撞","国防预算、民防韧性和兵役议题对青年与风险家庭的影响","事实查核、AI假信息和社交平台再框架化机制"]},"events":[{"id":"E001","date":"2024-01-13","title":"台湾总统与立委选举","type":"选举政治","risk_level":4,"confidence":"高","source_status":"需在正式版回填原始链接","triggered_narratives":["民主韧性","疑美论","战争风险","选举干预"],"platforms":["YouTube","Facebook","LINE","PTT","Dcard","Threads"],"actors":["总统府","民进党","国民党","民众党","事实查核机构","主流媒体"],"summary":"赖清德胜选,民进党保住总统职位,但立法院形成朝小野大格局。选举期间战争风险、外部因素、假信息与选举干预等叙事被持续激活。","observation_points":["总统胜选与国会失去多数同时发生,形成后续国会叙事冲突的制度背景","选举信息战议题强化事实查核与平台治理的重要性","战争风险与疑美论在选前选后均有延续性"],"risk_dimensions":{"content":4,"spread":4,"audience":4,"political":5},"risk_label":"高风险","research_value":["可作为叙事触发点观察不同平台的框架转换","可用于比对官方定性、媒体再框架和社群反应之间的差异","可继续补充原始链接、热度曲线、事实查核与跨平台传播链"],"data_to_add":["一手公开来源链接","主流媒体报道链接","平台样本截图或标题","热度指标","事实查核记录","后续政策或舆论影响"],"risk_dimension_text":["content:4/5","spread:4/5","audience:4/5","political:5/5"]},{"id":"E002","date":"2024-01","title":"选举期间 AI 与假信息争议","type":"信息战/假信息","risk_level":4,"confidence":"中","source_status":"需回填查核报告、研究报告与平台样本链接","triggered_narratives":["AI假信息","认知战","选举干预","境外信息操纵"],"platforms":["LINE","YouTube","TikTok/Reels/Shorts","Facebook","PTT","X"],"actors":["事实查核机构","研究机构","社交平台","媒体"],"summary":"围绕2024年台湾选举,AI生成内容、深伪、断章取义视频、图卡和私域转传内容成为重要监测对象。","observation_points":["应区分真实政治表达、本地党派攻防和外部信息操纵","LINE私域样本需要依赖查核机构和用户提交样本","短影音平台更容易出现低上下文、强情绪内容"],"risk_dimensions":{"content":5,"spread":4,"audience":4,"operation":5},"risk_label":"高风险","research_value":["可作为叙事触发点观察不同平台的框架转换","可用于比对官方定性、媒体再框架和社群反应之间的差异","可继续补充原始链接、热度曲线、事实查核与跨平台传播链"],"data_to_add":["一手公开来源链接","主流媒体报道链接","平台样本截图或标题","热度指标","事实查核记录","后续政策或舆论影响"],"risk_dimension_text":["content:5/5","spread:4/5","audience:4/5","operation:5/5"]},{"id":"E003","date":"2024-05-20","title":"赖清德就职演说","type":"两岸政治","risk_level":5,"confidence":"高","source_status":"需回填总统府原文、大陆回应与媒体报道链接","triggLine truncated
|
||||
<script>
|
||||
const db = JSON.parse(document.getElementById('DATA').textContent);
|
||||
const panes = [
|
||||
['overview','总览仪表盘'], ['events','事件时间线'], ['narratives','核心叙事库'], ['structures','叙事结构拆解'],
|
||||
['platforms','平台传播生态'], ['audiences','受众反应观察'], ['competing','竞争叙事'], ['actors','主体与传播节点']
|
||||
];
|
||||
let state = { search:'', eventRisk:'all', eventType:'all' };
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = s => String(s ?? '').replace(/[&<>'"]/g, c => ({'&':'&','<':'<','>':'>',"'":''','"':'"'}[c]));
|
||||
const list = arr => Array.isArray(arr) && arr.length ? '<ul class="clean">'+arr.map(x=>'<li>'+esc(x)+'</li>').join('')+'</ul>' : '<span class="muted">暂无</span>';
|
||||
const tags = (arr, cls='') => Array.isArray(arr) && arr.length ? '<div class="tagrow">'+arr.map(x=>'<span class="tag '+cls+'">'+esc(x)+'</span>').join('')+'</div>' : '';
|
||||
const riskTag = lv => '<span class="tag risk'+esc(lv)+'">风险 '+esc(lv)+' / 5</span>';
|
||||
function contains(obj, q) { return !q || JSON.stringify(obj).toLowerCase().includes(q.toLowerCase()); }
|
||||
function sectionTitle(title, desc) { return `<div class="section-title"><div><h2>${esc(title)}</h2><p>${esc(desc)}</p></div></div>`; }
|
||||
function card(title, body, extra='') { return `<div class="card"><h3>${esc(title)}</h3>${body}${extra}</div>`; }
|
||||
|
||||
function initTabs() {
|
||||
$('tabs').innerHTML = panes.map(([id,name]) => `<button class="tab-btn ${id==='overview'?'active':''}" data-tab="${id}">${name}</button>`).join('');
|
||||
document.querySelectorAll('.tab-btn').forEach(b => b.addEventListener('click', () => {
|
||||
document.querySelectorAll('.tab-btn').forEach(x=>x.classList.remove('active'));
|
||||
b.classList.add('active');
|
||||
document.querySelectorAll('.tab-pane').forEach(x=>x.classList.remove('active'));
|
||||
$('pane-'+b.dataset.tab).classList.add('active');
|
||||
}));
|
||||
}
|
||||
function initMeta() {
|
||||
$('topMeta').innerHTML = [
|
||||
['时间范围', db.metadata.time_range], ['时区', db.metadata.timezone || 'Asia/Tokyo'], ['版本', db.metadata.version], ['生成时间', db.metadata.generated_at]
|
||||
].map(([k,v])=>`<span class="chip"><b>${esc(k)}:</b>${esc(v)}</span>`).join('');
|
||||
}
|
||||
|
||||
function renderOverview() {
|
||||
const counts = db.module_counts || [];
|
||||
const kpis = counts.map(m => `<div class="card kpi"><div class="label">${esc(m.module)}</div><div class="num">${esc(m.count)}</div><div class="label">${esc(m.status)}</div></div>`).join('');
|
||||
const focus = (db.dashboard?.current_focus || []).map(f => `<div class="card plain"><h4>${esc(f.title || f.name || '重点')}</h4><p>${esc(f.desc || f.description || f.summary || f)}</p></div>`).join('');
|
||||
const map = (db.research_map || []).map(m => `<div class="card plain"><h3>${esc(m.name)}</h3><p>${esc(m.purpose)}</p>${tags(m.core_fields)}</div>`).join('');
|
||||
$('pane-overview').innerHTML = sectionTitle('总览仪表盘','集中展示专题边界、数据模块、栏目结构和当前可继续补充的数据方向。') +
|
||||
`<div class="grid cols-4">${kpis}</div>`+
|
||||
`<div style="height:18px"></div><div class="notice"><b>更新机制:</b>${esc(db.metadata.update_cycle)}<br><b>页面设计:</b>${esc((db.metadata.display_principles||[]).join('、'))}</div>`+
|
||||
`<div style="height:18px"></div>`+
|
||||
sectionTitle('专题栏目结构','每个栏目都对应一个可维护的数据模块,避免页面只展示标题而缺少内容。')+
|
||||
`<div class="grid cols-4">${map}</div>`+
|
||||
(focus ? `<div style="height:18px"></div>${sectionTitle('当前重点','从专题数据中抽取的近期观察方向。')}<div class="grid cols-3">${focus}</div>` : '');
|
||||
}
|
||||
|
||||
function renderEvents() {
|
||||
const types = [...new Set(db.events.map(e=>e.type))];
|
||||
let events = db.events.filter(e => contains(e, state.search));
|
||||
if (state.eventRisk !== 'all') events = events.filter(e => String(e.risk_level) === state.eventRisk);
|
||||
if (state.eventType !== 'all') events = events.filter(e => e.type === state.eventType);
|
||||
events.sort((a,b)=>String(b.date).localeCompare(String(a.date)));
|
||||
const controls = `<div class="filters"><select id="eventRisk"><option value="all">全部风险等级</option>${[5,4,3,2,1].map(x=>`<option value="${x}" ${state.eventRisk==String(x)?'selected':''}>风险 ${x} / 5</option>`).join('')}</select><select id="eventType"><option value="all">全部事件类型</option>${types.map(t=>`<option value="${esc(t)}" ${state.eventType===t?'selected':''}>${esc(t)}</option>`).join('')}</select></div>`;
|
||||
const rows = events.length ? `<div class="timeline">${events.map(e=>`<div class="event-card"><div class="event-dot">${esc(e.risk_level)}</div><div class="event-body"><div class="event-head"><div><div class="event-date">${esc(e.date)} · ${esc(e.type)}</div><h3>${esc(e.title)}</h3></div><div>${riskTag(e.risk_level)}</div></div><p>${esc(e.summary)}</p>${tags(e.triggered_narratives)}<div class="detail-grid"><div class="detail-box"><b>观察要点</b>${list(e.observation_points)}</div><div class="detail-box"><b>风险维度</b>${tags(e.risk_dimension_text)}</div></div><div class="tagrow"><button class="btn ghost" onclick="openEvent('${esc(e.id)}')">查看完整事件卡</button></div></div></div>`).join('')}</div>` : '<div class="empty">没有匹配事件。</div>';
|
||||
$('pane-events').innerHTML = sectionTitle('事件时间线','按时间顺序展示叙事触发事件,每张事件卡都保留摘要、观察要点、触发叙事、平台和风险维度。') + controls + rows;
|
||||
$('eventRisk').onchange = e => { state.eventRisk=e.target.value; renderEvents(); };
|
||||
$('eventType').onchange = e => { state.eventType=e.target.value; renderEvents(); };
|
||||
}
|
||||
|
||||
function renderNarratives() {
|
||||
const items = db.narratives.filter(n=>contains(n,state.search));
|
||||
const html = items.length ? `<div class="grid cols-3">${items.map(n=>`<div class="card narrative-card"><div class="badge-line"><h3 style="margin-right:auto">${esc(n.name)}</h3>${riskTag(n.risk_level)}</div><p><b>核心命题:</b>${esc(n.core_claim)}</p>${tags(n.keywords)}<div class="grow"><div class="detail-grid"><div class="detail-box"><b>常见表达</b>${list(n.common_forms)}</div><div class="detail-box"><b>触发事件</b>${list(n.trigger_events)}</div></div></div><div class="tagrow"><button class="btn ghost" onclick="openNarrative('${esc(n.id)}')">查看叙事详情</button></div></div>`).join('')}</div>` : '<div class="empty">没有匹配叙事。</div>';
|
||||
$('pane-narratives').innerHTML = sectionTitle('核心叙事库','展示每类叙事的核心命题、关键词、常见表达、触发事件、反叙事、反弹风险和数据缺口。') + html;
|
||||
}
|
||||
|
||||
function renderStructures() {
|
||||
const items = db.narratives.filter(n=>contains(n,state.search));
|
||||
$('pane-structures').innerHTML = sectionTitle('叙事结构拆解','将叙事拆成问题定义、责任归因、情绪机制、道德框架、反叙事与数据需求,便于研究而非只看口号。')+
|
||||
(items.length ? `<div class="grid cols-2">${items.map(n=>`<div class="card"><div class="badge-line"><h3 style="margin-right:auto">${esc(n.name)}</h3>${riskTag(n.risk_level)}</div><p><b>核心命题:</b>${esc(n.core_claim)}</p><div class="detail-grid">${(n.structure_list||[]).map(s=>`<div class="detail-box"><b>${esc(s.label)}</b><p>${esc(s.value)}</p></div>`).join('')}</div><div class="detail-grid"><div class="detail-box"><b>反叙事</b>${list(n.counter_narratives)}</div><div class="detail-box"><b>反弹风险</b>${list(n.backlash_risks)}</div><div class="detail-box"><b>数据缺口</b>${list(n.data_needs)}</div><div class="detail-box"><b>样本采集字段</b>${list(n.sample_collection_fields)}</div></div></div>`).join('')}</div>` : '<div class="empty">没有匹配结构。</div>');
|
||||
}
|
||||
|
||||
function renderPlatforms() {
|
||||
const items = db.platforms.filter(p=>contains(p,state.search));
|
||||
$('pane-platforms').innerHTML = sectionTitle('平台传播生态','将平台差异转化为可采集字段:内容形态、叙事类型、监测字段、风险点和分析注意事项。')+
|
||||
(items.length ? `<div class="grid cols-3">${items.map(p=>`<div class="card"><h3>${esc(p.name)}</h3><div class="detail-box"><b>内容形态</b>${list(p.content_forms)}</div><div class="detail-box"><b>高频叙事</b>${list(p.high_frequency_narratives)}</div><div class="detail-box"><b>监测字段</b>${list(p.monitor_fields)}</div><div class="detail-box"><b>风险点</b>${list(p.risk_points)}</div><div class="detail-box"><b>样本字段</b>${list(p.sample_fields)}</div><div class="detail-box"><b>分析注意</b>${list(p.analysis_notes)}</div></div>`).join('')}</div>` : '<div class="empty">没有匹配平台。</div>');
|
||||
}
|
||||
|
||||
function renderAudiences() {
|
||||
const items = db.audiences.filter(a=>contains(a,state.search));
|
||||
$('pane-audiences').innerHTML = sectionTitle('受众反应观察','只做匿名群体层级观察:主要关切、共鸣模块、反感模块、平台分布与伦理边界。')+
|
||||
(items.length ? `<div class="grid cols-3">${items.map(a=>`<div class="card"><h3>${esc(a.group)}</h3><p><b>反应类型:</b>${esc(a.reaction_type)}</p><div class="detail-box"><b>主要关切</b>${list(a.concerns)}</div><div class="detail-grid"><div class="detail-box"><b>容易共鸣</b>${list(a.accepted_modules)}</div><div class="detail-box"><b>容易反感</b>${list(a.rejected_modules)}</div></div><div class="detail-box"><b>观察平台</b>${tags(a.platforms)}</div><div class="detail-box"><b>伦理边界</b><p>${esc(a.ethics || a.observation_rule)}</p></div></div>`).join('')}</div>` : '<div class="empty">没有匹配群体。</div>');
|
||||
}
|
||||
|
||||
function renderCompeting() {
|
||||
const items = db.competing_narratives.filter(c=>contains(c,state.search));
|
||||
$('pane-competing').innerHTML = sectionTitle('竞争叙事分析','呈现不同叙事之间如何互相对抗、校正或引发反弹。')+
|
||||
(items.length ? `<div class="grid cols-2">${items.map(c=>`<div class="card"><h3>${esc(c.name)}</h3><p><b>核心主张:</b>${esc(c.core_claim)}</p><div class="detail-grid"><div class="detail-box"><b>主要对抗对象</b>${list(c.against)}</div><div class="detail-box"><b>典型证据来源</b>${list(c.evidence_sources)}</div><div class="detail-box"><b>反弹风险</b><p>${esc(c.risk)}</p></div><div class="detail-box"><b>待补数据</b>${list(c.data_needs)}</div></div></div>`).join('')}</div>` : '<div class="empty">没有匹配竞争叙事。</div>');
|
||||
}
|
||||
|
||||
function renderActors() {
|
||||
const items = db.actors.filter(a=>contains(a,state.search));
|
||||
$('pane-actors').innerHTML = sectionTitle('主体与传播节点','把公开机构、政党、媒体、事实查核机构、研究机构与国际媒体作为可观察节点管理。')+
|
||||
(items.length ? `<div class="grid cols-3">${items.map(a=>`<div class="card"><div class="actor-row"><div class="actor-icon">${esc((a.name||'?').slice(0,1))}</div><div><h3>${esc(a.name)}</h3><div class="tagrow"><span class="tag">${esc(a.type)}</span></div></div></div><p><b>主要角色:</b>${esc(a.role)}</p><div class="detail-box"><b>议题范围</b>${list(a.issues)}</div><div class="detail-box"><b>采集字段</b>${list(a.collect_fields)}</div><div class="detail-box"><b>监测维度</b>${list(a.monitor_dimensions)}</div><div class="detail-box"><b>边界提示</b><p>${esc(a.boundary_note)}</p></div></div>`).join('')}</div>` : '<div class="empty">没有匹配主体。</div>');
|
||||
}
|
||||
|
||||
|
||||
function openModal(title, sub, content) {
|
||||
$('modalTitle').innerHTML = esc(title); $('modalSub').innerHTML = esc(sub || ''); $('modalContent').innerHTML = content; $('modalBackdrop').classList.add('active');
|
||||
}
|
||||
function closeModal() { $('modalBackdrop').classList.remove('active'); }
|
||||
$('modalBackdrop').addEventListener('click', e => { if(e.target.id === 'modalBackdrop') closeModal(); });
|
||||
function openEvent(id) {
|
||||
const e = db.events.find(x=>x.id===id); if(!e) return;
|
||||
openModal(e.title, `${e.date} · ${e.type} · 风险 ${e.risk_level}/5 · 信心:${e.confidence}`,
|
||||
`<p>${esc(e.summary)}</p><div class="detail-grid"><div class="detail-box"><b>触发叙事</b>${list(e.triggered_narratives)}</div><div class="detail-box"><b>传播平台</b>${list(e.platforms)}</div><div class="detail-box"><b>相关主体</b>${list(e.actors)}</div><div class="detail-box"><b>观察要点</b>${list(e.observation_points)}</div><div class="detail-box"><b>风险维度</b>${list(e.risk_dimension_text)}</div><div class="detail-box"><b>研究价值</b>${list(e.research_value)}</div><div class="detail-box"><b>后续需补数据</b>${list(e.data_to_add)}</div><div class="detail-box"><b>来源状态</b><p>${esc(e.source_status)}</p></div></div>`);
|
||||
}
|
||||
function openNarrative(id) {
|
||||
const n = db.narratives.find(x=>x.id===id); if(!n) return;
|
||||
openModal(n.name, `风险 ${n.risk_level}/5 · ${n.id}`,
|
||||
`<p><b>核心命题:</b>${esc(n.core_claim)}</p>${tags(n.keywords)}<div class="detail-grid"><div class="detail-box"><b>常见表达</b>${list(n.common_forms)}</div><div class="detail-box"><b>触发事件</b>${list(n.trigger_events)}</div>${(n.structure_list||[]).map(s=>`<div class="detail-box"><b>${esc(s.label)}</b><p>${esc(s.value)}</p></div>`).join('')}<div class="detail-box"><b>竞争/反叙事</b>${list(n.counter_narratives)}</div><div class="detail-box"><b>反弹风险</b>${list(n.backlash_risks)}</div><div class="detail-box"><b>数据缺口</b>${list(n.data_needs)}</div><div class="detail-box"><b>字段说明</b>${Object.entries(n.field_notes||{}).map(([k,v])=>`<p><b>${esc(k)}:</b>${esc(v)}</p>`).join('')}</div></div>`);
|
||||
}
|
||||
|
||||
function renderAll() { renderOverview(); renderEvents(); renderNarratives(); renderStructures(); renderPlatforms(); renderAudiences(); renderCompeting(); renderActors(); }
|
||||
$('globalSearch').addEventListener('input', e => { state.search = e.target.value.trim(); renderAll(); });
|
||||
initTabs(); initMeta(); renderAll();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>美国涉华决策咨询群体专题库</title>
|
||||
<style>
|
||||
:root{--bg:#f6f7f9;--panel:#fff;--text:#1f2933;--muted:#5b6573;--line:#d8dee8;--red:#8b1e1e;--red2:#5f1515;--gold:#c9a227;--green:#2f6f5e;--blue:#245c7a;--purple:#6b4e9b;--tag:#f1f3f6;--shadow:0 12px 30px rgba(25,35,55,.08);--radius:16px}*{box-sizing:border-box}body{margin:0;font-family:"Microsoft YaHei","PingFang SC","Noto Sans CJK SC",Arial,sans-serif;background:radial-gradient(circle at 12% 0%,rgba(139,30,30,.16),transparent 25%),linear-gradient(180deg,#fff,var(--bg) 280px);color:var(--text)}.app{max-width:1440px;margin:0 auto;padding:24px}.hero{background:linear-gradient(135deg,var(--red2),var(--red));color:#fff;border-radius:24px;padding:28px 32px;box-shadow:var(--shadow);position:relative;overflow:hidden}.hero:after{content:"";position:absolute;right:-80px;top:-80px;width:260px;height:260px;border:36px solid rgba(255,255,255,.08);border-radius:50%}.hero h1{margin:0 0 8px;font-size:32px;letter-spacing:.5px}.hero p{margin:0;color:rgba(255,255,255,.86);line-height:1.65;max-width:980px}.meta-row{display:flex;flex-wrap:wrap;gap:8px;margin-top:18px}.hero-badge{padding:6px 10px;border:1px solid rgba(255,255,255,.35);border-radius:999px;font-size:12px;background:rgba(255,255,255,.08)}.search-panel{margin:18px 0 14px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:14px;display:grid;grid-template-columns:1fr auto auto;gap:12px;box-shadow:var(--shadow);align-items:center}.search-panel input,.search-panel select{border:1px solid var(--line);border-radius:12px;padding:12px 14px;font-size:14px;outline:none;background:#fff}.search-panel input:focus,.search-panel select:focus{border-color:rgba(139,30,30,.55);box-shadow:0 0 0 3px rgba(139,30,30,.08)}.tab-bar{display:flex;gap:8px;overflow-x:auto;padding:6px 2px 12px;scrollbar-width:thin}.tab-btn{flex:0 0 auto;border:1px solid var(--line);background:#fff;color:var(--text);border-radius:999px;padding:10px 15px;cursor:pointer;font-size:14px;transition:.2s;white-space:nowrap}.tab-btn:hover{border-color:var(--red);color:var(--red)}.tab-btn.active{background:var(--red);color:#fff;border-color:var(--red)}.content{background:rgba(255,255,255,.74);border:1px solid var(--line);border-radius:24px;padding:18px;box-shadow:var(--shadow);min-height:680px}.summary{display:grid;grid-template-columns:minmax(0,1.2fr) minmax(260px,.8fr);gap:16px;margin-bottom:18px}.summary-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:18px}.summary-card h2{margin:0 0 8px;font-size:22px}.summary-card p{margin:0;color:var(--muted);line-height:1.75}.stat-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}.stat{border:1px solid var(--line);background:linear-gradient(180deg,#fff,#fafafa);border-radius:14px;padding:12px}.stat b{display:block;color:var(--red);font-size:24px}.stat span{color:var(--muted);font-size:12px}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}.grid.two{grid-template-columns:repeat(2,minmax(0,1fr))}.card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:0 4px 14px rgba(25,35,55,.04);transition:.18s;min-height:180px;display:flex;flex-direction:column;gap:10px}.card:hover{transform:translateY(-2px);border-color:rgba(139,30,30,.45);box-shadow:var(--shadow)}.card h3{margin:0;font-size:18px;line-height:1.35}.card .sub,.sub{color:var(--muted);font-size:13px;line-height:1.5}.card p{color:var(--muted);margin:0;line-height:1.7;font-size:14px}.tags{display:flex;flex-wrap:wrap;gap:6px}.tag{display:inline-flex;align-items:center;border-radius:999px;background:var(--tag);color:#3e4652;padding:5px 9px;font-size:12px;max-width:100%}.tag.red{background:rgba(139,30,30,.1);color:var(--red)}.tag.green{background:rgba(47,111,94,.12);color:var(--green)}.tag.blue{background:rgba(36,92,122,.12);color:var(--blue)}.tag.purple{background:rgba(107,78,155,.12);color:var(--purple)}.btn{margin-top:auto;align-self:flex-start;border:1px solid var(--red);color:var(--red);background:#fff;border-radius:999px;padding:8px 12px;cursor:pointer}.btn:hover{background:var(--red);color:#fff}.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:var(--radius);background:#fff}table{width:100%;border-collapse:collapse;font-size:14px}th,td{padding:12px;border-bottom:1px solid var(--line);vertical-align:top;text-align:left}th{background:#fafafa;color:#333;position:sticky;top:0;z-index:1}tr:hover td{background:#fff8f8}.chain{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:16px}.chain-title{display:flex;justify-content:space-between;gap:12px;align-items:center}.steps{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px;align-items:center}.step{padding:8px 10px;border:1px solid var(--line);border-radius:10px;background:#fafafa;font-size:13px}.arrow{color:var(--red);font-weight:bold}.role-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px}.role-card{background:linear-gradient(180deg,#fff,#fbfbfb);border:1pxLine truncated
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
<header class="hero" id="hero"></header>
|
||||
<section class="search-panel">
|
||||
<input id="globalSearch" placeholder="搜索机构、人物、议题、政策工具、地方议题..." />
|
||||
<select id="scopeSelect"><option value="current">当前栏目搜索</option><option value="all">全库搜索</option></select>
|
||||
<select id="quickFilter"><option value="">全部类型/标签</option></select>
|
||||
</section>
|
||||
<nav class="tab-bar" id="tabBar"></nav>
|
||||
<main class="content"><section id="tabSummary"></section><section id="tabContent"></section></main>
|
||||
</div>
|
||||
<div id="detailModal" class="modal hidden"><div class="modal-content"><div class="modal-head"><div><h2 id="modalTitle">详情</h2><div id="modalSubtitle" style="opacity:.85;margin-top:6px;"></div></div><button class="modal-close" onclick="closeModal()">关闭</button></div><div class="modal-body" id="modalBody"></div></div></div>
|
||||
<script>
|
||||
const DATA = {"meta": {"title": "美国涉华决策咨询群体专题库", "subtitle": "机构、人物、资金、议题联盟、国家安全化、涉台政策想象、媒体传播与地方嵌入综合展示", "version": "v1.0", "language": "zh-CN", "lastUpdated": "2026-06-24", "coreJudgment": "美国涉华决策咨询群体不是统一指挥的单一集团,而是围绕台湾、科技、供应链、人权、军事安全、地方治理等议题形成的半制度化议题联盟生态。", "dataPrinciples": ["仅使用公开来源研究框架和可核验字段,不纳入个人隐私数据。", "资金关联不等于政策操控,需要结合公开披露、报告内容、听证记录和政策采纳路径交叉判断。", "避免简单使用“亲华/反华”二分标签,改用强竞争、克制、商业稳定、技术安全、人权优先、二轨交流等功能性标签。"], "dataScope": ["国会与准官方机构", "主流战略智库", "强硬派与保守派倡议机构", "克制派与外交派机构", "技术政策机构", "产业协会与商业组织", "人权与价值观组织", "二轨交流机构", "媒体传播节点", "地方政策网络"]}, "tabs": [{"id": "overview", "name": "总体生态", "description": "展示群体边界、生态分层、核心判断和总体运行机制。"}, {"id": "institutions", "name": "机构资料库", "description": "展示核心机构分类、职能、议题、政策倾向和影响路径。"}, {"id": "persons", "name": "人物与旋转门", "description": "展示核心人物、公开履历、机构流动和议题专长。"}, {"id": "funding", "name": "资金利益链", "description": "展示资金类型、产业关联、政府合同、基金会和议题关系。"}, {"id": "alliances", "name": "议题联盟", "description": "展示不同涉华议题上的主推联盟、制衡力量和政策工具。"}, {"id": "securitization", "name": "安全化机制", "description": "展示普通议题如何被转化为国家安全议题。"}, {"id": "taiwan", "name": "涉台政策想象", "description": "展示台湾在美国政策咨询群体中的八重角色。"}, {"id": "policyTools", "name": "政策工具", "description": "展示听证、报告、法案、行政规则、制裁、出口管制等制度化路径。"}, {"id": "media", "name": "媒体传播", "description": "展示智库报告、国会听证、媒体报道和社交平台之间的传播链。"}, {"id": "opinion", "name": "民意反应", "description": "展示美国公众、党派、年龄、企业、亚裔社群等不同群体反应。"}, {"id": "local", "name": "地方嵌入", "description": "展示涉华议题如何进入州议会、农地、大学、采购、港口和养老金。"}, {"id": "trends", "name": "危机与趋势", "description": "展示危机阶段作用、未来十年趋势和长期演化方向。"}], "overview": {"coreJudgment": "美国涉华决策咨询群体不是统一集团,而是由国会机构、准官方委员会、战略智库、保守派倡议网络、克制派智库、技术政策机构、产业协会、人权组织、二轨交流平台、媒体节点和地方政策网络共同构成的复杂生态。", "definition": {"broad": "通过报告、听证、证词、简报、媒体评论、产业游说、二轨交流、地方倡议等方式影响美国对华政策的机构与人物网络。", "narrow": "持续生产涉华政策知识并对国会、行政部门、产业界、媒体或地方政府具有可验证影响力的机构、专家和利益网络。"}, "inclusionCriteria": ["涉华议题持续性", "政策接口清晰", "公开输出稳定", "影响对象明确", "来源可验证", "议题代表性较强", "网络连接性较高"], "exclusionCriteria": ["普通社交媒体用户", "偶发评论者", "无公开资料私人顾问", "阴谋论型自媒体", "个人隐私数据"], "ecosystemLayers": [{"name": "国会与准官方政策知识层", "representativeEntities": ["USCC", "CECC", "CRS", "众议院中共问题特设委员会"], "functions": ["议题设置", "年度报告", "国会听证", "政策建议"], "influenceTargets": ["国会", "行政部门", "媒体", "政策圈"], "summary": "最接近正式政策流程,能够把涉华议题转化为听证、报告、建议和立法语言。"}, {"name": "主流战略智库层", "representativeEntities": ["CSIS", "RAND", "CNAS", "Brookings", "CFR", "Carnegie", "Stimson"], "functions": ["战略研究", "政策分析", "人才储备", "媒体解释"], "influenceTargets": ["政府", "国会", "盟友", "公众"], "summary": "承担政策知识生产、概念生产和专家解释功能,是涉华战略讨论的核心区。"}, {"name": "强硬派与保守派倡议层", "representativeEntities": ["Heritage", "Hudson", "AEI", "Hoover", "FDD", "Project 2049"], "functions": ["强硬政策倡议", "制裁", "脱钩", "军事威慑", "地方反制"], "influenceTargets": ["共和党网络", "州政府", "保守派媒体", "国会"], "summarLine truncated
|
||||
let currentTab = 'overview', keyword = '', quickFilter = '';
|
||||
const dataMap = {institutions:'institutions',persons:'persons',funding:'fundingChains',alliances:'issueAlliances',securitization:'securitizationCases',taiwan:'taiwanPolicyImaginations',policyTools:'policyTools',media:'mediaPropagation',opinion:'publicOpinion',local:'localEmbedding'};
|
||||
function arr(v){return Array.isArray(v)?v:(v?[v]:[])}
|
||||
function escapeHtml(str){return String(str??'').replace(/[&<>"']/g,s=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[s]))}
|
||||
function tagClass(t){const s=String(t); if(s.includes('强')||s.includes('安全')||s.includes('威慑')||s.includes('制裁'))return'red'; if(s.includes('克制')||s.includes('稳定')||s.includes('交流')||s.includes('外交'))return'green'; if(s.includes('技术')||s.includes('AI')||s.includes('芯片')||s.includes('数据'))return'blue'; if(s.includes('人权')||s.includes('民主')||s.includes('价值'))return'purple'; return''}
|
||||
function tags(list,limit=8){return `<div class="tags">${arr(list).slice(0,limit).map(x=>`<span class="tag ${tagClass(x)}">${escapeHtml(x)}</span>`).join('')}</div>`}
|
||||
function includesKeyword(item){if(!keyword)return true; return JSON.stringify(item).toLowerCase().includes(keyword.toLowerCase())}
|
||||
function matchesFilter(item){return !quickFilter || JSON.stringify(item).includes(quickFilter)}
|
||||
function filterList(list){return list.filter(x=>includesKeyword(x)&&matchesFilter(x))}
|
||||
function allItems(){let groups=['institutions','persons','fundingChains','issueAlliances','securitizationCases','taiwanPolicyImaginations','policyTools','mediaPropagation','publicOpinion','localEmbedding']; let all=[]; groups.forEach(g=>DATA[g].forEach(x=>all.push(x))); DATA.crisisAndTrends.futureTrends.forEach(x=>all.push(x)); return all}
|
||||
function findItem(id){return allItems().find(x=>x.id===id)}
|
||||
function titleOf(x){return x.name||x.issue||x.topic||x.role||x.group||x.trend||x.originalIssue||'详情'}
|
||||
function init(){renderHero();renderTabs();renderQuickFilterOptions();document.getElementById('globalSearch').addEventListener('input',e=>{keyword=e.target.value.trim();renderTab()});document.getElementById('scopeSelect').addEventListener('change',renderTab);document.getElementById('quickFilter').addEventListener('change',e=>{quickFilter=e.target.value;renderTab()});renderTab()}
|
||||
function renderHero(){const m=DATA.meta;document.getElementById('hero').innerHTML=`<h1>${m.title}</h1><p>${m.subtitle}</p><div class="meta-row"><span class="hero-badge">版本:${m.version}</span><span class="hero-badge">更新时间:${m.lastUpdated}</span><span class="hero-badge">数据范围:${m.dataScope.length} 类主体</span><span class="hero-badge">核心判断:半制度化议题联盟生态</span></div>`}
|
||||
function renderTabs(){document.getElementById('tabBar').innerHTML=DATA.tabs.map(t=>`<button class="tab-btn ${t.id===currentTab?'active':''}" onclick="switchTab('${t.id}')">${t.name}</button>`).join('')}
|
||||
function switchTab(id){currentTab=id;renderTabs();renderQuickFilterOptions();renderTab()}
|
||||
function renderQuickFilterOptions(){const select=document.getElementById('quickFilter'); const key=dataMap[currentTab]; let list=key?DATA[key]:(currentTab==='trends'?DATA.crisisAndTrends.futureTrends:[]); const opts=new Set(); list.forEach(item=>{['type','subType','priority','securityLevel','localLevel','rotationStrength','status'].forEach(k=>item[k]&&opts.add(item[k])); arr(item.policyOrientation).forEach(x=>opts.add(x)); arr(item.personTypes).forEach(x=>opts.add(x));}); select.innerHTML='<option value="">全部类型/标签</option>'+[...opts].sort().map(o=>`<option value="${escapeHtml(o)}">${escapeHtml(o)}</option>`).join(''); quickFilter=''}
|
||||
function renderSummary(){const t=DATA.tabs.find(x=>x.id===currentTab); const stat=Object.entries(DATA.statistics).slice(0,6).map(([k,v])=>`<div class="stat"><b>${v}</b><span>${k}</span></div>`).join(''); document.getElementById('tabSummary').innerHTML=`<div class="summary"><div class="summary-card"><h2>${t.name}</h2><p>${t.description}</p></div><div class="summary-card"><div class="stat-grid">${stat}</div></div></div>`}
|
||||
function renderTab(){renderSummary(); if(document.getElementById('scopeSelect').value==='all'&&keyword){renderGlobalResults();return} if(currentTab==='overview')renderOverview(); else if(currentTab==='institutions')renderInstitutions(); else if(currentTab==='persons')renderPersons(); else if(currentTab==='funding')renderFunding(); else if(currentTab==='alliances')renderAlliances(); else if(currentTab==='securitization')renderSecuritization(); else if(currentTab==='taiwan')renderTaiwan(); else if(currentTab==='policyTools')renderPolicyTools(); else if(currentTab==='media')renderMedia(); else if(currentTab==='opinion')renderOpinion(); else if(currentTab==='local')renderLocal(); else if(currentTab==='trends')renderTrends()}
|
||||
function renderOverview(){const o=DATA.overview; const layers=filterList(o.ecosystemLayers); document.getElementById('tabContent').innerHTML=`<div class="notice">${DATA.meta.dataPrinciples.join(' ')}</div><div class="grid">${layers.map((x,i)=>`<div class="card"><h3>${x.name}</h3><div class="sub">代表主体:${x.representativeEntities.join('、')}</div>${tags(x.functions)}<p>${x.summary}</p><button class="btn" onclick="openLayer(${i})">查看详情</button></div>`).join('')}</div><h2 style="margin:24px 0 12px;">运行机制</h2><div class="grid">${o.mechanisms.map(m=>`<div class="chain"><div class="chain-title"><h3>${m.name}</h3></div><div class="steps">${m.steps.map((s,i)=>`<span class="step">${s}</span>${i<m.steps.length-1?'<span class="arrow">→</span>':''}`).join('')}</div></div>`).join('')}</div>`}
|
||||
function openLayer(i){openModal('生态层详情',DATA.overview.ecosystemLayers[i])}
|
||||
function renderInstitutions(){const list=filterList(DATA.institutions); document.getElementById('tabContent').innerHTML=list.length?`<div class="grid">${list.map(x=>`<div class="card"><h3>${x.shortName}|${x.name}</h3><div class="sub">${x.englishName}</div>${tags([x.type,x.subType,x.priority])}${tags(x.policyOrientation)}<p>${x.summary}</p><div class="sub">涉华:${arr(x.chinaIssues).slice(0,5).join('、')}</div><div class="sub">涉台:${arr(x.taiwanIssues).slice(0,4).join('、')}</div><button class="btn" onclick="openById('机构详情','${x.id}')">查看详情</button></div>`).join('')}</div>`:'<div class="empty">没有匹配的机构数据</div>'}
|
||||
function renderPersons(){const list=filterList(DATA.persons); document.getElementById('tabContent').innerHTML=list.length?`<div class="grid">${list.map(x=>`<div class="card"><h3>${x.name}${x.chineseName?'|'+x.chineseName:''}</h3><div class="sub">${x.currentRole}</div>${tags(x.personTypes)}${tags([x.rotationStrength,...arr(x.policyOrientation)],6)}<p>${x.summary}</p><div class="sub">关联机构:${arr(x.relatedInstitutions).slice(0,5).join('、')}</div><button class="btn" onclick="openById('人物详情','${x.id}')">查看详情</button></div>`).join('')}</div>`:'<div class="empty">没有匹配的人物数据</div>'}
|
||||
function renderFunding(){const list=filterList(DATA.fundingChains); document.getElementById('tabContent').innerHTML=`<div class="notice">资金关联不等于政策操控。页面仅展示公开研究中可作为线索的资金、项目、机构与议题关系,具体影响需要结合公开披露、报告内容、听证记录和政策采纳路径交叉判断。</div><div class="funding-layout"><div class="funding-legend"><span class="tag red">资金来源</span><span class="tag blue">相关机构</span><span class="tag purple">关联议题</span><span class="tag green">政策输出</span></div>${list.map(x=>`<div class="funding-map-card"><div class="funding-map-head"><div><h3>${x.name}</h3><p class="funding-map-sub">${x.summary}</p></div><span class="tag ${tagClass(x.evidenceStrength)}">证据强度:${x.evidenceStrength}</span></div><div class="funding-topline">${tags([...(arr(x.fundingSources).slice(0,2).map(i=>'资金线索|'+i)),...(arr(x.relatedInstitutions).slice(0,2).map(i=>'机构节点|'+i)),...(arr(x.relatedIssues).slice(0,2).map(i=>'议题节点|'+i))],6)}</div><div class="funding-graph"><div class="funding-col col-source"><div class="funding-col-title"><span>资金来源</span><span class="funding-col-index">01</span></div><div class="funding-node-list">${arr(x.fundingSources).map(i=>`<span class="funding-node source">${i}</span>`).join('')}</div></div><div class="funding-link"><span>→</span></div><div class="funding-col col-inst"><div class="funding-col-title"><span>相关机构</span><span class="funding-col-index">02</span></div><div class="funding-node-list">${arr(x.relatedInstitutions).map(i=>`<span class="funding-node inst">${i}</span>`).join('')}</div></div><div class="funding-link"><span>→</span></div><div class="funding-col col-issue"><div class="funding-col-title"><span>关联议题</span><span class="funding-col-index">03</span></div><div class="funding-node-list">${arr(x.relatedIssues).map(i=>`<span class="funding-node issue">${i}</span>`).join('')}</div></div><div class="funding-link"><span>→</span></div><div class="funding-col col-output"><div class="funding-col-title"><span>政策输出</span><span class="funding-col-index">04</span></div><div class="funding-node-list">${arr(x.policyOutputs).map(i=>`<span class="funding-node output">${i}</span>`).join('')}</div></div></div><div class="funding-note"><b>分析提示:</b>${x.riskNotes}</div><div class="funding-actions"><button class="btn" onclick="openById('资金链详情','${x.id}')">查看详情</button></div></div>`).join('')}</div>`}
|
||||
function renderAlliances(){const list=filterList(DATA.issueAlliances); document.getElementById('tabContent').innerHTML=`<div class="table-wrap"><table><thead><tr><th>议题</th><th>主推联盟</th><th>制衡联盟</th><th>代表机构</th><th>政策工具</th><th>分歧轴</th><th>详情</th></tr></thead><tbody>${list.map(x=>`<tr><td><b>${x.issue}</b><br><span class="sub">${x.summary}</span></td><td>${tags(x.mainAlliance)}</td><td>${tags(x.counterAlliance)}</td><td>${arr(x.representativeInstitutions).join('、')}</td><td>${tags(x.policyTools)}</td><td>${arr(x.disputeAxes).join('<br>')}</td><td><button class="btn" onclick="openById('议题联盟详情','${x.id}')">查看</button></td></tr>`).join('')}</tbody></table></div>`}
|
||||
function renderSecuritization(){const list=filterList(DATA.securitizationCases); document.getElementById('tabContent').innerHTML=`<div class="grid two">${list.map(x=>`<div class="chain"><div class="chain-title"><h3>${x.originalIssue} → ${x.securitizedIssue}</h3><span class="tag red">${x.securityLevel}</span></div><p style="color:var(--muted);line-height:1.7;">${x.summary}</p><div class="steps">${arr(x.steps).map((s,i)=>`<span class="step">${s}</span>${i<x.steps.length-1?'<span class="arrow">→</span>':''}`).join('')}</div><button class="btn" onclick="openById('安全化案例详情','${x.id}')">查看详情</button></div>`).join('')}</div>`}
|
||||
function renderTaiwan(){const list=filterList(DATA.taiwanPolicyImaginations); document.getElementById('tabContent').innerHTML=`<div class="role-grid">${list.map(x=>`<div class="role-card" onclick="openById('涉台角色详情','${x.id}')"><h3>${x.role}</h3><p style="color:var(--muted);line-height:1.7;">${x.meaning}</p>${tags(x.policyImplications,4)}<p style="margin-top:10px;color:var(--muted);">${x.summary}</p></div>`).join('')}</div>`}
|
||||
function renderPolicyTools(){const list=filterList(DATA.policyTools); document.getElementById('tabContent').innerHTML=`<div class="grid">${list.map(x=>`<div class="card"><h3>${x.name}</h3>${tags([x.type])}${tags(x.applicableIssues,5)}<p>${x.summary}</p><div class="sub">路径:${arr(x.institutionalPath).join(' → ')}</div><button class="btn" onclick="openById('政策工具详情','${x.id}')">查看详情</button></div>`).join('')}</div>`}
|
||||
function renderMedia(){const list=filterList(DATA.mediaPropagation); document.getElementById('tabContent').innerHTML=`<div class="grid two">${list.map(x=>`<div class="chain"><div class="chain-title"><h3>${x.topic}</h3></div><p style="color:var(--muted);line-height:1.7;">${x.summary}</p><div class="steps"><span class="step">${x.sourceStage}</span><span class="arrow">→</span><span class="step">媒体/平台</span><span class="arrow">→</span><span class="step">公众认知</span><span class="arrow">→</span><span class="step">政策反馈</span></div>${tags(x.commonFrames,6)}<button class="btn" onclick="openById('传播议题详情','${x.id}')">查看详情</button></div>`).join('')}</div>`}
|
||||
function renderOpinion(){const list=filterList(DATA.publicOpinion); document.getElementById('tabContent').innerHTML=`<div class="grid">${list.map(x=>`<div class="card"><h3>${x.group}</h3><p>${x.attitude}</p>${tags(x.relatedIssues,6)}<div class="sub">可能反应:${arr(x.potentialReaction).join(';')}</div><button class="btn" onclick="openById('群体反应详情','${x.id}')">查看详情</button></div>`).join('')}</div>`}
|
||||
function renderLocal(){const list=filterList(DATA.localEmbedding); document.getElementById('tabContent').innerHTML=`<div class="grid">${list.map(x=>`<div class="card"><h3>${x.issue}</h3>${tags([x.localLevel,x.status])}${tags(x.securityFrame,4)}<p>${x.summary}</p><div class="sub">政策工具:${arr(x.policyTools).join('、')}</div><button class="btn" onclick="openById('地方嵌入详情','${x.id}')">查看详情</button></div>`).join('')}</div>`}
|
||||
function renderTrends(){const stages=DATA.crisisAndTrends.crisisStages.filter(x=>includesKeyword(x)&&matchesFilter(x)); const trends=DATA.crisisAndTrends.futureTrends.filter(x=>includesKeyword(x)&&matchesFilter(x)); document.getElementById('tabContent').innerHTML=`<h2>危机阶段作用</h2><div class="timeline">${stages.map(x=>`<div class="timeline-item"><h3>${x.stage}</h3><p style="color:var(--muted);line-height:1.7;">${x.summary}</p>${tags(x.consultingGroupRoles)}<div class="sub">代表主体:${arr(x.representativeActors).join('、')}</div></div>`).join('')}</div><h2 style="margin-top:24px;">未来十年趋势</h2><div class="grid">${trends.map(x=>`<div class="card"><h3>${x.trend}</h3><p>${x.description}</p>${tags(x.relatedIssues)}<div class="sub">代表机构:${arr(x.representativeInstitutions).join('、')}</div><button class="btn" onclick="openById('趋势详情','${x.id}')">查看详情</button></div>`).join('')}</div>`}
|
||||
function renderGlobalResults(){const results=allItems().filter(x=>includesKeyword(x)&&matchesFilter(x)); document.getElementById('tabContent').innerHTML=`<div class="notice">全库搜索结果:${results.length} 条。点击卡片查看二级详情。</div><div class="grid">${results.map(x=>`<div class="card"><h3>${titleOf(x)}</h3>${tags([typeLabel(x)])}<p>${x.summary||x.description||x.attitude||''}</p><button class="btn" onclick="openById('${typeLabel(x)}详情','${x.id}')">查看详情</button></div>`).join('')||'<div class="empty">没有匹配结果</div>'}</div>`}
|
||||
function typeLabel(x){if(DATA.institutions.includes(x))return'机构'; if(DATA.persons.includes(x))return'人物'; if(DATA.fundingChains.includes(x))return'资金链'; if(DATA.issueAlliances.includes(x))return'议题联盟'; if(DATA.securitizationCases.includes(x))return'安全化案例'; if(DATA.taiwanPolicyImaginations.includes(x))return'涉台角色'; if(DATA.policyTools.includes(x))return'政策工具'; if(DATA.mediaPropagation.includes(x))return'媒体传播'; if(DATA.publicOpinion.includes(x))return'民意反应'; if(DATA.localEmbedding.includes(x))return'地方嵌入'; return'趋势'}
|
||||
function openById(kind,id){const item=findItem(id); if(item)openModal(kind,item)}
|
||||
function openModal(title,item){document.getElementById('modalTitle').textContent=title+'|'+titleOf(item); document.getElementById('modalSubtitle').textContent=item.summary||item.description||item.attitude||''; const skip=new Set(['id','summary']); const body=[]; for(const [k,v] of Object.entries(item)){if(skip.has(k))continue; if(k==='careerPath'&&Array.isArray(v)){body.push(`<div class="detail-section"><h4>公开履历 / 旋转门路径</h4><div class="timeline">${v.map(c=>`<div class="timeline-item"><b>${escapeHtml(c.period)}</b>|${escapeHtml(c.institution)}|${escapeHtml(c.role)}<br><span class="sub">${escapeHtml(c.sector)}</span></div>`).join('')}</div></div>`)} else if(Array.isArray(v)){body.push(`<div class="detail-section"><h4>${fieldName(k)}</h4>${tags(v,80)}</div>`)} else if(typeof v==='object'&&v){body.push(`<div class="detail-section"><h4>${fieldName(k)}</h4><pre style="white-space:pre-wrap;line-height:1.6;background:#fafafa;border:1px solid var(--line);border-radius:12px;padding:12px;">${escapeHtml(JSON.stringify(v,null,2))}</pre></div>`)} else {body.push(`<div class="detail-section"><div class="kv"><div class="k">${fieldName(k)}</div><div>${escapeHtml(v)}</div></div></div>`)}} document.getElementById('modalBody').innerHTML=body.join(''); document.getElementById('detailModal').classList.remove('hidden')}
|
||||
function closeModal(){document.getElementById('detailModal').classList.add('hidden')}
|
||||
function fieldName(k){const map={name:'名称',englishName:'英文名称',shortName:'简称',type:'类型',subType:'子类型',policyOrientation:'政策倾向',chinaIssues:'涉华议题',taiwanIssues:'涉台议题',mainOutputs:'主要输出',influenceTargets:'影响对象',priority:'优先级',currentInstitution:'当前机构',currentRole:'当前职务',personTypes:'人物类型',careerPath:'公开履历',relatedInstitutions:'关联机构',influenceChannels:'影响渠道',rotationStrength:'旋转门强度',fundingSources:'资金来源',relatedIssues:'关联议题',policyOutputs:'政策输出',evidenceStrength:'证据强度',riskNotes:'风险提示',mainAlliance:'主推联盟',counterAlliance:'制衡联盟',representativeInstitutions:'代表机构',representativePersons:'代表人物',policyTools:'政策工具',disputeAxes:'分歧轴',originalIssue:'原始议题',securitizedIssue:'安全化后议题',steps:'过程链条',keyActors:'关键行为体',securityLevel:'安全化程度',role:'角色',meaning:'含义',representativeGroups:'代表群体',policyImplications:'政策含义',counterViews:'制衡观点',mainActors:'主要行为体',applicableIssues:'适用议题',institutionalPath:'制度化路径',policyEffects:'政策效果',topic:'主题',sourceStage:'传播起点',sourceActors:'源头行为体',amplificationChannels:'放大渠道',commonFrames:'常见框架',targetAudiences:'目标受众',feedbackToPolicy:'政策反馈',group:'群体',attitude:'态度',potentialReaction:'可能反应',balancingFactors:'制衡因素',localLevel:'地方层级',securityFrame:'安全化框架',counterActors:'反向制衡',controversies:'争议点',status:'状态',trend:'趋势',description:'说明'}; return map[k]||k}
|
||||
document.getElementById('detailModal').addEventListener('click',e=>{if(e.target.id==='detailModal')closeModal()}); init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>台湾经济安全与公共叙事研究专题数据库</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg:#7f171d;
|
||||
--bg2:#b7423d;
|
||||
--paper:#fffaf2;
|
||||
--card:#fffdf8;
|
||||
--line:#ead9c8;
|
||||
--text:#2a1b1b;
|
||||
--muted:#7c6860;
|
||||
--red:#9b1c24;
|
||||
--red2:#c64d45;
|
||||
--gold:#d8a24a;
|
||||
--shadow:0 18px 45px rgba(50,16,18,.18);
|
||||
--radius:22px;
|
||||
}
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Microsoft YaHei',Arial,sans-serif; color:var(--text); background:linear-gradient(135deg,var(--bg),var(--bg2)); min-height:100vh; }
|
||||
a { color:var(--red); }
|
||||
.app { max-width:1480px; margin:0 auto; padding:28px 26px 48px; }
|
||||
.hero { background:rgba(255,250,242,.96); border:1px solid rgba(255,255,255,.45); border-radius:30px; padding:26px; box-shadow:var(--shadow); position:relative; overflow:hidden; }
|
||||
.hero:before { content:''; position:absolute; right:-120px; top:-160px; width:420px; height:420px; background:radial-gradient(circle,rgba(216,162,74,.42),rgba(216,162,74,0) 65%); }
|
||||
.kicker { display:inline-flex; gap:8px; align-items:center; padding:6px 12px; border:1px solid #e4c3b0; background:#fff3e6; border-radius:999px; color:#8d211f; font-size:13px; font-weight:700; }
|
||||
h1 { margin:14px 0 8px; font-size:34px; line-height:1.2; letter-spacing:.2px; }
|
||||
.subtitle { max-width:980px; line-height:1.75; color:#614c45; font-size:15px; }
|
||||
.toolbar { margin-top:20px; display:flex; gap:12px; flex-wrap:wrap; align-items:center; }
|
||||
.search { flex:1; min-width:260px; position:relative; }
|
||||
.search input { width:100%; padding:13px 16px 13px 42px; border:1px solid #e3cbbb; background:#fffdfa; border-radius:15px; outline:none; font-size:14px; }
|
||||
.search span { position:absolute; left:15px; top:12px; opacity:.55; }
|
||||
select, button { border:1px solid #e3cbbb; background:#fffdfa; border-radius:14px; padding:12px 14px; font-size:14px; color:var(--text); }
|
||||
button { cursor:pointer; font-weight:700; }
|
||||
button.primary { background:linear-gradient(135deg,var(--red),var(--red2)); color:white; border:none; }
|
||||
.stats { display:grid; grid-template-columns:repeat(6,1fr); gap:14px; margin:18px 0; }
|
||||
.stat { background:rgba(255,250,242,.94); border:1px solid rgba(255,255,255,.5); border-radius:18px; padding:15px; box-shadow:0 8px 24px rgba(50,16,18,.1); }
|
||||
.stat b { display:block; font-size:28px; color:#8c191e; }
|
||||
.stat span { color:#725f59; font-size:13px; }
|
||||
.tabs { display:flex; gap:10px; overflow-x:auto; padding:10px 0 16px; scrollbar-width:thin; }
|
||||
.tab { white-space:nowrap; border:1px solid rgba(255,255,255,.52); background:rgba(255,250,242,.92); padding:12px 16px; border-radius:999px; font-weight:800; color:#6c2928; cursor:pointer; box-shadow:0 8px 18px rgba(0,0,0,.08); }
|
||||
.tab.active { background:#2b1616; color:#fffaf2; border-color:#2b1616; }
|
||||
.panel { display:none; background:var(--paper); border-radius:28px; padding:22px; box-shadow:var(--shadow); border:1px solid rgba(255,255,255,.55); }
|
||||
.panel.active { display:block; }
|
||||
.panel-title { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; margin-bottom:18px; border-bottom:1px solid var(--line); padding-bottom:16px; }
|
||||
.panel-title h2 { margin:0; font-size:24px; }
|
||||
.panel-title p { margin:7px 0 0; color:var(--muted); line-height:1.7; }
|
||||
.grid { display:grid; gap:16px; }
|
||||
.grid.cols-2 { grid-template-columns:repeat(2, minmax(0,1fr)); }
|
||||
.grid.cols-3 { grid-template-columns:repeat(3, minmax(0,1fr)); }
|
||||
.grid.cols-4 { grid-template-columns:repeat(4, minmax(0,1fr)); }
|
||||
.card { background:var(--card); border:1px solid var(--line); border-radius:20px; padding:17px; box-shadow:0 10px 28px rgba(90,40,30,.07); }
|
||||
.card h3 { margin:0 0 10px; font-size:18px; color:#451b1b; }
|
||||
.card p { line-height:1.72; color:#604e48; font-size:14px; margin:8px 0; }
|
||||
.meta { display:flex; flex-wrap:wrap; gap:7px; margin:10px 0; }
|
||||
.badge { display:inline-flex; align-items:center; gap:4px; padding:5px 9px; border-radius:999px; background:#f7eadc; color:#7a2725; border:1px solid #ead2be; font-size:12px; font-weight:700; }
|
||||
.badge.dark { background:#2d1919; color:white; border-color:#2d1919; }
|
||||
.badge.gold { background:#fff1cf; color:#835513; border-color:#f1d99b; }
|
||||
.table-wrap { overflow:auto; border:1px solid var(--line); border-radius:18px; background:white; }
|
||||
table { border-collapse:collapse; width:100%; min-width:850px; }
|
||||
th,td { padding:12px 13px; border-bottom:1px solid #f0e1d4; text-align:left; vertical-align:top; font-size:13px; line-height:1.55; }
|
||||
th { position:sticky; top:0; background:#fff2e5; color:#5d201f; z-index:1; }
|
||||
tr:hover td { background:#fffaf4; }
|
||||
.event-list { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:14px; }
|
||||
.event-card { cursor:pointer; transition:.18s transform,.18s box-shadow; }
|
||||
.event-card:hover { transform:translateY(-2px); box-shadow:0 15px 32px rgba(90,30,30,.12); }
|
||||
.event-head { display:flex; justify-content:space-between; gap:10px; align-items:flex-start; }
|
||||
.event-id { font-weight:900; color:#981b20; }
|
||||
.time { color:#80645a; font-size:13px; font-weight:700; }
|
||||
.timeline { position:relative; padding-left:20px; }
|
||||
.timeline:before { content:''; position:absolute; left:6px; top:8px; bottom:8px; width:2px; background:#e4c6b1; }
|
||||
.timeline-item { position:relative; padding:0 0 15px 18px; }
|
||||
.timeline-item:before { content:''; position:absolute; left:-19px; top:5px; width:12px; height:12px; border-radius:50%; background:#9b1c24; border:3px solid #f8e7d5; }
|
||||
.timeline-item b { color:#4a1d1d; }
|
||||
.notice { background:#fff4dc; border:1px solid #efd49d; border-radius:18px; padding:14px 16px; color:#6b4b18; line-height:1.7; }
|
||||
.modal-backdrop { position:fixed; inset:0; background:rgba(0,0,0,.5); display:none; align-items:center; justify-content:center; padding:20px; z-index:20; }
|
||||
.modal { max-width:840px; width:100%; max-height:86vh; overflow:auto; background:var(--paper); border-radius:24px; padding:22px; box-shadow:0 35px 90px rgba(0,0,0,.35); }
|
||||
.modal h2 { margin:0 0 8px; }
|
||||
.modal-close { float:right; border:none; background:#2d1919; color:white; padding:8px 12px; border-radius:999px; }
|
||||
.detail-grid { display:grid; grid-template-columns:130px 1fr; gap:10px; margin-top:15px; }
|
||||
.detail-grid div { border-bottom:1px solid #ead9c8; padding:9px 0; line-height:1.65; }
|
||||
.detail-grid .label { color:#7a5148; font-weight:900; }
|
||||
.footer { color:#fff4e8; opacity:.92; text-align:center; margin-top:24px; font-size:13px; line-height:1.8; }
|
||||
.empty { padding:32px; text-align:center; color:#795e55; }
|
||||
@media(max-width:1100px) { .stats { grid-template-columns:repeat(3,1fr); } .grid.cols-3,.grid.cols-4 { grid-template-columns:repeat(2,1fr); } .event-list { grid-template-columns:1fr; } }
|
||||
@media(max-width:720px) { .app { padding:16px; } h1 { font-size:26px; } .stats { grid-template-columns:repeat(2,1fr); } .grid.cols-2,.grid.cols-3,.grid.cols-4 { grid-template-columns:1fr; } .panel { padding:16px; } .detail-grid { grid-template-columns:1fr; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="app">
|
||||
<section class="hero">
|
||||
<span class="kicker">专题数据库 · JSON + HTML 离线版</span>
|
||||
<h1>台湾经济安全与公共叙事研究专题</h1>
|
||||
<div class="subtitle">围绕台积电赴美、CHIPS Act、军费军购、台美贸易倡议、CPTPP/RCEP、ECFA、两岸经贸、台商供应链与平台舆情进行结构化整理。页面强调事实边界,避免把事件直接写成单向结论。</div>
|
||||
<div class="toolbar">
|
||||
<div class="search"><span>⌕</span><input id="globalSearch" placeholder="搜索事件、叙事、企业、人物、平台关键词……" /></div>
|
||||
<select id="categoryFilter"><option value="">全部事件分类</option></select>
|
||||
<button class="primary" onclick="downloadJSON()">导出当前 JSON</button>
|
||||
<button onclick="resetFilters()">重置筛选</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="stats" id="stats"></section>
|
||||
|
||||
<nav class="tabs" id="tabs"></nav>
|
||||
|
||||
<main id="panels"></main>
|
||||
|
||||
<div class="footer">生成日期:2026-06-25 · 使用边界:公开资料研究、事实核查、政策与产业分析,不用于欺骗性影响行动或定向操控。</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-backdrop" id="modalBackdrop" onclick="closeModal(event)">
|
||||
<div class="modal" id="modal"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const DATA = {"metadata": {"title": "台湾经济安全与公共叙事研究专题数据库", "version": "1.0", "generated_date": "2026-06-25", "language": "zh-CN", "scope": "公开资料研究、事实核查、产业与经贸安全、军费军购、两岸经贸、平台生态与竞争叙事分析", "safety_boundary": "研究型、分析型、非欺骗、非煽动、非操控;区分事实、观点、归因、推论与未确认信息。", "source_note": "本库由用户提供的 skill 框架与本轮补充数据整理而成;部分事件为待持续更新项,页面以“事实边界”提示不可过度推论。"}, "modules": [{"id": "M01", "name": "专题总览与议题地图", "desc": "说明台湾经济安全叙事的整体结构,呈现产业、军费、经贸、财政、台美关系和两岸关系等主线。"}, {"id": "M02", "name": "核心叙事结构库", "desc": "拆解台积电赴美、硅盾、军购延迟、军费挤压、台美贸易、RCEP/CPTPP、台商两难、前线化等叙事。"}, {"id": "M03", "name": "关键事件与证据库", "desc": "建立事件卡、时间线和事实边界,标注事件能支撑什么、不能证明什么。"}, {"id": "M04", "name": "半导体与产业安全", "desc": "研究台积电赴美、半导体供应链、人才外流、硅盾争议和台湾产业根基。"}, {"id": "M05", "name": "军购、军费与财政压力", "desc": "研究对美军购、国防预算、交付延迟、战力形成与财政排挤争议。"}, {"id": "M06", "name": "区域经贸与两岸经济", "desc": "研究台美贸易倡议、CPTPP、RCEP、ECFA、两岸贸易和供应链转移。"}, {"id": "M07", "name": "企业、台商与产业组织", "desc": "研究重点企业、台商、工商团体、产业协会的利益和结构性压力。"}, {"id": "M08", "name": "人物、政党、媒体与组织网络", "desc": "研究台湾政党人物、官员、媒体、智库、事实核查组织与美国相关人物。"}, {"id": "M09", "name": "受众群体与平台生态", "desc": "研究不同群体如何接收经济安全叙事,以及不同平台上的表达方式。"}, {"id": "M10", "name": "竞争叙事、事实核查与风险边界", "desc": "比较不同阵营对同一事件的解释,标注事实、推论、过度归因和稳健表达。"}], "issue_map": [{"id": "I01", "name": "台积电赴美与硅盾变化", "desc": "研究台积电海外先进制程布局是否影响台湾产业安全与硅盾叙事。", "actors": ["台积电", "美国商务部", "台湾经济部门", "半导体供应链"], "indicators": ["海外厂制程", "台湾本土先进制程", "研发留台程度", "补贴条件"]}, {"id": "I02", "name": "半导体人才与技术外流", "desc": "研究工程师外派、美国本地招聘和制造经验转移是否削弱台湾本土人才密度。", "actors": ["台积电", "工程师群体", "美国亚利桑那地方政府"], "indicators": ["外派人数", "招聘岗位", "训练计划", "薪资结构"]}, {"id": "I03", "name": "CHIPS Act 与美国产业政策", "desc": "研究美国补贴条件、供应链回流政策对台湾企业的约束与机会。", "actors": ["美国商务部", "TSMC Arizona", "美国客户"], "indicators": ["补贴金额", "拨付条件", "限制条款", "项目里程碑"]}, {"id": "I04", "name": "对美军购与交付延迟", "desc": "研究台湾采购美国武器是否存在价格、交付和战力形成争议。", "actors": ["台湾防务部门", "美国军工企业", "DSCA", "AIT"], "indicators": ["军售金额", "交付时间", "延迟原因", "训练完成情况"]}, {"id": "I05", "name": "军费上升与民生财政竞争", "desc": "研究国防支出上升是否挤压社会福利、教育、医疗、产业升级预算。", "actors": ["台湾财政部门", "防务部门", "立法机构"], "indicators": ["GDP占比", "特别预算", "举债", "民生预算变化"]}, {"id": "I06", "name": "台美贸易倡议是否对等", "desc": "研究台美21世纪贸易倡议是否带来关税红利或只是制度对接。", "actors": ["USTR", "TECRO", "AIT", "台湾经贸部门"], "indicators": ["协议章节", "关税减免", "企业受益", "规则成本"]}, {"id": "I07", "name": "CPTPP/RCEP 与区域整合缺口", "desc": "研究台湾未加入RCEP、CPTPP迟迟未入会对传统产业的影响。", "actors": ["台湾经济部门", "传统产业", "CPTPP成员"], "indicators": ["关税差距", "订单转移", "传统产业出口表现"]}, {"id": "I08", "name": "两岸贸易依赖变化", "desc": "研究台湾对大陆、香港、美国、东盟出口结构变化。", "actors": ["出口商", "台商", "传统制造业", "高科技产业"], "indicators": ["出口占比", "贸易顺差", "产业类别"]}, {"id": "I09", "name": "台商供应链转移与选边压力", "desc": "研究台商在大陆、美国、东南亚之间的市场和政治压力。", "actors": ["台商协会", "电子代工", "传统产业"], "indicators": ["投资流向", "迁厂Line truncated
|
||||
const TAB_CONFIG = [
|
||||
['overview','总览'], ['issues','议题地图'], ['narratives','叙事结构'], ['events','关键事件'], ['semiconductor','半导体产业'], ['defense','军购预算'], ['trade','经贸区域'], ['orgs','企业组织'], ['actors','人物网络'], ['audience','受众平台'], ['facts','事实核查']
|
||||
];
|
||||
let activeTab = 'overview';
|
||||
let searchTerm = '';
|
||||
let categoryFilter = '';
|
||||
|
||||
function esc(s) { return String(s ?? '').replace(/[&<>'"]/g, ch => ({'&':'&','<':'<','>':'>',"'":''','"':'"'}[ch])); }
|
||||
function arr(a) { return Array.isArray(a) ? a : (a ? [a] : []); }
|
||||
function badges(items, cls='') { return arr(items).map(x => `<span class="badge ${cls}">${esc(x)}</span>`).join(''); }
|
||||
function contains(obj, q) { if(!q) return true; return JSON.stringify(obj).toLowerCase().includes(q.toLowerCase()); }
|
||||
function filteredEvents() { return DATA.events.filter(e => (!categoryFilter || e.category === categoryFilter) && contains(e, searchTerm)); }
|
||||
function filtered(list) { return list.filter(x => contains(x, searchTerm)); }
|
||||
|
||||
function init() {
|
||||
renderStats(); renderTabs(); fillFilter(); renderPanels(); bind();
|
||||
}
|
||||
function bind() {
|
||||
document.getElementById('globalSearch').addEventListener('input', e => { searchTerm = e.target.value.trim(); renderPanels(); });
|
||||
document.getElementById('categoryFilter').addEventListener('change', e => { categoryFilter = e.target.value; renderPanels(); });
|
||||
}
|
||||
function renderStats() {
|
||||
const s = [
|
||||
['研究栏目', DATA.modules.length], ['核心叙事', DATA.narratives.length], ['关键事件', DATA.events.length], ['企业样本', DATA.companies.length], ['组织样本', DATA.organizations.length], ['人物样本', DATA.actors.length]
|
||||
];
|
||||
document.getElementById('stats').innerHTML = s.map(([k,v]) => `<div class="stat"><b>${v}</b><span>${k}</span></div>`).join('');
|
||||
}
|
||||
function renderTabs() {
|
||||
document.getElementById('tabs').innerHTML = TAB_CONFIG.map(([id,name]) => `<button class="tab ${id===activeTab?'active':''}" onclick="setTab('${id}')">${name}</button>`).join('');
|
||||
}
|
||||
function setTab(id) { activeTab = id; renderTabs(); renderPanels(); window.scrollTo({top:190,behavior:'smooth'}); }
|
||||
function fillFilter() {
|
||||
const cats = [...new Set(DATA.events.map(e=>e.category))].sort();
|
||||
document.getElementById('categoryFilter').innerHTML = '<option value="">全部事件分类</option>' + cats.map(c=>`<option value="${esc(c)}">${esc(c)}</option>`).join('');
|
||||
}
|
||||
function resetFilters() { searchTerm=''; categoryFilter=''; document.getElementById('globalSearch').value=''; document.getElementById('categoryFilter').value=''; renderPanels(); }
|
||||
|
||||
function panel(title, desc, body) { return `<section class="panel active"><div class="panel-title"><div><h2>${title}</h2><p>${desc}</p></div></div>${body}</section>`; }
|
||||
function renderPanels() {
|
||||
const root = document.getElementById('panels');
|
||||
if(activeTab==='overview') root.innerHTML = renderOverview();
|
||||
if(activeTab==='issues') root.innerHTML = renderIssues();
|
||||
if(activeTab==='narratives') root.innerHTML = renderNarratives();
|
||||
if(activeTab==='events') root.innerHTML = renderEvents();
|
||||
if(activeTab==='semiconductor') root.innerHTML = renderSemiconductor();
|
||||
if(activeTab==='defense') root.innerHTML = renderDefense();
|
||||
if(activeTab==='trade') root.innerHTML = renderTrade();
|
||||
if(activeTab==='orgs') root.innerHTML = renderOrgs();
|
||||
if(activeTab==='actors') root.innerHTML = renderActors();
|
||||
if(activeTab==='audience') root.innerHTML = renderAudience();
|
||||
if(activeTab==='facts') root.innerHTML = renderFacts();
|
||||
}
|
||||
|
||||
function renderOverview() {
|
||||
const body = `<div class="notice"><b>资料边界:</b>${esc(DATA.metadata.safety_boundary)} 本页面保留来源链接和事实边界字段,适合作为专题研究初版数据库,不应替代逐条原始资料核验。</div>
|
||||
<div class="grid cols-2" style="margin-top:16px">${DATA.modules.map(m=>`<div class="card"><div class="meta"><span class="badge dark">${m.id}</span></div><h3>${esc(m.name)}</h3><p>${esc(m.desc)}</p></div>`).join('')}</div>`;
|
||||
return panel('专题总览', '10个一级栏目与数据库结构,可作为后续JSON扩展和HTML页面长期更新的基础。', body);
|
||||
}
|
||||
function renderIssues() {
|
||||
const list = filtered(DATA.issue_map);
|
||||
const body = `<div class="grid cols-2">${list.map(i=>`<div class="card"><div class="meta"><span class="badge dark">${i.id}</span>${badges(i.indicators,'gold')}</div><h3>${esc(i.name)}</h3><p>${esc(i.desc)}</p><p><b>关联对象:</b>${esc(i.actors.join('、'))}</p></div>`).join('') || '<div class="empty">没有匹配结果</div>'}</div>`;
|
||||
return panel('议题地图', '把产业、经贸、军费、两岸关系和安全焦虑拆成可观察的研究议题。', body);
|
||||
}
|
||||
function renderNarratives() {
|
||||
const list = filtered(DATA.narratives);
|
||||
const body = `<div class="grid cols-2">${list.map(n=>`<div class="card"><div class="meta"><span class="badge dark">${n.id}</span>${badges(n.keywords)}</div><h3>${esc(n.name)}</h3><p><b>核心主张:</b>${esc(n.claim)}</p><p><b>情绪基础:</b>${esc(n.emotion.join('、'))}</p><p><b>反方解释:</b>${esc(n.counter)}</p><p><b>事实边界:</b>${esc(n.boundary)}</p></div>`).join('') || '<div class="empty">没有匹配结果</div>'}</div>`;
|
||||
return panel('核心叙事结构库', '每条叙事均包含核心主张、关键词、情绪基础、支撑事实、反方解释和事实边界。', body);
|
||||
}
|
||||
function renderEvents() {
|
||||
const list = filteredEvents();
|
||||
const body = `<div class="notice">当前显示 <b>${list.length}</b> 条事件。点击任一事件卡可查看完整字段、关联叙事、来源链接与事实边界。</div><div class="event-list" style="margin-top:15px">${list.map(e=>eventCard(e)).join('') || '<div class="empty">没有匹配结果</div>'}</div>`;
|
||||
return panel('关键事件与证据库', 'E01—E80事件库,覆盖半导体、台美经贸、区域协定、ECFA、军费军购与安全环境。', body);
|
||||
}
|
||||
function eventCard(e) {
|
||||
return `<div class="card event-card" onclick="showEvent('${e.id}')"><div class="event-head"><span class="event-id">${e.id}</span><span class="time">${esc(e.time)}</span></div><div class="meta"><span class="badge gold">${esc(e.category)}</span>${badges(e.supports_narratives,'dark')}</div><h3>${esc(e.name)}</h3><p>${esc(e.summary)}</p><p><b>事实边界:</b>${esc(e.fact_boundary)}</p></div>`;
|
||||
}
|
||||
function showEvent(id) {
|
||||
const e = DATA.events.find(x=>x.id===id); if(!e) return;
|
||||
const src = arr(e.source_urls).map(u=>`<a href="${esc(u)}" target="_blank">${esc(u)}</a>`).join('<br>') || '待补充';
|
||||
const html = `<button class="modal-close" onclick="closeModal()">关闭</button><h2>${esc(e.id)} · ${esc(e.name)}</h2><div class="meta"><span class="badge gold">${esc(e.category)}</span>${badges(e.supports_narratives,'dark')}</div><div class="detail-grid"><div class="label">时间</div><div>${esc(e.time)}</div><div class="label">事件摘要</div><div>${esc(e.summary)}</div><div class="label">可支撑叙事</div><div>${esc(e.supports_narratives.join('、'))}</div><div class="label">事实边界</div><div>${esc(e.fact_boundary)}</div><div class="label">来源链接</div><div>${src}</div><div class="label">可信度</div><div>${esc(e.credibility)}</div></div>`;
|
||||
document.getElementById('modal').innerHTML = html;
|
||||
document.getElementById('modalBackdrop').style.display='flex';
|
||||
}
|
||||
function closeModal(ev) { if(!ev || ev.target.id==='modalBackdrop' || ev.target.className==='modal-close') document.getElementById('modalBackdrop').style.display='none'; }
|
||||
function renderSemiconductor() {
|
||||
const list = filtered(DATA.companies.filter(c=>/晶圆|IC|封测|硅|半导体|台积电|联发科|日月光|环球/.test(c.sector+c.name)));
|
||||
const body = `<div class="grid cols-3">${list.map(c=>`<div class="card"><div class="meta"><span class="badge dark">${c.id}</span>${badges(c.narratives)}</div><h3>${esc(c.name)}</h3><p><b>产业位置:</b>${esc(c.sector)}</p><p>${esc(c.focus)}</p></div>`).join('')}</div>`;
|
||||
return panel('半导体与产业安全', '聚焦台积电、先进制程、半导体供应链、人才外流和硅盾争议。', body);
|
||||
}
|
||||
function renderDefense() {
|
||||
const list = filteredEvents().filter(e=>e.category==='军费军购与预算');
|
||||
const body = `<div class="event-list">${list.map(e=>eventCard(e)).join('') || '<div class="empty">没有匹配结果</div>'}</div>`;
|
||||
return panel('军购、军费与财政压力', '集中展示防务特别预算、对美军购、交付延迟、后勤依赖和战力形成边界。', body);
|
||||
}
|
||||
function renderTrade() {
|
||||
const indicators = filtered(DATA.trade_indicators);
|
||||
const events = filteredEvents().filter(e=>/经贸|区域|贸易|ECFA|协定/.test(e.category+e.name));
|
||||
const table = `<div class="table-wrap"><table><thead><tr><th>编号</th><th>指标</th><th>年份</th><th>数值</th><th>研究意义</th></tr></thead><tbody>${indicators.map(t=>`<tr><td>${t.id}</td><td>${esc(t.name)}</td><td>${esc(t.year)}</td><td>${esc(t.value)}</td><td>${esc(t.meaning)}</td></tr>`).join('')}</tbody></table></div>`;
|
||||
const cards = `<div class="event-list" style="margin-top:16px">${events.map(e=>eventCard(e)).join('')}</div>`;
|
||||
return panel('区域经贸与两岸经济', '包含贸易指标、台美贸易倡议、RCEP/CPTPP、ECFA与两岸贸易结构变化。', table + cards);
|
||||
}
|
||||
function renderOrgs() {
|
||||
const companies = filtered(DATA.companies);
|
||||
const orgs = filtered(DATA.organizations);
|
||||
const comp = `<h3>企业样本</h3><div class="grid cols-3">${companies.map(c=>`<div class="card"><div class="meta"><span class="badge dark">${c.id}</span>${badges(c.narratives)}</div><h3>${esc(c.name)}</h3><p><b>产业位置:</b>${esc(c.sector)}</p><p>${esc(c.focus)}</p></div>`).join('')}</div>`;
|
||||
const orgHtml = `<h3 style="margin-top:24px">组织样本</h3><div class="grid cols-3">${orgs.map(o=>`<div class="card"><div class="meta"><span class="badge gold">${o.id}</span><span class="badge">${esc(o.type)}</span></div><h3>${esc(o.name)}</h3><p>${esc(o.focus)}</p></div>`).join('')}</div>`;
|
||||
return panel('企业、台商与产业组织', '企业与产业组织是叙事落地的重要利益主体,需要继续补公开表态和政策诉求。', comp + orgHtml);
|
||||
}
|
||||
function renderActors() {
|
||||
const list = filtered(DATA.actors);
|
||||
const body = `<div class="grid cols-3">${list.map(p=>`<div class="card"><div class="meta"><span class="badge dark">${p.id}</span>${badges(p.issues,'gold')}</div><h3>${esc(p.name)}</h3><p><b>身份:</b>${esc(p.role)}</p><p>${esc(p.note)}</p></div>`).join('') || '<div class="empty">没有匹配结果</div>'}</div>`;
|
||||
return panel('人物、政党、媒体与组织网络', '当前先放官方人物样本;后续应扩充政党、立法机构、政论人物、财经媒体、智库和事实查核组织。', body);
|
||||
}
|
||||
function renderAudience() {
|
||||
const audiences = filtered(DATA.audiences);
|
||||
const platforms = filtered(DATA.platforms);
|
||||
const ahtml = `<h3>受众群体</h3><div class="grid cols-2">${audiences.map(g=>`<div class="card"><div class="meta"><span class="badge dark">${g.id}</span>${badges(g.concerns)}</div><h3>${esc(g.name)}</h3><p><b>容易共鸣:</b>${esc(g.resonant_issues.join('、'))}</p><p><b>反弹风险:</b>${esc(g.risk)}</p></div>`).join('')}</div>`;
|
||||
const phtml = `<h3 style="margin-top:24px">平台采样计划</h3><div class="grid cols-4">${platforms.map(p=>`<div class="card"><div class="meta"><span class="badge gold">目标 ${p.sample_target} 条</span></div><h3>${esc(p.name)}</h3><p>${esc(p.focus)}</p><p><b>字段:</b>${esc(p.fields.join('、'))}</p></div>`).join('')}</div>`;
|
||||
return panel('受众群体与平台生态', '受众画像用于理解议题接收方式;平台数据只应作为舆情样本,不能代表整体民意。', ahtml + phtml);
|
||||
}
|
||||
function renderFacts() {
|
||||
const checks = filtered(DATA.fact_checks);
|
||||
const gaps = DATA.data_gaps;
|
||||
const table = `<div class="table-wrap"><table><thead><tr><th>争议说法</th><th>事实状态</th><th>建议稳健表达</th><th>高风险表达</th></tr></thead><tbody>${checks.map(f=>`<tr><td>${esc(f.claim)}</td><td>${esc(f.status)}</td><td>${esc(f.safe_expression)}</td><td>${esc(f.risky_expression)}</td></tr>`).join('')}</tbody></table></div>`;
|
||||
const gapHtml = `<h3 style="margin-top:24px">后续数据缺口</h3><div class="grid cols-3">${gaps.map(g=>`<div class="card"><div class="meta"><span class="badge ${g.priority==='高'?'dark':'gold'}">${esc(g.priority)}优先级</span></div><h3>${esc(g.name)}</h3><p>${esc(g.target)}</p></div>`).join('')}</div>`;
|
||||
return panel('竞争叙事、事实核查与风险边界', '该栏目用于把绝对化、阴谋化或证据不足的表达改写成研究型表述。', table + gapHtml);
|
||||
}
|
||||
function downloadJSON() {
|
||||
const blob = new Blob([JSON.stringify(DATA,null,2)], {type:'application/json;charset=utf-8'});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a'); a.href=url; a.download='taiwan_economic_security_narrative_database.json'; a.click(); URL.revokeObjectURL(url);
|
||||
}
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Canonical serialization for LangChain / LangGraph objects.
|
||||
|
||||
Provides a single source of truth for converting LangChain message
|
||||
objects, Pydantic models, and LangGraph state dicts into plain
|
||||
JSON-serialisable Python structures.
|
||||
|
||||
Consumers: ``deerflow.runtime.runs.worker`` (SSE publishing) and
|
||||
``app.gateway.routers.threads`` (REST responses).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
from typing import Any
|
||||
|
||||
|
||||
def serialize_lc_object(obj: Any) -> Any:
|
||||
"""Recursively serialize a LangChain object to a JSON-serialisable dict."""
|
||||
if obj is None:
|
||||
return None
|
||||
if isinstance(obj, (str, int, float, bool)):
|
||||
return obj
|
||||
if isinstance(obj, dict):
|
||||
return {k: serialize_lc_object(v) for k, v in obj.items()}
|
||||
if isinstance(obj, (list, tuple)):
|
||||
return [serialize_lc_object(item) for item in obj]
|
||||
# Pydantic v2
|
||||
if hasattr(obj, "model_dump"):
|
||||
try:
|
||||
return obj.model_dump()
|
||||
except Exception:
|
||||
pass
|
||||
# Pydantic v1 / older objects
|
||||
if hasattr(obj, "dict"):
|
||||
try:
|
||||
return obj.dict()
|
||||
except Exception:
|
||||
pass
|
||||
# Dataclass instances —— LangGraph 的 ``Interrupt`` 就是 dataclass 没有
|
||||
# model_dump 也没有 dict 方法;之前 fallback 到 ``str(obj)`` 会把
|
||||
# ``Interrupt(value=..., id='...')`` 序列化成字符串,下游 SDK
|
||||
# (``@langchain/langgraph-sdk``) 期待 dict 结构 → 直接丢弃 → AI 写作
|
||||
# 的 4 个干预卡永远不弹(参 ai-writing-优化.md §阶段 3 排查记录)。
|
||||
if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
|
||||
try:
|
||||
return {k: serialize_lc_object(v) for k, v in dataclasses.asdict(obj).items()}
|
||||
except Exception:
|
||||
pass
|
||||
# Last resort
|
||||
try:
|
||||
return str(obj)
|
||||
except Exception:
|
||||
return repr(obj)
|
||||
|
||||
|
||||
def serialize_channel_values(channel_values: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Serialize channel values, stripping internal LangGraph keys.
|
||||
|
||||
``__pregel_*`` 键始终剥离。``__interrupt__`` 仅在**为空时**剥离 —— 因为
|
||||
``@langchain/langgraph-sdk`` 的 ``useStream`` 只在 ``event === "values"``
|
||||
通道里读 ``data.__interrupt__`` 并通过 ``stream.interrupt`` 暴露给上层。
|
||||
AI 写作的 4 个干预卡(material/outline/draft/review)就是靠它触发的;
|
||||
继续过滤会让前端永远拿不到 interrupt。
|
||||
|
||||
主聊天不消费 ``stream.interrupt``,但若我们让一个空数组溜过去,SDK 会
|
||||
fallback 成 ``{when: "breakpoint"}`` 的伪 interrupt —— 所以仅在数组非空
|
||||
时保留,两侧都不破坏。
|
||||
"""
|
||||
result: dict[str, Any] = {}
|
||||
for key, value in channel_values.items():
|
||||
if key.startswith("__pregel_"):
|
||||
continue
|
||||
if key == "__interrupt__" and not value:
|
||||
continue
|
||||
result[key] = serialize_lc_object(value)
|
||||
return result
|
||||
|
||||
|
||||
def serialize_messages_tuple(obj: Any) -> Any:
|
||||
"""Serialize a messages-mode tuple ``(chunk, metadata)``."""
|
||||
if isinstance(obj, tuple) and len(obj) == 2:
|
||||
chunk, metadata = obj
|
||||
return [serialize_lc_object(chunk), metadata if isinstance(metadata, dict) else {}]
|
||||
return serialize_lc_object(obj)
|
||||
|
||||
|
||||
def serialize(obj: Any, *, mode: str = "") -> Any:
|
||||
"""Serialize LangChain objects with mode-specific handling.
|
||||
|
||||
* ``messages`` — obj is ``(message_chunk, metadata_dict)``
|
||||
* ``values`` — obj is the full state dict; ``__pregel_*`` keys stripped
|
||||
* everything else — recursive ``model_dump()`` / ``dict()`` fallback
|
||||
"""
|
||||
if mode == "messages":
|
||||
return serialize_messages_tuple(obj)
|
||||
if mode == "values":
|
||||
return serialize_channel_values(obj) if isinstance(obj, dict) else serialize_lc_object(obj)
|
||||
return serialize_lc_object(obj)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Store provider for the DeerFlow runtime.
|
||||
|
||||
Re-exports the public API of both the async provider (for long-running
|
||||
servers) and the sync provider (for CLI tools and the embedded client).
|
||||
|
||||
Async usage (FastAPI lifespan)::
|
||||
|
||||
from deerflow.runtime.store import make_store
|
||||
|
||||
async with make_store() as store:
|
||||
app.state.store = store
|
||||
|
||||
Sync usage (CLI / DeerFlowClient)::
|
||||
|
||||
from deerflow.runtime.store import get_store, store_context
|
||||
|
||||
store = get_store() # singleton
|
||||
with store_context() as store: ... # one-shot
|
||||
"""
|
||||
|
||||
from .async_provider import make_store
|
||||
from .provider import get_store, reset_store, store_context
|
||||
|
||||
__all__ = [
|
||||
# async
|
||||
"make_store",
|
||||
# sync
|
||||
"get_store",
|
||||
"reset_store",
|
||||
"store_context",
|
||||
]
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"""Shared SQLite connection utilities for store and checkpointer providers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
|
||||
from deerflow.config.paths import resolve_path
|
||||
|
||||
|
||||
def resolve_sqlite_conn_str(raw: str) -> str:
|
||||
"""Return a SQLite connection string ready for use with store/checkpointer backends.
|
||||
|
||||
SQLite special strings (``":memory:"`` and ``file:`` URIs) are returned
|
||||
unchanged. Plain filesystem paths — relative or absolute — are resolved
|
||||
to an absolute string via :func:`resolve_path`.
|
||||
"""
|
||||
if raw == ":memory:" or raw.startswith("file:"):
|
||||
return raw
|
||||
return str(resolve_path(raw))
|
||||
|
||||
|
||||
def ensure_sqlite_parent_dir(conn_str: str) -> None:
|
||||
"""Create parent directory for a SQLite filesystem path.
|
||||
|
||||
No-op for in-memory databases (``":memory:"``) and ``file:`` URIs.
|
||||
"""
|
||||
if conn_str != ":memory:" and not conn_str.startswith("file:"):
|
||||
pathlib.Path(conn_str).parent.mkdir(parents=True, exist_ok=True)
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
"""Async Store factory — backend mirrors the configured checkpointer.
|
||||
|
||||
The store and checkpointer share the same ``checkpointer`` section in
|
||||
*config.yaml* so they always use the same persistence backend:
|
||||
|
||||
- ``type: memory`` → :class:`langgraph.store.memory.InMemoryStore`
|
||||
- ``type: sqlite`` → :class:`langgraph.store.sqlite.aio.AsyncSqliteStore`
|
||||
- ``type: postgres`` → :class:`langgraph.store.postgres.aio.AsyncPostgresStore`
|
||||
|
||||
Usage (e.g. FastAPI lifespan)::
|
||||
|
||||
from deerflow.runtime.store import make_store
|
||||
|
||||
async with make_store() as store:
|
||||
app.state.store = store
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from langgraph.store.base import BaseStore
|
||||
|
||||
from deerflow.config.app_config import AppConfig, get_app_config
|
||||
from deerflow.runtime.store.provider import POSTGRES_CONN_REQUIRED, POSTGRES_STORE_INSTALL, SQLITE_STORE_INSTALL, ensure_sqlite_parent_dir, resolve_sqlite_conn_str
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _pool_size_env(name: str, default: int) -> int:
|
||||
import os
|
||||
|
||||
raw = os.getenv(name, "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
return max(0, int(raw))
|
||||
except ValueError:
|
||||
logger.warning("Invalid %s=%r; using default %d", name, raw, default)
|
||||
return default
|
||||
|
||||
|
||||
def _postgres_pool_config() -> dict:
|
||||
"""Pool config for the Postgres store.
|
||||
|
||||
A single long-lived connection (the default ``from_conn_string`` behavior)
|
||||
dies permanently on a server restart / idle timeout / network blip — every
|
||||
later store call then fails with "server closed the connection
|
||||
unexpectedly". A pool with ``check=check_connection`` validates each
|
||||
connection on checkout and replaces dead ones, so the runtime self-heals.
|
||||
Extra keys (``check``/``max_idle``/``max_lifetime``) are passed straight
|
||||
through to ``AsyncConnectionPool`` by ``from_conn_string``.
|
||||
"""
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
|
||||
return {
|
||||
"min_size": _pool_size_env("DEER_FLOW_PG_POOL_MIN", 1),
|
||||
"max_size": _pool_size_env("DEER_FLOW_PG_POOL_MAX", 10),
|
||||
"check": AsyncConnectionPool.check_connection,
|
||||
"max_idle": 300.0,
|
||||
"max_lifetime": 3600.0,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Internal backend factory
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def _async_store(config) -> AsyncIterator[BaseStore]:
|
||||
"""Async context manager that constructs and tears down a Store.
|
||||
|
||||
The ``config`` argument is a :class:`deerflow.config.checkpointer_config.CheckpointerConfig`
|
||||
instance — the same object used by the checkpointer factory.
|
||||
"""
|
||||
if config.type == "memory":
|
||||
from langgraph.store.memory import InMemoryStore
|
||||
|
||||
logger.info("Store: using InMemoryStore (in-process, not persistent)")
|
||||
yield InMemoryStore()
|
||||
return
|
||||
|
||||
if config.type == "sqlite":
|
||||
try:
|
||||
from langgraph.store.sqlite.aio import AsyncSqliteStore
|
||||
except ImportError as exc:
|
||||
raise ImportError(SQLITE_STORE_INSTALL) from exc
|
||||
|
||||
conn_str = resolve_sqlite_conn_str(config.connection_string or "store.db")
|
||||
ensure_sqlite_parent_dir(conn_str)
|
||||
|
||||
async with AsyncSqliteStore.from_conn_string(conn_str) as store:
|
||||
await store.setup()
|
||||
logger.info("Store: using AsyncSqliteStore (%s)", conn_str)
|
||||
yield store
|
||||
return
|
||||
|
||||
if config.type == "postgres":
|
||||
try:
|
||||
from langgraph.store.postgres.aio import AsyncPostgresStore # type: ignore[import]
|
||||
except ImportError as exc:
|
||||
raise ImportError(POSTGRES_STORE_INSTALL) from exc
|
||||
|
||||
if not config.connection_string:
|
||||
raise ValueError(POSTGRES_CONN_REQUIRED)
|
||||
|
||||
async with AsyncPostgresStore.from_conn_string(config.connection_string, pool_config=_postgres_pool_config()) as store:
|
||||
await store.setup()
|
||||
logger.info("Store: using AsyncPostgresStore (pooled, self-healing)")
|
||||
yield store
|
||||
return
|
||||
|
||||
raise ValueError(f"Unknown store backend type: {config.type!r}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public async context manager
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def make_store(app_config: AppConfig | None = None) -> AsyncIterator[BaseStore]:
|
||||
"""Async context manager that yields a Store whose backend matches the
|
||||
configured checkpointer.
|
||||
|
||||
Reads from the same ``checkpointer`` section of *config.yaml* used by
|
||||
:func:`deerflow.runtime.checkpointer.async_provider.make_checkpointer` so
|
||||
that both singletons always use the same persistence technology::
|
||||
|
||||
async with make_store(app_config) as store:
|
||||
app.state.store = store
|
||||
|
||||
Yields an :class:`~langgraph.store.memory.InMemoryStore` when no
|
||||
``checkpointer`` section is configured (emits a WARNING in that case).
|
||||
"""
|
||||
if app_config is None:
|
||||
app_config = get_app_config()
|
||||
|
||||
if app_config.checkpointer is None:
|
||||
from langgraph.store.memory import InMemoryStore
|
||||
|
||||
logger.warning("No 'checkpointer' section in config.yaml — using InMemoryStore for the store. Thread list will be lost on server restart. Configure a sqlite or postgres backend for persistence.")
|
||||
yield InMemoryStore()
|
||||
return
|
||||
|
||||
async with _async_store(app_config.checkpointer) as store:
|
||||
yield store
|
||||
@@ -0,0 +1,188 @@
|
||||
"""Sync Store factory.
|
||||
|
||||
Provides a **sync singleton** and a **sync context manager** for CLI tools
|
||||
and the embedded :class:`~deerflow.client.DeerFlowClient`.
|
||||
|
||||
The backend mirrors the configured checkpointer so that both always use the
|
||||
same persistence technology. Supported backends: memory, sqlite, postgres.
|
||||
|
||||
Usage::
|
||||
|
||||
from deerflow.runtime.store.provider import get_store, store_context
|
||||
|
||||
# Singleton — reused across calls, closed on process exit
|
||||
store = get_store()
|
||||
|
||||
# One-shot — fresh connection, closed on block exit
|
||||
with store_context() as store:
|
||||
store.put(("ns",), "key", {"value": 1})
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
from collections.abc import Iterator
|
||||
|
||||
from langgraph.store.base import BaseStore
|
||||
|
||||
from deerflow.config.app_config import get_app_config
|
||||
from deerflow.runtime.store._sqlite_utils import ensure_sqlite_parent_dir, resolve_sqlite_conn_str
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Error message constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SQLITE_STORE_INSTALL = "langgraph-checkpoint-sqlite is required for the SQLite store. Install it with: uv add langgraph-checkpoint-sqlite"
|
||||
POSTGRES_STORE_INSTALL = "langgraph-checkpoint-postgres is required for the PostgreSQL store. Install it with: uv add langgraph-checkpoint-postgres psycopg[binary] psycopg-pool"
|
||||
POSTGRES_CONN_REQUIRED = "checkpointer.connection_string is required for the postgres backend"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sync factory
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _sync_store_cm(config) -> Iterator[BaseStore]:
|
||||
"""Context manager that creates and tears down a sync Store.
|
||||
|
||||
The ``config`` argument is a
|
||||
:class:`~deerflow.config.checkpointer_config.CheckpointerConfig` instance —
|
||||
the same object used by the checkpointer factory.
|
||||
"""
|
||||
if config.type == "memory":
|
||||
from langgraph.store.memory import InMemoryStore
|
||||
|
||||
logger.info("Store: using InMemoryStore (in-process, not persistent)")
|
||||
yield InMemoryStore()
|
||||
return
|
||||
|
||||
if config.type == "sqlite":
|
||||
try:
|
||||
from langgraph.store.sqlite import SqliteStore
|
||||
except ImportError as exc:
|
||||
raise ImportError(SQLITE_STORE_INSTALL) from exc
|
||||
|
||||
conn_str = resolve_sqlite_conn_str(config.connection_string or "store.db")
|
||||
ensure_sqlite_parent_dir(conn_str)
|
||||
|
||||
with SqliteStore.from_conn_string(conn_str) as store:
|
||||
store.setup()
|
||||
logger.info("Store: using SqliteStore (%s)", conn_str)
|
||||
yield store
|
||||
return
|
||||
|
||||
if config.type == "postgres":
|
||||
try:
|
||||
from langgraph.store.postgres import PostgresStore # type: ignore[import]
|
||||
except ImportError as exc:
|
||||
raise ImportError(POSTGRES_STORE_INSTALL) from exc
|
||||
|
||||
if not config.connection_string:
|
||||
raise ValueError(POSTGRES_CONN_REQUIRED)
|
||||
|
||||
with PostgresStore.from_conn_string(config.connection_string) as store:
|
||||
store.setup()
|
||||
logger.info("Store: using PostgresStore")
|
||||
yield store
|
||||
return
|
||||
|
||||
raise ValueError(f"Unknown store backend type: {config.type!r}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sync singleton
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_store: BaseStore | None = None
|
||||
_store_ctx = None # open context manager keeping the connection alive
|
||||
|
||||
|
||||
def get_store() -> BaseStore:
|
||||
"""Return the global sync Store singleton, creating it on first call.
|
||||
|
||||
Returns an :class:`~langgraph.store.memory.InMemoryStore` when no
|
||||
checkpointer is configured in *config.yaml* (emits a WARNING in that case).
|
||||
|
||||
Raises:
|
||||
ImportError: If the required package for the configured backend is not installed.
|
||||
ValueError: If ``connection_string`` is missing for a backend that requires it.
|
||||
"""
|
||||
global _store, _store_ctx
|
||||
|
||||
if _store is not None:
|
||||
return _store
|
||||
|
||||
# Lazily load app config, mirroring the checkpointer singleton pattern so
|
||||
# that tests that set the global checkpointer config explicitly remain isolated.
|
||||
from deerflow.config.app_config import _app_config
|
||||
from deerflow.config.checkpointer_config import get_checkpointer_config
|
||||
|
||||
config = get_checkpointer_config()
|
||||
|
||||
if config is None and _app_config is None:
|
||||
try:
|
||||
get_app_config()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
config = get_checkpointer_config()
|
||||
|
||||
if config is None:
|
||||
from langgraph.store.memory import InMemoryStore
|
||||
|
||||
logger.warning("No 'checkpointer' section in config.yaml — using InMemoryStore for the store. Thread list will be lost on server restart. Configure a sqlite or postgres backend for persistence.")
|
||||
_store = InMemoryStore()
|
||||
return _store
|
||||
|
||||
_store_ctx = _sync_store_cm(config)
|
||||
_store = _store_ctx.__enter__()
|
||||
return _store
|
||||
|
||||
|
||||
def reset_store() -> None:
|
||||
"""Reset the sync singleton, forcing recreation on the next call.
|
||||
|
||||
Closes any open backend connections and clears the cached instance.
|
||||
Useful in tests or after a configuration change.
|
||||
"""
|
||||
global _store, _store_ctx
|
||||
if _store_ctx is not None:
|
||||
try:
|
||||
_store_ctx.__exit__(None, None, None)
|
||||
except Exception:
|
||||
logger.warning("Error during store cleanup", exc_info=True)
|
||||
_store_ctx = None
|
||||
_store = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sync context manager
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def store_context() -> Iterator[BaseStore]:
|
||||
"""Sync context manager that yields a Store and cleans up on exit.
|
||||
|
||||
Unlike :func:`get_store`, this does **not** cache the instance — each
|
||||
``with`` block creates and destroys its own connection. Use it in CLI
|
||||
scripts or tests where you want deterministic cleanup::
|
||||
|
||||
with store_context() as store:
|
||||
store.put(("threads",), thread_id, {...})
|
||||
|
||||
Yields an :class:`~langgraph.store.memory.InMemoryStore` when no
|
||||
checkpointer is configured in *config.yaml*.
|
||||
"""
|
||||
config = get_app_config()
|
||||
if config.checkpointer is None:
|
||||
from langgraph.store.memory import InMemoryStore
|
||||
|
||||
logger.warning("No 'checkpointer' section in config.yaml — using InMemoryStore for the store. Thread list will be lost on server restart. Configure a sqlite or postgres backend for persistence.")
|
||||
yield InMemoryStore()
|
||||
return
|
||||
|
||||
with _sync_store_cm(config.checkpointer) as store:
|
||||
yield store
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
"""Stream bridge — decouples agent workers from SSE endpoints.
|
||||
|
||||
A ``StreamBridge`` sits between the background task that runs an agent
|
||||
(producer) and the HTTP endpoint that pushes Server-Sent Events to
|
||||
the client (consumer). This package provides an abstract protocol
|
||||
(:class:`StreamBridge`) plus a default in-memory implementation backed
|
||||
by :mod:`asyncio.Queue`.
|
||||
"""
|
||||
|
||||
from .async_provider import make_stream_bridge
|
||||
from .base import END_SENTINEL, HEARTBEAT_SENTINEL, StreamBridge, StreamEvent
|
||||
from .memory import MemoryStreamBridge
|
||||
|
||||
__all__ = [
|
||||
"END_SENTINEL",
|
||||
"HEARTBEAT_SENTINEL",
|
||||
"MemoryStreamBridge",
|
||||
"StreamBridge",
|
||||
"StreamEvent",
|
||||
"make_stream_bridge",
|
||||
]
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
"""Async stream bridge factory.
|
||||
|
||||
Provides an **async context manager** aligned with
|
||||
:func:`deerflow.runtime.checkpointer.async_provider.make_checkpointer`.
|
||||
|
||||
Usage (e.g. FastAPI lifespan)::
|
||||
|
||||
from deerflow.agents.stream_bridge import make_stream_bridge
|
||||
|
||||
async with make_stream_bridge() as bridge:
|
||||
app.state.stream_bridge = bridge
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.config.stream_bridge_config import get_stream_bridge_config
|
||||
|
||||
from .base import StreamBridge
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def make_stream_bridge(app_config: AppConfig | None = None) -> AsyncIterator[StreamBridge]:
|
||||
"""Async context manager that yields a :class:`StreamBridge`.
|
||||
|
||||
Falls back to :class:`MemoryStreamBridge` when no configuration is
|
||||
provided and nothing is set globally.
|
||||
"""
|
||||
if app_config is None:
|
||||
config = get_stream_bridge_config()
|
||||
else:
|
||||
config = app_config.stream_bridge
|
||||
|
||||
if config is None or config.type == "memory":
|
||||
from deerflow.runtime.stream_bridge.memory import MemoryStreamBridge
|
||||
|
||||
maxsize = config.queue_maxsize if config is not None else 256
|
||||
bridge = MemoryStreamBridge(queue_maxsize=maxsize)
|
||||
logger.info("Stream bridge initialised: memory (queue_maxsize=%d)", maxsize)
|
||||
try:
|
||||
yield bridge
|
||||
finally:
|
||||
await bridge.close()
|
||||
return
|
||||
|
||||
if config.type == "redis":
|
||||
raise NotImplementedError("Redis stream bridge planned for Phase 2")
|
||||
|
||||
raise ValueError(f"Unknown stream bridge type: {config.type!r}")
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
"""Abstract stream bridge protocol.
|
||||
|
||||
StreamBridge decouples agent workers (producers) from SSE endpoints
|
||||
(consumers), aligning with LangGraph Platform's Queue + StreamManager
|
||||
architecture.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StreamEvent:
|
||||
"""Single stream event.
|
||||
|
||||
Attributes:
|
||||
id: Monotonically increasing event ID (used as SSE ``id:`` field,
|
||||
supports ``Last-Event-ID`` reconnection).
|
||||
event: SSE event name, e.g. ``"metadata"``, ``"updates"``,
|
||||
``"events"``, ``"error"``, ``"end"``.
|
||||
data: JSON-serialisable payload.
|
||||
"""
|
||||
|
||||
id: str
|
||||
event: str
|
||||
data: Any
|
||||
|
||||
|
||||
HEARTBEAT_SENTINEL = StreamEvent(id="", event="__heartbeat__", data=None)
|
||||
END_SENTINEL = StreamEvent(id="", event="__end__", data=None)
|
||||
|
||||
|
||||
class StreamBridge(abc.ABC):
|
||||
"""Abstract base for stream bridges."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def publish(self, run_id: str, event: str, data: Any) -> None:
|
||||
"""Enqueue a single event for *run_id* (producer side)."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def publish_end(self, run_id: str) -> None:
|
||||
"""Signal that no more events will be produced for *run_id*."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def subscribe(
|
||||
self,
|
||||
run_id: str,
|
||||
*,
|
||||
last_event_id: str | None = None,
|
||||
heartbeat_interval: float = 15.0,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
"""Async iterator that yields events for *run_id* (consumer side).
|
||||
|
||||
Yields :data:`HEARTBEAT_SENTINEL` when no event arrives within
|
||||
*heartbeat_interval* seconds. Yields :data:`END_SENTINEL` once
|
||||
the producer calls :meth:`publish_end`.
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def cleanup(self, run_id: str, *, delay: float = 0) -> None:
|
||||
"""Release resources associated with *run_id*.
|
||||
|
||||
If *delay* > 0 the implementation should wait before releasing,
|
||||
giving late subscribers a chance to drain remaining events.
|
||||
"""
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Release backend resources. Default is a no-op."""
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
"""In-memory stream bridge backed by an in-process event log."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from .base import END_SENTINEL, HEARTBEAT_SENTINEL, StreamBridge, StreamEvent
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _RunStream:
|
||||
events: list[StreamEvent] = field(default_factory=list)
|
||||
condition: asyncio.Condition = field(default_factory=asyncio.Condition)
|
||||
ended: bool = False
|
||||
start_offset: int = 0
|
||||
|
||||
|
||||
class MemoryStreamBridge(StreamBridge):
|
||||
"""Per-run in-memory event log implementation.
|
||||
|
||||
Events are retained for a bounded time window per run so late subscribers
|
||||
and reconnecting clients can replay buffered events from ``Last-Event-ID``.
|
||||
"""
|
||||
|
||||
def __init__(self, *, queue_maxsize: int = 256) -> None:
|
||||
self._maxsize = queue_maxsize
|
||||
self._streams: dict[str, _RunStream] = {}
|
||||
self._counters: dict[str, int] = {}
|
||||
|
||||
# -- helpers ---------------------------------------------------------------
|
||||
|
||||
def _get_or_create_stream(self, run_id: str) -> _RunStream:
|
||||
if run_id not in self._streams:
|
||||
self._streams[run_id] = _RunStream()
|
||||
self._counters[run_id] = 0
|
||||
return self._streams[run_id]
|
||||
|
||||
def _next_id(self, run_id: str) -> str:
|
||||
self._counters[run_id] = self._counters.get(run_id, 0) + 1
|
||||
ts = int(time.time() * 1000)
|
||||
seq = self._counters[run_id] - 1
|
||||
return f"{ts}-{seq}"
|
||||
|
||||
def _resolve_start_offset(self, stream: _RunStream, last_event_id: str | None) -> int:
|
||||
if last_event_id is None:
|
||||
return stream.start_offset
|
||||
|
||||
for index, entry in enumerate(stream.events):
|
||||
if entry.id == last_event_id:
|
||||
return stream.start_offset + index + 1
|
||||
|
||||
if stream.events:
|
||||
logger.warning(
|
||||
"last_event_id=%s not found in retained buffer; replaying from earliest retained event",
|
||||
last_event_id,
|
||||
)
|
||||
return stream.start_offset
|
||||
|
||||
# -- StreamBridge API ------------------------------------------------------
|
||||
|
||||
async def publish(self, run_id: str, event: str, data: Any) -> None:
|
||||
stream = self._get_or_create_stream(run_id)
|
||||
entry = StreamEvent(id=self._next_id(run_id), event=event, data=data)
|
||||
async with stream.condition:
|
||||
stream.events.append(entry)
|
||||
if len(stream.events) > self._maxsize:
|
||||
overflow = len(stream.events) - self._maxsize
|
||||
del stream.events[:overflow]
|
||||
stream.start_offset += overflow
|
||||
stream.condition.notify_all()
|
||||
|
||||
async def publish_end(self, run_id: str) -> None:
|
||||
stream = self._get_or_create_stream(run_id)
|
||||
async with stream.condition:
|
||||
stream.ended = True
|
||||
stream.condition.notify_all()
|
||||
|
||||
async def subscribe(
|
||||
self,
|
||||
run_id: str,
|
||||
*,
|
||||
last_event_id: str | None = None,
|
||||
heartbeat_interval: float = 15.0,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
stream = self._get_or_create_stream(run_id)
|
||||
async with stream.condition:
|
||||
next_offset = self._resolve_start_offset(stream, last_event_id)
|
||||
|
||||
while True:
|
||||
async with stream.condition:
|
||||
if next_offset < stream.start_offset:
|
||||
logger.warning(
|
||||
"subscriber for run %s fell behind retained buffer; resuming from offset %s",
|
||||
run_id,
|
||||
stream.start_offset,
|
||||
)
|
||||
next_offset = stream.start_offset
|
||||
|
||||
local_index = next_offset - stream.start_offset
|
||||
if 0 <= local_index < len(stream.events):
|
||||
entry = stream.events[local_index]
|
||||
next_offset += 1
|
||||
elif stream.ended:
|
||||
entry = END_SENTINEL
|
||||
else:
|
||||
try:
|
||||
await asyncio.wait_for(stream.condition.wait(), timeout=heartbeat_interval)
|
||||
except TimeoutError:
|
||||
entry = HEARTBEAT_SENTINEL
|
||||
else:
|
||||
continue
|
||||
|
||||
if entry is END_SENTINEL:
|
||||
yield END_SENTINEL
|
||||
return
|
||||
yield entry
|
||||
|
||||
async def cleanup(self, run_id: str, *, delay: float = 0) -> None:
|
||||
if delay > 0:
|
||||
await asyncio.sleep(delay)
|
||||
self._streams.pop(run_id, None)
|
||||
self._counters.pop(run_id, None)
|
||||
|
||||
async def close(self) -> None:
|
||||
self._streams.clear()
|
||||
self._counters.clear()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Canonical owner resolution for a thread's filesystem paths.
|
||||
|
||||
The agent's generated files (md / artifacts) and uploads live under a
|
||||
*per-user* directory::
|
||||
|
||||
{base_dir}/users/{user_id}/threads/{thread_id}/user-data/...
|
||||
|
||||
Using the request context alone is not reliable for filesystem lookup: an
|
||||
internal call or a context propagation edge case resolves to ``users/default``
|
||||
even though the authenticated route has already verified access to a persisted
|
||||
thread. The thread creator is an immutable, stable filesystem bucket, so all
|
||||
persisted threads resolve to ``threads_meta.user_id``. Task-deeplink and
|
||||
roundtable threads additionally need this because they can intentionally be
|
||||
reopened by another account.
|
||||
|
||||
For missing metadata rows (legacy/memory-mode threads), resolution safely falls
|
||||
back to the current login.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from deerflow.runtime.user_context import get_effective_user_id
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# thread_id -> creator user_id. The pair is immutable for a persisted thread,
|
||||
# so positive results are cached forever; the fallback (current login) is never
|
||||
# cached because a row may appear after the first lookup.
|
||||
_owner_cache: dict[str, str] = {}
|
||||
_owner_cache_lock = threading.Lock()
|
||||
_OWNER_CACHE_MAX = 4096
|
||||
_LOCAL_ONLY_THREAD_PREFIXES = ("open-", "__skill-review__")
|
||||
|
||||
|
||||
def _is_local_only_thread(thread_id: str | None) -> bool:
|
||||
"""Return True for synthetic threads that are never persisted in threads_meta."""
|
||||
return bool(thread_id) and str(thread_id).startswith(_LOCAL_ONLY_THREAD_PREFIXES)
|
||||
|
||||
|
||||
def _cache_get(thread_id: str) -> str | None:
|
||||
with _owner_cache_lock:
|
||||
return _owner_cache.get(thread_id)
|
||||
|
||||
|
||||
def _cache_put(thread_id: str, owner: str) -> None:
|
||||
with _owner_cache_lock:
|
||||
# Crude bound: clear wholesale rather than track LRU order. The mapping
|
||||
# is tiny and immutable, so a rare full clear just re-warms lazily.
|
||||
if len(_owner_cache) >= _OWNER_CACHE_MAX:
|
||||
_owner_cache.clear()
|
||||
_owner_cache[thread_id] = owner
|
||||
|
||||
|
||||
async def _fetch_thread_owner(thread_id: str) -> str | None:
|
||||
"""Return the persisted creator user_id for *thread_id*.
|
||||
|
||||
Returns ``None`` for untracked threads, the memory-mode store, or any DB
|
||||
error — callers then fall back to the current login.
|
||||
"""
|
||||
from deerflow.persistence.engine import get_session_factory
|
||||
from deerflow.persistence.thread_meta import ThreadMetaRepository
|
||||
|
||||
session_factory = get_session_factory()
|
||||
if session_factory is None:
|
||||
return None
|
||||
store = ThreadMetaRepository(session_factory)
|
||||
# user_id=None bypasses the owner filter so we can read any thread's row.
|
||||
row = await store.get(thread_id, user_id=None)
|
||||
if not row:
|
||||
return None
|
||||
owner = row.get("user_id")
|
||||
if owner:
|
||||
return str(owner)
|
||||
return None
|
||||
|
||||
|
||||
def resolve_path_user_id(thread_id: str | None) -> str:
|
||||
"""Canonical user bucket for *thread_id*'s files (sync).
|
||||
|
||||
A persisted thread always uses its creator's stable directory. This is the
|
||||
same bucket as the current user for ordinary owned threads, and also keeps
|
||||
file lookup correct when request context is unavailable. Legacy/untracked
|
||||
threads use the current login (``get_effective_user_id``).
|
||||
"""
|
||||
if not thread_id or _is_local_only_thread(thread_id):
|
||||
return get_effective_user_id()
|
||||
cached = _cache_get(thread_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
from deerflow.persistence.engine import run_db_blocking
|
||||
|
||||
owner = run_db_blocking(_fetch_thread_owner(thread_id))
|
||||
except Exception:
|
||||
logger.debug("Failed to resolve creator for thread %s", thread_id, exc_info=True)
|
||||
owner = None
|
||||
if owner:
|
||||
_cache_put(thread_id, owner)
|
||||
return owner
|
||||
return get_effective_user_id()
|
||||
|
||||
|
||||
async def aresolve_path_user_id(thread_id: str | None) -> str:
|
||||
"""Async variant of :func:`resolve_path_user_id` for FastAPI handlers."""
|
||||
if not thread_id or _is_local_only_thread(thread_id):
|
||||
return get_effective_user_id()
|
||||
cached = _cache_get(thread_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
owner = await _fetch_thread_owner(thread_id)
|
||||
except Exception:
|
||||
logger.debug("Failed to resolve creator for thread %s", thread_id, exc_info=True)
|
||||
owner = None
|
||||
if owner:
|
||||
_cache_put(thread_id, owner)
|
||||
return owner
|
||||
return get_effective_user_id()
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Request-scoped user context for user-based authorization.
|
||||
|
||||
This module holds a :class:`~contextvars.ContextVar` that the gateway's
|
||||
auth middleware sets after a successful authentication. Repository
|
||||
methods read the contextvar via a sentinel default parameter, letting
|
||||
routers stay free of ``user_id`` boilerplate.
|
||||
|
||||
Three-state semantics for the repository ``user_id`` parameter (the
|
||||
consumer side of this module lives in ``deerflow.persistence.*``):
|
||||
|
||||
- ``_AUTO`` (module-private sentinel, default): read from contextvar;
|
||||
raise :class:`RuntimeError` if unset.
|
||||
- Explicit ``str``: use the provided value, overriding contextvar.
|
||||
- Explicit ``None``: no WHERE clause — used only by migration scripts
|
||||
and admin CLIs that intentionally bypass isolation.
|
||||
|
||||
Dependency direction
|
||||
--------------------
|
||||
``persistence`` (lower layer) reads from this module; ``gateway.auth``
|
||||
(higher layer) writes to it. ``CurrentUser`` is defined here as a
|
||||
:class:`typing.Protocol` so that ``persistence`` never needs to import
|
||||
the concrete ``User`` class from ``gateway.auth.models``. Any object
|
||||
with an ``.id: str`` attribute structurally satisfies the protocol.
|
||||
|
||||
Asyncio semantics
|
||||
-----------------
|
||||
``ContextVar`` is task-local under asyncio, not thread-local. Each
|
||||
FastAPI request runs in its own task, so the context is naturally
|
||||
isolated. ``asyncio.create_task`` and ``asyncio.to_thread`` inherit the
|
||||
parent task's context, which is typically the intended behaviour; if
|
||||
a background task must *not* see the foreground user, wrap it with
|
||||
``contextvars.copy_context()`` to get a clean copy.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextvars import ContextVar, Token
|
||||
from typing import Final, Protocol, runtime_checkable
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class CurrentUser(Protocol):
|
||||
"""Structural type for the current authenticated user.
|
||||
|
||||
Any object with an ``.id: str`` attribute satisfies this protocol.
|
||||
Concrete implementations live in ``app.gateway.auth.models.User``.
|
||||
"""
|
||||
|
||||
id: str
|
||||
|
||||
|
||||
_current_user: Final[ContextVar[CurrentUser | None]] = ContextVar("deerflow_current_user", default=None)
|
||||
|
||||
|
||||
def set_current_user(user: CurrentUser) -> Token[CurrentUser | None]:
|
||||
"""Set the current user for this async task.
|
||||
|
||||
Returns a reset token that should be passed to
|
||||
:func:`reset_current_user` in a ``finally`` block to restore the
|
||||
previous context.
|
||||
"""
|
||||
return _current_user.set(user)
|
||||
|
||||
|
||||
def reset_current_user(token: Token[CurrentUser | None]) -> None:
|
||||
"""Restore the context to the state captured by ``token``."""
|
||||
_current_user.reset(token)
|
||||
|
||||
|
||||
def get_current_user() -> CurrentUser | None:
|
||||
"""Return the current user, or ``None`` if unset.
|
||||
|
||||
Safe to call in any context. Used by code paths that can proceed
|
||||
without a user (e.g. migration scripts, public endpoints).
|
||||
"""
|
||||
return _current_user.get()
|
||||
|
||||
|
||||
def require_current_user() -> CurrentUser:
|
||||
"""Return the current user, or raise :class:`RuntimeError`.
|
||||
|
||||
Used by repository code that must not be called outside a
|
||||
request-authenticated context. The error message is phrased so
|
||||
that a caller debugging a stack trace can locate the offending
|
||||
code path.
|
||||
"""
|
||||
user = _current_user.get()
|
||||
if user is None:
|
||||
raise RuntimeError("repository accessed without user context")
|
||||
return user
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Effective user_id helpers (filesystem isolation)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
DEFAULT_USER_ID: Final[str] = "default"
|
||||
|
||||
|
||||
def get_effective_user_id() -> str:
|
||||
"""Return the current user's id as a string, or DEFAULT_USER_ID if unset.
|
||||
|
||||
Unlike :func:`require_current_user` this never raises — it is designed
|
||||
for filesystem-path resolution where a valid user bucket is always needed.
|
||||
"""
|
||||
user = _current_user.get()
|
||||
if user is None:
|
||||
return DEFAULT_USER_ID
|
||||
return str(user.id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sentinel-based user_id resolution
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# Repository methods accept a ``user_id`` keyword-only argument that
|
||||
# defaults to ``AUTO``. The three possible values drive distinct
|
||||
# behaviours; see the docstring on :func:`resolve_user_id`.
|
||||
|
||||
|
||||
class _AutoSentinel:
|
||||
"""Singleton marker meaning 'resolve user_id from contextvar'."""
|
||||
|
||||
_instance: _AutoSentinel | None = None
|
||||
|
||||
def __new__(cls) -> _AutoSentinel:
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "<AUTO>"
|
||||
|
||||
|
||||
AUTO: Final[_AutoSentinel] = _AutoSentinel()
|
||||
|
||||
|
||||
def resolve_user_id(
|
||||
value: str | None | _AutoSentinel,
|
||||
*,
|
||||
method_name: str = "repository method",
|
||||
) -> str | None:
|
||||
"""Resolve the user_id parameter passed to a repository method.
|
||||
|
||||
Three-state semantics:
|
||||
|
||||
- :data:`AUTO` (default): read from contextvar; raise
|
||||
:class:`RuntimeError` if no user is in context. This is the
|
||||
common case for request-scoped calls.
|
||||
- Explicit ``str``: use the provided id verbatim, overriding any
|
||||
contextvar value. Useful for tests and admin-override flows.
|
||||
- Explicit ``None``: no filter — the repository should skip the
|
||||
user_id WHERE clause entirely. Reserved for migration scripts
|
||||
and CLI tools that intentionally bypass isolation.
|
||||
"""
|
||||
if isinstance(value, _AutoSentinel):
|
||||
user = _current_user.get()
|
||||
if user is None:
|
||||
raise RuntimeError(f"{method_name} called with user_id=AUTO but no user context is set; pass an explicit user_id, set the contextvar via auth middleware, or opt out with user_id=None for migration/CLI paths.")
|
||||
# Coerce to ``str`` at the boundary: ``User.id`` is typed as
|
||||
# ``UUID`` for the API surface, but the persistence layer
|
||||
# stores ``user_id`` as ``String(64)`` and aiosqlite cannot
|
||||
# bind a raw UUID object to a VARCHAR column ("type 'UUID' is
|
||||
# not supported"). Honour the documented return type here
|
||||
# rather than ripple a type change through every caller.
|
||||
return str(user.id)
|
||||
return value
|
||||
Reference in new issue
Block a user