From 8cdc45ffa39003bdfa2da252210838973b790918 Mon Sep 17 00:00:00 2001 From: YuanShiJiLoong <2450829984@qq.com> Date: Sun, 22 Feb 2026 01:01:05 +0900 Subject: [PATCH] v1.0.0 - Author AI Writing Platform --- .gitignore | 41 + LICENSE | 661 ++ README.md | 141 + README.zh.md | 141 + app/api/ai/gemini/models/route.js | 62 + app/api/ai/gemini/route.js | 158 + app/api/ai/models/route.js | 111 + app/api/ai/route.js | 145 + app/api/ai/test/route.js | 105 + app/api/embed/route.js | 100 + app/components/AiSidebar.js | 1089 +++ app/components/ChatMarkdown.js | 94 + app/components/Editor.js | 1168 ++++ app/components/GhostMark.js | 99 + app/components/HelpPanel.js | 503 ++ app/components/MathExtension.js | 282 + app/components/PageBreakExtension.js | 312 + app/components/SettingsItemEditor.js | 457 ++ app/components/SettingsPanel.js | 752 ++ app/components/SettingsTree.js | 267 + app/components/Sidebar.js | 321 + app/components/SnapshotManager.js | 226 + app/components/TourOverlay.js | 280 + app/components/WelcomeModal.js | 118 + app/favicon.ico | Bin 0 -> 25931 bytes app/globals.css | 4742 +++++++++++++ app/layout.js | 42 + app/lib/chat-sessions.js | 306 + app/lib/context-engine.js | 827 +++ app/lib/embeddings.js | 58 + app/lib/project-io.js | 134 + app/lib/settings.js | 717 ++ app/lib/snapshots.js | 101 + app/lib/storage.js | 137 + app/lib/useI18n.js | 38 + app/locales/en.json | 405 ++ app/locales/ru.json | 405 ++ app/locales/zh.json | 405 ++ app/page.js | 359 + app/store/useAppStore.js | 90 + eslint.config.mjs | 16 + image-1.png | Bin 0 -> 29827 bytes image-2.png | Bin 0 -> 29827 bytes image-3.png | Bin 0 -> 29827 bytes image.png | Bin 0 -> 29827 bytes jsconfig.json | 7 + next.config.mjs | 6 + package-lock.json | 9565 ++++++++++++++++++++++++++ package.json | 46 + postcss.config.mjs | 7 + public/file.svg | 1 + public/globe.svg | 1 + public/next.svg | 1 + public/vercel.svg | 1 + public/window.svg | 1 + 55 files changed, 26051 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 README.zh.md create mode 100644 app/api/ai/gemini/models/route.js create mode 100644 app/api/ai/gemini/route.js create mode 100644 app/api/ai/models/route.js create mode 100644 app/api/ai/route.js create mode 100644 app/api/ai/test/route.js create mode 100644 app/api/embed/route.js create mode 100644 app/components/AiSidebar.js create mode 100644 app/components/ChatMarkdown.js create mode 100644 app/components/Editor.js create mode 100644 app/components/GhostMark.js create mode 100644 app/components/HelpPanel.js create mode 100644 app/components/MathExtension.js create mode 100644 app/components/PageBreakExtension.js create mode 100644 app/components/SettingsItemEditor.js create mode 100644 app/components/SettingsPanel.js create mode 100644 app/components/SettingsTree.js create mode 100644 app/components/Sidebar.js create mode 100644 app/components/SnapshotManager.js create mode 100644 app/components/TourOverlay.js create mode 100644 app/components/WelcomeModal.js create mode 100644 app/favicon.ico create mode 100644 app/globals.css create mode 100644 app/layout.js create mode 100644 app/lib/chat-sessions.js create mode 100644 app/lib/context-engine.js create mode 100644 app/lib/embeddings.js create mode 100644 app/lib/project-io.js create mode 100644 app/lib/settings.js create mode 100644 app/lib/snapshots.js create mode 100644 app/lib/storage.js create mode 100644 app/lib/useI18n.js create mode 100644 app/locales/en.json create mode 100644 app/locales/ru.json create mode 100644 app/locales/zh.json create mode 100644 app/page.js create mode 100644 app/store/useAppStore.js create mode 100644 eslint.config.mjs create mode 100644 image-1.png create mode 100644 image-2.png create mode 100644 image-3.png create mode 100644 image.png create mode 100644 jsconfig.json create mode 100644 next.config.mjs create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 postcss.config.mjs create mode 100644 public/file.svg create mode 100644 public/globe.svg create mode 100644 public/next.svg create mode 100644 public/vercel.svg create mode 100644 public/window.svg diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5ef6a52 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1ed37e2 --- /dev/null +++ b/README.md @@ -0,0 +1,141 @@ +**English** | [简体中文](README.zh.md) + +# ✍️ Author — AI-Powered Creative Writing Platform + +> An AI-powered writing studio for novelists, screenwriters, and storytellers. + +**Author** is an AI-assisted creative writing tool designed for fiction writers. It brings together a professional rich text editor, an intelligent AI writing assistant, and a complete worldbuilding management system — all in one seamless experience. + +--- + +## 💬 Why I Built This + +I've been using AI for a while now — from the early days of ChatGPT 3.5, to Gemini 2.0 Exp Thinking, and eventually settling on Gemini 2.5 Pro Thinking after the ChatGPT o1 era. + +As a novelist, I care deeply about AI's ability to handle language. Novels are long, so I need models with strong context windows and high recall. But what truly moved me about Gemini was its characters — there were moments when the words on screen made me want to cry. That's emotional resonance. I need writing that embraces the full complexity of being human. + +Then the coding-focused trend took over. Every company started optimizing for code. I thought it was a good thing — until Gemini 3.1 Pro started describing its characters in biological and psychological terminology. Code-optimized models had begun deconstructing humans into biological components. Claude Opus 4.6 was even worse: every character spoke with peak efficiency — concise, economical, not like a human, but like a machine wearing a human mask. + +**I could no longer see the models understanding human complexity. They didn't care about what humans *do* — only what humans *are*. They stopped showing personality through behavior and emotion, and instead slapped simple definitions onto human beings.** + +I watched the versatility of these models being gutted. I don't want us to live in a cold world of code. I built this project so that AI can preserve **our own language** — beyond the mechanical operators. + +> To all the authors, screenwriters, hobbyists, readers, and players who use this project: I hope you can bring out the best of your craft, create works with a human touch, and keep the flame of our language alive. 🔥 + +--- + +## ✨ Features + +### 📝 Professional Editor +- Rich text editor powered by **Tiptap** — bold, italic, headings, lists, code blocks, and more +- **Word-style pagination** with WYSIWYG layout +- **KaTeX** math formula support +- Customizable fonts, font size, line height, and colors +- Real-time word / character / paragraph count + +### 🤖 AI Writing Assistant +- **Multi-provider support**: ZhipuAI GLM-4 / DeepSeek / OpenAI / Google Gemini +- **Continue / Rewrite / Polish / Expand** — one-click generation +- **Ghost Text** streaming preview — see AI output in real-time like Cursor, with accept/reject +- **Free chat mode** — discuss plot, characters, and settings with AI +- **Context engine** — AI automatically reads your character profiles, worldbuilding, and previous chapters to maintain story consistency + +### 📚 Worldbuilding Manager +- **Tree-structured** management for characters, locations, items, outlines, and writing rules +- Three writing modes: **Web Novel** / **Literary Fiction** / **Screenplay**, each with dedicated fields +- Color-coded categories with glassmorphism design +- Settings automatically injected into AI context + +### 💾 Data Management +- **Local-first** — all data stored in browser IndexedDB, never uploaded to servers +- **Snapshot system** — manual/auto versioning with one-click rollback +- **Project import/export** — full project JSON backup +- **Markdown export** — single chapter or entire book + +### 🌐 Internationalization +- 🇨🇳 简体中文 / 🇺🇸 English / 🇷🇺 Русский + +### 🎨 User Experience +- Eye-comfort warm tones / dark mode toggle +- Interactive onboarding tour +- Help panel with keyboard shortcuts + +--- + +## 🚀 Getting Started + +### Requirements +- **Node.js** 18+ +- **npm** 9+ + +### Installation + +```bash +# Clone the repository +git clone https://github.com/YuanShiJiLoong/author.git +cd author + +# Install dependencies +npm install + +# Configure environment variables (optional) +cp .env.example .env.local +# Edit .env.local with your API keys +# You can also configure them in the app's Settings panel +``` + +### Development Server + +```bash +npm run dev +``` + +Open [http://localhost:3000](http://localhost:3000) to start writing. + +### Production Build + +```bash +npm run build +npm start +``` + +### Deploy to Vercel + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/YuanShiJiLoong/author) + +--- + +## ⚙️ AI Configuration + +Author supports multiple AI providers. Configure via **environment variables** or **in-app settings**: + +| Provider | Env Variable | Get API Key | +|----------|-------------|-------------| +| ZhipuAI (GLM-4) | `ZHIPU_API_KEY` | [open.bigmodel.cn](https://open.bigmodel.cn/) | +| Google Gemini | `GEMINI_API_KEY` | [aistudio.google.com](https://aistudio.google.com/apikey) | +| DeepSeek | In-app config | [platform.deepseek.com](https://platform.deepseek.com/) | +| OpenAI / Compatible | In-app config | [platform.openai.com](https://platform.openai.com/) | + +> 💡 **No API key required** for most editing features. AI features need at least one provider configured. + +--- + +## 📄 License + +This project is licensed under [AGPL-3.0](LICENSE). + +**In short**: +- ✅ Free to use, modify, and distribute +- ✅ Commercial use allowed +- ⚠️ Modified versions must also be open-sourced (including network services) +- ⚠️ Original copyright notice must be preserved + +--- + +## 🙏 Acknowledgments + +- [Google Antigravity](https://antigravity.google/) — AI programming partner +- [Tiptap](https://tiptap.dev/) — Editor framework +- [Next.js](https://nextjs.org/) — React full-stack framework +- [Zustand](https://zustand-demo.pmnd.rs/) — State management +- [KaTeX](https://katex.org/) — Math rendering diff --git a/README.zh.md b/README.zh.md new file mode 100644 index 0000000..84e9c3a --- /dev/null +++ b/README.zh.md @@ -0,0 +1,141 @@ +[English](README.md) | **简体中文** + +# ✍️ Author — AI-Powered Creative Writing Platform + +> AI 驱动的网文创作平台 | AI-Powered Web Novel Writing Studio + +**Author** 是一款面向小说作者的 AI 辅助创作工具。它将专业的富文本编辑器、智能 AI 写作助手和完整的世界观管理系统整合在一起,为创作者提供一站式写作体验。 + +--- + +## 💬 为什么做这个项目 + +我使用 AI 已经有一段日子了,各家公司的模型基本上都用过——从最开始的 ChatGPT 3.5,到 Gemini 2.0 Exp Thinking,接着从 ChatGPT o1 时代之后,彻底转入 Gemini 2.5 Pro Thinking。 + +我本人是写小说的,对 AI 的文字能力比较看重。小说的文本很长,因此我对模型的上下文以及召回率有很高的要求。当然,Gemini 最触动我的点还是祂笔下的人物——总会有那么一瞬间,让我有种想要落泪的冲动。这是情感共鸣。我需要这种接受了人类本身复杂性的文字。 + +然而,随着代码趋势的兴起,所有公司都开始往这个方向死磕。我本来觉得是好事,但当 Gemini 3.1 Pro 第一次将笔下的人物描述成生物学和心理学的术语时,我发现我错了——代码方向的模型将人类本身解构成一堆生物学零件。特别是 Claude Opus 4.6,这个模型笔下的所有人物都在某种心理学定义的性格里达成了极致的效率:说话言简意赅、惜字如金,不像人类,像个人机。 + +**我看不到模型对人类本身复杂性的理解。模型不在乎人类做了什么,只在乎人类是什么。模型不从人的行为去体现人的性格和情感,反而直接对人类本身下一个很简单的定义。** + +我看到模型的通用性在被阉割。我不希望我们活在冰冷的代码世界。建立这个项目,是为了让 AI 能够在那些机械算符之外,**保留我们人类自己的语言**。 + +> 希望所有使用该项目的作者、编剧、爱好者,甚至读者、玩家,能够发挥自己的长处,创建出有人味儿的作品,保住我们自己语言的火种。🔥 + +--- + +## ✨ 核心功能 + +### 📝 专业编辑器 +- 基于 **Tiptap** 的富文本编辑器,支持加粗、斜体、标题、列表、代码块等 +- **Word 风格分页**排版,所见即所得 +- **KaTeX** 数学公式支持 +- 字体、字号、行距、颜色自定义 +- 实时字数/字符/段落统计 + +### 🤖 AI 写作助手 +- **多 AI 供应商**:智谱 GLM-4 / DeepSeek / OpenAI / Google Gemini +- **续写 / 改写 / 润色 / 扩写**,一键生成 +- **Ghost Text** 流式预览 — 像 Cursor 一样实时显示 AI 生成内容,支持接受/拒绝 +- **自由对话模式** — 与 AI 讨论剧情、角色、设定 +- **上下文引擎** — AI 自动感知你的角色设定、世界观、前文,保持剧情连贯 + +### 📚 设定集管理 +- **树形结构**管理角色、地点、物品、大纲、写作规则 +- 三种写作模式:**网文** / **传统文学** / **剧本**,每种模式有专属字段 +- 分类配色 + glassmorphism 视觉风格 +- 设定内容自动注入 AI 上下文 + +### 💾 数据管理 +- **本地优先** — 所有数据存储在浏览器 IndexedDB,不上传服务器 +- **快照系统** — 手动/自动版本存档,支持一键回滚 +- **项目导入导出** — 完整项目 JSON 备份 +- **Markdown 导出** — 单章或全部导出 + +### 🌐 国际化 +- 🇨🇳 简体中文 / 🇺🇸 English / 🇷🇺 Русский + +### 🎨 界面体验 +- 护眼暖色调 / 深色模式切换 +- 新手引导教程 +- 帮助面板 + 快捷键说明 + +--- + +## 🚀 快速开始 + +### 环境要求 +- **Node.js** 18+ +- **npm** 9+ + +### 安装 + +```bash +# 克隆仓库 +git clone https://github.com/YuanShiJiLoong/author.git +cd author + +# 安装依赖 +npm install + +# 配置环境变量(可选) +cp .env.example .env.local +# 编辑 .env.local 填入你的 API Key +# 也可以在应用内「设置」面板中配置 +``` + +### 启动开发服务器 + +```bash +npm run dev +``` + +打开 [http://localhost:3000](http://localhost:3000) 即可使用。 + +### 生产构建 + +```bash +npm run build +npm start +``` + +### 部署到 Vercel + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/YuanShiJiLoong/author) + +--- + +## ⚙️ AI 配置 + +Author 支持多种 AI 供应商,你可以通过 **环境变量** 或 **应用内设置** 来配置: + +| 供应商 | 环境变量 | 获取 API Key | +|--------|---------|-------------| +| 智谱 AI (GLM-4) | `ZHIPU_API_KEY` | [open.bigmodel.cn](https://open.bigmodel.cn/) | +| Google Gemini | `GEMINI_API_KEY` | [aistudio.google.com](https://aistudio.google.com/apikey) | +| DeepSeek | 应用内配置 | [platform.deepseek.com](https://platform.deepseek.com/) | +| OpenAI / 兼容 | 应用内配置 | [platform.openai.com](https://platform.openai.com/) | + +> 💡 **无需 API Key 也能使用**大部分编辑功能。AI 功能需要至少配置一个供应商。 + +--- + +## 开源协议 + +本项目采用 [AGPL-3.0](LICENSE) 协议开源。 + +**简单说**: +- ✅ 你可以自由使用、修改、分发 +- ✅ 你可以用于个人/商业用途 +- ⚠️ 修改后的版本也必须开源(包括网络服务) +- ⚠️ 必须保留原始版权声明 + +--- + +## 🙏 致谢 + +- [Google Antigravity](https://antigravity.google/) — AI 编程伙伴 +- [Tiptap](https://tiptap.dev/) — 编辑器框架 +- [Next.js](https://nextjs.org/) — React 全栈框架 +- [Zustand](https://zustand-demo.pmnd.rs/) — 状态管理 +- [KaTeX](https://katex.org/) — 数学公式渲染 diff --git a/app/api/ai/gemini/models/route.js b/app/api/ai/gemini/models/route.js new file mode 100644 index 0000000..2d7019a --- /dev/null +++ b/app/api/ai/gemini/models/route.js @@ -0,0 +1,62 @@ +import { NextResponse } from 'next/server'; + +// 拉取 Gemini 可用模型列表 +export async function POST(request) { + try { + const { apiKey, baseUrl } = await request.json(); + + if (!apiKey) { + return NextResponse.json( + { error: '请填入 API Key' }, + { status: 400 } + ); + } + + const base = (baseUrl || 'https://generativelanguage.googleapis.com/v1beta').replace(/\/$/, ''); + const url = `${base}/models?key=${apiKey}`; + + const response = await fetch(url, { + method: 'GET', + headers: { 'Content-Type': 'application/json' }, + }); + + if (!response.ok) { + const errorText = await response.text(); + console.error('拉取模型列表失败:', response.status, errorText); + + if (response.status === 401 || response.status === 403) { + return NextResponse.json( + { error: 'API Key 无效或无权限' }, + { status: 401 } + ); + } + return NextResponse.json( + { error: `拉取失败(${response.status})` }, + { status: response.status } + ); + } + + const data = await response.json(); + + // 过滤出支持 generateContent 的模型 + const models = (data.models || []) + .filter(m => m.supportedGenerationMethods?.includes('generateContent')) + .map(m => ({ + id: m.name?.replace('models/', '') || m.name, + displayName: m.displayName || m.name, + description: m.description || '', + inputTokenLimit: m.inputTokenLimit, + outputTokenLimit: m.outputTokenLimit, + })) + .sort((a, b) => a.id.localeCompare(b.id)); + + return NextResponse.json({ models }); + + } catch (error) { + console.error('拉取模型列表错误:', error); + return NextResponse.json( + { error: '网络连接失败' }, + { status: 500 } + ); + } +} diff --git a/app/api/ai/gemini/route.js b/app/api/ai/gemini/route.js new file mode 100644 index 0000000..0f27371 --- /dev/null +++ b/app/api/ai/gemini/route.js @@ -0,0 +1,158 @@ +// Gemini 原生 API — SSE 流式转发(Edge Runtime 确保流式不被缓冲) +// 使用 streamGenerateContent 端点 + +export const runtime = 'edge'; + +export async function POST(request) { + try { + const { systemPrompt, userPrompt, apiConfig, maxTokens } = await request.json(); + + const apiKey = apiConfig?.apiKey || process.env.GEMINI_API_KEY; + let rawBaseUrl = apiConfig?.baseUrl; + if (!rawBaseUrl || rawBaseUrl.includes('open.bigmodel.cn')) { + rawBaseUrl = 'https://generativelanguage.googleapis.com/v1beta'; + } + const baseUrl = rawBaseUrl.replace(/\/$/, ''); + const model = apiConfig?.model || 'gemini-2.0-flash'; + + if (!apiKey) { + return new Response( + JSON.stringify({ error: '请先配置 API Key。点击左下角 ⚙️ → API配置,填入你的 Gemini Key' }), + { status: 400, headers: { 'Content-Type': 'application/json' } } + ); + } + + // 使用 streamGenerateContent 端点 + alt=sse + const url = `${baseUrl}/models/${model}:streamGenerateContent?alt=sse&key=${apiKey}`; + + const requestBody = { + system_instruction: { + parts: [{ text: systemPrompt }] + }, + contents: [ + { + role: 'user', + parts: [{ text: userPrompt }] + } + ], + generationConfig: { + temperature: 0.8, + topP: 0.9, + maxOutputTokens: maxTokens || 4000, + }, + }; + + const response = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(requestBody), + }); + + if (!response.ok) { + const errorText = await response.text(); + console.error('Gemini API错误:', response.status, errorText); + + const errorHandlers = { + 400: () => { + try { + const errObj = JSON.parse(errorText); + return `Gemini 请求错误:${errObj?.error?.message || errorText}`; + } catch { + return `Gemini 请求错误(400):${errorText}`; + } + }, + 401: () => 'API Key 无效或无权限,请检查你的 Gemini API Key', + 403: () => 'API Key 无效或无权限,请检查你的 Gemini API Key', + 429: () => '请求频率过高或配额不足,请稍后再试', + }; + const errMsg = errorHandlers[response.status]?.() + || `Gemini 服务返回错误(${response.status}),请检查 API 配置`; + + return new Response( + JSON.stringify({ error: errMsg }), + { status: response.status, headers: { 'Content-Type': 'application/json' } } + ); + } + + // 将 Gemini SSE 流转换为统一格式转发给前端 + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + + const stream = new ReadableStream({ + async start(controller) { + const reader = response.body.getReader(); + let buffer = ''; + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; + + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith(':')) continue; + + if (trimmed.startsWith('data: ')) { + try { + const json = JSON.parse(trimmed.slice(6)); + const candidate = json.candidates?.[0]; + const parts = candidate?.content?.parts || []; + + for (const part of parts) { + if (part.thought === true && part.text) { + // Gemini 思维链 + controller.enqueue(encoder.encode(`data: ${JSON.stringify({ thinking: part.text })}\n\n`)); + } else if (part.text) { + // 正文内容 + controller.enqueue(encoder.encode(`data: ${JSON.stringify({ text: part.text })}\n\n`)); + } + } + + // 提取 usage(通常在最后一个 chunk) + const usageMeta = json.usageMetadata; + if (usageMeta?.totalTokenCount) { + controller.enqueue(encoder.encode(`data: ${JSON.stringify({ + usage: { + promptTokens: usageMeta.promptTokenCount || 0, + completionTokens: usageMeta.candidatesTokenCount || 0, + totalTokens: usageMeta.totalTokenCount || 0, + } + })}\n\n`)); + } + } catch { + // 解析失败跳过 + } + } + } + } + // 发送结束信号 + controller.enqueue(encoder.encode('data: [DONE]\n\n')); + } catch (err) { + console.error('Gemini Stream 读取错误:', err.message); + } finally { + controller.close(); + reader.releaseLock(); + } + } + }); + + return new Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive', + }, + }); + + } catch (error) { + console.error('Gemini 接口错误:', error); + return new Response( + JSON.stringify({ error: '网络连接失败,请检查 API 地址是否正确' }), + { status: 500, headers: { 'Content-Type': 'application/json' } } + ); + } +} diff --git a/app/api/ai/models/route.js b/app/api/ai/models/route.js new file mode 100644 index 0000000..9921dbd --- /dev/null +++ b/app/api/ai/models/route.js @@ -0,0 +1,111 @@ +import { NextResponse } from 'next/server'; + +// 通用模型列表拉取 — 支持 OpenAI 兼容格式和 Gemini 原生格式 +export async function POST(request) { + try { + const { apiKey, baseUrl, provider } = await request.json(); + + if (!apiKey) { + return NextResponse.json( + { error: '请先填入 API Key' }, + { status: 400 } + ); + } + + // Gemini 原生格式 + if (provider === 'gemini-native') { + return await fetchGeminiModels(apiKey, baseUrl); + } + + // OpenAI 兼容格式(适用于所有其他供应商) + return await fetchOpenAIModels(apiKey, baseUrl); + + } catch (error) { + console.error('拉取模型列表错误:', error); + return NextResponse.json( + { error: '网络连接失败,请检查 API 地址' }, + { status: 500 } + ); + } +} + +// Gemini 原生格式拉取模型 +async function fetchGeminiModels(apiKey, baseUrl) { + const base = (baseUrl || 'https://generativelanguage.googleapis.com/v1beta').replace(/\/$/, ''); + const url = `${base}/models?key=${apiKey}`; + + const response = await fetch(url, { + method: 'GET', + headers: { 'Content-Type': 'application/json' }, + }); + + if (!response.ok) { + return handleFetchError(response); + } + + const data = await response.json(); + const models = (data.models || []) + .filter(m => m.supportedGenerationMethods?.includes('generateContent') || m.supportedGenerationMethods?.includes('embedContent')) + .map(m => ({ + id: m.name?.replace('models/', '') || m.name, + displayName: m.displayName || m.name, + })) + .sort((a, b) => a.id.localeCompare(b.id)); + + return NextResponse.json({ models }); +} + +// OpenAI 兼容格式拉取模型(/v1/models) +async function fetchOpenAIModels(apiKey, baseUrl) { + const base = (baseUrl || '').replace(/\/$/, ''); + if (!base) { + return NextResponse.json( + { error: '请先填写 API 地址' }, + { status: 400 } + ); + } + + const url = `${base}/models`; + + const response = await fetch(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${apiKey}`, + }, + }); + + if (!response.ok) { + return handleFetchError(response); + } + + const data = await response.json(); + // OpenAI 格式返回 { data: [{id, ...}, ...] } + const models = (data.data || []) + .map(m => ({ + id: m.id, + displayName: m.id, + })) + .sort((a, b) => a.id.localeCompare(b.id)); + + return NextResponse.json({ models }); +} + +async function handleFetchError(response) { + const errorText = await response.text(); + if (response.status === 401 || response.status === 403) { + return NextResponse.json( + { error: 'API Key 无效或无权限' }, + { status: 401 } + ); + } + let errMsg = `拉取失败(${response.status})`; + try { + const errObj = JSON.parse(errorText); + errMsg = errObj?.error?.message || errMsg; + } catch { /* ignore */ } + return NextResponse.json( + { error: errMsg }, + { status: response.status } + ); +} diff --git a/app/api/ai/route.js b/app/api/ai/route.js new file mode 100644 index 0000000..73aed98 --- /dev/null +++ b/app/api/ai/route.js @@ -0,0 +1,145 @@ +// OpenAI 兼容 API — SSE 流式转发(Edge Runtime 确保流式不被缓冲) +// 支持智谱、DeepSeek、OpenAI、Moonshot 等所有兼容 OpenAI 格式的 API + +export const runtime = 'edge'; + +export async function POST(request) { + try { + const { systemPrompt, userPrompt, apiConfig, maxTokens } = await request.json(); + + const apiKey = apiConfig?.apiKey || process.env.ZHIPU_API_KEY; + const baseUrl = apiConfig?.baseUrl || 'https://open.bigmodel.cn/api/paas/v4'; + const model = apiConfig?.model || 'glm-4-flash'; + + if (!apiKey) { + return new Response( + JSON.stringify({ error: '请先配置 API Key。点击左下角 ⚙️ → API配置,填入你的 Key' }), + { status: 400, headers: { 'Content-Type': 'application/json' } } + ); + } + + const url = `${baseUrl.replace(/\/$/, '')}/chat/completions`; + + // 请求上游 API,开启 stream 模式 + const response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${apiKey}`, + }, + body: JSON.stringify({ + model, + messages: [ + { role: 'system', content: systemPrompt }, + { role: 'user', content: userPrompt } + ], + temperature: 0.8, + max_tokens: maxTokens || 4096, + stream: true, + }), + }); + + if (!response.ok) { + const errorText = await response.text(); + console.error('API错误:', response.status, errorText); + + const errorMessages = { + 401: 'API Key 无效或已过期,请检查后重新填写', + 429: '请求频率过高或额度不足,请稍后再试', + }; + const errMsg = errorMessages[response.status] + || `AI服务返回错误(${response.status}),请检查 API 配置`; + + return new Response( + JSON.stringify({ error: errMsg }), + { status: response.status, headers: { 'Content-Type': 'application/json' } } + ); + } + + // 将上游 SSE 流透传给前端 + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + + const stream = new ReadableStream({ + async start(controller) { + const reader = response.body.getReader(); + let buffer = ''; + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split('\n'); + // 最后一行可能不完整,留到下次 + buffer = lines.pop() || ''; + + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith(':')) continue; + + if (trimmed === 'data: [DONE]') { + controller.enqueue(encoder.encode('data: [DONE]\n\n')); + continue; + } + + if (trimmed.startsWith('data: ')) { + try { + const json = JSON.parse(trimmed.slice(6)); + const delta = json.choices?.[0]?.delta; + + // 转发思维链内容(DeepSeek reasoning_content) + const reasoning = delta?.reasoning_content; + if (reasoning) { + controller.enqueue(encoder.encode(`data: ${JSON.stringify({ thinking: reasoning })}\n\n`)); + } + + // 转发文本 delta + const content = delta?.content; + if (content) { + controller.enqueue(encoder.encode(`data: ${JSON.stringify({ text: content })}\n\n`)); + } + + // 检查是否包含 usage 信息(某些 API 在最后一个事件中返回) + if (json.usage) { + controller.enqueue(encoder.encode(`data: ${JSON.stringify({ + usage: { + promptTokens: json.usage.prompt_tokens || 0, + completionTokens: json.usage.completion_tokens || 0, + totalTokens: json.usage.total_tokens || 0, + } + })}\n\n`)); + } + } catch { + // 解析失败的行直接跳过 + } + } + } + } + } catch (err) { + // 客户端断开等情况 + console.error('Stream 读取错误:', err.message); + } finally { + controller.close(); + reader.releaseLock(); + } + } + }); + + return new Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive', + }, + }); + + } catch (error) { + console.error('AI接口错误:', error); + return new Response( + JSON.stringify({ error: '网络连接失败,请检查 API 地址是否正确' }), + { status: 500, headers: { 'Content-Type': 'application/json' } } + ); + } +} diff --git a/app/api/ai/test/route.js b/app/api/ai/test/route.js new file mode 100644 index 0000000..66cdeda --- /dev/null +++ b/app/api/ai/test/route.js @@ -0,0 +1,105 @@ +import { NextResponse } from 'next/server'; + +// 测试 API 连接(通用 — 支持 OpenAI 兼容格式和 Gemini 原生格式) +export async function POST(request) { + try { + const { apiConfig } = await request.json(); + const { apiKey, baseUrl, model, provider } = apiConfig || {}; + + if (!apiKey) { + return NextResponse.json( + { success: false, error: '请先填入 API Key' }, + { status: 400 } + ); + } + + // Gemini 原生格式的测试 + if (provider === 'gemini-native') { + return await testGeminiNative(apiKey, baseUrl, model); + } + + // OpenAI 兼容格式的测试 + return await testOpenAICompat(apiKey, baseUrl, model); + + } catch (error) { + console.error('API测试错误:', error); + return NextResponse.json( + { success: false, error: '网络连接失败,请检查 API 地址' }, + { status: 500 } + ); + } +} + +async function testGeminiNative(apiKey, baseUrl, model) { + const base = (baseUrl || 'https://generativelanguage.googleapis.com/v1beta').replace(/\/$/, ''); + const m = model || 'gemini-2.0-flash'; + const url = `${base}/models/${m}:generateContent?key=${apiKey}`; + + const response = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + contents: [{ role: 'user', parts: [{ text: '说"连接成功"' }] }], + generationConfig: { maxOutputTokens: 20 }, + }), + }); + + if (!response.ok) { + const errText = await response.text(); + let errMsg = `连接失败(${response.status})`; + try { + const errObj = JSON.parse(errText); + errMsg = errObj?.error?.message || errMsg; + } catch { /* ignore parse error */ } + return NextResponse.json({ success: false, error: errMsg }); + } + + const data = await response.json(); + const reply = data.candidates?.[0]?.content?.parts?.[0]?.text || ''; + + return NextResponse.json({ + success: true, + message: `✅ Gemini 原生 API 连接成功!`, + model: m, + reply: reply.trim(), + }); +} + +async function testOpenAICompat(apiKey, baseUrl, model) { + const base = (baseUrl || 'https://open.bigmodel.cn/api/paas/v4').replace(/\/$/, ''); + const m = model || 'gpt-4o-mini'; + const url = `${base}/chat/completions`; + + const response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${apiKey}`, + }, + body: JSON.stringify({ + model: m, + messages: [{ role: 'user', content: '说"连接成功"' }], + max_tokens: 20, + }), + }); + + if (!response.ok) { + const errText = await response.text(); + let errMsg = `连接失败(${response.status})`; + try { + const errObj = JSON.parse(errText); + errMsg = errObj?.error?.message || errMsg; + } catch { /* ignore parse error */ } + return NextResponse.json({ success: false, error: errMsg }); + } + + const data = await response.json(); + const reply = data.choices?.[0]?.message?.content || ''; + + return NextResponse.json({ + success: true, + message: `✅ API 连接成功!`, + model: m, + reply: reply.trim(), + }); +} diff --git a/app/api/embed/route.js b/app/api/embed/route.js new file mode 100644 index 0000000..55185d9 --- /dev/null +++ b/app/api/embed/route.js @@ -0,0 +1,100 @@ +// Gemini 原生 API & OpenAI 兼容 API — 文本向量化 (Text Embeddings) + +export const runtime = 'edge'; + +export async function POST(request) { + try { + const { text, apiConfig } = await request.json(); + + const isCustomEmbed = apiConfig?.useCustomEmbed; + const provider = isCustomEmbed ? apiConfig.embedProvider : (apiConfig?.provider || 'zhipu'); + const apiKey = isCustomEmbed ? (apiConfig.embedApiKey || apiConfig?.apiKey) : apiConfig?.apiKey; + + // 自动识别默认填写或遗留的智谱URL并矫正为对应官方URL + let defaultBaseUrl = provider === 'gemini-native' ? 'https://generativelanguage.googleapis.com/v1beta' : 'https://open.bigmodel.cn/api/paas/v4'; + + let rawBaseUrl; + if (isCustomEmbed) { + rawBaseUrl = apiConfig.embedBaseUrl; + } else { + // 如果是自定义提供商且没开独立Embed,默认继承对聊的baseUrl + rawBaseUrl = apiConfig?.baseUrl || defaultBaseUrl; + } + + if (!rawBaseUrl || (provider === 'gemini-native' && rawBaseUrl.includes('open.bigmodel.cn'))) { + rawBaseUrl = defaultBaseUrl; + } + + const baseUrl = rawBaseUrl.replace(/\/$/, ''); + + let embedModelName; + if (isCustomEmbed) { + embedModelName = apiConfig.embedModel || 'embedding-3'; + } else if (provider === 'custom') { + // 如果没开独立embed,但选了custom,默认用text-embedding-v3-small或用户主模型 + embedModelName = 'text-embedding-v3-small'; + } else { + embedModelName = provider === 'zhipu' ? 'embedding-3' : 'text-embedding-v3-small'; + } + + if (!apiKey) { + return new Response(JSON.stringify({ error: isCustomEmbed ? '请在API配置中填写独立的 Embedding API Key' : '请先配置 API Key' }), { status: 400 }); + } + + if (!text || typeof text !== 'string') { + return new Response(JSON.stringify({ error: '无效的文本输入' }), { status: 400 }); + } + + let embeddings = []; + + if (provider === 'gemini-native') { + const geminiModel = embedModelName || 'text-embedding-004'; + const url = `${baseUrl}/models/${geminiModel}:embedContent?key=${apiKey}`; + console.log('Fetching Gemini Embeddings:', url); + const res = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + model: `models/${geminiModel}`, + content: { parts: [{ text }] } + }) + }); + + if (!res.ok) { + const errText = await res.text(); + throw new Error(`Gemini Embedding Error: ${errText}`); + } + const data = await res.json(); + embeddings = data.embedding.values; + } else { + // OpenAI 兼容格式 + const url = `${baseUrl}/embeddings`; + + const res = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${apiKey}` + }, + body: JSON.stringify({ + input: text, + model: embedModelName + }) + }); + + if (!res.ok) { + const errText = await res.text(); + throw new Error(`Embedding API Error: ${errText}`); + } + const data = await res.json(); + embeddings = data.data[0].embedding; + } + + return new Response(JSON.stringify({ embedding: embeddings }), { + headers: { 'Content-Type': 'application/json' } + }); + } catch (err) { + console.error('Embedding API Error:', err); + return new Response(JSON.stringify({ error: err.message }), { status: 500 }); + } +} diff --git a/app/components/AiSidebar.js b/app/components/AiSidebar.js new file mode 100644 index 0000000..eac151a --- /dev/null +++ b/app/components/AiSidebar.js @@ -0,0 +1,1089 @@ +'use client'; + +import { useState, useRef, useEffect, useCallback, useMemo } from 'react'; +import { INPUT_TOKEN_BUDGET, buildContext, compileSystemPrompt } from '../lib/context-engine'; +import { + saveSessionStore, createSession, deleteSession as deleteSessionFn, + renameSession, switchSession, getActiveSession, addMessage, editMessage as editMsgFn, + deleteMessage as deleteMsgFn, createBranch, addVariant, switchVariant, replaceMessages +} from '../lib/chat-sessions'; +import { getProjectSettings, getActiveWorkId, getSettingsNodes, addSettingsNode, updateSettingsNode, deleteSettingsNode } from '../lib/settings'; +import { useAppStore } from '../store/useAppStore'; +import ChatMarkdown from './ChatMarkdown'; +import { useI18n } from '../lib/useI18n'; + +// 解析消息中的 [SETTINGS_ACTION] 块 +function parseSettingsActions(content) { + if (!content) return { parts: [content || ''], actions: [] }; + const regex = /\[SETTINGS_ACTION\]\s*([\s\S]*?)\s*\[\/SETTINGS_ACTION\]/g; + const parts = []; + const actions = []; + let lastIndex = 0; + let match; + while ((match = regex.exec(content)) !== null) { + if (match.index > lastIndex) parts.push(content.slice(lastIndex, match.index)); + try { + const action = JSON.parse(match[1].trim()); + actions.push(action); + parts.push({ _action: true, index: actions.length - 1 }); + } catch { + parts.push(match[0]); // parse failed, show raw + } + lastIndex = regex.lastIndex; + } + if (lastIndex < content.length) parts.push(content.slice(lastIndex)); + return { parts, actions }; +} + +// Removed static label maps in favor of i18n + +// ==================== AI 对话侧栏 ==================== +export default function AiSidebar({ onInsertText }) { + const { + aiSidebarOpen: open, setAiSidebarOpen, setShowSettings, + activeChapterId, + sessionStore, setSessionStore, + chatStreaming, setChatStreaming, + generationArchive, + contextItems, contextSelection, setContextSelection, + showToast + } = useAppStore(); + const { t } = useI18n(); + + const onClose = useCallback(() => setAiSidebarOpen(false), [setAiSidebarOpen]); + const onOpenSettings = useCallback(() => { setAiSidebarOpen(false); setShowSettings(true); }, [setAiSidebarOpen, setShowSettings]); + + // 派生状态 + const activeSession = useMemo(() => getActiveSession(sessionStore), [sessionStore]); + const chatHistory = useMemo(() => activeSession?.messages || [], [activeSession]); + + // 会话管理回调 + const setChatHistory = useCallback((newMessages) => setSessionStore(prev => replaceMessages(prev, newMessages)), [setSessionStore]); + const onNewSession = useCallback(() => setSessionStore(prev => createSession(prev)), [setSessionStore]); + const onDeleteSession = useCallback((id) => setSessionStore(prev => deleteSessionFn(prev, id)), [setSessionStore]); + const onRenameSession = useCallback((id, title) => setSessionStore(prev => renameSession(prev, id, title)), [setSessionStore]); + const onSwitchSession = useCallback((id) => setSessionStore(prev => switchSession(prev, id)), [setSessionStore]); + const onEditMessage = useCallback((msgId, newContent) => setSessionStore(prev => editMsgFn(prev, msgId, newContent)), [setSessionStore]); + const onDeleteMessage = useCallback((msgId) => setSessionStore(prev => deleteMsgFn(prev, msgId)), [setSessionStore]); + const onBranch = useCallback((msgId) => setSessionStore(prev => createBranch(prev, msgId)), [setSessionStore]); + const onSwitchVariant = useCallback((msgId, variantIndex) => setSessionStore(prev => switchVariant(prev, msgId, variantIndex)), [setSessionStore]); + const [activeTab, setActiveTab] = useState('chat'); + const [inputText, setInputText] = useState(''); + const [archiveSearch, setArchiveSearch] = useState(''); + const [expandedArchive, setExpandedArchive] = useState(null); + // 对话历史勾选状态 + const [checkedHistory, setCheckedHistory] = useState(new Set()); + const [slidingWindow, setSlidingWindow] = useState(false); + const [slidingWindowSize, setSlidingWindowSize] = useState(8); + // 总结编辑 + const [summaryDraft, setSummaryDraft] = useState(null); + // 参考 Tab 状态 + const [contextSearch, setContextSearch] = useState(''); + const [collapsedGroups, setCollapsedGroups] = useState(new Set()); + // 消息编辑状态 + const [editingMsgId, setEditingMsgId] = useState(null); + const [editingContent, setEditingContent] = useState(''); + // 会话重命名 + const [renamingSessionId, setRenamingSessionId] = useState(null); + const [renameTitle, setRenameTitle] = useState(''); + // 显示会话列表 + const [showSessionList, setShowSessionList] = useState(false); + // 设定操作卡片展开状态 + const [expandedActions, setExpandedActions] = useState(new Set()); + + const chatEndRef = useRef(null); + const chatContainerRef = useRef(null); + const inputRef = useRef(null); + + // 新消息时只在用户已滚动到底部时才自动滚动(不劫持用户滚动) + useEffect(() => { + const container = chatContainerRef.current; + if (!container) { + chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); + return; + } + const threshold = 80; + const isNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < threshold; + if (isNearBottom) { + chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); + } + }, [chatHistory]); + + // 切到聊天 Tab 时聚焦输入框 + useEffect(() => { + if (activeTab === 'chat' && open) { + setTimeout(() => inputRef.current?.focus(), 100); + } + }, [activeTab, open]); + + // 新消息自动加入 checkedHistory(仅追加,不全量重置) + useEffect(() => { + if (chatHistory.length === 0) { + setCheckedHistory(new Set()); + return; + } + setCheckedHistory(prev => { + const next = new Set(prev); + for (const m of chatHistory) { + if (!next.has(m.id)) next.add(m.id); + } + // 清理已删除的消息 ID + const currentIds = new Set(chatHistory.map(m => m.id)); + for (const id of next) { + if (!currentIds.has(id)) next.delete(id); + } + return next; + }); + }, [chatHistory]); + + // 滑动窗口联动 + useEffect(() => { + if (slidingWindow && chatHistory.length > 0) { + const recent = chatHistory.slice(-slidingWindowSize); + setCheckedHistory(new Set(recent.map(m => m.id))); + } + }, [slidingWindow, slidingWindowSize, chatHistory.length]); + + // --- 通用 SSE 流式读取,支持 text+thinking --- + const streamResponse = useCallback(async (apiEndpoint, systemPrompt, userPrompt, apiConfig, onUpdate, onDone) => { + const res = await fetch(apiEndpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ systemPrompt, userPrompt, apiConfig, maxTokens: 2000 }), + }); + + const contentType = res.headers.get('content-type') || ''; + if (contentType.includes('application/json')) { + const data = await res.json(); + throw new Error(data.error || '请求失败'); + } + + const reader = res.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + let fullText = ''; + let fullThinking = ''; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + const events = buffer.split('\n\n'); + buffer = events.pop() || ''; + let hasUpdate = false; + for (const event of events) { + const trimmed = event.trim(); + if (!trimmed || trimmed === 'data: [DONE]') continue; + if (trimmed.startsWith('data: ')) { + try { + const json = JSON.parse(trimmed.slice(6)); + if (json.thinking) { fullThinking += json.thinking; hasUpdate = true; } + if (json.text) { fullText += json.text; hasUpdate = true; } + } catch { } + } + } + if (hasUpdate) onUpdate(fullText, fullThinking); + } + onDone(fullText, fullThinking); + }, []); + + const onChatMessage = useCallback(async (text, selectedHistory) => { + const userMsg = { id: `msg-${Date.now()}-u`, role: 'user', content: text, timestamp: Date.now() }; + setSessionStore(prev => addMessage(prev, userMsg)); + setChatStreaming(true); + const aiMsgId = `msg-${Date.now()}-a`; + + try { + const { apiConfig } = getProjectSettings(); + const apiEndpoint = apiConfig?.provider === 'gemini-native' ? '/api/ai/gemini' : '/api/ai'; + + const context = await buildContext(activeChapterId, '', contextSelection.size > 0 ? contextSelection : null); + const systemPrompt = compileSystemPrompt(context, 'chat'); + const historyForApi = selectedHistory.map(m => `${m.role === 'user' ? t('aiSidebar.roleYou') : t('aiSidebar.roleAi')}: ${m.content}`).join('\n'); + const userPrompt = historyForApi ? `${historyForApi}\n${t('aiSidebar.roleYou')}: ${text}` : text; + + const aiPlaceholder = { id: aiMsgId, role: 'assistant', content: '', thinking: '', timestamp: Date.now() }; + setSessionStore(prev => addMessage(prev, aiPlaceholder)); + + await streamResponse(apiEndpoint, systemPrompt, userPrompt, apiConfig, + (snapText, snapThinking) => { + setSessionStore(prev => ({ + ...prev, sessions: prev.sessions.map(s => { + if (s.id !== prev.activeSessionId) return s; + return { ...s, messages: s.messages.map(m => m.id === aiMsgId ? { ...m, content: snapText, thinking: snapThinking } : m) }; + }), + })); + }, + (finalText, finalThinking) => { + setSessionStore(prev => { + const finalStore = { + ...prev, sessions: prev.sessions.map(s => { + if (s.id !== prev.activeSessionId) return s; + return { + ...s, messages: s.messages.map(m => m.id === aiMsgId ? { ...m, content: finalText || '(AI 未返回内容)', thinking: finalThinking } : m), + updatedAt: Date.now(), + }; + }), + }; + saveSessionStore(finalStore); + return finalStore; + }); + } + ); + } catch (err) { + const errorMsg = { id: `msg-${Date.now()}-e`, role: 'assistant', content: `❌ ${err.message}`, timestamp: Date.now() }; + setSessionStore(prev => addMessage(prev, errorMsg)); + } finally { + setChatStreaming(false); + } + }, [activeChapterId, contextSelection, streamResponse, setSessionStore, setChatStreaming]); + + const onRegenerate = useCallback(async (aiMsgId) => { + if (chatStreaming) return; + + const msgs = chatHistory; + const aiIdx = msgs.findIndex(m => m.id === aiMsgId); + if (aiIdx < 0) return; + + let userMsgIdx = -1; + for (let i = aiIdx - 1; i >= 0; i--) { + if (msgs[i].role === 'user') { userMsgIdx = i; break; } + } + if (userMsgIdx < 0) return; + + const userMsg = msgs[userMsgIdx]; + const priorHistory = msgs.slice(0, userMsgIdx); + setChatStreaming(true); + + try { + const { apiConfig } = getProjectSettings(); + const apiEndpoint = apiConfig?.provider === 'gemini-native' ? '/api/ai/gemini' : '/api/ai'; + + const context = await buildContext(activeChapterId, '', contextSelection.size > 0 ? contextSelection : null); + const systemPrompt = compileSystemPrompt(context, 'chat'); + const historyForApi = priorHistory + .filter(m => m.role === 'user' || m.role === 'assistant') + .map(m => `${m.role === 'user' ? t('aiSidebar.roleYou') : t('aiSidebar.roleAi')}: ${m.content}`).join('\n'); + const userPrompt = historyForApi ? `${historyForApi}\n${t('aiSidebar.roleYou')}: ${userMsg.content}` : userMsg.content; + + setSessionStore(prev => ({ + ...prev, sessions: prev.sessions.map(s => { + if (s.id !== prev.activeSessionId) return s; + return { + ...s, messages: s.messages.map(m => { + if (m.id !== aiMsgId) return m; + const variants = m.variants || [{ content: m.content, thinking: m.thinking || '', timestamp: m.timestamp }]; + return { ...m, variants, content: '', thinking: '' }; + }), + }; + }), + })); + + await streamResponse(apiEndpoint, systemPrompt, userPrompt, apiConfig, + (snapText, snapThinking) => { + setSessionStore(prev => ({ + ...prev, sessions: prev.sessions.map(s => { + if (s.id !== prev.activeSessionId) return s; + return { ...s, messages: s.messages.map(m => m.id === aiMsgId ? { ...m, content: snapText, thinking: snapThinking } : m) }; + }), + })); + }, + (finalText, finalThinking) => { + setSessionStore(prev => { + const newStore = addVariant(prev, aiMsgId, { content: finalText || '(AI 未返回内容)', thinking: finalThinking, timestamp: Date.now() }); + saveSessionStore(newStore); + return newStore; + }); + } + ); + } catch (err) { + setSessionStore(prev => ({ + ...prev, sessions: prev.sessions.map(s => { + if (s.id !== prev.activeSessionId) return s; + return { ...s, messages: s.messages.map(m => m.id === aiMsgId ? { ...m, content: `❌ ${err.message}` } : m) }; + }), + })); + } finally { + setChatStreaming(false); + } + }, [chatHistory, chatStreaming, activeChapterId, contextSelection, streamResponse, setSessionStore, setChatStreaming]); + + const onApplySettingsAction = useCallback(async (action, actionKey) => { + try { + const nodes = await getSettingsNodes(); + const workId = getActiveWorkId() || 'work-default'; + const catToSuffix = { character: 'characters', world: 'world', location: 'locations', object: 'objects', plot: 'plot', rules: 'rules', custom: 'rules' }; + const suffix = catToSuffix[action.category] || 'rules'; + let parentId = `${workId}-${suffix}`; + const parentNode = nodes.find(n => n.id === parentId); + if (!parentNode) parentId = nodes.find(n => n.parentId === workId && n.category === action.category)?.id || parentId; + + const resolveNode = () => { + if (action.nodeId) return nodes.find(n => n.id === action.nodeId); + if (action.name) return nodes.find(n => n.name === action.name && n.category === action.category && n.type === 'item'); + return null; + }; + + if (action.action === 'add') { + const existing = resolveNode(); + if (existing) { + const mergedContent = { ...(existing.content || {}), ...(action.content || {}) }; + await updateSettingsNode(existing.id, { name: action.name || existing.name, content: mergedContent }); + } else { + await addSettingsNode({ name: action.name || '新条目', type: 'item', category: action.category || 'custom', parentId, content: action.content || {} }); + } + } else if (action.action === 'update') { + const target = resolveNode(); + if (target) { + const updates = {}; + if (action.name) updates.name = action.name; + if (action.content) updates.content = { ...(target.content || {}), ...action.content }; + await updateSettingsNode(target.id, updates); + } else { + await addSettingsNode({ name: action.name || '新条目', type: 'item', category: action.category || 'custom', parentId, content: action.content || {} }); + } + } else if (action.action === 'delete') { + const target = resolveNode(); + if (target) await deleteSettingsNode(target.id); + } + + const msgIdFromKey = actionKey.split('-action-')[0].replace(/-v\d+$/, ''); + setSessionStore(prev => { + const newStore = { + ...prev, sessions: prev.sessions.map(s => { + if (s.id !== prev.activeSessionId) return s; + return { ...s, messages: s.messages.map(m => m.id === msgIdFromKey ? { ...m, _appliedActions: [...(m._appliedActions || []), actionKey] } : m), updatedAt: Date.now() }; + }), + }; + saveSessionStore(newStore); + return newStore; + }); + showToast('应用设定成功', 'success'); + } catch (err) { + console.error('Settings action failed:', err); + showToast('应用操作失败:' + err.message, 'error'); + } + }, [setSessionStore, showToast]); + + // 发送消息 + const handleSend = useCallback(() => { + const text = inputText.trim(); + if (!text || chatStreaming) return; + + const selectedHistory = chatHistory.filter(m => checkedHistory.has(m.id)); + onChatMessage?.(text, selectedHistory); + setInputText(''); + }, [inputText, chatStreaming, chatHistory, checkedHistory, onChatMessage]); + + // 重新发送某条用户消息 + const handleResend = useCallback((msgId) => { + const msg = chatHistory.find(m => m.id === msgId); + if (!msg || msg.role !== 'user' || chatStreaming) return; + const selectedHistory = chatHistory.filter(m => checkedHistory.has(m.id) && m.timestamp < msg.timestamp); + onChatMessage?.(msg.content, selectedHistory); + }, [chatHistory, checkedHistory, chatStreaming, onChatMessage]); + + // 思维链折叠状态 + const [expandedThinking, setExpandedThinking] = useState(new Set()); + const toggleThinking = useCallback((msgId) => { + setExpandedThinking(prev => { + const next = new Set(prev); + if (next.has(msgId)) next.delete(msgId); + else next.add(msgId); + return next; + }); + }, []); + + // 开始编辑消息 + const startEdit = useCallback((msg) => { + setEditingMsgId(msg.id); + setEditingContent(msg.content); + }, []); + + // 确认编辑 + const confirmEdit = useCallback(() => { + if (editingMsgId && editingContent.trim()) { + onEditMessage?.(editingMsgId, editingContent.trim()); + } + setEditingMsgId(null); + setEditingContent(''); + }, [editingMsgId, editingContent, onEditMessage]); + + // 取消编辑 + const cancelEdit = useCallback(() => { + setEditingMsgId(null); + setEditingContent(''); + }, []); + + // 切换单条历史勾选 + const toggleCheck = (id) => { + setCheckedHistory(prev => { + const next = new Set(prev); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + }; + + // 总结历史 + const handleSummarize = useCallback(() => { + const checked = chatHistory.filter(m => checkedHistory.has(m.id)); + if (checked.length < 2) return; + const summaryLines = checked.map(m => + `${m.role === 'user' ? t('aiSidebar.roleYou') : t('aiSidebar.roleAi')}: ${m.content.slice(0, 80)}${m.content.length > 80 ? '...' : ''}` + ); + setSummaryDraft(summaryLines.join('\n')); + }, [chatHistory, checkedHistory, t]); + + // 确认总结 + const confirmSummary = useCallback(() => { + if (!summaryDraft) return; + const checkedIds = new Set(checkedHistory); + const unchecked = chatHistory.filter(m => !checkedIds.has(m.id)); + const summaryMsg = { + id: `summary-${Date.now()}`, + role: 'system', + content: `[对话摘要]\n${summaryDraft}`, + timestamp: Date.now(), + isSummary: true, + }; + setChatHistory?.([...unchecked, summaryMsg]); + setSummaryDraft(null); + }, [summaryDraft, checkedHistory, chatHistory, setChatHistory]); + + // 清空对话 + const handleClearChat = () => { + setChatHistory?.([]); + setCheckedHistory(new Set()); + }; + + // 存档过滤 + const filteredArchive = archiveSearch + ? generationArchive.filter(a => + a.text?.includes(archiveSearch) || a.mode?.includes(archiveSearch) + ) + : generationArchive; + + // 参考 Tab 分组 + const groupedItems = useMemo(() => { + const groups = {}; + const filteredItems = contextSearch + ? contextItems.filter(it => it.name.toLowerCase().includes(contextSearch.toLowerCase())) + : contextItems; + for (const item of filteredItems) { + if (item._empty) continue; + // 不显示没有创建条目的空分类 + if (item.tokens === 0 && item.name === '(暂无条目)') continue; + const g = item.group || '其他'; + if (!groups[g]) groups[g] = []; + groups[g].push(item); + } + return groups; + }, [contextItems, contextSearch]); + + // Token 统计 + const totalSelectedTokens = useMemo(() => { + return contextItems + .filter(it => contextSelection?.has(it.id)) + .reduce((sum, it) => sum + (it.tokens || 0), 0); + }, [contextItems, contextSelection]); + + // 参考条目切换 + const toggleContextItem = useCallback((itemId) => { + setContextSelection(prev => { + const next = new Set(prev); + if (next.has(itemId)) next.delete(itemId); + else next.add(itemId); + return next; + }); + }, [setContextSelection]); + + const toggleGroup = useCallback((groupName) => { + const items = groupedItems[groupName] || []; + setContextSelection(prev => { + const next = new Set(prev); + const allChecked = items.every(it => prev.has(it.id)); + items.forEach(it => { + if (allChecked) next.delete(it.id); + else next.add(it.id); + }); + return next; + }); + }, [groupedItems, contextSelection, setContextSelection]); + + const toggleCollapse = useCallback((groupName) => { + setCollapsedGroups(prev => { + const next = new Set(prev); + if (next.has(groupName)) next.delete(groupName); + else next.add(groupName); + return next; + }); + }, []); + + const selectAll = useCallback(() => { + if (!contextItems) return; + setContextSelection(new Set(contextItems.map(it => it.id))); + }, [contextItems, setContextSelection]); + + const selectNone = useCallback(() => { + setContextSelection(new Set()); + }, [setContextSelection]); + + const resetSelection = useCallback(() => { + if (!contextItems) return; + setContextSelection(new Set(contextItems.filter(it => it.enabled).map(it => it.id))); + }, [contextItems, setContextSelection]); + + // Token 预算 + const budgetPercent = Math.min(100, (totalSelectedTokens / INPUT_TOKEN_BUDGET) * 100); + const isOverBudget = totalSelectedTokens > INPUT_TOKEN_BUDGET; + + const tabs = [ + { key: 'chat', label: t('aiSidebar.tabChat') }, + { key: 'archive', label: t('aiSidebar.tabArchive') }, + { key: 'reference', label: t('aiSidebar.tabReference') }, + ]; + + const MODE_LABELS = { + continue: '续写', + rewrite: '改写', + expand: '扩写', + condense: '精简', + dialogue: '对话', + chat: '对话', + }; + + const STATUS_LABELS = { + accepted: '✓ 已接受', + rejected: '✗ 已拒绝', + pending: '⏳ 待确认', + }; + + // 会话列表 + const sessions = sessionStore?.sessions || []; + const activeSessionId = sessionStore?.activeSessionId; + + if (!open) return null; + + return ( +
+ {/* 标题栏 */} +
+ {t('aiSidebar.title')} +
+ + + +
+
+ + {/* 会话列表面板 */} + {showSessionList && ( +
+
+ {t('aiSidebar.historyCount').replace('{count}', sessions.length)} +
+
+ {[...sessions].reverse().map(s => ( +
{ onSwitchSession?.(s.id); setShowSessionList(false); }} + > + {renamingSessionId === s.id ? ( + setRenameTitle(e.target.value)} + onKeyDown={e => { + if (e.key === 'Enter') { + onRenameSession?.(s.id, renameTitle.trim() || s.title); + setRenamingSessionId(null); + } else if (e.key === 'Escape') { + setRenamingSessionId(null); + } + }} + onBlur={() => { + onRenameSession?.(s.id, renameTitle.trim() || s.title); + setRenamingSessionId(null); + }} + onClick={e => e.stopPropagation()} + autoFocus + /> + ) : ( + <> +
+ {s.title} + + {s.messages?.length || 0} 条 · {new Date(s.updatedAt || s.createdAt).toLocaleDateString('zh-CN')} + +
+
e.stopPropagation()}> + + {sessions.length > 1 && ( + + )} +
+ + )} +
+ ))} +
+
+ )} + + {/* Tab 切换 */} +
+ {tabs.map(t => ( + + ))} +
+ + {/* ==================== 💬 对话 Tab ==================== */} + {activeTab === 'chat' && ( +
+ {/* 对话控制栏 */} +
+ +
+ + +
+
+ + {summaryDraft !== null && ( +
+
{t('aiSidebar.editSummary')}
+ + + `; + + overlay.appendChild(dialog); + document.body.appendChild(overlay); + + const textarea = dialog.querySelector('.math-editor-input'); + const preview = dialog.querySelector('.math-editor-preview'); + const closeBtn = dialog.querySelector('.math-editor-close'); + const cancelBtn = dialog.querySelector('.math-editor-cancel'); + const saveBtn = dialog.querySelector('.math-editor-save'); + + textarea.value = currentLatex || ''; + + // 实时预览 + const updatePreview = () => { + const val = textarea.value.trim(); + if (!val) { + preview.innerHTML = '此处显示公式预览…'; + return; + } + try { + preview.innerHTML = katex.renderToString(val, { + throwOnError: false, + displayMode: true, + }); + } catch (e) { + preview.innerHTML = `${e.message}`; + } + }; + updatePreview(); + textarea.addEventListener('input', updatePreview); + + // 关闭 + const close = () => { + overlay.classList.add('closing'); + setTimeout(() => overlay.remove(), 150); + }; + + // 保存 + const save = () => { + const val = textarea.value.trim(); + if (val) onSave(val); + close(); + }; + + closeBtn.addEventListener('click', close); + cancelBtn.addEventListener('click', close); + saveBtn.addEventListener('click', save); + overlay.addEventListener('click', (e) => { + if (e.target === overlay) close(); + }); + + // 键盘 + textarea.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { close(); e.preventDefault(); } + if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { save(); e.preventDefault(); } + }); + + // 聚焦 + requestAnimationFrame(() => { + textarea.focus(); + textarea.setSelectionRange(textarea.value.length, textarea.value.length); + }); +} + +// ==================== 行内公式节点 $...$ ==================== +export const MathInline = Node.create({ + name: 'mathInline', + group: 'inline', + inline: true, + atom: true, + + addAttributes() { + return { + latex: { default: '' }, + }; + }, + + parseHTML() { + return [{ + tag: 'span[data-math-inline]', + getAttrs: (el) => ({ latex: el.getAttribute('data-latex') || '' }), + }]; + }, + + renderHTML({ node }) { + return ['span', { + 'data-math-inline': '', + 'data-latex': node.attrs.latex, + class: 'math-inline', + contenteditable: 'false', + }]; + }, + + addNodeView() { + return ({ node, getPos, editor }) => { + const dom = document.createElement('span'); + dom.classList.add('math-inline'); + dom.contentEditable = 'false'; + + const render = (latex) => { + try { + dom.innerHTML = katex.renderToString(latex, { + throwOnError: false, + displayMode: false, + }); + } catch { + dom.textContent = latex; + } + }; + render(node.attrs.latex); + + // 双击打开编辑弹窗 + dom.addEventListener('dblclick', (e) => { + e.preventDefault(); + e.stopPropagation(); + openMathEditor(node.attrs.latex, (newLatex) => { + const pos = getPos(); + if (typeof pos === 'number') { + editor.chain().focus() + .command(({ tr }) => { + tr.setNodeMarkup(pos, undefined, { latex: newLatex }); + return true; + }) + .run(); + } + }); + }); + + return { + dom, + update(updatedNode) { + if (updatedNode.type.name !== 'mathInline') return false; + render(updatedNode.attrs.latex); + return true; + }, + }; + }; + }, + + addInputRules() { + return [ + new InputRule({ + find: /(? { + const latex = match[1]; + if (!latex.trim()) return null; + const { tr } = state; + tr.replaceWith( + range.from, + range.to, + this.type.create({ latex }) + ); + }, + }), + ]; + }, +}); + + +// ==================== 块级公式节点 $$...$$ ==================== +export const MathBlock = Node.create({ + name: 'mathBlock', + group: 'block', + atom: true, + defining: true, + + addAttributes() { + return { + latex: { default: '' }, + }; + }, + + parseHTML() { + return [{ + tag: 'div[data-math-block]', + getAttrs: (el) => ({ latex: el.getAttribute('data-latex') || '' }), + }]; + }, + + renderHTML({ node }) { + return ['div', { + 'data-math-block': '', + 'data-latex': node.attrs.latex, + class: 'math-block', + contenteditable: 'false', + }]; + }, + + addNodeView() { + return ({ node, getPos, editor }) => { + const dom = document.createElement('div'); + dom.classList.add('math-block'); + dom.contentEditable = 'false'; + + const render = (latex) => { + try { + dom.innerHTML = katex.renderToString(latex, { + throwOnError: false, + displayMode: true, + }); + } catch { + dom.textContent = latex; + } + }; + render(node.attrs.latex); + + // 双击打开编辑弹窗 + dom.addEventListener('dblclick', (e) => { + e.preventDefault(); + e.stopPropagation(); + openMathEditor(node.attrs.latex, (newLatex) => { + const pos = getPos(); + if (typeof pos === 'number') { + editor.chain().focus() + .command(({ tr }) => { + tr.setNodeMarkup(pos, undefined, { latex: newLatex }); + return true; + }) + .run(); + } + }); + }); + + return { + dom, + update(updatedNode) { + if (updatedNode.type.name !== 'mathBlock') return false; + render(updatedNode.attrs.latex); + return true; + }, + }; + }; + }, + + addInputRules() { + return [ + new InputRule({ + find: /\$\$([^$]+)\$\$$/, + handler: ({ state, range, match }) => { + const latex = match[1]; + if (!latex.trim()) return null; + const { tr } = state; + tr.replaceWith( + range.from, + range.to, + this.type.create({ latex }) + ); + }, + }), + ]; + }, +}); diff --git a/app/components/PageBreakExtension.js b/app/components/PageBreakExtension.js new file mode 100644 index 0000000..e680771 --- /dev/null +++ b/app/components/PageBreakExtension.js @@ -0,0 +1,312 @@ +'use client'; + +import { Extension } from '@tiptap/core'; +import { Plugin, PluginKey } from '@tiptap/pm/state'; +import { Decoration, DecorationSet } from '@tiptap/pm/view'; + +const PAGE_HEIGHT = 1056; +const PAGE_GAP = 24; + +const pluginKey = new PluginKey('pageBreakSpacer'); + +export const PageBreakExtension = Extension.create({ + name: 'pageBreakSpacer', + + addProseMirrorPlugins() { + return [ + new Plugin({ + key: pluginKey, + + state: { + init() { + return DecorationSet.empty; + }, + apply(tr, decoSet) { + const meta = tr.getMeta(pluginKey); + if (meta) { + if (meta.clear) return DecorationSet.empty; + if (meta.apply) return meta.decoSet; + } + // 文档变更时,不再立刻清除装饰器,而是利用 Tiptap 的 Mapping 机制让占位符随着文本自动漂移。 + // 这样打字时旧的断头台还在,高度不变,绝对不会导致内容突然上缩。 + if (tr.docChanged) { + return decoSet.map(tr.mapping, tr.doc); + } + return decoSet; + }, + }, + + props: { + decorations(state) { + return pluginKey.getState(state) || DecorationSet.empty; + }, + }, + + view(editorView) { + let updateTimer = null; + let isProcessing = false; + + const performPagination = () => { + if (isProcessing) return; + isProcessing = true; + + const dom = editorView.dom; + if (!dom || !dom.isConnected) { + isProcessing = false; + return; + } + + // 1. 锁定容器高度:防止清空占位符瞬间因高度收缩引发滚动条狂跳 + // 注意:不再保存/恢复 scrollTop,避免与用户滚动操作冲突 + const oldMinHeight = dom.style.minHeight; + dom.style.minHeight = `${dom.scrollHeight}px`; + + // 2. 瞬间剥离旧排版 + const oldState = pluginKey.getState(editorView.state); + let cleared = false; + if (oldState && oldState !== DecorationSet.empty) { + const trClear = editorView.state.tr; + trClear.setMeta(pluginKey, { clear: true }); + trClear.setMeta('addToHistory', false); + editorView.dispatch(trClear); + cleared = true; + } + + // 【魔法核心】强制浏览器在当前帧立即进行同步布局重排 (Reflow),暴露天然文档流 + void dom.offsetHeight; + + // 3. 进入"绝对坐标系"精准测量 + const doc = editorView.state.doc; + const domRect = dom.getBoundingClientRect(); + const domTop = domRect.top; + + // 自动侦测当前的真实 Padding (不再需要通过 React 传参) + const computedStyle = window.getComputedStyle(dom); + const marginY = parseFloat(computedStyle.paddingTop) || 96; + + let accumulatedSpacers = 0; + let currentPage = 0; + const spacerData = []; + + // 纸张可用区域计算公式 + const getUsableBottom = (page) => page * (PAGE_HEIGHT + PAGE_GAP) + PAGE_HEIGHT - marginY; + const getUsableTop = (page) => page * (PAGE_HEIGHT + PAGE_GAP) + marginY; + + // 收集顶级内容块 + const blocks = []; + doc.descendants((node, pos) => { + if (node.isTextblock || (node.isBlock && node.isAtom)) { + blocks.push({ node, pos }); + return false; + } + return true; + }); + + for (const { node, pos } of blocks) { + const domNode = editorView.nodeDOM(pos); + if (!domNode || domNode.nodeType !== 1) continue; + + const rect = domNode.getBoundingClientRect(); + if (rect.height === 0) continue; + + const naturalTop = rect.top - domTop; + const naturalBottom = rect.bottom - domTop; + + let actualTop = naturalTop + accumulatedSpacers; + let actualBottom = naturalBottom + accumulatedSpacers; + + // 如果段落已经完全位于下一页的内容区域内,直接跳过前面的页码 + // 注意:用 getUsableTop(next) 而非 getUsableBottom(current), + // 避免跳过"边距区"或"间隙区"的段落(它们仍需由跨页逻辑推送) + while (actualTop >= getUsableTop(currentPage + 1)) { + currentPage++; + } + + // 触发跨页逻辑! + while (actualBottom > getUsableBottom(currentPage)) { + const limitY = getUsableBottom(currentPage); + const nextTopY = getUsableTop(currentPage + 1); + + // 无法拆分的原子块(如大图片、公式),整体推向下一页 + if (node.isAtom || !node.isTextblock) { + const spacerHeight = nextTopY - actualTop; + if (spacerHeight > 0) { + spacerData.push({ pos, height: spacerHeight, isBlock: true }); + accumulatedSpacers += spacerHeight; + actualTop += spacerHeight; + actualBottom += spacerHeight; + } + currentPage++; + } else { + // 常规文字段落,开始寻找破界点 + const startPos = pos + 1; + const endPos = pos + node.nodeSize - 1; + + if (startPos > endPos) { + currentPage++; continue; + } + + // 【二分查找】极速锁定越过边界的那一个字符 + let low = startPos; + let high = endPos; + let crossPos = null; + + while (low <= high) { + let mid = Math.floor((low + high) / 2); + let coords; + try { coords = editorView.coordsAtPos(mid); } catch (e) { } + + // 容错处理:某些特殊字符可能拿不到坐标,就近偏移 + if (!coords) { + let fallback = null; + for (let step = 1; step < 5; step++) { + if (mid + step <= high) { try { fallback = editorView.coordsAtPos(mid + step); if (fallback) { mid = mid + step; coords = fallback; break; } } catch (e) { } } + if (mid - step >= low) { try { fallback = editorView.coordsAtPos(mid - step); if (fallback) { mid = mid - step; coords = fallback; break; } } catch (e) { } } + } + if (!coords) { low = mid + 1; continue; } + } + + const charActualBottom = (coords.bottom - domTop) + accumulatedSpacers; + if (charActualBottom > limitY) { + crossPos = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + + // 若没找到(通常是段落的 Margin 溢出),忽略 + if (crossPos === null) { + break; + } + + // 【精确回溯】找到了越界字,往回倒退,找出这行字的行首 + let lineStartPos = crossPos; + let currentLineTop = null; + try { + let crossCoords = editorView.coordsAtPos(crossPos); + if (crossCoords) { + currentLineTop = crossCoords.top - domTop; + for (let p = crossPos - 1; p >= startPos; p--) { + let c = editorView.coordsAtPos(p); + if (!c) continue; + let cTop = c.top - domTop; + // Y轴剧烈跳跃说明退到了上一行 + if (cTop < currentLineTop - 4) break; + lineStartPos = p; + } + } + } catch (e) { } + + let lineCoords; + try { lineCoords = editorView.coordsAtPos(lineStartPos); } catch (e) { } + let lineActualTop = lineCoords ? (lineCoords.top - domTop) + accumulatedSpacers : actualTop; + + let spacerHeight = nextTopY - lineActualTop; + + if (spacerHeight > 0) { + // 判断:段落整体已经超出当前页可用区域时,整块推走 + // 否则使用行内断裂(即使越界行是第一行,前面仍有段间空白可利用) + if (actualTop >= limitY) { + // 段落完全在边界之后,整体推到下一页 + spacerData.push({ pos, height: nextTopY - actualTop, isBlock: true }); + accumulatedSpacers += (nextTopY - actualTop); + actualBottom += (nextTopY - actualTop); + actualTop = nextTopY; + } else { + // 段落跨越边界,在越界行首处插入行内断裂 + spacerData.push({ pos: lineStartPos, height: spacerHeight, isBlock: false }); + accumulatedSpacers += spacerHeight; + actualBottom += spacerHeight; + actualTop += spacerHeight; + } + } + currentPage++; + } + } + } + + // 4. 重组排版,生成全新的物理占位 Decoration Widget + const decorations = spacerData.map(data => { + if (data.isBlock) { + const spacer = document.createElement('div'); + spacer.className = 'page-break-spacer-block'; + spacer.style.height = `${data.height}px`; + spacer.style.width = '100%'; + spacer.style.clear = 'both'; + spacer.setAttribute('data-pb-spacer', '1'); + return Decoration.widget(data.pos, spacer, { key: `pb-${data.pos}`, side: -1, ignoreSelection: true }); + } else { + // 隐形断头台:利用 inline-block 占满 100% 宽度,直接把后半行文字生生挤到下一页 + const spacer = document.createElement('span'); + spacer.className = 'page-break-spacer-inline'; + spacer.style.display = 'block'; + spacer.style.width = '100%'; + spacer.style.height = `${data.height}px`; + spacer.style.lineHeight = '0'; + spacer.style.fontSize = '0'; + spacer.style.verticalAlign = 'top'; + spacer.style.userSelect = 'none'; // 忽略光标焦点 + spacer.style.pointerEvents = 'none'; + spacer.setAttribute('data-pb-spacer', '1'); + return Decoration.widget(data.pos, spacer, { key: `pb-${data.pos}`, side: -1, ignoreSelection: true }); + } + }); + + const decoSet = decorations.length > 0 ? DecorationSet.create(doc, decorations) : DecorationSet.empty; + + // 5. 无缝推送回视图 + if (decorations.length > 0 || cleared) { + const trApply = editorView.state.tr; + trApply.setMeta(pluginKey, { apply: true, decoSet }); + trApply.setMeta('addToHistory', false); + editorView.dispatch(trApply); + } + + // 解除 DOM 高度锁定 + dom.style.minHeight = oldMinHeight; + isProcessing = false; + }; + + let initTimer = null; + let debounceTimer = null; + + // 立即调度(初始化 & 窗口 resize) + const scheduleImmediate = () => { + if (updateTimer) cancelAnimationFrame(updateTimer); + if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = null; } + updateTimer = requestAnimationFrame(performPagination); + }; + + // 延迟调度(文档变更触发,加长防抖避免打字中途重排) + // 只要在连续打字,就绝不重排页面;停手 500ms 后再安静地后台重新计算分页 + const scheduleDebouncedForDoc = () => { + if (debounceTimer) clearTimeout(debounceTimer); + debounceTimer = setTimeout(() => { + debounceTimer = null; + if (updateTimer) cancelAnimationFrame(updateTimer); + updateTimer = requestAnimationFrame(performPagination); + }, 500); + }; + + // 初始化延迟——等 Editor DOM 完全挂载后首次计算 + initTimer = setTimeout(scheduleImmediate, 200); + window.addEventListener('resize', scheduleImmediate); + + return { + update(view, prevState) { + // 文档内容变化引发重算(防抖) + if (prevState.doc !== view.state.doc) scheduleDebouncedForDoc(); + }, + destroy() { + if (updateTimer) cancelAnimationFrame(updateTimer); + if (debounceTimer) clearTimeout(debounceTimer); + if (initTimer) clearTimeout(initTimer); + window.removeEventListener('resize', scheduleImmediate); + }, + }; + }, + }), + ]; + }, +}); diff --git a/app/components/SettingsItemEditor.js b/app/components/SettingsItemEditor.js new file mode 100644 index 0000000..0a0ccbf --- /dev/null +++ b/app/components/SettingsItemEditor.js @@ -0,0 +1,457 @@ +'use client'; + +import { useState } from 'react'; +import { useI18n } from '../lib/useI18n'; + +// ==================== 分类配色 ==================== +const CATEGORY_COLORS = { + character: { color: 'var(--cat-character)', bg: 'var(--cat-character-bg)' }, + location: { color: 'var(--cat-location)', bg: 'var(--cat-location-bg)' }, + world: { color: 'var(--cat-world)', bg: 'var(--cat-world-bg)' }, + object: { color: 'var(--cat-object)', bg: 'var(--cat-object-bg)' }, + plot: { color: 'var(--cat-plot)', bg: 'var(--cat-plot-bg)' }, + rules: { color: 'var(--cat-rules)', bg: 'var(--cat-rules-bg)' }, + custom: { color: 'var(--cat-custom)', bg: 'var(--cat-custom-bg)' }, +}; + +// ==================== 通用字段组件 ==================== + +function TextField({ label, value, onChange, placeholder, multiline = false, rows = 3, aiBtn = false }) { + const { t } = useI18n(); + return ( +
+
+ + {aiBtn && ( + + )} +
+ {multiline ? ( +