@playpilot/tpi 8.11.0-beta.2 → 8.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@playpilot/tpi",
3
- "version": "8.11.0-beta.2",
3
+ "version": "8.12.0",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "dev": "vite dev",
@@ -6,6 +6,7 @@ import type { LinkInjectionResponse, LinkInjection } from '../types/injection'
6
6
  import { getFullUrlPath } from '../url'
7
7
  import { api } from './api'
8
8
  import { getApiToken } from '$lib/token'
9
+ import { getPageTextAndElements } from '$lib/injectionElements'
9
10
 
10
11
  let pollTimeout: ReturnType<typeof setTimeout> | null = null
11
12
 
@@ -13,9 +14,8 @@ let pollTimeout: ReturnType<typeof setTimeout> | null = null
13
14
  * Fetch link injections for a URL. This will be either a POST or a GET request depending on whether on not the AI should run.
14
15
  */
15
16
  export async function fetchLinkInjections(
16
- pageText: string | null,
17
- { url = getFullUrlPath(), hash = stringToHash(pageText || ''), params = {}, method = 'GET' }:
18
- { url?: string, hash?: string, params?: Record<string, any>, method?: 'GET' | 'POST' } = {},
17
+ { url = getFullUrlPath(), params = {}, method = 'GET' }:
18
+ { url?: string, params?: Record<string, any>, method?: 'GET' | 'POST' } = {},
19
19
  ): Promise<LinkInjectionResponse> {
20
20
  const apiToken = getApiToken()
21
21
  const isEditorialMode = isEditorialModeEnabled() ? await authorize() : false
@@ -29,8 +29,10 @@ export async function fetchLinkInjections(
29
29
  // We use separate requests when running the AI or setting the editor session vs when only getting the results.
30
30
  // For regular requests we use a GET endpoint, but when saving data we POST to the same url.
31
31
  if (method === 'POST') {
32
+ const { pageText } = getPageTextAndElements()
33
+
32
34
  if (params.run_ai) {
33
- params.hash = hash
35
+ params.hash = stringToHash(pageText || '')
34
36
  params.page_text = pageText
35
37
  }
36
38
 
@@ -60,7 +62,6 @@ export async function fetchLinkInjections(
60
62
  * The results return `injections_ready=false` while the injections are not yet ready.
61
63
  */
62
64
  export async function pollLinkInjections(
63
- pageText: string,
64
65
  { requireCompletedResult = false, runAiWhenRelevant = false, pollInterval = 3000, maxTries = 600, onpoll = () => null }:
65
66
  { requireCompletedResult?: boolean, runAiWhenRelevant?: boolean, pollInterval?: number, maxTries?: number, onpoll?: (_response: LinkInjectionResponse) => void } = {},
66
67
  ): Promise<LinkInjectionResponse> {
@@ -77,19 +78,22 @@ export async function pollLinkInjections(
77
78
  // if it does. We're still interested in handling the response from here and don't want it to short circuit
78
79
  // just because the fetch failed.
79
80
  try {
80
- response = await fetchLinkInjections(pageText)
81
+ response = await fetchLinkInjections()
81
82
  } catch(error: any) {
83
+ console.error(error)
82
84
  if (error?.status === 404) {
83
85
  // If the GET endpoint returns a 404 no article has been generated yet and we can safely generate
84
86
  // a new article. We can safely throw here (meaning we poll again) as nothing will be returned.
85
87
  // The first POST indexes the article, the second runs the AI if needed.
86
- response = await fetchLinkInjections(pageText, { method: 'POST' })
87
- if (response.ai_enabled) response = await fetchLinkInjections(pageText, { params: { run_ai: true }, method: 'POST' })
88
+ response = await fetchLinkInjections({ method: 'POST' })
89
+ if (response.ai_enabled) response = await fetchLinkInjections({ params: { run_ai: true }, method: 'POST' })
88
90
  }
89
91
 
90
92
  throw new Error
91
93
  }
92
94
 
95
+ const { pageText } = getPageTextAndElements()
96
+
93
97
  if (response && runAiWhenRelevant) response = await runAiBasedOnResponse(pageText, response)
94
98
  if (requireCompletedResult && (response.ai_enabled && response.ai_running)) throw new Error
95
99
 
@@ -133,10 +137,10 @@ export async function runAiBasedOnResponse(pageText: string, response: LinkInjec
133
137
  if (response.ai_last_run && isCurrentTimeEqualToResponseTime) return response
134
138
  if (new Date(currentModifiedTime || 0) <= new Date(responseModifiedTime || 0)) return response
135
139
 
136
- return await fetchLinkInjections(pageText, { params: { run_ai: true }, method: 'POST' })
140
+ return await fetchLinkInjections({ params: { run_ai: true }, method: 'POST' })
137
141
  }
138
142
 
139
- export async function saveLinkInjections(linkInjections: LinkInjection[], pageText: string): Promise<LinkInjection[]> {
143
+ export async function saveLinkInjections(linkInjections: LinkInjection[]): Promise<LinkInjection[]> {
140
144
  const selector = window.PlayPilotLinkInjections?.selector
141
145
 
142
146
  // Only save manual injections, AI injections should be left intact and can't be saved over
@@ -156,7 +160,7 @@ export async function saveLinkInjections(linkInjections: LinkInjection[], pageTe
156
160
  removed: !!linkInjection.removed,
157
161
  }))
158
162
 
159
- const response = await fetchLinkInjections(pageText, {
163
+ const response = await fetchLinkInjections({
160
164
  method: 'POST',
161
165
  params: {
162
166
  private_token: getAuthToken(),
@@ -11,10 +11,9 @@ export const sessionPeriodMilliseconds = sessionPollPeriodMilliseconds * 2
11
11
  * where we save the session.
12
12
  * Along with that, we also return ai_enabled and injections_enabled as they are used to update the state of
13
13
  * the current editing session.
14
- * @param pageText Despite not being used, the request still requires a valid pageText string
15
14
  */
16
- export async function fetchAsSession(pageText: string): Promise<SessionResponse> {
17
- const { ai_enabled, injections_enabled, ai_last_run, session_id, session_last_ping } = await fetchLinkInjections(pageText)
15
+ export async function fetchAsSession(): Promise<SessionResponse> {
16
+ const { ai_enabled, injections_enabled, ai_last_run, session_id, session_last_ping } = await fetchLinkInjections()
18
17
 
19
18
  const isCurrentlyAllowToEdit = isAllowedToEdit(session_id || null, session_last_ping || null)
20
19
 
@@ -28,15 +27,14 @@ export async function fetchAsSession(pageText: string): Promise<SessionResponse>
28
27
 
29
28
  if (!isCurrentlyAllowToEdit) return response
30
29
 
31
- return await saveCurrentSession(pageText)
30
+ return await saveCurrentSession()
32
31
  }
33
32
 
34
33
  /**
35
34
  * Save the current users session id as the currently active session. This is always completed regardless of if the user
36
35
  * is the current owner of the session, so check that first if necessary!
37
- * @param pageText Despite not being used, the request still requires a valid pageText string
38
36
  */
39
- export async function saveCurrentSession(pageText: string): Promise<SessionResponse> {
37
+ export async function saveCurrentSession(): Promise<SessionResponse> {
40
38
  const sessionId = getSessionId()
41
39
  const now = new Date(Date.now()).toISOString()
42
40
 
@@ -45,7 +43,7 @@ export async function saveCurrentSession(pageText: string): Promise<SessionRespo
45
43
  session_last_ping: now.toString(),
46
44
  }
47
45
 
48
- const { ai_enabled, injections_enabled, ai_last_run } = await fetchLinkInjections(pageText, { params })
46
+ const { ai_enabled, injections_enabled, ai_last_run } = await fetchLinkInjections({ params })
49
47
 
50
48
  return {
51
49
  ai_enabled,
@@ -91,7 +91,7 @@ export function getPageText(elements: HTMLElement[]): string {
91
91
  return elements.map(element => element.innerText).join('\n\n')
92
92
  }
93
93
 
94
- export function getPageTextAndElements(config: ConfigResponse | null): { parentElement: HTMLElement, elements: HTMLElement[], pageText: string } {
94
+ export function getPageTextAndElements(config: ConfigResponse | null = window.PlayPilotLinkInjections?.config || null): { parentElement: HTMLElement, elements: HTMLElement[], pageText: string } {
95
95
  const parentElement = getLinkInjectionsParentElement()
96
96
  const elements = getLinkInjectionElements(parentElement, config?.exclude_elements_selector || '')
97
97
  const pageText = getPageText(elements)
package/src/lib/meta.ts CHANGED
@@ -68,7 +68,8 @@ export function getDatetime(datetime: string): string | null {
68
68
  }
69
69
 
70
70
  export function getSchemaJson(): Record<string, any> {
71
- const schemaElement = document.querySelector('[type="application/ld+json"]')
71
+ const schemaElements = Array.from(document.querySelectorAll('[type="application/ld+json"]'))
72
+ const schemaElement = schemaElements.find(element => element.textContent.includes('dateModified') || element.textContent.includes('datePublished'))
72
73
 
73
74
  if (!schemaElement) return {}
74
75
 
@@ -42,6 +42,8 @@ export type ScriptConfig = {
42
42
  config?: ConfigResponse
43
43
  // All ads as fetched from the ads endpoint. This is used as the primary store for ads, each individual ads gets it's data from here.
44
44
  ads?: Campaign[]
45
+ // Estimate playtimes of video embeds listed by their video id.
46
+ video_playtimes?: Record<string, number>
45
47
  // The region the user is in, either fetched from an external service or based on the default region in the config object
46
48
  region?: string | null
47
49
  // The time at which the script was initialized
package/src/main.ts CHANGED
@@ -3,7 +3,6 @@ import { fetchConfig } from '$lib/api/config'
3
3
  import { pollLinkInjections } from '$lib/api/externalPages'
4
4
  import { setConsent } from '$lib/consent'
5
5
  import { isCrawler } from '$lib/crawler'
6
- import { getPageTextAndElements } from '$lib/injectionElements'
7
6
  import { isUrlExcludedViaConfig } from '$lib/url'
8
7
 
9
8
  window.PlayPilotLinkInjections ||= {
@@ -24,6 +23,7 @@ window.PlayPilotLinkInjections ||= {
24
23
  initial_link_injections_promise: null,
25
24
  time_at_initialize: 0,
26
25
  ads: [],
26
+ video_playtimes: {},
27
27
  require_consent: true,
28
28
  no_affiliate: false,
29
29
  consents: {
@@ -70,9 +70,7 @@ window.PlayPilotLinkInjections ||= {
70
70
 
71
71
  if (isUrlExcludedViaConfig(this.config)) return
72
72
 
73
- const { pageText } = getPageTextAndElements(this.config)
74
-
75
- this.initial_link_injections_promise = pollLinkInjections(pageText, { maxTries: 1, runAiWhenRelevant: !isCrawler() })
73
+ this.initial_link_injections_promise = pollLinkInjections({ maxTries: 1, runAiWhenRelevant: !isCrawler() })
76
74
 
77
75
  this.mount()
78
76
  },
@@ -128,9 +128,14 @@
128
128
  line-height: 1.8;
129
129
 
130
130
  nav {
131
- display: flex;
131
+ display: grid;
132
+ grid-template-columns: 1fr 1fr;
132
133
  gap: margin(1);
133
134
 
135
+ @include desktop {
136
+ display: flex;
137
+ }
138
+
134
139
  a {
135
140
  padding: margin(0.25) margin(0.75);
136
141
  border: 1px solid currentColor;
@@ -2,7 +2,6 @@
2
2
  import { onDestroy } from 'svelte'
3
3
  import { pollLinkInjections } from '$lib/api/externalPages'
4
4
  import { clearLinkInjections, injectLinksInDocument, separateLinkInjectionTypes } from '$lib/injection'
5
- import { getPageText, getPageTextAndElements } from '$lib/injectionElements'
6
5
  import { fireQueuedTrackingEvents, setTrackingSids, track } from '$lib/tracking'
7
6
  import { isUrlExcludedViaConfig } from '$lib/url'
8
7
  import { isCrawler } from '$lib/crawler'
@@ -11,6 +10,7 @@
11
10
  import { fetchConfig } from '$lib/api/config'
12
11
  import { insertExplore, insertExploreIntoNavigation } from '$lib/explore'
13
12
  import { authorize, getAuthToken, isEditorialModeEnabled, removeAuthCookie, setEditorialParamInUrl } from '$lib/api/auth'
13
+ import { getPageTextAndElements } from '$lib/injectionElements'
14
14
  import type { LinkInjectionResponse, LinkInjection, LinkInjectionTypes } from '$lib/types/injection'
15
15
  import Editor from './components/Editorial/Editor.svelte'
16
16
  import EditorTrigger from './components/Editorial/EditorTrigger.svelte'
@@ -22,8 +22,6 @@
22
22
  import PostersScrollReveal from './components/PostersScrollReveal.svelte'
23
23
  import TrackingPixelsForTitleDataPerLink from './components/TrackingPixelsForTitleDataPerLink.svelte'
24
24
 
25
- let elements: HTMLElement[] = $state([])
26
-
27
25
  let response: LinkInjectionResponse | null = $state(null)
28
26
  let isEditorialMode = $state(isEditorialModeEnabled())
29
27
  let hasAuthToken = $state(!!getAuthToken())
@@ -35,8 +33,6 @@
35
33
  // @ts-ignore It's ok if the response is empty
36
34
  const { ai_injections: aiInjections = [], manual_injections: manualInjections = [] } = $derived(response || {})
37
35
 
38
- const pageText = $derived(getPageText(elements))
39
-
40
36
  const initializePromise = initialize()
41
37
 
42
38
  $effect(() => {
@@ -86,8 +82,6 @@
86
82
  if (isUrlExcluded) return
87
83
 
88
84
  if (config?.html_selector) window.PlayPilotLinkInjections.selector = config?.html_selector
89
-
90
- elements = getPageTextAndElements(window.PlayPilotLinkInjections.config).elements
91
85
  } catch(error) {
92
86
  // We return if the config did not get fetched properly, as we can't determine what should and should
93
87
  // get injected without it.
@@ -98,7 +92,7 @@
98
92
 
99
93
  try {
100
94
  response = await window.PlayPilotLinkInjections.initial_link_injections_promise || null
101
- response ||= await pollLinkInjections(pageText, { maxTries: 1, runAiWhenRelevant: !isCrawler() })
95
+ response ||= await pollLinkInjections({ maxTries: 1, runAiWhenRelevant: !isCrawler() })
102
96
 
103
97
  loading = false
104
98
 
@@ -114,7 +108,7 @@
114
108
 
115
109
  if (!isEditorialMode || isCrawler()) return
116
110
 
117
- response = await pollLinkInjections(pageText, { requireCompletedResult: true, onpoll: (update) => response = update })
111
+ response = await pollLinkInjections({ requireCompletedResult: true, onpoll: (update) => response = update })
118
112
  inject({ aiInjections, manualInjections })
119
113
  } catch(error: unknown) {
120
114
  console.error(error)
@@ -136,6 +130,7 @@
136
130
  }
137
131
 
138
132
  function inject(injections: LinkInjectionTypes = { aiInjections, manualInjections }): void {
133
+ const { elements } = getPageTextAndElements()
139
134
  const filteredInjections = injectLinksInDocument(elements, injections)
140
135
 
141
136
  if (JSON.stringify(filteredInjections) !== JSON.stringify(linkInjections)) {
@@ -206,7 +201,6 @@
206
201
  <svelte:boundary onerror={(error) => track(TrackingEvent.EditorError, null, { message: (error as Error).message })}>
207
202
  <Editor
208
203
  bind:linkInjections
209
- {pageText}
210
204
  {loading}
211
205
  onreinitialize={reinitializeEditor}
212
206
  injectionsEnabled={response?.injections_enabled}
@@ -33,7 +33,6 @@
33
33
 
34
34
  let {
35
35
  linkInjections = $bindable(),
36
- pageText = '',
37
36
  loading = false,
38
37
  injectionsEnabled = false,
39
38
  aiStatus = {},
@@ -46,6 +45,8 @@
46
45
  const position: Position = JSON.parse(localStorage.getItem(editorPositionKey) || '{ "x": 0, "y": 0 }')
47
46
  const height: number = parseInt(localStorage.getItem(editorHeightKey) || '0')
48
47
 
48
+
49
+
49
50
  let editorElement: HTMLElement | null = $state(null)
50
51
  let manualInjectionActive = $state(false)
51
52
  let saving = $state(false)
@@ -85,7 +86,7 @@
85
86
  saving = true
86
87
  hasError = false
87
88
 
88
- linkInjections = await saveLinkInjections(linkInjections, pageText)
89
+ linkInjections = await saveLinkInjections(linkInjections)
89
90
  initialStateString = linkInjectionsString
90
91
  } catch {
91
92
  hasError = true
@@ -177,7 +178,6 @@
177
178
 
178
179
  {#if !loading}
179
180
  <Session
180
- {pageText}
181
181
  onallow={() => allowEditing = true}
182
182
  ondisallow={() => allowEditing = false}
183
183
  ontakeover={onreinitialize}
@@ -231,7 +231,6 @@
231
231
  style:top="{scrollDistance}px"
232
232
  transition:fly={{ x: Math.min(window.innerWidth, 320), duration: 200, opacity: 1 }}>
233
233
  <ManualInjection
234
- {pageText}
235
234
  onclose={() => manualInjectionActive = false}
236
235
  onsave={(linkInjection) => linkInjections.push(linkInjection)} />
237
236
  </div>
@@ -4,7 +4,7 @@
4
4
  import { onMount } from 'svelte'
5
5
  import { playPilotBaseUrl } from '$lib/constants'
6
6
  import { generateInjectionKey } from '$lib/api/externalPages'
7
- import { getLinkInjectionsParentElement } from '$lib/injectionElements'
7
+ import { getLinkInjectionsParentElement, getPageTextAndElements } from '$lib/injectionElements'
8
8
  import { heading } from '$lib/actions/heading'
9
9
  import { findSurroundingPhrases, cleanPhrase } from '$lib/text'
10
10
  import { getIndexOfSelection } from '$lib/selection'
@@ -15,12 +15,13 @@
15
15
  import TitleSearch from './Search/TitleSearch.svelte'
16
16
 
17
17
  interface Props {
18
- pageText: string
19
18
  onsave: (linkInjection: LinkInjection) => void
20
19
  onclose?: () => void
21
20
  }
22
21
 
23
- const { pageText = '', onsave, onclose = () => null }: Props = $props()
22
+ const { onsave, onclose = () => null }: Props = $props()
23
+
24
+ const { pageText } = getPageTextAndElements()
24
25
 
25
26
  let currentSelection = $state('')
26
27
  let selectionSentence = $state('')
@@ -4,7 +4,6 @@
4
4
  import Alert from './Alert.svelte'
5
5
 
6
6
  interface Props {
7
- pageText?: string,
8
7
  onpoll?: ({ injectionsEnabled, aiEnabled }: { injectionsEnabled: boolean, aiEnabled: boolean }) => void,
9
8
  onallow?: () => void,
10
9
  ondisallow?: () => void,
@@ -12,7 +11,6 @@
12
11
  }
13
12
 
14
13
  const {
15
- pageText = '',
16
14
  onpoll = () => null,
17
15
  onallow = () => null,
18
16
  ondisallow = () => null,
@@ -36,7 +34,7 @@
36
34
  }
37
35
 
38
36
  async function setSession(): Promise<void> {
39
- const result = await fetchAsSession(pageText)
37
+ const result = await fetchAsSession()
40
38
 
41
39
  if (!result) return
42
40
 
@@ -49,7 +47,7 @@
49
47
  }
50
48
 
51
49
  function takeOverEditing(): void {
52
- saveCurrentSession(pageText)
50
+ saveCurrentSession()
53
51
  ontakeover()
54
52
  }
55
53
  </script>
@@ -78,7 +78,7 @@
78
78
  </Modal>
79
79
 
80
80
  <style lang="scss">
81
- $size: min(600px, 80vw);
81
+ $size: min(600px, 85vw);
82
82
 
83
83
  .rail-modal {
84
84
  --gap: #{margin(0.25)};
@@ -156,7 +156,7 @@
156
156
  }
157
157
 
158
158
  .arrow {
159
- --offset: #{margin(-2)};
159
+ --offset: #{margin(-1.25)};
160
160
  --scale: 1;
161
161
  cursor: pointer;
162
162
  z-index: 2;
@@ -60,12 +60,15 @@
60
60
  const activeElement = element?.querySelectorAll('.title')[index]!
61
61
  const parentOffset = element?.getBoundingClientRect().right || 0
62
62
  const elementOffsetInParent = parentOffset - activeElement.getBoundingClientRect().right
63
+ const isFullyVisible = elementOffsetInParent > activeElement.clientWidth * 2
63
64
 
64
65
  recentlyExpanded = true
65
66
  setTimeout(() => recentlyExpanded = false, 500)
66
67
 
67
- if (size === 'flexible' && elementOffsetInParent < activeElement.clientWidth * 2) {
68
+ if (size === 'flexible' && !isFullyVisible) {
68
69
  slider?.setIndex(index - 2)
70
+ } else if (size === 'huge' && !isFullyVisible) {
71
+ slider?.setIndex(index)
69
72
  }
70
73
 
71
74
  expandTitleIntoTrailer(title)
@@ -43,8 +43,10 @@
43
43
  return '.' + classnames.join('.')
44
44
  }
45
45
 
46
- function elementHasDirectTextContent(element: Element): Node | undefined {
47
- return Array.from(element.childNodes).find(node => node.nodeName === '#text' && !!node.textContent?.trim())
46
+ function elementHasDirectTextContent(element: Element | undefined): Node | null {
47
+ if (!element?.childNodes?.length) return null
48
+
49
+ return Array.from(element.childNodes).find(node => node.nodeName === '#text' && !!node.textContent?.trim()) || null
48
50
  }
49
51
  </script>
50
52
 
@@ -1,5 +1,6 @@
1
1
  <script lang="ts">
2
2
  import { getVideoId } from '$lib/trailer'
3
+ import { onMount } from 'svelte'
3
4
  import IconMute from './Icons/IconMute.svelte'
4
5
 
5
6
  interface Props {
@@ -14,11 +15,26 @@
14
15
  const { embeddable_url = '', controls = [], muted = false, loop = false, captions = false, showMuteControls = false }: Props = $props()
15
16
 
16
17
  const videoId = $derived(getVideoId(embeddable_url))
18
+ const startTime = $derived((window?.PlayPilotLinkInjections?.video_playtimes?.[videoId || ''] || 1) - 1)
17
19
  const color = window?.getComputedStyle(document.body).getPropertyValue('--playpilot-primary')?.replace('#', '') || 'fa548a'
18
20
 
19
21
  let iframe: HTMLIFrameElement | null = $state(null)
20
22
  let isMuted = $state(muted)
21
23
 
24
+ onMount(() => {
25
+ if (!videoId) return
26
+
27
+ if (!window.PlayPilotLinkInjections.video_playtimes) window.PlayPilotLinkInjections.video_playtimes = {}
28
+
29
+ let elapsedSeconds = startTime
30
+ const interval = setInterval(() => {
31
+ elapsedSeconds++
32
+ window.PlayPilotLinkInjections.video_playtimes![videoId] = elapsedSeconds
33
+ }, 1000)
34
+
35
+ return () => clearInterval(interval)
36
+ })
37
+
22
38
  export function toggleMute(state = !isMuted): void {
23
39
  if (isMuted != state) iframe?.contentWindow?.postMessage('mute', '*')
24
40
  isMuted = state
@@ -30,7 +46,7 @@
30
46
  bind:this={iframe}
31
47
  width="600"
32
48
  height="338"
33
- src="https://video.playpilot.net/?video_id={videoId}&color={color}&muted={muted}&loop={loop}&captions={captions}&controls={controls.join(',')}&autoplay=true&playsinline=true"
49
+ src="https://video.playpilot.net/?video_id={videoId}&color={color}&muted={muted}&loop={loop}&captions={captions}&controls={controls.join(',')}&start_time={startTime}&autoplay=true&playsinline=true"
34
50
  title="YouTube video player"
35
51
  frameborder="0"
36
52
  referrerpolicy="strict-origin-when-cross-origin"