Building a Digital Script Marker: Solving Text Matching and Duplicate Issues
1. Project Background
During digital human video production, scripts are not only used to define what the digital presenter says. They also help determine where additional video materials, such as cutaway shots, sample footage, or other visual elements, should be inserted.
To make this process easier, a script marking tool is needed. It allows users to identify specific lines in the original script and mark the corresponding positions for subsequent video editing.
The initial requirement was to build a lightweight tool using native HTML, CSS, and JavaScript. It does not depend on a backend service. Users simply paste the original script into the page, select the lines they want to mark, and let the program locate those lines automatically.
At first glance, this seems like a relatively simple task. However, several problems emerged during actual use:
The number of markers and their positions cannot be predefined.
The same dialogue may appear multiple times in a script, and different occurrences must be distinguishable.
When identical dialogue appears more than once, the text alone cannot determine the intended position.
Context matching must support multiple lines of text.
Even when different amounts of context are provided, the same position must not be marked more than once.
These issues were not all identified at the beginning. They were discovered and resolved progressively through real-world usage.
2. Stage One: Building a Dynamic Text-Marking Mechanism
2.1 The Problem
When developing the initial marking feature, the first question was how users should specify the dialogue they wanted to mark.
One possible approach would be to define a fixed number of marker positions in advance and let users select the corresponding line numbers.
However, this approach is not suitable for real-world scripts.
Script length and content vary, and users cannot know in advance how many markers they will need. If the tool relies on fixed line numbers, any changes to the script may invalidate the original positions.
In practice, users prefer a simpler workflow:
Paste the complete script into the original text area.
Copy the dialogue they want to mark.
Paste the copied text into the marker input area.
Let the program find the corresponding position in the original script.
There is another important detail: the position of the copied text in the marker input area has no relationship to its original position in the script.
For example, even if the user copies the third line of the original script and pastes it at the end of the marker input area, the program must still locate the third line in the original script.
2.2 Root Cause
The marker input area and the original script are two independent text fields.
The cursor position, text length, and content position in the marker input area have no direct relationship with the actual position in the original script.
Therefore, the program cannot determine the target position using the input field's cursor position or a manually entered line number.
The reliable approach is to compare the marker text with the original script.
2.3 Solution
A dynamic text-matching mechanism was introduced:
Retrieve the original script.
Retrieve the text entered in the marker input area.
Normalize the text to handle formatting differences.
Split both the original script and marker text into line arrays.
Search for consecutive lines in the original script that exactly match the marker text.
Display the complete original script in the result area and highlight the matched lines.
This approach eliminates the need to define a fixed number of markers or ask users to enter line numbers.
The number of markers is determined by the user's actual input, while their positions are calculated automatically from the original script.
2.4 Results
After this stage, the tool supported basic text marking:
Users could add markers dynamically.
Marker positions were identified automatically.
Fixed line numbers were no longer required.
The complete original script remained visible, with marked lines highlighted in red.
However, another problem remained: what happens when the same dialogue appears multiple times in the script?
3. Stage Two: Resolving Ambiguous Positions for Repeated Dialogue
3.1 The Problem
The same dialogue may appear more than once in a real-world script.
For example:
The weather is very nice today.
We are getting ready to leave.
The weather is very nice today.If the user wants to mark the first or third line, searching only by dialogue content will return two matching positions.
The program can identify both occurrences, but it cannot determine which one the user intends to mark.
Simply selecting the first match may produce an incorrect result. Selecting the last match is equally unreliable.
3.2 Root Cause
The original matching mechanism relied primarily on the target text itself.
When the target text appears only once, this approach works correctly.
However, when identical text appears multiple times, the text content is no longer sufficient to identify a unique position.
In other words:
Identical text does not necessarily mean identical positions in a script.
Additional positioning conditions are therefore required.
3.3 Solution: Introducing Context-Based Positioning
The solution was to introduce two additional conditions: the preceding line and the following line.
For example:
The weather is very nice today.
We are getting ready to leave.
The weather is very nice today.If the user wants to mark the third line, the context can be provided as follows:
Previous line:
We are getting ready to leave.
Target text:
The weather is very nice today.
Next line:
@@@The program can now use the surrounding context to identify the intended occurrence.
The matching process works as follows:
Find all occurrences of the target text in the original script.
If the target text appears only once, use that position directly.
If it appears multiple times, ask the user to provide context.
Use the preceding and following context to filter the matching positions.
Add the marker only when exactly one position matches.
It is important to understand that context does not replace the target text. It acts as an additional condition for identifying the correct occurrence.
3.4 Handling the Beginning and End of a Script
Introducing context matching revealed another edge case.
If the target text is located on the first line, there is no preceding line.
Similarly, if it is located on the last line, there is no following line.
Requiring both context fields to contain actual text would make it impossible to mark dialogue at the beginning or end of a script.
To solve this, a special placeholder was introduced:
@@@The convention is simple:
@@@means that the corresponding context does not exist.The first line of a script can use
@@@as its preceding context.The last line of a script can use
@@@as its following context.Repeated text in the middle of a script still requires actual context to identify its position.
This approach handles boundary conditions without treating missing context as an error.
3.5 Results
The tool evolved from basic text matching into context-assisted positioning.
Identical dialogue could now be distinguished based on its surrounding content.
However, actual usage revealed another interaction issue: the display behavior of the previous-line and next-line input fields was inconsistent.
4. Stage Three: Standardizing Context Input and Handling Missing Context
4.1 The Problem
The initial context interface was designed to display input fields based on whether the corresponding context existed.
For example, a target line at the beginning of a script has no preceding line, so the previous-line input field might be hidden.
Although this reduced unnecessary input, it made the interface less consistent:
Sometimes only the previous-line field was displayed.
Sometimes only the next-line field was displayed.
Users had to determine which field was available before entering context.
The interaction differed depending on the target position.
The requirement was to keep both context fields visible at all times.
If one direction has no context, users should simply enter @@@.
4.2 Root Cause
The original design linked the visibility of an input field to the existence of its corresponding context.
This introduced unnecessary interface complexity.
From the user's perspective, previous and next context are simply two fixed positioning conditions. Their input fields should not change depending on where the target text appears.
4.3 Solution
The context interface was redesigned to always display both input fields:
Previous line:
[Input field]
Next line:
[Input field]The same interface is used whether the target text appears at the beginning, middle, or end of the script.
The rules are:
| Target Position | Previous Context | Next Context |
|---|---|---|
| Beginning | @@@ | Actual context |
| Middle | Actual context | Actual context |
| End | Actual context | @@@ |
Users no longer need to determine which input field should be displayed. They simply provide the available context based on the script.
4.4 Results
This stage improved the consistency of the user interface.
Both context fields remain visible, and @@@ provides a unified way to represent missing context.
The positioning rules also became easier to understand.
However, another issue appeared during actual use: users did not always copy just one line of context.
5. Stage Four: Supporting Multi-Line Context Matching
5.1 The Problem
Although context-based positioning had been implemented, the original matching logic still relied on single-line comparisons.
For example:
lines[startIndex - 1] === beforeThis expression can only compare the input with the single line immediately preceding the target text.
However, users may copy multiple lines from the original script and paste them into the previous-context or next-context field.
For example:
Previous context:
This is the first background sentence.
This is the second background sentence.
Target text:
The weather is very nice today.
Next context:
We are getting ready to leave.In this example, the previous context contains two lines.
If the program still compares the entire input against only one preceding line, it cannot locate the correct position.
As a result, the program reports that the target position cannot be found, even though the user has provided the correct context.
5.2 Root Cause
The problem was not that the context was incorrect.
The actual issue was that the original matching algorithm only supported single-line string comparisons.
When the input contained multiple lines, the program did not split the context into separate lines and compare them consecutively.
Therefore, the original logic could not handle multi-line context.
This demonstrated that text positioning must consider the line structure of the target text and both context sections.
5.3 Solution: Converting Context into Line Arrays
The solution was to process previous context, target text, and next context using a consistent line-based approach.
First, normalize line breaks and convert each text section into an array of lines.
For example:
const beforeLines = getContextLines(beforeText);
const targetLines = getMarkerLines(targetText);
const afterLines = getContextLines(afterText);
A multi-line context is then converted into an array:
[
"This is the first background sentence.",
"This is the second background sentence."
]
Instead of comparing a single string, the program checks each context line against the corresponding position in the original script.
The matching process can be understood as:
Previous context lines
↓
Target text lines
↓
Next context linesAll three sections must appear consecutively in the original script and in the correct order.
The matching process is:
Find all occurrences of the target text.
Use the target's starting position to determine where the previous context should appear.
Compare each previous-context line with the corresponding line in the original script.
Use the target's ending position to determine where the next context should appear.
Compare each next-context line with the corresponding line in the original script.
Consider the position valid only when all required context lines match.
The special @@@ placeholder is preserved.
If the previous context is @@@, the program skips previous-context matching. If the next context is @@@, it skips next-context matching.
5.4 The Key Change in the Matching Strategy
The most important change in this stage was upgrading the matching method from:
Single-line string comparison
to:
Consecutive multi-line context matching.
This resolved the issue where multi-line context could not be located and made the matching process more consistent.
5.5 Results
After this modification, users could provide either single-line or multi-line context.
Both previous and next context fields could contain multiple lines. As long as the context appeared immediately before or after the target text in the original script, in the correct order, the program could identify the position.
However, further testing revealed another problem. This time, it was not a positioning issue but a duplicate-prevention issue.
6. Stage Five: Preventing Duplicate Markers at the Same Position
6.1 The Problem
This was one of the easiest problems to overlook during development.
Because identical dialogue may appear in different positions, the tool must allow the same text to be marked more than once.
For example:
The weather is very nice today.
We are getting ready to leave.
The weather is very nice today.The two identical lines appear at different positions. The user may genuinely need to mark both occurrences.
Therefore, checking only the marker text cannot determine whether a marker is a duplicate.
However, another issue appeared during actual use.
When adding a marker for the first time, the user might copy only one preceding line. When adding it again, the user might copy several preceding lines.
Although the context lengths were different, both attempts eventually identified the same position in the original script.
The program still allowed the second marker to be added.
In other words, the original duplicate-checking logic could mistake different context lengths for different markers.
6.2 Root Cause
The previous design could use the content of the context fields as part of the duplicate-checking conditions.
However, context is only used to locate the target text. It should not determine the identity of the marker itself.
Consider these two inputs:
First attempt:
Previous context:
We are getting ready to leave.
Target text:
The weather is very nice today.Second attempt:
Previous context:
This is the introduction to the previous section.
We are getting ready to leave.
Target text:
The weather is very nice today.The previous context has different lengths, but both inputs may identify exactly the same position.
Therefore, the key principle is:
Duplicate detection should be based on the final target position, not on the format or length of the context provided by the user.
6.3 Solution: Using the Target Position as the Duplicate-Checking Criterion
The marker validation rules were clarified:
Identical text at different positions: allowed.
Identical text at the same position: not allowed.
Different context lengths that resolve to the same position: still considered duplicates.
The implementation uses the starting line index of the target text in the original script, together with the target text itself, to determine whether a marker already exists.
The logic can be summarized as:
Marker identity = Starting position + Target text contentA simplified implementation is:
function isMarkerAlreadyAdded(startIndex, targetLines) {
return markers.some(marker => {
if (marker.startIndex !== startIndex) {
return false;
}
if (marker.targetLines.length !== targetLines.length) {
return false;
}
return marker.targetLines.every((line, index) => {
return line === targetLines[index];
});
});
}
Here:
startIndexrepresents the starting line position of the target text in the original script.targetLinesrepresents the lines that need to be marked.
The previous and next context lengths are no longer part of the duplicate identity.
This separates two different concepts:
Positioning conditions: Previous context, target text, and next context are used to find the intended position.
Duplicate-checking conditions: The actual position and target text are used to determine whether the marker already exists.
These two responsibilities are no longer mixed together.
6.4 Why Not Check Duplicates Using Text Content Alone?
Consider a script containing the same dialogue in three different positions:
First section.
The weather is very nice today.
Second section.
Third section.
The weather is very nice today.
Fourth section.
Fifth section.
The weather is very nice today.
Sixth section.If duplicate detection relies only on text content, marking the first occurrence would prevent the user from marking the second and third occurrences.
That clearly does not meet the actual requirement.
Therefore, duplicate detection must consider both the text content and its position in the original script.
6.5 Results
After this modification, duplicate marking was handled correctly:
Identical dialogue could be marked at different positions.
The same position could not be marked more than once.
Different context lengths could still be recognized as the same marker when they resolved to the same position.
Duplicate detection was no longer affected by how the user entered context.
7. Key Design Decisions in the Final Implementation
After these five stages of development, the core logic of the tool became much clearer.
7.1 Text Normalization
Before matching, text needs to be normalized.
Typical operations include:
Standardizing line breaks across different operating systems.
Handling full-width spaces.
Applying consistent whitespace processing to individual lines.
Converting text into a unified array of lines.
This reduces matching failures caused by differences in line-break formats or whitespace.
It is important to note that normalization should make matching consistent without arbitrarily changing the actual script content.
7.2 Separating Target Matching from Context Positioning
The target text identifies what needs to be marked.
The context identifies which occurrence is intended when the target text appears multiple times.
These two steps are related, but they should remain logically independent.
If the target text appears only once, the program can use that position directly. If multiple matches exist, the surrounding context is used to narrow down the result.
7.3 Performing Duplicate Checks Only After Successful Positioning
Duplicate detection should happen only after the program has successfully identified a position.
Without knowing the exact position, it is impossible to determine reliably whether the new marker duplicates an existing one.
The overall process is therefore:
User enters marker text
↓
Find all matching occurrences
↓
Is there only one match?
↓
Yes: Determine the position directly
No: Use previous and next context
↓
Has exactly one position been identified?
↓
Check whether a marker already exists there
↓
Allow the marker or report a duplicate
↓
Update the marking results7.4 Separating Marker Identity from Context Information
Previous and next context are positioning data. They are not the marker itself.
This distinction is important for future maintenance.
If context length, context content, and marker identity are all tied together, changes in the context input may cause incorrect duplicate detection.
Separating positioning information from marker identity makes the code easier to understand, maintain, and extend.
8. Lessons Learned During Development
The main challenge in this project was not the HTML interface or highlighting a line of text in red. It was understanding how users actually interact with the tool and translating those interactions into reliable program logic.
Several lessons can be drawn from the development process.
8.1 Do Not Make Premature Assumptions About Input Formats
The initial positioning logic considered only single-line context.
However, users may copy one line or several lines from the original script.
If a program is designed around only one expected input format, problems are likely to emerge during real-world use.
When developing text-processing features, it is important to consider structural variations in user input.
8.2 Identical Text Does Not Mean Identical Position
This was the most important issue in the repeated-dialogue feature.
In many simple text-processing programs, checking whether a string exists is sufficient.
However, in a script-marking tool, text content and text position are two separate dimensions.
Both must be considered to handle repeated dialogue correctly.
8.3 Positioning and Duplicate Detection Should Be Separate Steps
Positioning answers the question:
Where exactly is the text the user wants to mark?
Duplicate detection answers a different question:
Has this position already been marked?
Combining these two responsibilities can lead to problems, such as different context lengths causing duplicate checks to fail.
Separating them makes the overall logic simpler and more reliable.
8.4 Boundary Conditions Should Be Part of the Normal Design
The absence of previous context at the beginning of a script, or next context at the end, is not an exceptional error. It is a normal characteristic of the data.
Using @@@ to explicitly represent missing context is clearer than introducing many special cases throughout the code.
8.5 Improve the Program Through Real-World Feedback
All requirements were not fully defined at the beginning of this project.
Instead, the development process started with basic marking functionality. Repeated text, multi-line context, inconsistent input fields, and duplicate markers at the same position were discovered one by one through actual use.
Each modification did more than add another conditional statement. It helped clarify the responsibilities of different parts of the program.
This is a common pattern in practical software development: implement the basic requirements first, identify edge cases through real usage, and then progressively improve the algorithms and user interactions.
9. Conclusion
The development of this digital script marker tool involved a gradual transition from simple text matching to context-based positioning and position-aware duplicate detection.
The entire process can be summarized in five stages:
| Stage | Actual Problem | Solution |
|---|---|---|
| Stage 1 | Marker quantities and positions were not fixed | Dynamically locate markers using the original script |
| Stage 2 | Repeated dialogue made positions ambiguous | Introduce previous and next context |
| Stage 3 | Missing context at script boundaries and inconsistent input behavior | Keep both context fields visible and use @@@ for missing context |
| Stage 4 | Multi-line context could not be matched | Convert context into line arrays and perform consecutive multi-line matching |
| Stage 5 | Different context lengths could create duplicate markers at the same position | Detect duplicates using the actual position and target text |
The most valuable part of this development process was not any individual JavaScript function, but the way each problem was gradually broken down and addressed.
When a feature involves text matching, position detection, context validation, and duplicate handling, it is not enough to check whether individual conditions work correctly. It is also necessary to understand exactly what each step is responsible for.
By separating text content, text position, positioning conditions, and marker identity, the tool became more reliable when handling real-world scripts.
A feature is not truly complete simply because it works under normal conditions. It should also handle repeated data, multi-line input, and boundary positions correctly—situations that frequently occur in practical use.
The final code is as follows:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数字人剧本标记工具</title>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 24px;
background: #f5f7fa;
color: #303133;
font-family: Arial, "Microsoft YaHei", sans-serif;
}
.container {
max-width: 1400px;
margin: auto;
}
.header {
margin-bottom: 20px;
}
.header h2 {
margin: 0 0 8px;
font-size: 22px;
}
.header p {
margin: 0;
color: #909399;
font-size: 13px;
}
.main {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.panel {
min-width: 0;
background: #fff;
border: 1px solid #e4e7ed;
border-radius: 8px;
overflow: hidden;
}
.panel-header {
height: 52px;
padding: 0 18px;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid #ebeef5;
}
.panel-title {
font-size: 15px;
font-weight: 600;
}
.tip {
font-size: 12px;
color: #909399;
}
.panel-body {
padding: 18px;
}
.script-input {
width: 100%;
min-height: 300px;
padding: 12px;
border: 1px solid #dcdfe6;
border-radius: 5px;
outline: none;
resize: vertical;
font-family: inherit;
font-size: 14px;
line-height: 1.8;
}
.script-input:focus,
.marker-input:focus,
.context-input:focus {
border-color: #409eff;
}
.marker-section {
margin-top: 20px;
}
.section-title {
margin-bottom: 12px;
font-size: 14px;
font-weight: 600;
}
.marker-input-group {
display: flex;
gap: 10px;
align-items: stretch;
}
.marker-input {
flex: 1;
min-width: 0;
height: 80px;
padding: 10px;
border: 1px solid #dcdfe6;
border-radius: 4px;
outline: none;
resize: vertical;
font-family: inherit;
font-size: 13px;
}
button {
height: 36px;
padding: 0 16px;
border: 1px solid #dcdfe6;
border-radius: 4px;
background: #fff;
color: #606266;
cursor: pointer;
white-space: nowrap;
}
button:hover {
opacity: .85;
}
button:disabled {
opacity: .5;
cursor: not-allowed;
}
.btn-primary {
color: #fff;
background: #409eff;
border-color: #409eff;
}
.btn-danger {
color: #f56c6c;
border-color: #fbc4c4;
}
.context-box {
display: none;
margin-top: 16px;
padding: 14px;
border: 1px solid #f5c6cb;
border-radius: 6px;
background: #fffafa;
}
.context-box.show {
display: block;
}
.context-title {
margin-bottom: 8px;
font-size: 14px;
font-weight: 600;
color: #e36b6b;
}
.context-description {
margin-bottom: 14px;
font-size: 12px;
line-height: 1.7;
color: #909399;
}
.context-item {
margin-bottom: 12px;
}
.context-label {
display: block;
margin-bottom: 6px;
font-size: 13px;
color: #606266;
}
.context-input {
width: 100%;
min-height: 65px;
padding: 9px 10px;
border: 1px solid #dcdfe6;
border-radius: 4px;
outline: none;
resize: vertical;
font-family: inherit;
font-size: 13px;
}
.context-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 14px;
}
.context-error {
display: none;
margin-top: 10px;
color: #f56c6c;
font-size: 12px;
line-height: 1.6;
}
.context-error.show {
display: block;
}
.marker-list {
margin-top: 14px;
display: flex;
flex-direction: column;
gap: 8px;
}
.marker-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 10px 12px;
background: #fafafa;
border: 1px solid #ebeef5;
border-radius: 5px;
}
.marker-text {
flex: 1;
min-width: 0;
font-size: 13px;
line-height: 1.7;
white-space: pre-wrap;
word-break: break-all;
}
.marker-index {
display: inline-block;
margin-right: 6px;
color: #909399;
}
.marker-location {
display: block;
margin-top: 4px;
color: #909399;
font-size: 11px;
}
.remove-btn {
flex-shrink: 0;
height: 28px;
padding: 0 10px;
color: #f56c6c;
border-color: #fbc4c4;
}
.empty-marker {
padding: 15px;
text-align: center;
color: #c0c4cc;
font-size: 13px;
border: 1px dashed #dcdfe6;
border-radius: 5px;
}
.result-content {
min-height: 400px;
max-height: 700px;
overflow-y: auto;
padding: 12px;
background: #fafafa;
border: 1px solid #ebeef5;
border-radius: 5px;
font-size: 14px;
line-height: 2;
white-space: pre-wrap;
word-break: break-word;
user-select: text;
}
.result-marked {
color: #f56c6c;
background: rgba(245, 108, 108, .12);
font-weight: 600;
border-radius: 2px;
}
.empty-tip {
color: #c0c4cc;
}
.footer {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-top: 16px;
}
.stats {
color: #909399;
font-size: 12px;
}
.actions {
display: flex;
gap: 8px;
}
@media(max-width: 768px) {
body {
padding: 12px;
}
.main {
grid-template-columns: 1fr;
}
.footer {
align-items: flex-start;
flex-direction: column;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>数字人剧本标记工具</h2>
<p>添加需要标记的剧本文案,系统自动定位原文并进行红色标记。</p>
</div>
<div class="main">
<!-- 左侧 -->
<div class="panel">
<div class="panel-header">
<span class="panel-title">原始剧本</span>
<span class="tip">支持多行粘贴</span>
</div>
<div class="panel-body">
<textarea
id="scriptInput"
class="script-input"
placeholder="请粘贴剧本文案,每句话占一行..."
></textarea>
<div class="marker-section">
<div class="section-title">
添加标记
</div>
<div class="marker-input-group">
<textarea
id="markerInput"
class="marker-input"
placeholder="请输入或粘贴需要标记的原文,支持单行或多行..."
></textarea>
<button id="addBtn" class="btn-primary">
添加标记
</button>
</div>
<!-- 重复台词上下文输入 -->
<div id="contextBox" class="context-box">
<div class="context-title">
检测到重复台词,请补充上下文
</div>
<div id="contextDescription"
class="context-description">
</div>
<div class="context-item">
<label class="context-label">
前一句 / 前文
</label>
<textarea
id="beforeInput"
class="context-input"
placeholder="粘贴目标文本前面紧邻的内容,支持多行;开头填写 @@@"
></textarea>
</div>
<div class="context-item">
<label class="context-label">
后一句 / 后文
</label>
<textarea
id="afterInput"
class="context-input"
placeholder="粘贴目标文本后面紧邻的内容,支持多行;结尾填写 @@@"
></textarea>
</div>
<div id="contextError" class="context-error"></div>
<div class="context-actions">
<button id="cancelContextBtn">
取消
</button>
<button id="confirmContextBtn"
class="btn-primary">
确认定位并添加
</button>
</div>
</div>
<div class="tip" style="margin-top:8px;">
如果标记文本只出现一次,将直接添加;
如果出现多次,需要填写上下文。
前后文均支持多行复制。
</div>
<div id="markerList" class="marker-list">
</div>
</div>
</div>
</div>
<!-- 右侧 -->
<div class="panel">
<div class="panel-header">
<span class="panel-title">生成剧本</span>
<span class="tip">只读 · 自动匹配</span>
</div>
<div class="panel-body">
<div
id="resultContent"
class="result-content"
aria-readonly="true"
>
<span class="empty-tip">
生成后的剧本将在这里显示...
</span>
</div>
<div class="footer">
<div id="stats" class="stats">
共 0 行,已标记 0 处
</div>
<div class="actions">
<button id="clearBtn" class="btn-danger">
清空
</button>
<button id="copyBtn" class="btn-primary">
复制生成剧本
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
(function () {
const scriptInput = document.getElementById('scriptInput');
const markerInput = document.getElementById('markerInput');
const markerList = document.getElementById('markerList');
const resultContent = document.getElementById('resultContent');
const stats = document.getElementById('stats');
const addBtn = document.getElementById('addBtn');
const clearBtn = document.getElementById('clearBtn');
const copyBtn = document.getElementById('copyBtn');
const contextBox = document.getElementById('contextBox');
const contextDescription = document.getElementById('contextDescription');
const beforeInput = document.getElementById('beforeInput');
const afterInput = document.getElementById('afterInput');
const contextError = document.getElementById('contextError');
const confirmContextBtn = document.getElementById('confirmContextBtn');
const cancelContextBtn = document.getElementById('cancelContextBtn');
const NO_CONTEXT = '@@@';
// 原始剧本
let scriptText = '';
// 标记数据
let markers = [];
// 当前待定位的标记
let pendingMarker = null;
/**
* 文本标准化
*
* 只用于匹配,不修改原始剧本。
*/
function normalizeText(text) {
return String(text || '')
.replace(/\r\n|\r/g, '\n')
.replace(/\u3000/g, ' ')
.split('\n')
.map(line => line.replace(/^[ \t]+|[ \t]+$/g, ''))
.join('\n')
.trim();
}
/**
* 获取标准化后的剧本行
*/
function getScriptLines() {
return scriptText
.replace(/\r\n|\r/g, '\n')
.split('\n')
.map(line => normalizeText(line));
}
/**
* 获取标记文本行
*/
function getMarkerLines(text) {
return normalizeText(text).split('\n');
}
/**
* 将上下文文本转换成多行数组。
*
* @@@ 表示该方向不存在上下文。
*/
function getContextLines(text) {
const normalized = normalizeText(text);
if (!normalized || normalized === NO_CONTEXT) {
return [];
}
return normalized.split('\n');
}
/**
* 查找标记文本所有出现的位置。
*
* 返回起始行号。
*/
function findOccurrences(targetLines) {
const lines = getScriptLines();
const result = [];
if (!targetLines.length) {
return result;
}
if (targetLines.some(line => line === '')) {
return result;
}
for (
let i = 0;
i <= lines.length - targetLines.length;
i++
) {
let matched = true;
for (let j = 0; j < targetLines.length; j++) {
if (lines[i + j] !== targetLines[j]) {
matched = false;
break;
}
}
if (matched) {
result.push(i);
}
}
return result;
}
/**
* 判断前后文是否与目标文本紧邻。
*
* 前文:必须是目标文本之前连续的多行。
* 后文:必须是目标文本之后连续的多行。
*
* 不允许跳过中间行。
*/
function matchAdjacentLines(
lines,
startIndex,
targetLength,
beforeLines,
afterLines
) {
const endIndex = startIndex + targetLength - 1;
// 前文行数不能超过目标文本之前的行数
if (beforeLines.length > startIndex) {
return false;
}
// 后文行数不能超过目标文本之后的行数
if (endIndex + afterLines.length >= lines.length) {
return false;
}
// 检查前文:从目标文本前面紧邻的位置开始匹配
for (let i = 0; i < beforeLines.length; i++) {
const scriptIndex =
startIndex - beforeLines.length + i;
if (lines[scriptIndex] !== beforeLines[i]) {
return false;
}
}
// 检查后文:从目标文本后面紧邻的位置开始匹配
for (let i = 0; i < afterLines.length; i++) {
const scriptIndex = endIndex + 1 + i;
if (lines[scriptIndex] !== afterLines[i]) {
return false;
}
}
return true;
}
/**
* 根据上下文筛选唯一位置。
*
* 剧本开头:
* 前文必须填写 @@@,后文填写真实内容。
*
* 剧本结尾:
* 后文必须填写 @@@,前文填写真实内容。
*
* 中间位置:
* 前后文都必须填写真实内容。
*
* 前后文均支持多行。
*/
function findPositionByContext(
targetLines,
beforeText,
afterText
) {
const lines = getScriptLines();
const occurrences = findOccurrences(targetLines);
const before = normalizeText(beforeText);
const after = normalizeText(afterText);
const beforeIsNone = before === NO_CONTEXT;
const afterIsNone = after === NO_CONTEXT;
const beforeLines = beforeIsNone
? []
: getContextLines(before);
const afterLines = afterIsNone
? []
: getContextLines(after);
const targetLength = targetLines.length;
const matchedPositions = [];
// 两个输入框都没有填写,不允许定位
if (!before && !after) {
return matchedPositions;
}
occurrences.forEach(startIndex => {
const endIndex = startIndex + targetLength - 1;
const isStart = startIndex === 0;
const isEnd = endIndex === lines.length - 1;
// 情况一:标记文本覆盖整个剧本
if (isStart && isEnd) {
if (beforeIsNone && afterIsNone) {
matchedPositions.push(startIndex);
}
return;
}
// 情况二:标记文本位于剧本开头
if (isStart) {
if (
beforeIsNone &&
!afterIsNone &&
afterLines.length > 0 &&
matchAdjacentLines(
lines,
startIndex,
targetLength,
[],
afterLines
)
) {
matchedPositions.push(startIndex);
}
return;
}
// 情况三:标记文本位于剧本结尾
if (isEnd) {
if (
afterIsNone &&
!beforeIsNone &&
beforeLines.length > 0 &&
matchAdjacentLines(
lines,
startIndex,
targetLength,
beforeLines,
[]
)
) {
matchedPositions.push(startIndex);
}
return;
}
// 情况四:标记文本位于剧本中间
// 中间位置不允许使用 @@@
if (
beforeIsNone ||
afterIsNone ||
beforeLines.length === 0 ||
afterLines.length === 0
) {
return;
}
if (
matchAdjacentLines(
lines,
startIndex,
targetLength,
beforeLines,
afterLines
)
) {
matchedPositions.push(startIndex);
}
});
return matchedPositions;
}
/**
* 隐藏上下文区域
*/
function hideContext() {
contextBox.classList.remove('show');
beforeInput.value = '';
afterInput.value = '';
contextError.classList.remove('show');
pendingMarker = null;
}
/**
* 显示重复文本的上下文输入区域
*/
function showContext(targetLines, occurrences) {
pendingMarker = {
targetLines: targetLines,
originalText: markerInput.value
};
contextBox.classList.add('show');
contextError.classList.remove('show');
beforeInput.value = '';
afterInput.value = '';
contextDescription.textContent =
'这段文本在剧本中出现了 ' +
occurrences.length +
' 次。请填写目标文本前面和后面紧邻的内容,支持复制多行。' +
'如果目标位于剧本开头,前文填写 @@@;' +
'如果目标位于剧本结尾,后文填写 @@@。' +
'如果标记内容覆盖整个剧本,前后两项都填写 @@@。' +
'中间位置必须填写真实的前后文,不能使用 @@@。';
beforeInput.focus();
}
/**
* 判断指定位置是否已经添加过相同标记。
*
* 核心规则:
* 1. 文本相同。
* 2. 起始行号相同。
*
* 不比较上下文内容,也不比较上下文行数。
*
* 因此:
* 第一次复制前文1行定位到第5行;
* 第二次复制前文3行也定位到第5行;
* 第二次会被判定为重复。
*/
function isMarkerAlreadyAdded(startIndex, targetLines) {
return markers.some(marker => {
if (marker.startIndex !== startIndex) {
return false;
}
if (marker.targetLines.length !== targetLines.length) {
return false;
}
return marker.targetLines.every((line, index) => {
return line === targetLines[index];
});
});
}
/**
* 保存标记
*/
function saveMarker(
startIndex,
targetLines,
originalText,
before,
after
) {
// 先检查具体位置是否已经添加过
if (isMarkerAlreadyAdded(startIndex, targetLines)) {
return false;
}
markers.push({
text: originalText.trim(),
targetLines: [...targetLines],
startIndex: startIndex,
before: before || '',
after: after || ''
});
return true;
}
/**
* 添加标记
*/
function addMarker() {
if (!scriptText.trim()) {
alert('请先输入原始剧本');
return;
}
const originalText = markerInput.value;
const normalizedText = normalizeText(originalText);
if (!normalizedText) {
alert('请输入需要标记的文本');
return;
}
const targetLines = getMarkerLines(normalizedText);
// 不允许空行混入标记文本
if (targetLines.some(line => !line)) {
alert('标记文本中不能包含空白行,请检查复制内容');
return;
}
// 查找原文出现次数
const occurrences = findOccurrences(targetLines);
if (occurrences.length === 0) {
alert('原始剧本中没有找到这段文本,请检查内容是否一致');
return;
}
// 唯一出现:直接添加
if (occurrences.length === 1) {
const success = saveMarker(
occurrences[0],
targetLines,
originalText,
'',
''
);
if (!success) {
alert('这个位置已经添加过相同标记,不能重复添加');
return;
}
markerInput.value = '';
hideContext();
renderMarkers();
renderResult();
return;
}
// 重复出现:要求补充上下文
showContext(targetLines, occurrences);
}
/**
* 确认上下文并添加标记
*/
function confirmContext() {
if (!pendingMarker) {
return;
}
const before = normalizeText(beforeInput.value);
const after = normalizeText(afterInput.value);
const targetLines = pendingMarker.targetLines;
// 查找符合上下文的所有位置
const positions = findPositionByContext(
targetLines,
before,
after
);
// 没有匹配的位置
if (positions.length === 0) {
contextError.textContent =
'没有找到符合上下文条件的位置。请检查前文、后文是否与目标文本紧邻,' +
'多行内容是否完整,以及开头或结尾是否正确使用 @@@。';
contextError.classList.add('show');
return;
}
// 匹配到多个位置
if (positions.length > 1) {
contextError.textContent =
'当前上下文仍然匹配到多个位置,请补充更多前文或后文,' +
'直到能够唯一定位。';
contextError.classList.add('show');
return;
}
const startIndex = positions[0];
// 唯一定位成功后,再检查具体位置是否已经添加
const success = saveMarker(
startIndex,
targetLines,
pendingMarker.originalText,
before,
after
);
if (!success) {
contextError.textContent =
'这个位置已经添加过相同标记,不能重复添加。' +
'即使本次复制的上下文行数不同,只要最终定位位置相同,也不能重复添加。';
contextError.classList.add('show');
return;
}
markerInput.value = '';
hideContext();
renderMarkers();
renderResult();
}
/**
* 删除标记
*/
function removeMarker(index) {
markers.splice(index, 1);
renderMarkers();
renderResult();
}
/**
* 重新验证已有标记。
*
* 剧本修改后,根据之前保存的上下文重新定位。
*/
function refreshMarkers() {
const validMarkers = [];
markers.forEach(marker => {
const positions = findOccurrences(marker.targetLines);
if (positions.length === 0) {
return;
}
// 原来唯一的文本,修改后仍然唯一
if (positions.length === 1) {
marker.startIndex = positions[0];
validMarkers.push(marker);
return;
}
// 原来有上下文的文本,重新验证上下文
if (marker.before || marker.after) {
const matched = findPositionByContext(
marker.targetLines,
marker.before,
marker.after
);
if (matched.length === 1) {
marker.startIndex = matched[0];
validMarkers.push(marker);
}
}
});
markers = validMarkers;
}
/**
* 渲染标记列表
*/
function renderMarkers() {
markerList.innerHTML = '';
if (markers.length === 0) {
const empty = document.createElement('div');
empty.className = 'empty-marker';
empty.textContent = '暂未添加标记';
markerList.appendChild(empty);
return;
}
markers.forEach((marker, index) => {
const item = document.createElement('div');
item.className = 'marker-item';
const content = document.createElement('div');
content.className = 'marker-text';
const number = document.createElement('span');
number.className = 'marker-index';
number.textContent = (index + 1) + '.';
const value = document.createElement('span');
value.textContent = marker.text;
content.appendChild(number);
content.appendChild(value);
const location = document.createElement('span');
location.className = 'marker-location';
const endLine =
marker.startIndex + marker.targetLines.length;
location.textContent =
'定位位置:第 ' +
(marker.startIndex + 1) +
' - ' +
endLine +
' 行';
content.appendChild(location);
const removeBtn = document.createElement('button');
removeBtn.className = 'remove-btn';
removeBtn.textContent = '删除';
removeBtn.addEventListener('click', function () {
removeMarker(index);
});
item.appendChild(content);
item.appendChild(removeBtn);
markerList.appendChild(item);
});
}
/**
* 渲染右侧剧本
*
* 根据已经确定的行号进行标记。
*/
function renderResult() {
resultContent.innerHTML = '';
if (scriptText === '') {
const empty = document.createElement('span');
empty.className = 'empty-tip';
empty.textContent = '生成后的剧本将在这里显示...';
resultContent.appendChild(empty);
stats.textContent = '共 0 行,已标记 0 处';
return;
}
const lines = scriptText
.replace(/\r\n|\r/g, '\n')
.split('\n');
// 建立需要标红的行号集合
const markedLines = new Set();
markers.forEach(marker => {
for (
let i = 0;
i < marker.targetLines.length;
i++
) {
markedLines.add(marker.startIndex + i);
}
});
const fragment = document.createDocumentFragment();
lines.forEach((line, index) => {
if (markedLines.has(index)) {
const marked = document.createElement('span');
marked.className = 'result-marked';
marked.textContent = line;
fragment.appendChild(marked);
} else {
fragment.appendChild(
document.createTextNode(line)
);
}
// 保留原始换行效果
if (index < lines.length - 1) {
fragment.appendChild(
document.createTextNode('\n')
);
}
});
resultContent.appendChild(fragment);
stats.textContent =
'共 ' + lines.length +
' 行,已标记 ' + markers.length + ' 处';
}
/**
* 监听原始剧本变化
*/
function handleScriptChange() {
scriptText = scriptInput.value;
// 如果正在填写上下文,剧本发生变化则取消本次待添加操作
if (pendingMarker) {
hideContext();
}
// 重新检查已经添加的标记
refreshMarkers();
renderMarkers();
renderResult();
}
/**
* 复制原始完整剧本
*/
async function copyResult() {
if (!scriptText.trim()) {
alert('请先输入剧本文案');
return;
}
try {
if (
navigator.clipboard &&
window.isSecureContext
) {
await navigator.clipboard.writeText(scriptText);
} else {
const textarea = document.createElement('textarea');
textarea.value = scriptText;
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
const success = document.execCommand('copy');
document.body.removeChild(textarea);
if (!success) {
throw new Error('复制失败');
}
}
alert('剧本复制成功');
} catch (error) {
console.error(error);
alert('复制失败,请检查浏览器权限');
}
}
/**
* 清空所有内容
*/
function clearAll() {
if (!confirm('确定清空原始剧本和所有标记吗?')) {
return;
}
scriptInput.value = '';
markerInput.value = '';
scriptText = '';
markers = [];
hideContext();
renderMarkers();
renderResult();
}
// 事件绑定
scriptInput.addEventListener(
'input',
handleScriptChange
);
addBtn.addEventListener(
'click',
addMarker
);
// Ctrl + Enter 添加标记
markerInput.addEventListener('keydown', function (event) {
if (
event.key === 'Enter' &&
(event.ctrlKey || event.metaKey)
) {
event.preventDefault();
addMarker();
}
});
confirmContextBtn.addEventListener(
'click',
confirmContext
);
cancelContextBtn.addEventListener(
'click',
hideContext
);
clearBtn.addEventListener(
'click',
clearAll
);
copyBtn.addEventListener(
'click',
copyResult
);
// 初始化
handleScriptChange();
})();
</script>
</body>
</html>








Comments
Post a Comment