Kā es pārveidoju Hemingveja redaktoru - populāru rakstīšanas lietotni - un izveidoju savu no Taizemes pludmales

Es izmantoju Hemingveja lietotni, lai mēģinātu uzlabot savas ziņas. Tajā pašā laikā esmu mēģinājis rast idejas maziem projektiem. Man radās ideja integrēt Hemingveja stila redaktoru iezīmēšanas redaktorā. Tāpēc man vajadzēja uzzināt, kā Hemingvejs strādāja!

Iegūt loģiku

Man nebija ne jausmas, kā lietotne darbojās, kad es pirmo reizi startēju. Tas varētu būt nosūtījis tekstu serverim, lai aprēķinātu rakstīšanas sarežģītību, bet es gaidīju, ka tas tiks aprēķināts klienta pusē.

Atbildes sniedza izstrādātāja rīku atvēršana pārlūkā Chrome (Control + Shift + I vai F12 operētājsistēmā Windows / Linux, Command + Option + I operētājsistēmā Mac) un navigācija uz avotiem . Tur es atradu meklēto failu: hemingway3-web.js.

Šis kods ir saīsinātā formā, kuru ir grūti lasīt un saprast. Lai to atrisinātu, es nokopēju failu VS kodā un formatēju dokumentu ( Control + Shift + I VS kodam). Tas maina 3 rindu failu 4859 rindiņu failā, kurā viss ir labi formatēts.

Kodeksa izpēte

Es sāku meklēt failā visu, kas man varētu būt jēga. Faila sākumā bija uzreiz izsauktas funkciju izteiksmes. Man bija maz nojausmas par notiekošo.

!function(e) { function t(r) { if (n[r]) return n[r].exports; var o = n[r] = { exports: {}, id: r, loaded: !1 }; ...

Tas turpinājās apmēram 200 rindas, pirms es nolēmu, ka es, iespējams, lasīju kodu, lai lapa darbotos (React?). Es sāku pārlūkot pārējo kodu, līdz atradu kaut ko saprotamu. (Man pietrūka diezgan daudz, ko vēlāk atradu, meklējot funkciju izsaukumus un aplūkojot funkciju definīciju).

Pirmais koda bits, ko es sapratu, bija līdz galam 3496 rindā!

getTokens: function(e) { var t = this.getAdverbs(e), n = this.getQualifiers(e), r = this.getPassiveVoices(e), o = this.getComplexWords(e); return [].concat(t, n, r, o).sort(function(e, t) { return e.startIndex - t.startIndex }) }

Un pārsteidzoši, visas šīs funkcijas tika definētas tieši zemāk. Tagad es zināju, kā lietotne definē apstākļa vārdus, kvalifikatorus, pasīvo balsi un sarežģītus vārdus. Daži no tiem ir ļoti vienkārši. Lietotne pārbauda katru vārdu pēc kvalifikatoru, sarežģītu vārdu un pasīvo balss frāžu sarakstiem. this.getAdverbs filtrē vārdus, pamatojoties uz to, vai tie beidzas ar “ly”, un pēc tam pārbauda, ​​vai tie ir bez vārdu vārdiem, kas beidzas ar “ly”.

Nākamais mazliet noderīgais kods bija vārdu vai teikumu izcelšana. Šajā kodā ir rinda:

e.highlight.hardSentences += h

“hardSentences” bija kaut kas, ko es varēju saprast, kaut kas ar nozīmi. Pēc tam es meklēju failu hardSentencesun saņēmu 13 sērkociņus. Tas noved pie līnijas, kas aprēķina lasāmības statistiku:

n.stats.readability === i.default.readability.hard && (e.hardSentences += 1), n.stats.readability === i.default.readability.veryHard && (e.veryHardSentences += 1)

Tagad es zināju, ka readabilityabos statsun i.default. Meklējot failu, es saņēmu 40 sērkociņus. Viena no šīm spēlēm bija getReadabilityStylefunkcija, kurā viņi vērtē jūsu rakstīto.

Ir trīs līmeņi: normāls, grūti un ļoti grūti.

t = e.words; n = e.readingLevel; return t = 10 && n = 14 ? i.default.readability.veryHard : i.default.readability.normal;

“Normāls” ir mazāks par 14 vārdiem, “grūti” ir 10–14 vārdi un “ļoti grūti” ir vairāk nekā 14 vārdi.

Tagad, lai uzzinātu, kā aprēķināt lasīšanas līmeni.

Es šeit pavadīju kādu laiku, mēģinot atrast jebkādu priekšstatu par to, kā aprēķināt lasīšanas līmeni. Es to atradu 4 rindas virs getReadabilityStylefunkcijas.

e = letters in paragraph; t = words in paragraph; n = sentences in paragraph; getReadingLevel: function(e, t, n) { if (0 === t 0 === n) return 0; var r = Math.round(4.71 * (e / t) + 0.5 * (t / n) - 21.43); return r <= 0 ? 0 : r; }

Tas nozīmē, ka jūsu rezultāts ir 4,71 * vidējais vārda garums + 0,5 * vidējais teikuma garums -21,43. Tieši tā. Tā Hemingvejs vērtē katru jūsu teikumu.

Citas interesantas lietas, kuras atradu

  • Izceltais komentārs (informācija par jūsu rakstīto labajā pusē) ir liels slēdzis. Trīsdaļīgi paziņojumi tiek izmantoti, lai mainītu atbildi atkarībā no tā, cik labi esat uzrakstījis.
  • Novērtējums iet līdz 16, pirms tas tiek klasificēts kā “pēcdiploma” līmenis.

Ko es ar šo darīšu

Es plānoju izveidot pamata vietni un pielietot to, ko esmu iemācījies, rekonstruējot Hemingveja lietotni. Nekas nav izdomāts, vairāk kā vingrinājums kādas loģikas īstenošanai. Iepriekš esmu izveidojis Markdown priekšskatītāju, tāpēc es varētu arī mēģināt izveidot rakstīšanas lietojumprogrammu ar izcelšanas un vērtēšanas sistēmu.

Mana Hemingveja lietotnes izveide

Uzzinājis, kā darbojas Hemingveja lietotne, tad es nolēmu īstenot iemācīto, lai izveidotu daudz vienkāršotu versiju.

Es gribēju pārliecināties, vai es to ievēroju, pievēršoties vairāk loģikai, nevis stilam. Es izvēlējos iet ar vienkāršu tekstlodziņa ievades lodziņu.

Izaicinājumi

1. Kā nodrošināt veiktspēju. Visa dokumenta atkārtota skenēšana katrā taustiņa nospiešanā varētu būt ļoti dārga skaitļošanas ziņā. Tas var izraisīt UX bloķēšanu, kas acīmredzami nav tas, ko mēs vēlamies.

2. Kā sadalīt tekstu rindkopās, teikumos un vārdos izcelšanai.

Iespējamie risinājumi

  • Pārskenēt tikai tos punktus, kas mainās. Dariet to, saskaitot rindkopu skaitu un salīdzinot to ar dokumentu pirms izmaiņām. Izmantojiet šo, lai atrastu mainīto rindkopu vai jauno rindkopu un tikai to skenētu.
  • Ir poga, lai skenētu dokumentu. Tas ievērojami samazina skenēšanas funkcijas izsaukumus.

2. Izmantojiet to, ko uzzināju no Hemingveja - katrs punkts ir a

un visi teikumi vai vārdi, kas jāizceļ, tiek iesaiņoti iekšējā ar nepieciešamo klasi.

Lietotnes veidošana

Nesen esmu lasījis daudz rakstu par minimāli dzīvotspējīga produkta (MVP) izveidi, tāpēc nolēmu, ka šo mazo projektu vadīšu tāpat. Tas nozīmēja, ka viss ir vienkārši. Es nolēmu iet ar ievades lodziņu, skenēšanas pogu un izvades laukumu.

This was all very easy to set up in my index.html file.

 Fake Hemingway 

Fake Hemingway

Test Me

Now to start on the interesting part. Now to get the Javascript working.

The first thing to do was to render the text from the text box into the output area. This involves finding the input text and setting the output’s inner html to that text.

function format() { let inputArea = document.getElementById(“text-area”); let text = inputArea.value; let outputArea = document.getElementById(“output”); outputArea.innerHTML = text; }

Next is getting the text split into paragraphs. This is accomplished by splitting the text by ‘\n’ and putting each of these into a

tag. To do this we can map over the array of paragraphs, putting them in between

tags. Using template strings makes doing this very easy.

let paragraphs = text.split(“\n”); let inParagraphs = paragraphs.map(paragraph => `

${paragraph}

`); outputArea.innerHTML = inParagraphs.join(“ “);

Whilst I was working though that, I was becoming annoyed having to copy and paste the test text into the text box. To solve this, I implemented an Immediately Invoked Function Expression (IIFE) to populate the text box when the web page renders.

(function start() { let inputArea = document.getElementById(“text-area”); let text = `The app highlights lengthy, …. compose something new.`; inputArea.value = text; })();

Now the text box was pre-populated with the test text whenever you load or refresh the web page. Much simpler.

Highlighting

Now that I was rendering the text well and I was testing on a consistent text, I had to work on the highlighting. The first type of highlighting I decided to tackle was the hard and very hard sentence highlighting.

The first stage of this is to loop over every paragraph and split them into an array of sentences. I did this using a `split()` function, splitting on every full stop with a space after it.

let sentences = paragraph.split(‘. ’);

From Heminway I knew that I needed to calculate the number of words and level of each of the sentences. The level of the sentence is dependant on the average length of words and the average words per sentence. Here is how I calculated the number of words and the total words per sentence.

let words = sentence.split(“ “).length; let letters = sentence.split(“ “).join(“”).length;

Using these numbers, I could use the equation that I found in the Hemingway app.

let level = Math.round(4.71 * (letters / words) + 0.5 * words / sentences — 21.43);

With the level and number of words for each of the sentences, set their difficulty level.

if (words = 10 && level < 14) { return `${sentence}`; } else if (level >= 14) { return `${sentence}`; } else { return sentence; }

This code says that if a sentence is longer than 14 words and has a level of 10 to 14 then its hard, if its longer than 14 words and has a level of 14 or up then its very hard. I used template strings again but include a class in the span tags. This is how I’m going to define the highlighting.

The CSS file is really simple; it just has each of the classes (adverb, passive, hardSentence) and sets their background colour. I took the exact colours from the Hemingway app.

Once the sentences have been returned, I join them all together to make each of the paragraphs.

At this point, I realised that there were a few problems in my code.

  • There were no full stops. When I split the paragraphs into sentences, I had removed all of the full stops.
  • The numbers of letters in the sentence included the commas, dashes, colons and semi-colons.

My first solution was very primitive but it worked. I used split(‘symbol’) and join(‘’) to remove the punctuation and then appended ‘.’ onto the end. Whist it worked, I searched for a better solution. Although I don’t have much experience using regex, I knew that it would be the best solution. After some Googling I found a much more elegant solution.

let cleanSentence = sent.replace(/[^a-z0–9. ]/gi, “”) + “.”;

With this done, I had a partially working product.

The next thing I decided to tackle was the adverbs. To find an adverb, Hemingway just finds words that end in ‘ly’ and then checks that it isn’t on a list of non-adverb ‘ly’ words. It would be bad if ‘apply’ or ‘Italy’ were tagged as adverbs.

To find these words, I took the sentences and split them into an arary of words. I mapped over this array and used an IF statement.

if(word.match(/ly$/) &&, !lyWords[word] ){ return `${word}`; } else { return word };

Whist this worked most of the time, I found a few exceptions. If a word was followed by a punctuation mark then it didn’t match ending with ‘ly’. For example, “The crocodile glided elegantly; it’s prey unaware” would have the word ‘elegantly;’ in the array. To solve this I reused the .replace(/^a-z0-9. ]/gi,””) functionality to clean each of the words.

Another exception was if the word was capitalised, which was easily solved by calling toLowerCase()on the string.

Now I had a result that worked with adverbs and highlighting individual words. I then implemented a very similar method for complex and qualifying words. That was when I realised that I was no longer just looking for individual words, I was looking for phrases. I had to change my approach from checking if each word was in the list to seeing if the sentence contained each of the phrases.

To do this I used the .indexOf() function on the sentences. If there was an index of the word or phrase, I inserted an opening span tag at that index and then the closing span tag after the key length.

let qualifiers = getQualifyingWords(); let wordList = Object.keys(qualifiers); wordList.forEach(key => { let index = sentence.toLowerCase().indexOf(key); if (index >= 0) { sentence = sentence.slice(0, index) + ‘’ + sentence.slice(index, index + key.length) + “” + sentence.slice(index + key.length); } });

With that working, it’s starting to look more and more like the Hemingway editor.

The last piece of the highlighting puzzle to implement was the passive voice. Hemingway used a 30 line function to find all of the passive phrases. I chose to use most of the logic that Hemingway implemented, but order the process differently. They looked to find any words that were in a list (is, are, was, were, be, been, being) and then checked whether the next word ended in ‘ed’.

I looped though each of the words in a sentence and checked if they ended in ‘ed’. For every ‘ed’ word I found, I checked whether the previous word was in the list of pre-words. This seemed much simpler, but may be less performant.

With that working I had an app that highlighted everything I wanted. This is my MVP.

Then I hit a problem

As I was writing this post I realised that there were two huge bugs in my code.

// from getQualifier and getComplex let index = sentence.toLowerCase().indexOf(key); // from getPassive let index = words.indexOf(match);

These will only ever find the first instance of the key or match. Here is an example of the results this code will produce.

‘Perhaps’ and ‘been marked’ should have been highlighted twice each but they aren’t.

To fix the bug in getQualifier and getComplex, I decided to use recursion. I created a findAndSpan function which uses .indexOf() to find the first instance of the word or phrase. It splits the sentence into 3 parts: before the phrase, the phrase, after the phrase. The recursion works by passing the ‘after the phrase’ string back into the function. This will continue until there are no more instances of the phrase, where the string will just be passed back.

function findAndSpan(sentence, string, type) { let index = sentence.toLowerCase().indexOf(key); if (index >= 0) { sentence = sentence.slice(0, index) + `` + sentence.slice(index, index + key.length) + "" + findAndSpan( sentence.slice(index + key.length), key, type); } return sentence; }

Something very similar had to be done for the passive voice. The recursion was in an almost identical pattern, passing the leftover array items instead of the leftover string. The result of the recursion call was spread into an array that was then returned. Now the app can deal with repeated adverbs, qualifiers, complex phrases and passive voice uses.

Statistics Counter

The last thing that I wanted to get working was the nice line of boxes informing you on how many adverbs or complex words you’d used.

To store the data I created an object with keys for each of the parameters I wanted to count. I started by having this variable as a global variable but knew I would have to change that later.

Now I had to populate the values. This was done by incrementing the value every time it was found.

data.sentences += sentence.length or data.adverbs += 1

Vērtības bija jāatiestata katru reizi, kad skenēšana tika veikta, lai pārliecinātos, ka vērtības nepārtraukti nepalielinās.

Izmantojot man vajadzīgās vērtības, man vajadzēja panākt, lai tās tiktu atveidotas ekrānā. Es mainīju HTML faila struktūru tā, lai ievades lodziņš un izvades laukums būtu div kreisajā pusē, atstājot skaitītājiem labo div. Šie skaitītāji ir tukši divi ar atbilstošu ID un klasi, kā arī “counter” klasi.

Izmantojot šos divus, es izmantoju document.querySelector, lai iestatītu iekšējo html katram skaitītājam, izmantojot savāktos datus. Ar nelielu “counter” klases veidošanu tīmekļa lietotne bija pabeigta. Izmēģiniet to šeit vai apskatiet manu kodu šeit.