-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
701 lines (583 loc) Β· 25.1 KB
/
script.js
File metadata and controls
701 lines (583 loc) Β· 25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
// Briefly Frontend - Client-side analysis based on the Python bot logic
class Briefly {
constructor() {
this.rules = {
"super_specific_how": {
"description": "Focus on actionable 'how' rather than 'what' and 'why'",
"check": this.checkSuperSpecificHow.bind(this),
"suggest": this.suggestSuperSpecificHow.bind(this)
},
"cut_backstory": {
"description": "Start right before you get eaten by the bear - cut unnecessary backstory",
"check": this.checkBackstory.bind(this),
"suggest": this.suggestCutBackstory.bind(this)
},
"clear_recommendations": {
"description": "Avoid communication surprises - be clear about your point of view",
"check": this.checkClearRecommendations.bind(this),
"suggest": this.suggestClearRecommendations.bind(this)
},
"bottom_line_first": {
"description": "Lead with conclusions, then provide context (Minto Pyramid Principle)",
"check": this.checkBottomLineFirst.bind(this),
"suggest": this.suggestBottomLineFirst.bind(this)
},
"sentence_structure": {
"description": "Use clear, concise sentences with proper structure (Casagrande principles)",
"check": this.checkSentenceStructure.bind(this),
"suggest": this.suggestSentenceStructure.bind(this)
},
"active_voice": {
"description": "Prefer active voice over passive voice for clarity and directness",
"check": this.checkActiveVoice.bind(this),
"suggest": this.suggestActiveVoice.bind(this)
},
"logical_flow": {
"description": "Structure arguments logically with clear hierarchy (Minto Pyramid)",
"check": this.checkLogicalFlow.bind(this),
"suggest": this.suggestLogicalFlow.bind(this)
},
"conciseness": {
"description": "Eliminate unnecessary words and redundant phrases",
"check": this.checkConciseness.bind(this),
"suggest": this.suggestConciseness.bind(this)
},
"clarity_simplicity": {
"description": "Write clearly and simply - avoid jargon and complex constructions (Zinsser)",
"check": this.checkClaritySimplicity.bind(this),
"suggest": this.suggestClaritySimplicity.bind(this)
},
"eliminate_clutter": {
"description": "Remove unnecessary words, adverbs, and complexity (Zinsser principles)",
"check": this.checkEliminateClutter.bind(this),
"suggest": this.suggestEliminateClutter.bind(this)
}
};
}
analyzeText(text) {
if (!text.trim()) {
return null;
}
const results = {
originalText: text,
analysis: {},
suggestions: []
};
for (const [ruleName, rule] of Object.entries(this.rules)) {
const issues = rule.check(text);
results.analysis[ruleName] = {
passed: issues.length === 0,
issues: issues,
description: rule.description
};
if (issues.length > 0) {
const suggestions = rule.suggest(text, issues);
results.suggestions.push(...suggestions);
}
}
return results;
}
// Analysis Methods (simplified versions of the Python logic)
checkSuperSpecificHow(text) {
const issues = [];
const vaguePatterns = [
/\b(you should|it's important to|make sure to)\s+(be|have|do|get|use)\s+\w+/gi,
/\b(focus on|prioritize|emphasize)\s+\w+\s+(more|better)/gi
];
vaguePatterns.forEach(pattern => {
if (pattern.test(text)) {
issues.push("Potential vague advice without specific implementation");
}
});
const specificIndicators = [
/\b(here's how|this is how|step 1|first,|second,|then|next)/gi,
/\b(specifically|exactly|precisely)/gi,
/\b(example|instance|case study)/gi,
/\d+\s+(minutes|hours|days|steps)/gi
];
const hasSpecificContent = specificIndicators.some(pattern => pattern.test(text));
if (!hasSpecificContent && text.split(' ').length > 100) {
issues.push("Text lacks specific implementation details - consider adding 'how-to' elements");
}
return issues;
}
checkBackstory(text) {
const issues = [];
const sentences = text.split('.').filter(s => s.trim());
const backstoryIndicators = [
/\b(let me|i want to|first, let me|to begin with|in order to understand)/gi,
/\b(context|background|history|overview|introduction)/gi,
/\b(going to|about to|planning to|will be talking about)/gi
];
const firstThird = sentences.slice(0, Math.floor(sentences.length / 3));
for (const sentence of firstThird) {
for (const pattern of backstoryIndicators) {
if (pattern.test(sentence)) {
issues.push(`Potential backstory in opening: '${sentence.trim().substring(0, 50)}...'`);
return issues;
}
}
}
return issues;
}
checkClearRecommendations(text) {
const issues = [];
const unclearPatterns = [
/\b(you might want to|it could be|perhaps|maybe|consider)/gi,
/\b(on one hand|on the other hand)\b.*\b(on the other hand|however|but)\b/gi
];
for (const pattern of unclearPatterns) {
if (pattern.test(text)) {
issues.push("Potentially unclear recommendation - consider stating your position more directly");
}
}
if (/\b(pros?|advantages?)\b.*\b(cons?|disadvantages?)\b/gi.test(text) &&
!/\b(recommend|suggest|think|believe)\b/gi.test(text)) {
issues.push("Pros/cons list detected without clear recommendation - state your position upfront");
}
return issues;
}
checkBottomLineFirst(text) {
const issues = [];
const sentences = text.split('.').filter(s => s.trim());
if (sentences.length < 3) {
return issues;
}
const firstThird = sentences.slice(0, Math.floor(sentences.length / 3));
const conclusionIndicators = [
/\b(recommend|suggest|conclude|believe|think|decision)/gi,
/\b(in summary|to summarize|bottom line|the point is)/gi,
/\b(action item|next steps|what to do)/gi
];
const hasEarlyConclusion = firstThird.some(sentence =>
conclusionIndicators.some(pattern => pattern.test(sentence))
);
if (!hasEarlyConclusion) {
issues.push("Main conclusion or recommendation may be buried - consider leading with the key takeaway");
}
return issues;
}
checkSentenceStructure(text) {
const issues = [];
const sentences = text.split('.').filter(s => s.trim());
for (const sentence of sentences) {
if (sentence.split(' ').length > 30) {
issues.push(`Very long sentence (${sentence.split(' ').length} words): '${sentence.substring(0, 50)}...'`);
}
const weakOpenings = [
/^there (is|are|was|were)\b/gi,
/^it (is|was)\b.*that/gi,
/^what (is|was)\b/gi,
/^the fact that\b/gi
];
for (const pattern of weakOpenings) {
if (pattern.test(sentence)) {
issues.push(`Consider stronger sentence opening: '${sentence.substring(0, 50)}...'`);
break;
}
}
}
return issues;
}
checkActiveVoice(text) {
const issues = [];
const passivePatterns = [
/\b(was|were|is|are|been|being)\s+\w+ed\b/gi,
/\b(was|were|is|are)\s+\w+\s+by\s+\w+/gi
];
const sentences = text.split('.');
for (let sentence of sentences) {
sentence = sentence.trim().toLowerCase();
for (const pattern of passivePatterns) {
if (pattern.test(sentence)) {
issues.push(`Passive voice detected: '${sentence.substring(0, 60)}...'`);
break;
}
}
}
return issues;
}
checkLogicalFlow(text) {
const issues = [];
const transitionIndicators = [
/\b(first|second|third|next|then|furthermore|moreover|however|therefore|consequently)\b/gi
];
const hasTransitions = transitionIndicators.some(pattern => pattern.test(text));
const hasStructure = /\b(1\.|2\.|3\.|first|second|third|-|\*)\b/gi.test(text);
const wordCount = text.split(' ').length;
if (wordCount > 150) {
if (!hasTransitions && !hasStructure) {
issues.push("Long text lacks clear logical structure - consider adding transitions or organizing in numbered points");
}
}
return issues;
}
checkConciseness(text) {
const issues = [];
const redundancies = [
{ pattern: /\babsolutely essential\b/gi, replacement: 'essential' },
{ pattern: /\bin order to\b/gi, replacement: 'to' },
{ pattern: /\bdue to the fact that\b/gi, replacement: 'because' },
{ pattern: /\bfor the purpose of\b/gi, replacement: 'to' }
];
for (const { pattern, replacement } of redundancies) {
if (pattern.test(text)) {
issues.push(`Redundant phrase found - consider using '${replacement}' instead`);
}
}
const fillerPatterns = [/\b(very|really|quite|rather|somewhat|quite a bit)\b/gi];
const fillerCount = fillerPatterns.reduce((count, pattern) => {
const matches = text.match(pattern);
return count + (matches ? matches.length : 0);
}, 0);
const wordCount = text.split(' ').length;
if (fillerCount > wordCount * 0.02) {
issues.push(`Excessive use of filler words (${fillerCount} instances) - consider removing some`);
}
return issues;
}
checkClaritySimplicity(text) {
const issues = [];
const jargonPatterns = [
/\b(utilize|utilization)\b/gi,
/\b(facilitate|facilitation)\b/gi,
/\b(leverage)\b(?=.*business)/gi,
/\b(paradigm|synergistic|holistic)\b/gi,
/\b(optimal|optimize|optimization)\b/gi
];
for (const pattern of jargonPatterns) {
if (pattern.test(text)) {
issues.push("Jargon detected - consider simpler alternatives");
}
}
return issues;
}
checkEliminateClutter(text) {
const issues = [];
const clutterWords = [
/\b(very|really|quite|rather|somewhat|pretty|fairly|relatively)\b/gi,
/\b(kind of|sort of|basically|essentially|literally|actually|totally)\b/gi
];
let clutterCount = 0;
for (const pattern of clutterWords) {
const matches = text.match(pattern);
clutterCount += matches ? matches.length : 0;
}
const wordCount = text.split(' ').length;
if (clutterCount > wordCount * 0.03) {
issues.push(`High clutter word density (${clutterCount} instances) - remove unnecessary qualifiers`);
}
return issues;
}
// Suggestion Methods
suggestSuperSpecificHow() {
return [
"β’ Add specific steps, examples, or concrete implementation details",
"β’ Replace vague advice with actionable instructions",
"β’ Include time estimates, specific tools, or measurable outcomes"
];
}
suggestCutBackstory() {
return [
"β’ Consider starting closer to the main point or key insight",
"β’ Ask: 'Does this opening sentence directly serve my reader's immediate need?'",
"β’ Try starting with the insight or recommendation, then provide minimal necessary context"
];
}
suggestClearRecommendations() {
return [
"β’ State your recommendation upfront (e.g., 'I recommend X because...')",
"β’ If presenting options, clearly indicate which you prefer and why",
"β’ Replace hedging language with confident statements where appropriate"
];
}
suggestBottomLineFirst() {
return [
"β’ Start with: 'Bottom line: [your main point]'",
"β’ Or begin with: 'I recommend [action] because [key reason]'",
"β’ Move supporting details and context after the main point"
];
}
suggestSentenceStructure() {
return [
"β’ Break sentences longer than 25-30 words into shorter, clearer sentences",
"β’ Start sentences with strong subjects and active verbs when possible",
"β’ Avoid starting with 'There is/are' - use more direct constructions"
];
}
suggestActiveVoice() {
return [
"β’ Rewrite passive voice to active voice for stronger, clearer writing",
"β’ Put the doer of the action before the verb when possible",
"β’ Example: 'The report was written by John' β 'John wrote the report'"
];
}
suggestLogicalFlow() {
return [
"β’ Use transition words to guide readers through your argument",
"β’ Start each paragraph with a clear topic sentence",
"β’ Organize ideas in logical order: most important first, supporting details second"
];
}
suggestConciseness() {
return [
"β’ Remove redundant phrases and unnecessary words",
"β’ Replace wordy constructions with shorter alternatives",
"β’ Example: 'in order to' β 'to', 'due to the fact that' β 'because'"
];
}
suggestClaritySimplicity() {
return [
"β’ Replace jargon with simple, clear words",
"β’ Use 'use' instead of 'utilize', 'help' instead of 'facilitate'",
"β’ Break complex sentences into shorter, clearer ones"
];
}
suggestEliminateClutter() {
return [
"β’ Remove clutter words: 'very', 'really', 'quite', 'rather', 'somewhat'",
"β’ Strengthen weak words instead of adding qualifiers",
"β’ Example: 'very good' β 'excellent', 'really important' β 'crucial'"
];
}
}
// Global variables and event handlers
const bot = new Briefly();
// AI Enhancement functionality
class AIEnhancer {
constructor() {
this.groqApiUrl = 'https://api.groq.com/openai/v1/chat/completions';
this.model = 'llama-3.1-8b-instant';
}
async enhanceText(text, apiKey) {
// Validate input length (Mixtral context is 32k tokens, ~128k chars)
if (text.length > 10000) {
throw new Error('Text too long. Please limit to 10,000 characters.');
}
const prompt = this.createWritingPrompt(text);
try {
const requestBody = {
model: this.model,
messages: [
{
role: 'system',
content: 'You are an expert writing coach who applies proven principles from Wes Kao, June Casagrande, the Minto Pyramid Principle, HBR Guide to Better Business Writing, and William Zinsser to improve business and creative writing.'
},
{
role: 'user',
content: prompt
}
],
temperature: 0.7,
max_tokens: 2000
};
console.log('Sending request to Groq API...', { model: this.model });
const response = await fetch(this.groqApiUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const errorMessage = errorData.error?.message || errorData.message || response.statusText;
console.error('API Error Details:', errorData);
throw new Error(`API Error (${response.status}): ${errorMessage}`);
}
const data = await response.json();
if (!data.choices || !data.choices[0] || !data.choices[0].message) {
throw new Error('Invalid response format from API');
}
return data.choices[0].message.content.trim();
} catch (error) {
console.error('AI Enhancement Error:', error);
throw error;
}
}
createWritingPrompt(originalText) {
return `Rewrite this text applying professional writing principles: be specific, cut unnecessary backstory, use active voice, lead with conclusions (bottom-line-up-front), keep sentences clear and concise, eliminate clutter and jargon.
Original text:
${originalText}
Improved version:`;
}
}
const aiEnhancer = new AIEnhancer();
function updateWordCount() {
const text = document.getElementById('textInput').value;
const wordCount = text.trim() ? text.trim().split(/\s+/).length : 0;
document.getElementById('wordCount').textContent = `${wordCount} words`;
}
async function analyzeText() {
const text = document.getElementById('textInput').value.trim();
const isAiMode = document.getElementById('aiModeToggle').checked;
if (!text) {
alert('Please enter some text to analyze.');
return;
}
const analyzeBtn = document.getElementById('analyzeBtn');
const btnText = document.getElementById('btnText');
const btnIcon = document.getElementById('btnIcon');
// Show loading state
analyzeBtn.disabled = true;
if (isAiMode) {
btnText.textContent = 'AI Enhancing...';
btnIcon.innerHTML = '<div class="loading"></div>';
const apiKey = document.getElementById('groqApiKey').value.trim() || localStorage.getItem('groqApiKey');
if (!apiKey) {
alert('Please enter your Groq API key for AI enhancement.');
analyzeBtn.disabled = false;
btnText.textContent = 'AI Enhance Text';
btnIcon.textContent = 'π€';
return;
}
try {
const enhancedText = await aiEnhancer.enhanceText(text, apiKey);
// Replace the text in the textarea with the enhanced version
document.getElementById('textInput').value = enhancedText;
updateWordCount();
// Now analyze the enhanced text
const results = bot.analyzeText(enhancedText);
displayResults(results, true); // true indicates this was AI enhanced
// Show success message
setTimeout(() => {
alert('β
Text enhanced with AI! Analysis shows the improved version.');
}, 500);
} catch (error) {
alert(`AI Enhancement failed: ${error.message}`);
console.error('AI Enhancement Error:', error);
} finally {
analyzeBtn.disabled = false;
btnText.textContent = 'AI Enhance Text';
btnIcon.textContent = 'π€';
}
} else {
btnText.textContent = 'Analyzing...';
btnIcon.innerHTML = '<div class="loading"></div>';
// Simulate analysis delay for better UX
setTimeout(() => {
const results = bot.analyzeText(text);
displayResults(results);
// Reset button
analyzeBtn.disabled = false;
btnText.textContent = 'Analyze Text';
btnIcon.textContent = 'π';
}, 1000);
}
}
function displayResults(results, isAiEnhanced = false) {
const resultsSection = document.getElementById('results');
const analysisContent = document.getElementById('analysisContent');
let html = '';
let allPassed = true;
// Add AI enhancement indicator if this was enhanced
if (isAiEnhanced) {
html += `
<div class="ai-enhanced-indicator">
<span class="ai-icon">π€</span>
<span class="ai-text">AI Enhanced Text - Analysis of Improved Version</span>
</div>
`;
}
// Display analysis for each rule
for (const [ruleName, ruleAnalysis] of Object.entries(results.analysis)) {
const displayName = ruleName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
const status = ruleAnalysis.passed ? 'β PASS' : 'β ISSUES FOUND';
const statusClass = ruleAnalysis.passed ? 'pass' : 'fail';
const statusIcon = ruleAnalysis.passed ? 'β
' : 'β';
if (!ruleAnalysis.passed) {
allPassed = false;
}
html += `
<div class="result-item ${statusClass}">
<div class="result-header">
<span class="status-indicator">${statusIcon}</span>
<span class="result-title">${displayName}: ${status}</span>
</div>
<div class="result-description">${ruleAnalysis.description}</div>
${ruleAnalysis.issues.length > 0 ? `
<ul class="issues-list">
${ruleAnalysis.issues.map(issue => `<li>${issue}</li>`).join('')}
</ul>
` : ''}
</div>
`;
}
// Add suggestions if any issues were found
if (results.suggestions.length > 0) {
html += `
<div class="suggestions">
<h3>π‘ Suggestions for Improvement</h3>
<ul>
${results.suggestions.map(suggestion => `<li>${suggestion}</li>`).join('')}
</ul>
</div>
`;
}
analysisContent.innerHTML = html;
resultsSection.style.display = 'block';
resultsSection.scrollIntoView({ behavior: 'smooth' });
// Show completion message
setTimeout(() => {
if (allPassed) {
alert('π Great! Your text follows the writing principles well!');
} else {
alert('π‘ Consider applying the suggestions above to improve your writing.');
}
}, 500);
}
function clearText() {
document.getElementById('textInput').value = '';
document.getElementById('results').style.display = 'none';
document.getElementById('wordCount').textContent = '0 words';
}
function toggleAiMode() {
const isAiMode = document.getElementById('aiModeToggle').checked;
const apiKeySection = document.getElementById('apiKeySection');
const btnText = document.getElementById('btnText');
const btnIcon = document.getElementById('btnIcon');
const modeLabel = document.getElementById('modeLabel');
if (isAiMode) {
apiKeySection.style.display = 'block';
btnText.textContent = 'AI Enhance Text';
btnIcon.textContent = 'π€';
modeLabel.textContent = 'AI Mode';
// Try to load saved API key
const savedKey = localStorage.getItem('groqApiKey');
if (savedKey) {
document.getElementById('groqApiKey').value = savedKey;
}
} else {
apiKeySection.style.display = 'none';
btnText.textContent = 'Analyze Text';
btnIcon.textContent = 'π';
modeLabel.textContent = 'Analysis Mode';
}
}
function saveApiKey() {
const apiKey = document.getElementById('groqApiKey').value;
if (apiKey) {
localStorage.setItem('groqApiKey', apiKey);
} else {
localStorage.removeItem('groqApiKey');
}
}
// Event listeners
document.addEventListener('DOMContentLoaded', function() {
const textInput = document.getElementById('textInput');
const aiToggle = document.getElementById('aiModeToggle');
const apiKeyInput = document.getElementById('groqApiKey');
textInput.addEventListener('input', updateWordCount);
textInput.addEventListener('keydown', function(e) {
if (e.ctrlKey && e.key === 'Enter') {
analyzeText();
}
});
// AI mode toggle
aiToggle.addEventListener('change', toggleAiMode);
// Save API key when typing
apiKeyInput.addEventListener('input', saveApiKey);
// Initial word count
updateWordCount();
});