All files / owid-grapher/explorerAdminClient ExplorerCreatePage.tsx

42.75% Statements 177/414
46.15% Branches 6/13
24% Functions 6/25
42.75% Lines 177/414

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 4831x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x     1x 1x 1x 1x 1x 1x         1x 1x                     1x 1x 1x 1x     1x 1x 1x 1x                         1x 1x       1x 1x     1x 1x     1x 1x     1x 1x 1x 1x 1x 1x                                   1x 1x                                           1x 1x             1x 1x               1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                          
import { observer } from "mobx-react"
import React from "react"
import { HotTable } from "@handsontable/react"
import { action, observable, computed } from "mobx"
import {
    ExplorerProgram,
    EXPLORER_FILE_SUFFIX,
    makeFullPath,
} from "../explorer/ExplorerProgram"
import { GitCmsClient } from "../gitCms/GitCmsClient"
import { Prompt } from "react-router-dom"
import Handsontable from "handsontable"
import { CoreMatrix } from "../coreTable/CoreTableConstants"
import {
    exposeInstanceOnWindow,
    slugify,
    toRectangularMatrix,
} from "../clientUtils/Util"
import { LoadingIndicator } from "../grapher/loadingIndicator/LoadingIndicator"
import {
    DefaultNewExplorerSlug,
    ExplorerChoiceParams,
    EXPLORERS_PREVIEW_ROUTE,
    UNSAVED_EXPLORER_DRAFT,
    UNSAVED_EXPLORER_PREVIEW_QUERYPARAMS,
} from "../explorer/ExplorerConstants"
import {
    AutofillColDefCommand,
    InlineDataCommand,
    SelectAllHitsCommand,
} from "./ExplorerCommands"
import { isEmpty } from "../gridLang/GrammarUtils"
import classNames from "classnames"
import { GitCmsFile, GIT_CMS_BASE_ROUTE } from "../gitCms/GitCmsConstants"
import { AdminManager } from "./AdminManager"
import { registerAllModules } from "handsontable/registry"
 
const RESERVED_NAMES = [DefaultNewExplorerSlug, "index", "new", "create"] // don't allow authors to save explorers with these names, otherwise might create some annoying situations.
 
// Register all Handsontable modules
registerAllModules()
 
@observer
export class ExplorerCreatePage extends React.Component<{
    slug: string
    gitCmsBranchName: string
    manager?: AdminManager
    doNotFetch?: boolean // for testing
}> {
    @computed private get manager() {
        return this.props.manager ?? {}
    }
 
    @action.bound private loadingModalOff() {
        this.manager.loadingIndicatorSetting = "off"
    }
 
    @action.bound private loadingModalOn() {
        this.manager.loadingIndicatorSetting = "loading"
    }
 
    @action.bound private resetLoadingModal() {
        this.manager.loadingIndicatorSetting = "default"
    }
 
    @action componentDidMount() {
        this.loadingModalOff()
        exposeInstanceOnWindow(this, "explorerEditor")
 
        if (this.props.doNotFetch) return

        this.fetchExplorerProgramOnLoad()
        this.startPollingLocalStorageForPreviewChanges()
    }
 
    @action.bound private startPollingLocalStorageForPreviewChanges() {
        setInterval(() => {
            const savedQueryParamsJSON = localStorage.getItem(
                `${UNSAVED_EXPLORER_PREVIEW_QUERYPARAMS}${this.program.slug}`
            )
            if (typeof savedQueryParamsJSON === "string")
                this.program.decisionMatrix.setValuesFromChoiceParams(
                    JSON.parse(savedQueryParamsJSON) as ExplorerChoiceParams
                )
        }, 1000)
    }
 
    @observable isReady = false
 
    @action componentWillUnmount() {
        this.resetLoadingModal()
    }
 
    private gitCmsClient = new GitCmsClient(GIT_CMS_BASE_ROUTE)
 
    @action.bound private async fetchExplorerProgramOnLoad() {
        const { slug } = this.props
        const response = await this.gitCmsClient.readRemoteFile({
            filepath: makeFullPath(slug),
        })
        this.programOnDisk = new ExplorerProgram("", response.content ?? "")
        this.setProgram(this.draftIfAny ?? this.programOnDisk.toString())
        this.isReady = true
        if (this.isModified)
            alert(
                `Your browser has a changed draft of '${slug}'. If you want to clear your local changes, click the "Clear Changes" button in the top right.`
            )
    }
 
    @action.bound private setProgram(code: string) {
        this.program = new ExplorerProgram(this.program.slug, code)
        this.saveDraft(code)
    }
 
    private saveDraft(code: string) {
        localStorage.setItem(UNSAVED_EXPLORER_DRAFT + this.program.slug, code)
    }
 
    get draftIfAny() {
        return localStorage.getItem(UNSAVED_EXPLORER_DRAFT + this.program.slug)
    }
 
    private clearDraft() {
        localStorage.removeItem(UNSAVED_EXPLORER_DRAFT + this.program.slug)
    }
 
    @observable.ref private programOnDisk = new ExplorerProgram("", "")
 
    @observable.ref private program = new ExplorerProgram(this.props.slug, "")
 
    @action.bound private async _save(slug: string, commitMessage: string) {
        this.loadingModalOn()
        this.program.slug = slug
        const res = await this.gitCmsClient.writeRemoteFile({
            filepath: this.program.fullPath,
            content: this.program.toString(),
            commitMessage,
        })
        if (!res.success) {
            alert(`Saving the explorer failed!\n\n${res.error}`)
            return
        }

        this.loadingModalOff()
        this.programOnDisk = new ExplorerProgram("", this.program.toString())
        this.setProgram(this.programOnDisk.toString())
        this.clearDraft()
    }
 
    @action.bound private async saveAs() {
        const userSlug = prompt(
            `Create a slug (URL friendly name) for this explorer. Your new file will be pushed to the '${this.props.gitCmsBranchName}' branch on GitHub.`,
            this.program.slug
        )
        if (!userSlug) return
        const slug = slugify(userSlug)
        if (!slug) {
            alert(`'${slug}' is not a valid slug`)
            return
        }
        if (new Set(RESERVED_NAMES).has(slug.toLowerCase())) {
            alert(
                `Cannot save '${userSlug}' because that is one of the reserved names: ${RESERVED_NAMES.join(
                    ", "
                )}`
            )
            return
        }
        await this._save(slug, `Saving ${this.program.slug} as ${slug}`)
        window.location.href = slug
    }
 
    @action.bound private clearChanges() {
        if (!confirm("Are you sure you want to clear your local changes?"))
            return

        this.setProgram(this.programOnDisk.toString())
        this.clearDraft()
    }
 
    @action.bound private async save() {
        const commitMessage = prompt(
            `Enter a message describing this change. Your change will be pushed to the '${this.props.gitCmsBranchName}' on GitHub.`,
            `Updated ${this.program.slug}`
        )
        if (!commitMessage) return
        await this._save(this.program.slug, commitMessage)
    }
 
    @computed get isModified() {
        return this.programOnDisk.toString() !== this.program.toString()
    }
 
    @observable gitCmsBranchName = this.props.gitCmsBranchName
 
    @action.bound private onSave() {
        if (this.program.isNewFile) this.saveAs()
        else if (this.isModified) this.save()
    }
 
    render() {
        if (!this.isReady) return <LoadingIndicator />

        const { program, isModified } = this
        const { isNewFile, slug } = program
        const previewLink = `/admin/${EXPLORERS_PREVIEW_ROUTE}/${slug}`

        const buttons = []

        buttons.push(
            <button
                key="save"
                disabled={!isModified && !isNewFile}
                className={classNames("btn", "btn-primary")}
                onClick={this.onSave}
                title="Saves file to disk, commits and pushes to GitHub"
            >
                Save
            </button>
        )
 
        buttons.push(
            <button
                key="saveAs"
                disabled={isNewFile}
                title={
                    isNewFile
                        ? "You need to save this file first."
                        : "Saves file to disk, commits and pushes to GitHub"
                }
                className={classNames("btn", "btn-secondary")}
                onClick={this.saveAs}
            >
                Save As
            </button>
        )
 
        buttons.push(
            <button
                key="clear"
                disabled={!isModified}
                title={isModified ? "" : "No changes"}
                className={classNames("btn", "btn-secondary")}
                onClick={this.clearChanges}
            >
                Clear Changes
            </button>
        )
 
        const modifiedMessage = isModified
            ? "Are you sure you want to leave? You have unsaved changes."
            : "" // todo: provide an explanation of how many cells are modified.
 
        return (
            <>
                <Prompt when={isModified} message={modifiedMessage} />
                <main
                    style={{
                        padding: 0,
                        position: "relative",
                    }}
                >
                    <div className="ExplorerCreatePageHeader">
                        <div>
                            <TemplatesComponent
                                onChange={this.setProgram}
                                isNewFile={isNewFile}
                            />
                        </div>
                        <div style={{ textAlign: "right" }}>{buttons}</div>
                    </div>
                    <HotEditor
                        onChange={this.setProgram}
                        program={program}
                        programOnDisk={this.programOnDisk}
                    />
                    <PictureInPicture previewLink={previewLink} />
                    <a className="PreviewLink" href={previewLink}>
                        Visit preview
                    </a>
                </main>
            </>
        )
    }
}
 
class HotEditor extends React.Component<{
    onChange: (code: string) => void
    program: ExplorerProgram
    programOnDisk: ExplorerProgram
}> {
    private hotTableComponent = React.createRef<HotTable>()

    @computed private get program() {
        return this.props.program
    }

    @computed private get programOnDisk() {
        return this.props.programOnDisk
    }

    @action.bound private updateProgramFromHot() {
        const newVersion =
            this.hotTableComponent.current?.hotInstance?.getData() as CoreMatrix
        if (!newVersion) return

        const newProgram = ExplorerProgram.fromMatrix(
            this.program.slug,
            newVersion
        )
        if (this.program.toString() === newProgram.toString()) return
        this.props.onChange(newProgram.toString())
    }

    private get hotSettings() {
        const { program, programOnDisk } = this
        const data = program.asArrays

        const { currentlySelectedGrapherRow } = program

        const cells = function (row: number, column: number) {
            const {
                comment,
                cssClasses,
                optionKeywords,
                placeholder,
                contents,
            } = program.getCell({ row, column })

            const cellContentsOnDisk = programOnDisk.getCellContents({
                row,
                column,
            })

            const cellProperties: Partial<Handsontable.CellProperties> = {}

            const allClasses = cssClasses?.slice() ?? []

            if (cellContentsOnDisk !== contents) {
                if (contents === "" && cellContentsOnDisk === undefined)
                    allClasses.push("cellCreated")
                else if (isEmpty(contents)) allClasses.push("cellDeleted")
                else if (isEmpty(cellContentsOnDisk))
                    allClasses.push("cellCreated")
                else allClasses.push("cellChanged")
            }

            if (currentlySelectedGrapherRow === row && column)
                allClasses.push(`currentlySelectedGrapherRow`)

            cellProperties.className = allClasses.join(" ")
            cellProperties.comment = comment ? { value: comment } : undefined
            cellProperties.placeholder = placeholder

            if (optionKeywords && optionKeywords.length) {
                cellProperties.type = "autocomplete"
                cellProperties.source = optionKeywords
            }

            return cellProperties
        }

        const hotSettings: Handsontable.GridSettings = {
            afterChange: () => this.updateProgramFromHot(),
            afterRemoveRow: () => this.updateProgramFromHot(),
            afterRemoveCol: () => this.updateProgramFromHot(),
            allowInsertRow: true,
            autoRowSize: false,
            autoColumnSize: false,
            cells,
            colHeaders: true,
            comments: true,
            contextMenu: {
                items: {
                    AutofillColDefCommand: new AutofillColDefCommand(
                        program,
                        (newProgram: string) => this.props.onChange(newProgram)
                    ).toHotCommand(),
                    InlineDataCommand: new InlineDataCommand(
                        program,
                        (newProgram: string) => this.props.onChange(newProgram)
                    ).toHotCommand(),
                    SelectAllHitsCommand: new SelectAllHitsCommand(
                        program
                    ).toHotCommand(),
                    sp0: { name: "---------" },
                    row_above: {},
                    row_below: {},
                    sp1: { name: "---------" },
                    remove_row: {},
                    remove_col: {},
                    sp2: { name: "---------" },
                    undo: {},
                    redo: {},
                    sp3: { name: "---------" },
                    copy: {},
                    cut: {},
                },
            },
            data: toRectangularMatrix(data, undefined),
            height: "100%",
            manualColumnResize: true,
            manualRowMove: true,
            minCols: program.width + 3,
            minSpareCols: 2,
            minRows: 40,
            minSpareRows: 20,
            rowHeaders: true,
            search: true,
            stretchH: "all",
            width: "100%",
            wordWrap: false,
        }

        return hotSettings
    }
 
    render() {
        return (
            <HotTable
                settings={this.hotSettings}
                ref={this.hotTableComponent as any}
                licenseKey={"non-commercial-and-evaluation"}
            />
        )
    }
}
 
class PictureInPicture extends React.Component<{
    previewLink: string
}> {
    render() {
        return (
            <iframe
                src={this.props.previewLink}
                className="ExplorerPipPreview"
            />
        )
    }
}
 
class TemplatesComponent extends React.Component<{
    isNewFile: boolean
    onChange: (code: string) => void
}> {
    @action.bound private loadTemplate(filename: string) {
        this.props.onChange(
            this.templates.find((template) => template.filename === filename)!
                .content
        )
    }
 
    @observable.ref templates: GitCmsFile[] = []
 
    componentDidMount() {
        if (this.props.isNewFile) this.fetchTemplatesOnLoad()
    }
 
    private gitCmsClient = new GitCmsClient(GIT_CMS_BASE_ROUTE)
 
    @action.bound private async fetchTemplatesOnLoad() {
        const response = await this.gitCmsClient.readRemoteFiles({
            glob: "*template*",
            folder: "explorers",
        })
        this.templates = response.files
    }
 
    render() {
        return this.templates.map((template) => (
            <button
                className={classNames("btn", "btn-primary")}
                key={template.filename}
                onClick={() => this.loadTemplate(template.filename)}
            >
                {template.filename
                    .replace(EXPLORER_FILE_SUFFIX, "")
                    .replace("-", " ")}
            </button>
        ))
    }
}