HTML Interfaces + Ink
Note: This series is a sequel to JavaScript + Ink series. It builds on the code and concepts found there.
Speaker CSS
When using the Continue() function to get the next text block from the Ink runtime, the result is a string. While this seems very obvious, it also means that the string result can be parsed before showing it to a user.
As a bridge between the Ink runtime and a user, JavaScript running in a browser can act on the contents of the string and even use CSS to style text before the user sees it.
Following the pattern setup in the last series, the Ink.js and story.js (called StoryDialogue.js in this example) are included along with a main.js file. This also follows the same setup as the Ink for Web functionality. (See JavaScript + Ink: Part 1: Ink for Web for more details.)
The main.js file looks similar to other examples from the previous series. It loads the storyContents variable and saves a reference to an element with the id of “story”.
The continueStory() function is where some changes happen.
// Get ink to generate the next paragraph
var paragraphText = story.Continue();
// Find the position where the colon start
var dialogueTag = paragraphText.indexOf(':');
// Get the string from the beginning to the position of colon
var speaker = paragraphText.substring(0, dialogueTag);
The results of the call to story.Continue() is saved. Then, the indexOf() function is used to get the position of the colon within the string. Next, it is used to get the speaker by getting a substring between the first position and the position of the colon within the string. In other words, it gets name of the speaker.
For this to make sense, consider the following Ink code:
The text of the story is broken up with a format where the speaker of the lines appear before the text they speak. It is separated by a colon.
Coming back to the main.js code, this can then be used to add a CSS class to the paragraph to mark who is speaking the lines.
The site.css file simply includes the names of the speakers as CSS classes with rules for how their text should be shown to the user. As the text is parsed as received by Continue(), these classes are applied to the paragraphs as they occur in the story.
Revising main.js
Showing only a single block of text from the Ink runtime is not very helpful. To fix that issue, an event listener could be added to add to the code to run continueStory() each time.
Within the continueStory() code, some additional checks could be added through using canContinue to check if there is more content to show and checking if there is a speaker or not. (The text “End of Story,” for example, would not have a speaker and thus needs to be checked against somehow.)
